content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import random
def delete_important_words(word_list, replace=''):
"""
randomly detele an important word in the query or replace (not in QUERY_SMALL_CHANGE_SETS)
"""
# replace can be [MASK]
important_word_list = set(word_list) - set(QUERY_SMALL_CHANGE_SETS)
target = random.sample(important_w... | 336518cb1c52f896fc9878e1c11b3f0e72c4f36a | 3,650,300 |
import numpy as np
def prot(vsini, st_rad):
"""
Function to convert stellar rotation velocity vsini in km/s to rotation period in days.
Parameters:
----------
vsini: Rotation velocity of star in km/s.
st_rad: Stellar radius in units of solar radii
Returns
------
... | db2ef4648c5142a996e4a700aee0c7df0f02a394 | 3,650,301 |
def dialog_sleep():
"""Return the time to sleep as set by the --exopy-sleep option.
"""
return DIALOG_SLEEP | cc40ffa09c83bd095f685b3b1d237545b8d7dd34 | 3,650,302 |
def required_overtime (db, user, frm) :
""" If required_overtime flag is set for overtime_period of dynamic
user record at frm, we return the overtime_period belonging to
this dyn user record. Otherwise return None.
"""
dyn = get_user_dynamic (db, user, frm)
if dyn and dyn.overtime_perio... | 052e1289a0d7110100b3a1ea0ad90fa7bd000cce | 3,650,303 |
def get_best_fit_member(*args):
"""
get_best_fit_member(sptr, offset) -> member_t
Get member that is most likely referenced by the specified offset.
Useful for offsets > sizeof(struct).
@param sptr (C++: const struc_t *)
@param offset (C++: asize_t)
"""
return _ida_struct.get_best_fit_member(*arg... | 7d4032d5cedb789d495e658eda939c36591f3506 | 3,650,304 |
def convert_time(time):
"""Convert given time to srt format."""
stime = '%(hours)02d:%(minutes)02d:%(seconds)02d,%(milliseconds)03d' % \
{'hours': time / 3600,
'minutes': (time % 3600) / 60,
'seconds': time % 60,
'milliseconds': (time % 1) * 1000}
return st... | 948e6567c8bc17ccb5f98cf8c8eaf8fe6e8d0bec | 3,650,305 |
def Returns1(target_bitrate, result):
"""Score function that returns a constant value."""
# pylint: disable=W0613
return 1.0 | 727e58e0d6d596cf4833ca3ca1cbcec6b9eedced | 3,650,306 |
def test_abstract_guessing():
"""Test abstract guessing property."""
class _CustomPsychometric(DiscriminationMethod):
def psychometric_function(self, d):
return 0.5
with pytest.raises(TypeError, match="abstract method"):
_CustomPsychometric() | 996f6fb4d6b819e15fb3a931c0dc2a1f211e3d58 | 3,650,307 |
import re
def remove_repeats(msg):
"""
This function removes repeated characters from text.
:param/return msg: String
"""
# twitter specific repeats
msg = re.sub(r"(.)\1{2,}", r"\1\1\1", msg) # characters repeated 3 or more times
# laughs
msg = re.sub(r"(ja|Ja)(ja|Ja)+(j)?", r"jaja",... | 590ab42f74deaa9f8dc1eb9c8b11d81622db2e6d | 3,650,308 |
def _legend_main_get(project, row):
"""
forma la leyenda de la serie principal del gráfico
input
project: es el tag project del proyecto seleccionado
en fichero XYplus_parameters.f_xml -en XYplus_main.py-
row: es fila activa devuelta por select_master) de donde se
ex... | 3938d723bd44a67313b86f956464fd186ef25386 | 3,650,309 |
import time
import os
def contrast_jwst_num(coro_floor, norm, matrix_dir, rms=50*u.nm):
"""
Compute the contrast for a random segmented OTE misalignment on the JWST simulator.
:param coro_floor: float, coronagraph contrast floor
:param norm: float, normalization factor for PSFs: peak of unaberrated d... | 750287224184cf6f49394b5bceee3307fe790810 | 3,650,310 |
def ordinal_mapper(fh, coords, idmap, fmt=None, n=1000000, th=0.8,
prefix=False):
"""Read an alignment file and match reads and genes in an ordinal system.
Parameters
----------
fh : file handle
Alignment file to parse.
coords : dict of list
Gene coordinates table... | 955c411e608fdb3cf55d0c52350b38061f87cd3a | 3,650,311 |
def file_lines(filename):
"""
>>> file_lines('test/foo.txt')
['foo', 'bar']
"""
return text_file(filename).split() | b121ba549606adeac244b063ff679192951c2ff8 | 3,650,312 |
def repr_should_be_defined(obj):
"""Checks the obj.__repr__() method is properly defined"""
obj_repr = repr(obj)
assert isinstance(obj_repr, str)
assert obj_repr == obj.__repr__()
assert obj_repr.startswith("<")
assert obj_repr.endswith(">")
return obj_repr | 28537f4f48b402a2eba290d8ece9b765eeb9fdc3 | 3,650,313 |
import os
def read_tiff(tiff_path):
"""
Args:
tiff_path: a tiff file path
Returns:
tiff image object
"""
if not os.path.isfile(tiff_path) or not is_tiff_file(tiff_path):
raise InvalidTiffFileError(tiff_path)
return imread(tiff_path) | 63a5ae406c47ba72a46d7c4a29bde9371e6ce824 | 3,650,314 |
def changePassword():
"""
Change to a new password and email user.
URL Path:
URL Args (required):
- JSON structure of change password data
Returns:
200 OK if invocation OK.
500 if server not configured.
"""
@testcase
def changePasswordWorker():
try:
... | 0c354535b2ff6be180ddec939be533b2a87a5a94 | 3,650,315 |
from typing import Callable
from typing import Any
from typing import List
from typing import Tuple
import os
import multiprocessing
def parallel_for(
loop_callback: Callable[[Any], Any],
parameters: List[Tuple[Any, ...]],
nb_threads: int = os.cpu_count()+4
) -> List[Any]:
"""Execute a for... | e3ae62d02ee886386e939a7f4890df74f3ab4879 | 3,650,316 |
def indexName():
"""Index start page."""
return render_template('index.html') | 0340e708a82052a98e6e9e92bfde2eb04128d354 | 3,650,317 |
def translate_http_code():
"""Print given code
:return:
"""
return make_http_code_translation(app) | c9b501b57323aeb765be47af134dd2de1c1d084e | 3,650,318 |
from re import DEBUG
def dose_rate(sum_shielding, isotope, disable_buildup = False):
"""
Calculate the dose rate for a specified isotope behind shielding
behind shielding barriers. The dose_rate is calculated for 1MBq
Args:
sum_shielding: dict with shielding elements
isotope: ... | 37b90720564c1a15b5e4fb40cb67df556caaa742 | 3,650,319 |
import warnings
def parmap(f, X, nprocs=1):
"""
parmap_fun() and parmap() are adapted from klaus se's post
on stackoverflow. https://stackoverflow.com/a/16071616/4638182
parmap allows map on lambda and class static functions.
Fall back to serial map when nprocs=1.
"""
if nprocs < 1:
... | 66a498966979ca00c9a7eedfc1113a07b9076245 | 3,650,320 |
def is_char_token(c: str) -> bool:
"""Return true for single character tokens."""
return c in ["+", "-", "*", "/", "(", ")"] | 3d5691c8c1b9a592987cdba6dd4809cf2c410ee8 | 3,650,321 |
import numpy
def _float_arr_to_int_arr(float_arr):
"""Try to cast array to int64. Return original array if data is not representable."""
int_arr = float_arr.astype(numpy.int64)
if numpy.any(int_arr != float_arr):
# we either have a float that is too large or NaN
return float_arr
else:
... | 73643757b84ec28ed721608a2176b292d6e90837 | 3,650,322 |
def latest(scores: Scores) -> int:
"""The last added score."""
return scores[-1] | 393c1d9a4b1852318d622a58803fff3286db98af | 3,650,323 |
def get_dp_2m(wrfin, timeidx=0, method="cat", squeeze=True,
cache=None, meta=True, _key=None, units="degC"):
"""Return the 2m dewpoint temperature.
This functions extracts the necessary variables from the NetCDF file
object in order to perform the calculation.
Args:
... | e16a5a3951312254eb852a5e03987aab32a91373 | 3,650,324 |
def fit_uncertainty(points, lower_wave, upper_wave, log_center_wave, filter_size):
"""Performs fitting many times to get an estimate of the uncertainty
"""
mock_points = []
for i in range(1, 100):
# First, fit the points
coeff = np.polyfit(np.log10(points['rest_wavelength']),
... | cca5193e55d7aeef710a08fb16df8c896bbeef90 | 3,650,325 |
def from_dateutil_rruleset(rruleset):
"""
Convert a `dateutil.rrule.rruleset` instance to a `Recurrence`
instance.
:Returns:
A `Recurrence` instance.
"""
rrules = [from_dateutil_rrule(rrule) for rrule in rruleset._rrule]
exrules = [from_dateutil_rrule(exrule) for exrule in rruleset.... | cd5ab771eebbf6f68ce70a8d100ad071561541de | 3,650,326 |
import re
def error_038_italic_tag(text):
"""Fix the error and return (new_text, replacements_count) tuple."""
backup = text
(text, count) = re.subn(r"<(i|em)>([^\n<>]+)</\1>", "''\\2''", text, flags=re.I)
if re.search(r"</?(?:i|em)>", text, flags=re.I):
return (backup, 0)
else:
re... | b0c2b571ade01cd483a3ffdc6f5c2bbb873cd13c | 3,650,327 |
def create_user():
""" Method that will create an user .
Returns:
user.id: The id of the created user
Raises:
If an error occurs it will be displayed in a error message.
"""
try:
new_user = User(name=login_session['username'], email=login_session[
'emai... | e5d555fb955523c6bff811efe308030de257e05a | 3,650,328 |
import numpy
def buildStartAndEndWigData(thisbam, LOG_EVERY_N=1000, logger=None):
"""parses a bam file for 3' and 5' ends and builds these into wig-track data
Returns a dictionary of various gathered statistics."""
def formatToWig(wigdata):
""" take in the read position dat... | f97a2b2c54f1cf2f978a17ef2b74435153ec4369 | 3,650,329 |
from pathlib import Path
from typing import List
from typing import Optional
def time_series_h5(timefile: Path, colnames: List[str]) -> Optional[DataFrame]:
"""Read temporal series HDF5 file.
If :data:`colnames` is too long, it will be truncated. If it is too short,
additional column names will be deduce... | e28194bcfead5b188ea947efe51fc2bac052bea9 | 3,650,330 |
def decode_jwt(token):
"""decodes a token and returns ID associated (subject) if valid"""
try:
payload = jwt.decode(token.encode(), current_app.config['SECRET_KEY'], algorithms=['HS256'])
return {"isError": False, "payload": payload["sub"]}
except jwt.ExpiredSignatureError as e:
curr... | 15938fc40d2fb5b60c4ef5ccb3d6f3211fa5952f | 3,650,331 |
def format_point(point: Point) -> str:
"""Return a str representing a Point object.
Args:
point:
Point obj to represent.
Returns:
A string representing the Point with ° for grades, ' for minutes and " for seconds.
Latitude is written before Longitude.
Example Output: 30... | 435a13d7198e6da99306c58d35249b666a03571c | 3,650,332 |
def families_horizontal_correctors():
"""."""
return ['CH'] | a3f8de3e0d44ea72d2fb98733050b7a2d598c142 | 3,650,333 |
import requests
def variable_select_source_data_proxy(request):
"""
@summary: 获取下拉框源数据的通用接口
@param request:
@return:
"""
url = request.GET.get('url')
try:
response = requests.get(
url=url,
verify=False
)
except Exception as e:
logger.exce... | c8d131d6c7d0e766e0a4dacd1b0086090ee02c4f | 3,650,334 |
async def select_guild_lfg_events(guild_id: int) -> list[asyncpg.Record]:
"""Gets the lfg messages for a specific guild ordered by the youngest creation date"""
select_sql = f"""
SELECT
id, message_id, creation_time, voice_channel_id
FROM
lfgmessages
WHERE
... | 3a1b98191b75b4ec0bbdb5942a7b5b2d8c8dca48 | 3,650,335 |
def ValueToString(descriptor, field_desc, value):
"""Renders a field value as a PHP literal.
Args:
descriptor: The descriptor module from the protobuf package, e.g.
google.protobuf.descriptor.
field_desc: The type descriptor for the field value to be rendered.
value: The value of the field to b... | e40815ab6e3b55e1a7cb026c33a9c9324da900b4 | 3,650,336 |
def get_checkpoints(run_dir, from_global_step=None, last_only=False):
"""Return all available checkpoints.
Args:
run_dir: Directory where the checkpoints are located.
from_global_step (int): Only return checkpoints after this global step.
The comparison is *strict*. If ``None``, ret... | c40a89049b11bda2688cb195956db3e50bc44c06 | 3,650,337 |
import tempfile
import sys
def write_env_file(env_dict):
""" Write the env_file information to a temporary file
If there is any error, return None;
otherwise return the temp file
"""
try:
temp_file = tempfile.NamedTemporaryFile(mode='w')
for key in env_dict.keys():
... | c53ee69cc12fafc7504f8adbbfbef40626f18427 | 3,650,338 |
def __load_txt_resource__(path):
"""
Loads a txt file template
:param path:
:return:
"""
txt_file = open(path, "r")
return txt_file | 9e3632098c297d1f6407559a86f0d8dc7b68ea75 | 3,650,339 |
def parse_cpu_spec(spec):
"""Parse a CPU set specification.
:param spec: cpu set string eg "1-4,^3,6"
Each element in the list is either a single
CPU number, a range of CPU numbers, or a
caret followed by a CPU number to be excluded
from a previous range.
:returns: a set of CPU indexes
... | fa323a2fc5c27a6645f0abfb3b4878f6ae6390ee | 3,650,340 |
import typing
def distance_fit_from_transits() -> typing.List[float]:
"""
This uses the observers position from full transits and then the runway positions from all
the transit lines fitted to a
"""
((x_mean, x_std), (y_mean, y_std)) = observer_position_mean_std_from_full_transits()
transits =... | 57b201b1328528191b4926a66325ca026855f09a | 3,650,341 |
import torch
def collate_fn_synthesize(batch):
"""
Create batch
Args : batch(tuple) : List of tuples / (x, c) x : list of (T,) c : list of (T, D)
Returns : Tuple of batch / Network inputs x (B, C, T), Network targets (B, T, 1)
"""
local_conditioning = len(batch[0]) >= 2
if local_condi... | b784a45eb753d5d84ae3bf18fd4e7a09e891753d | 3,650,342 |
def max_(context, mapping, args, **kwargs):
"""Return the max of an iterable"""
if len(args) != 1:
# i18n: "max" is a keyword
raise error.ParseError(_("max expects one argument"))
iterable = evalwrapped(context, mapping, args[0])
try:
return iterable.getmax(context, mapping)
... | 068f77031fb83dc9d88446863e39f38c14a7478d | 3,650,343 |
from typing import Optional
from typing import Dict
def dict_to_duration(time_dict: Optional[Dict[str, int]]) -> Duration:
"""Convert a QoS duration profile from YAML into an rclpy Duration."""
if time_dict:
try:
return Duration(seconds=time_dict['sec'], nanoseconds=time_dict['nsec'])
... | 7b20ed1ecbe496f55426562e791e591d8c5104e5 | 3,650,344 |
def gen_ex_tracking_df(subj_dir):
"""Generate subject tracking error data frames from time series CSVs.
This method generates tracking error (Jaccard distance, CSA, T, AR) data
frames from raw time series CSV data for a single subject.
Args:
subj_dir (str): path to subject data directory, incl... | 259f2533bf8a0d9a03c250fc937c4a99903c8994 | 3,650,345 |
def mse(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Compute the MSE (Mean Squared Error)."""
return sklearn.metrics.mean_squared_error(y_true, y_pred) | f9c669b04bc6a44bcd983c79dec5d630a6acbd09 | 3,650,346 |
import torch
def policy_improvement(env, V, gamma):
"""
Obtain an improved policy based on the values
@param env: OpenAI Gym environment
@param V: policy values
@param gamma: discount factor
@return: the policy
"""
n_state = env.observation_space.n
n_action = env.action_space.n
... | 10587e5d4fb08158eff06a4305de6c02fc2d878c | 3,650,347 |
def loudness_zwst_freq(spectrum, freqs, field_type="free"):
"""Zwicker-loudness calculation for stationary signals
Calculates the acoustic loudness according to Zwicker method for
stationary signals.
Normatice reference:
ISO 532:1975 (method B)
DIN 45631:1991
ISO 532-1:2017 (met... | 391e33784e355675b68b3e95ade084cbcb86d5b5 | 3,650,348 |
import sys
def func(back=2):
"""
Returns the function name
"""
return "{}".format(sys._getframe(back).f_code.co_name) | 97332c32195418e4bf6dd6427adabbc5c4360580 | 3,650,349 |
def normU(u):
"""
A function to scale Uranium map. We don't know what this function should be
"""
return u | e4bd83a26c502e9129d18091e807e17ab3294fd1 | 3,650,350 |
def exact_riemann_solution(q_l, q_r, gamma=1.4, phase_plane_curves=False):
"""Return the exact solution to the Riemann problem with initial states
q_l, q_r. The solution is given in terms of a list of states, a list of
speeds (each of which may be a pair in case of a rarefaction fan), and a
fu... | a5baa391d88a56026cc02a1a1fa841325e712ea0 | 3,650,351 |
def show_edge_scatter(N, s1, s2, t1, t2, d, dmax=None, fig_ax=None):
"""Draw the cell-edge contour and the displacement vectors.
The contour is drawn using a scatter plot to color-code the displacements."""
if fig_ax is None:
fig, ax = plt.subplots()
else:
fig, ax = fig_ax
plt.f... | d0575ec425828e895f24c3ff8cbf9f472ba62947 | 3,650,352 |
def get_A2_const(alpha1, alpha2, lam_c, A1):
"""Function to compute the constant A2.
Args:
alpha1 (float): The alpha1 parameter of the WHSCM.
alpha2 (float): The alpha2 parameter of the WHSCM.
lam_c (float): The switching point between the
two exponents of the dou... | 16fe12e9ef9d72cfe7250cf840e222512409d377 | 3,650,353 |
import argparse
def args_parser():
"""
Parese command line arguments
Args:
opt_args: Optional args for testing the function. By default sys.argv is used
Returns:
args: Dictionary of args.
Raises:
ValueError: Raises an exception if some arg values are invalid.
... | 10cfb19844e380d683bb7d50b6752e8d1b2a62eb | 3,650,354 |
def _parse_seq_tf_example(example, uint8_features, shapes):
"""Parse tf.Example containing one or two episode steps."""
def to_feature(key, shape):
if key in uint8_features:
return tf.io.FixedLenSequenceFeature(
shape=[], dtype=tf.string, allow_missing=True)
else:
return tf.io.FixedLen... | 5e0e4a6d3f26c28eb6e5dfe12e9295eb5b53979c | 3,650,355 |
def unique_list(a_list, unique_func=None, replace=False):
"""Unique a list like object.
- collection: list like object
- unique_func: the filter functions to return a hashable sign for unique
- replace: the following replace the above with the same sign
Return the unique subcollection of collectio... | 8d7957a8dffc18b82e8a45129ba3634c28dd0d52 | 3,650,356 |
def calculate_attitude_angle(eccentricity_ratio):
"""Calculates the attitude angle based on the eccentricity ratio.
Parameters
----------
eccentricity_ratio: float
The ratio between the journal displacement, called just eccentricity, and
the radial clearance.
Returns
-------
... | 24dcb463a0ebdcab8582309bf9ff44fdbfc44686 | 3,650,357 |
import torch
import pickle
def enc_obj2bytes(obj, max_size=4094):
"""
Encode Python objects to PyTorch byte tensors
"""
assert max_size <= MAX_SIZE_LIMIT
byte_tensor = torch.zeros(max_size, dtype=torch.uint8)
obj_enc = pickle.dumps(obj)
obj_size = len(obj_enc)
if obj_size > max_size:
... | bca30d1a88db42f66bdd978386a1c4d24c0c790b | 3,650,358 |
def featCompression (feats, deltas, deltas2):
"""
Returns augmented feature vectors for all cases.
"""
feats_total = np.zeros (78)
for i in range (len (feats)):
row_total = np.array ([])
feat_mean = np.mean (np.array (feats[i]), axis = 0)
delt_mean = np.mean (np.array (deltas... | 033b53fec9cf920daadb3ba5bef2fcce7cc11d21 | 3,650,359 |
def _array_indexing(array, key, key_dtype, axis):
"""Index an array or scipy.sparse consistently across NumPy version."""
if np_version < parse_version('1.12') or issparse(array):
# Remove the check for NumPy when using >= 1.12
# check if we have an boolean array-likes to make the proper indexin... | b8c04647ad79ce8ffd973d2b13fe7231854822de | 3,650,360 |
def get_stock_ledger_entries(previous_sle, operator=None,
order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
"""get stock ledger entries filtered by specific posting datetime conditions"""
conditions = " and timestamp(posting_date, posting_time) {0} time... | 14a3e7a9a0f207260a21ba4166b59d44c8ab15b9 | 3,650,361 |
import torch
def test_binary(test_data, model, criterion, batch_size, device, generate_batch=None):
"""Calculate performance of a Pytorch binary classification model
Parameters
----------
test_data : torch.utils.data.Dataset
Pytorch dataset
model: torch.nn.Module
Pytorch Model
... | 9bc8fefffca3d484abbcac48836fde3ca7b5287a | 3,650,362 |
def linear_imputer(y, missing_values=np.nan, copy=True):
"""
Replace missing values in y with values from a linear interpolation on their position in the array.
Parameters
----------
y: list or `numpy.array`
missing_values: number, string, np.nan or None, default=`np.nan`
The placeholder... | 2557e7647e8d7e0246bb15c57605b75bf3d4131b | 3,650,363 |
def gap2d_cx(cx):
"""Accumulates complexity of gap2d into cx = (h, w, flops, params, acts)."""
cx["h"] = 1
cx["w"] = 1
return cx | 28f6ba5f166f0b21674dfd507871743243fb4737 | 3,650,364 |
import requests
def test_is_not_healthy(requests_mock):
"""
Test is not healthy response
"""
metadata = Gen3Metadata("https://example.com")
def _mock_request(url, **kwargs):
assert url.endswith("/_status")
mocked_response = MagicMock(requests.Response)
mocked_response.sta... | 9b6fdb7b822ef83e0441bdafa1c87ea07ad901ad | 3,650,365 |
def kernelTrans(X, A, kTup):
"""
通过核函数将数据转换更高维的空间
Parameters:
X - 数据矩阵
A - 单个数据的向量
kTup - 包含核函数信息的元组
Returns:
K - 计算的核K
"""
m,n = np.shape(X)
K = np.mat(np.zeros((m,1)))
if kTup[0] == 'lin': K = X * A.T #线性核函数,只进行内积。
elif kTup[0] == 'rbf': #高斯核函数,根据高斯核函数公式进行计算
for j in range(m):
... | da43ab6aeff623b32d3287ad07acdc1ef5ec4bc3 | 3,650,366 |
def getBusEquipmentData(bhnd,paraCode):
"""
Retrieves the handle of all equipment of a given type (paraCode)
that is attached to bus [].
Args :
bhnd : [bus handle]
nParaCode : code data (BR_nHandle,GE_nBusHnd...)
Returns:
[][] = [len(bhnd)] [len(all equ... | 6e0e63846c7b934edbe9de078c7ad8561766e58d | 3,650,367 |
from typing import List
from typing import Counter
import click
def build_and_register(
client: "prefect.Client",
flows: "List[FlowLike]",
project_id: str,
labels: List[str] = None,
force: bool = False,
) -> Counter:
"""Build and register all flows.
Args:
- client (prefect.Client)... | 7e4634578b44b7b5a1743fa0cfab21c6c551930b | 3,650,368 |
from typing import List
import os
def generate_path_to_bulk_roms(
roms: List[models.BulkSystemROMS]) -> List[models.BulkSystemROMS]:
"""Creates the absolute path to where each rom should be downloaded"""
for system in roms:
for section in system.Sections:
if not 'number' in section... | 68c170aeef9af3d357a026229c9c5766260f70de | 3,650,369 |
import sys
import argparse
def parse_args(args=sys.argv[1:]):
""" Get the parsed arguments specified on this script.
"""
parser = argparse.ArgumentParser(description="")
parser.add_argument(
'path_to_xml',
action='store',
type=str,
help='Ful path to tei file.')
pa... | e934cfb5f0315fb0e834bef05fecaa67168485d4 | 3,650,370 |
def creer_element_xml(nom_elem,params):
"""
Créer un élément de la relation qui va donner un des attributs.
Par exemple, pour ajouter le code FANTOIR pour une relation, il faut que le code XML soit <tag k='ref:FR:FANTOIR' v='9300500058T' />"
Pour cela, il faut le nom de l'élément (ici tag) et un diction... | a4cd29b82531c7bc01864ae79de87643afeb8276 | 3,650,371 |
def get_display():
"""Getter function for the display keys
Returns:
list: list of dictionary keys
"""
return data.keys() | dcc8957faf30db15282d2e67025cd6d5fd07e9dd | 3,650,372 |
def calculate_class_probabilities(summaries, row) -> dict():
"""
Calculate the probability of a value using the Gaussian Probability Density Function from inputs:
summaries: prepared summaries of dataset
row: a row in the dataset for predicting its label (a row of X_test)
This function uses th... | ffdff84e27fe5e76d66176d5d1c862f16b1ee494 | 3,650,373 |
import logging
import os
def discard_missing_files(df: pd.DataFrame, path_colname: str) -> pd.DataFrame:
"""Discard rows where the indicated file does not exist or has
filesize 0.
Log a warning with the number of rows discarded, if not zero.
Args:
df
path_colname: Name of `df` column... | 7358192a8400a4cd46522b1b6e11d9ffe03d9db7 | 3,650,374 |
from typing import Sequence
from typing import Any
def find(sequence: Sequence, target_element: Any) -> int:
"""Find the index of the first occurrence of target_element in sequence.
Args:
sequence: A sequence which to search through
target_element: An element to search in the sequence
Re... | 20edfae45baafa218d8d7f37e0409e6f4868b75d | 3,650,375 |
def read_time_data(fname, unit):
"""
Read time data (csv) from file and load into Numpy array
"""
data = np.loadtxt(fname, delimiter=',')
t = data[:,0]
x = data[:,1]*unit
f = interp1d(t, x, kind='linear', bounds_error=False, fill_value=x[0])
return f | 588c3bc472aa05eb0ead983405f22ecdf260687c | 3,650,376 |
import sys
def run(connection, args):
"""Prints it out based on command line configuration.
Exceptions:
- SAPCliError:
- when the given type does not belong to the type white list
"""
types = {'program': sap.adt.Program, 'class': sap.adt.Class, 'package': sap.adt.Package}
... | 579d94aa22f9b1bd62ee757bfb4b328679901a75 | 3,650,377 |
from pathlib import Path
from typing import List
from typing import Dict
import json
def read_nli_data(p: Path) -> List[Dict]:
"""Read dataset which has been converted to nli form"""
with open(p) as f:
data = json.load(f)
return data | 2218d8dc06e3b9adfe89cb780a9ef4e7cb111d14 | 3,650,378 |
def stanley_control(state, cx, cy, cyaw, last_target_idx):
"""
Stanley steering control.
:param state: (State object)
:param cx: ([float])
:param cy: ([float])
:param cyaw: ([float])
:param last_target_idx: (int)
:return: (float, int)
"""
current_target_idx, error_front_axle = c... | bef2d7d075a6ef637d1423d6c85cdde3ac4d9d70 | 3,650,379 |
def get_predictions(my_map, reviews, restaurants):
"""
Get the topic predictions for all restaurants.
Parameters:
my_map - the Map object representation of the current city
reviews - a dictionary of reviews with restaurant ids for keys
restaurants - a list of restaurants of the curr... | ef900b9d3526a12f64951e9d7b6f4eb80db9f6f4 | 3,650,380 |
def decode_token(token, secret_key):
"""
解密websocket token
:param token:
:param secret_key:
:return:
"""
info = jwt.decode(token, secret_key, algorithms=['HS256'])
return info | 5807ce3428435eb0c15dd464164627fb342e46d6 | 3,650,381 |
import requests
def getPatternID(pattern_url):
"""asssumes pattern_url is a string, representing the URL of a ravelry pattern
e.g.https://www.ravelry.com/patterns/library/velvet-cache-cou
returns an int, the pattern ID
"""
permalink = pattern_url[41:]
with requests.Session() as a_session:
... | 0624457bad8753a9d15f8339c381ec233a207098 | 3,650,382 |
def make_multibonacci_modulo(history_length, limit):
"""Creates a function that generates the Multibonacci sequence modulo n."""
def sequence_fn(seq):
return np.sum(seq[-history_length:]) % limit
return sequence_fn | 358876a91fec23853bde843c7222cd837b45ada3 | 3,650,383 |
def _get_key(arguments):
"""
Determine the config key based on the arguments.
:param arguments: A dictionary of arguments already processed through
this file's docstring with docopt
:return: The datastore path for the config key.
"""
# Get the base path.
if arguments.get("felix"):
... | b68dd68a013ed2289ae60ab49a347858ce447964 | 3,650,384 |
def prepare_data_from_stooq(df, to_prediction = False, return_days = 5):
"""
Prepares data for X, y format from pandas dataframe
downloaded from stooq. Y is created as closing price in return_days
- opening price
Keyword arguments:
df -- data frame contaning data from stooq
return_days -- nu... | 4b5bc45529b70ed1e8517a1d91fb5a6c2ff0b504 | 3,650,385 |
def represents_int_above_0(s: str) -> bool:
"""Returns value evaluating if a string is an integer > 0.
Args:
s: A string to check if it wil be a float.
Returns:
True if it converts to float, False otherwise.
"""
try:
val = int(s)
if val > 0:
return True... | e39c4afeff8f29b86ef2a80be0af475223654449 | 3,650,386 |
def resnet18(pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url('https://download.pytor... | 89b71b447890e8986493abc90cca6e2ac2f0eca8 | 3,650,387 |
def sydney():
"""Import most recent Sydney dataset"""
d = {
'zip':'Sydney_geol_100k_shape',
'snap':-1,
}
return(d) | f79a5002ef548769096d3aeb1ad2c7d77ac5ce68 | 3,650,388 |
import json
async def apiAdminRoleNotExists(cls:"PhaazebotWeb", WebRequest:ExtendedRequest, **kwargs) -> Response:
"""
Optional keywords:
------------------
* msg `str` : (Default: None) * [Overwrites default]
* name `str` *
* role_id `str` *
Default message (*gets altered by optional keywords):
------------... | 535bf4740e6d95ef1d82d9fdc97b36577425fed7 | 3,650,389 |
def format_non_date(value):
"""Return non-date value as string."""
return_value = None
if value:
return_value = value
return return_value | 9a7a13d7d28a14f5e92920cfef7146f9259315ec | 3,650,390 |
def get_loss(loss_str):
"""Get loss type from config"""
def _get_one_loss(cur_loss_str):
if hasattr(keras_losses, cur_loss_str):
loss_cls = getattr(keras_losses, cur_loss_str)
elif hasattr(custom_losses, cur_loss_str):
loss_cls = getattr(custom_losses, cur_loss_str)
... | 4c5714b7e8ca0becf43922a9624d9a4dccc4ac28 | 3,650,391 |
from functools import cmp_to_key
def _hashable_policy(policy, policy_list):
"""
Takes a policy and returns a list, the contents of which are all hashable and sorted.
Example input policy:
{'Version': '2012-10-17',
'Statement': [{'Action': 's3:PutObjectAcl',
... | beb5b527f38d7d1a9cecf81918a3291c0c9960ad | 3,650,392 |
def LF_CD_NO_VERB(c):
"""
This label function is designed to fire if a given
sentence doesn't contain a verb. Helps cut out some of the titles
hidden in Pubtator abstracts
"""
if len([x for x in nltk.pos_tag(word_tokenize(c.get_parent().text)) if "VB" in x[1]]) == 0:
if "correlates with... | aa36b8a4cd00194fd1d786a7d3619ea46da0e1ab | 3,650,393 |
from typing import Tuple
def has_file_allowed_extension(filename: PATH_TYPE, extensions: Tuple[str, ...]) -> bool:
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (tuple of strings): extensions to consider (lowercase)
Returns:
bool:... | 2f0d5698ecdb10533b303a637fdc03747ef8060c | 3,650,394 |
def get_account_html(netid, timestamp=None):
"""
The Libraries object has a method for getting information
about a user's library account
"""
return _get_resource(netid, timestamp=timestamp, style='html') | 7c917f6778e42a1166d4a33819c2e51378933226 | 3,650,395 |
import functools
import math
def gcd_multiple(*args) -> int:
"""Return greatest common divisor of integers in args"""
return functools.reduce(math.gcd, args) | c686b9495cd45ff047f091e31a79bedcd61f8842 | 3,650,396 |
from typing import Counter
def chars_to_family(chars):
"""Takes a list of characters and constructs a family from them. So, A1B2
would be created from ['B', 'A', 'B'] for example."""
counter = Counter(chars)
return "".join(sorted([char + str(n) for char, n in counter.items()])) | e78de779599f332045a98edde2aa0a0edc5a653b | 3,650,397 |
import configparser
def get_config_properties(config_file="config.properties", sections_to_fetch = None):
"""
Returns the list of properties as a dict of key/value pairs in the file config.properties.
:param config_file: filename (string).
:param section: name of section to fetch properties from (if s... | 627d21327560595bb4c2905c98604926f03ca655 | 3,650,398 |
import base64
import secrets
import time
def process_speke():
"""Processes an incoming request from MediaLive, which is using SPEKE
A key is created and stored in DynamoDB."""
input_request = request.get_data()
# Parse request
tree = ET.fromstring(input_request)
content_id = tree.get("id")
... | 3caa1c0390ea699feab2f138942b6773933fbada | 3,650,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.