content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def load_experiment(experiment, dbname='traces.db', db='sqlite'): """Load specific experiment from a database file. :Arguments: experiment : dict (see run_experiment for the contents) dbname : str (default='traces.db') Name of the database file. db : str (default='sqlite') ...
774db4f22371a321cd4076ff66880e9bf247c58d
70,893
async def check_twitch_already_posted(twitch_username, channel_id) -> bool: """ Check if a twitch channel being live was already posted to a text cahnnel. :param twitch_username: Twitch username :param channel_id: Text Channel ID :return: True if the live announcement was already posted. """ ...
f3651f3700218453cfdc5438ddc4a248c59bc962
70,894
def component_idx(tile_rank, idx): """ Inputs: _______ tile_rank : int Outputs: _______ range : np.array (L,) Vector with """ init = tile_rank[:idx].sum() length = tile_rank[idx] return np.arange(init, init + length, dtype='int')
cf66502f2c43fe04f8bc962587a99d26638a80b7
70,896
def team_repo_explicit_perm( conf: config.Config, policy: Policy, team_name: str, repo: schema.Repo ) -> Perm | None: """Return the direct permissions of a team to a repository. Returns the permissions of a team as explicitly defined in the policy, without taking into account ancestors permissions. ...
2987710ced3fae866902d5a00f8d1f6c4ea81ac8
70,897
def mixer_l16_224(pretrained=False, **kwargs): """ Mixer-L/16 224x224. ImageNet-1k pretrained weights. Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601 """ model_args = dict(patch_size=16, num_blocks=24, embed_dim=1024, **kwargs) model = _create_mixer('mixer...
425bf1bb02db53c2601e33067894bf50a5cb28c0
70,898
def correct_wrong_entries(data: pd.DataFrame, corrections: dict) -> pd.DataFrame: """Correct erroneous entries in data. Parameters ---------- data: pd.DataFrame corrections: dict A dictionary whose keys are the columns to modify, and whose values are dictionaries characterizing the changes to be made. Re...
dc178b64a7d69c9226743dce73750a552021041c
70,899
def openl1(*args, **kwargs): """ Open(*args, **kwargs) Returns a file object opened with UTF-8 encoding. """ kwargs["encoding"] = "latin1" return _open(*args, **kwargs)
cdb9cf8b1edf3dee8a50ba4d2c18a0c2a0ec91c2
70,900
import warnings import tqdm def read_edf(edf_file, ch_nrs=None, ch_names=None, digital=False, verbose=False): """ Convenience function for reading EDF+/BDF data with pyedflib. Will load the edf and return the signals, the headers of the signals and the header of the EDF. If all signals have the same ...
e236c051babe8f291fe91b4b339e11f79801324b
70,902
def check_num_samples(beta, delta, std_dev, alpha=0.05, n=4, num_iter=1000, tol=1e-6, num_cycles=10000, m=5): """ This function is an implementation of the "Calculation of Number of Samples Required to Detect a Trend" section written by Sat Kumar Tomer (satkumartomer@gmail.com) whi...
9445a6fbcaf38a2d2119706e98e1b3bc6f2b5dd6
70,903
def calc_OR_from_list(dict_node_age, infected_nodelist): """ Calculate OR from list of infected nodes. Return OR as 1.0 if numerator or denominator are 0. """ main(calc_OR_from_list) infected_child = sum([1 for node in infected_nodelist if dict_node_age[node] == '3']) infected_adult = sum([1 for node in infected...
59c580c439236b042dbf0127ef70ecb8b48f2e03
70,904
def __validate_username(username: str, error_msg: str) -> str: """Validate the tweet's name. Parameters ---------- username : str Tweet's username. error_msg : str Error message to display for an invalid username. Returns ------- str Validated username. Rai...
b829251070b8ba657a60597547601376fa051607
70,905
def frequency(per_core=True, scale="mhz", precision=3): """Returns current cpu frequency :Params: :per_core (bool): When per_core is True it returns a list with values per logical cpu, if it's set to False returns a float with arithmetic mean of cores ...
6077478802e6257eb62fff1e95b04254db1458f8
70,906
from typing import List from typing import Tuple from textwrap import dedent def get_rt_object_to_complete_texts() -> List[Tuple[str, str]]: """Returns a list of tuples of riptable code object text with associated completion text.""" return [ ( dedent( '''Dataset({_k: list(...
007d2291fd922aab5627783897a56cd5fd715f98
70,907
import token import requests def create_mirror(gitlab_repo, github_token, github_user): """Creates a push mirror of GitLab repository. For more details see: https://docs.gitlab.com/ee/user/project/repository/repository_mirroring.html#pushing-to-a-remote-repository-core Args: - gitlab_repo: Git...
2a5d7e01ca04a6dcb09d42b5fc85092c3476af0d
70,908
def STYPP(data): """ Swing Typical Price Previous Typical Price :param pd.DataFrame data: pandas DataFrame with open, high, low, close data :return pd.Series: with indicator data calculation results """ stypp_list = [] typical_price = TYPPRICE(data) i = 0 while i < len(data['cl...
36bacb8f77c8645483da0cf3dddb10dc23dd6eef
70,910
def log_encoding_Log2(lin, middle_grey=0.18, min_exposure=0.18 * 2 ** -6.5, max_exposure=0.18 * 2 ** 6.5): """ Defines the common *Log2* encoding function. Parameters ---------- lin : numeric or array_like Linear data to un...
24549942553a792073cf059a9e1057df4dd4e10d
70,911
import uuid import json from datetime import datetime def add(queue_name, payload=None, content_type=None, source=None, task_id=None): """Adds a work item to a queue. Args: queue_name: Name of the queue to add the work item to. payload: Optional. Payload that describes the work to do ...
9dbdc0fc384732b47f857fa65edc2302ed6f110b
70,912
def index(): """ Test the compatibility This is just a test for flasgger 0.5.14 compat --- parameters: - in: body name: body schema: id: alert properties: message: type: string produces: application/json responses: ...
9757e42a61d11c4b5cea2ea4adb13c93b57fbbcc
70,913
def is_permutation(a, b): """ Test if the digits of a are a permutation of the digits of b """ digits_a = sorted(get_digits(a)) digits_b = sorted(get_digits(b)) if len(digits_a) != len(digits_b): return False for da, db in zip(digits_a, digits_b): if da != db: re...
4216e55cfad2a80ffb68f9420e02eec255d6af5a
70,914
def get_tcga_id( string_to_check , get_full_tcga_id): """ will either return the TCGA-12-3456 or the entire TCGA sample ID which is much much longer... TCGA-12-3456-12-23-232-32""" if(get_full_tcga_id): m = parse_full_TCGA_ID.match(string_to_check) if m: TCGA_FULL_ID = m.group(1)+'-'+m.group(2)+m.grou...
14c16a9899c9bd31a7b883391c13850ccf0ef752
70,915
import json def make_lld(msa, component, sessionkey, pretty=False): """ Form LLD JSON for Zabbix server. :param msa: MSA DNS name and IP address. :type msa: tuple :param sessionkey: Session key. :type sessionkey: str :param pretty: Print output in pretty format :type pretty: int :...
fd458ef492e9ee5b5d5496325a0c7efadd717d29
70,916
def stats_for_chapter_levels(chapter_id): """ Return a list of level names in a chapter and a list of students and their progress for all levels in requirement chapter. The data is meant to be displayed in a table. Since there's a unique entry for every student->level match we first need to create a cle...
6c360640921eaa4fb626362db5d3d3ac0aaa43eb
70,917
import random def generate_mac_address(): """ randomly generate a mac address, the first three bytes identify a manufacturer""" prefix = manufacturer_mac_address[random.randint(0, len(manufacturer_mac_address)-1)] mac = prefix+\ [random.randint(0x00, 0xff), random.randint(0x00, 0xff), random...
5369c6c3a0f9ddbc19c109ce50ab870ff5aa3a3a
70,918
def drop_info(df: pd.DataFrame) -> pd.DataFrame: """Takes a dataframe and drop rows whitout an splitted `info` length diferrent than four. Parameters ---------- df : The dataframe to search. Returns ------- The dataframe processed. """ before = df.shape print(f'Shap...
b3701830b6310ece2ace3138e531be044bc19d4b
70,919
def read_CSET_data(fname, var_list=None, start_date=None, end_date=None): """read in CSET UHSAS .nc file and returns requested variables """ with nc4.Dataset(fname, 'r') as nc: timevar = nc.variables['Time'] date = nc4.num2date(timevar[:], units=timevar.units) if ...
940d7740e8105b11c5d3ce94cc2b42c821779ea3
70,920
def expon_round(a: float, prec: int = None) -> float: """Rounds the left part of a two-part float.""" if type(a) != float: return a if "e" not in str(a): return round(a, prec) sig, exp = str(a).split("e") return float("%se%s" % (round(float(sig), prec), exp))
8ccafd58dd674c2351e02f50dc5bd65d88b4fd63
70,921
def genelist_mask(candidates, genelist, whitelist=True, split_on_dot=True): """Get a mask for genes on or off a list Parameters ---------- candidates : pd.Series Candidate genes (from matrix) genelist : pd.Series List of genes to filter against whitelist : bool, default True ...
53e1f80de097311faddd4bfbff636729b076c984
70,922
def add_polynomials(indices_list, coeffs_list): """ Add many polynomials together. Example: p1 = x1**2+x2+x3, p2 = x2**2+2*x3 p3 = p1+p2 return the degrees of each term in the the polynomial p3 = x1**2+x2+3*x3+x2**2 [2, 1, 1, 2] and the coefficients of eac...
53227650c983c846fb3b53751fe301480086f27d
70,923
from datetime import datetime def writenow(): """Return utcnow() as ISO foramat string""" return datetime.isoformat(datetime.utcnow())
19a0e4653bfa7cfab2528e81317fd2399ca630d5
70,925
def plate_msup(): """Resolve the path of the "msup/plate1.rst" result file. Originally: UnitTestDataFiles/DataProcessing/expansion/msup/Transient/plate1/file.rst """ return examples.msup_transient
3052ff7b5a2399cf80da91266daeae1bede0fb49
70,926
def _drop_noisy(points: DataFrame) -> DataFrame: """ Filter the outlier points in the data by delete the points lower than a certain area. """ df_copy = points.copy() df_describe = df_copy.describe() for column in points.columns: mean = df_describe.loc["mean", column] std = df_de...
9da845e0b03622486d5cb1cfd2272c874dbbc58f
70,927
from django.contrib.gis.utils import GeoIP def location(request): """ Location selection of the user profile """ profile, created = Profile.objects.get_or_create(user=request.user) geoip = hasattr(settings, "GEOIP_PATH") if geoip and request.method == "GET" and request.GET.get('ip') == "1": ...
85a9138b6f9fc3f13d1bf3f5789865fac0e5d82b
70,928
def parse_releases(list): """ Parse releases from a MangaUpdate's search results page. Parameters ---------- list : BeautifulSoup BeautifulSoup object of the releases section of the search page. Returns ------- releases : list of dicts List of recent releases found by t...
e7e93130732998b919bbd2ac69b7fc36c20dd62d
70,929
def remMap(matrizX, matrizY, l_1, l_2, tmax): """ Esta funcion implementa el algoritmo remap considerando lambda2 diferente de cero. Args: :param matrizX: matriz de datos de tamano n x p. :param matrizY: matriz de variables respuesta de tamano n x q. :param l_1: parametro de regularizacion lamb...
cd5d3b5928db66f7cf6e7e9a5ffdaf6c9fd88e0f
70,931
def cal_fuquan_price(input_stock_data, fuquan_type='后复权'): """ 计算复权价 :param input_stock_data: :param fuquan_type:复权类型, 可以是'后复权'或者'前复权' :return: """ # 创建空的df df = pd.DataFrame() # 计算复权收盘价 num = {'后复权': 0, '前复权': -1} price1 = input_stock_data['收盘价'].iloc[num[fuquan_type]] ...
bcfc5a7f506eebcb7d793b95c9387f6cda4e41e2
70,932
def read_data_with_ref(source_path, target_path, ref_path): """Read sentences and parallel sentence references.""" with open(source_path, "r", encoding="utf-8") as source_file,\ open(target_path, "r", encoding="utf-8") as target_file: source_lines = [l for l in source_file] targ...
1ce3d768ddb5d4de0f72cbe0633dfafe20bdc2c0
70,933
import http def update_draft_registration(auth, node, draft, *args, **kwargs): """Update an existing draft registration :return: serialized draft registration :rtype: dict :raises: HTTPError """ check_draft_state(draft) data = request.get_json() schema_data = data.get('schema_data', ...
d614214ca420ae97a7290e57f888e1d96bd3b631
70,934
def user_repository_spy(): """Fixture para montar o objeto UserRepository""" return UserRepositorySpy()
b184a2485a46a6e7615b4c931b8279f6f1f5de96
70,935
def to_rates(trace, kmin, kmax): """covert a trace of normalized values into kinetic rates in log space which are wihtin kmin and kmax""" lkmin = np.log10(kmin) lkmax = np.log10(kmax) x = (lkmax - lkmin) / 100 log_rates = trace*x + lkmin rates = 10**log_rates return rates
a4d44fef877ce95cd254eb13af4d4bbc09a1ffd2
70,936
import requests def get_req(url, referer, arg_proxy_local, proxies={}): """Get binary data from URL""" print('url= '+ url) #data = '' #or chunk in requests.get(url, headers={'User-agent': 'Mozilla/5.0'}, stream=True): # data += chunk parsed_uri=urlparse(url) domain = '{uri.netloc}'.form...
5883ec11901ccdcd3c6f795349267f6b284c838a
70,937
def dummy_rng_source(seed, num_elements): """Dummy TensorFlow random number generator. We need a custom random source, which would be always deterministic given a random seed. That is not currently available available in TensorFlow. This simple function serves an illustrative purpose. It is *not* a useful rand...
45bec9a89d4b0e66f2fff3ef011c13bf0855523d
70,938
def softmax(x): """ Softmax function with input vector x """ exp_x = npexp(x) exp_sum = sum(exp_x) smax = exp_x / exp_sum return smax
4c5d25f43cddbaf18c36ef0f04392f9a35708abb
70,939
def _linkify(value): """create link format""" out = [] for link in value: out.append(','.join(list(link))) return '^'.join(out)
1fa2020148ef1fd7ba7f10eecb54836517ff0abd
70,942
import json def objects_processing(target: str) -> Response: """ Apply object detection or segmentation on on image Parameters ---------- target: str 'segmentation' for semantic segmentation. Return response with RLE masks. 'detection' for object detection. Return respo...
05ae8cc42bd4187a08a3833a7c7e7b81827da270
70,943
def date_to_month_st(date): """Returns a string representing the month with MONTH_FORMAT.""" return date.strftime(MONTH_FORMAT)
c132475e895f826493ff5c1d139a237add82b934
70,944
def butter_lowpass(cutoff, fs, order=5): """ Design lowpass filter. Args: - cutoff (float) : the cutoff frequency of the filter. - fs (float) : the sampling rate. - order (int) : order of the filter, by default defined to 5. """ # calculate the Nyquist frequency n...
6befd134b069154f6fd40c840dbb4fee032e2103
70,945
def shape9(tik_instance, input_x_shape, input_x, res): """shape9""" total_elements9 = 1 for val in input_x_shape: total_elements9 *= val blocks = 32 each_block_element = total_elements9 // blocks with tik_instance.for_range(0, blocks, block_num=blocks) as block_index: input_x_ub ...
ae18605bd1309f30d4f8c506bbe3c6fa5cef8a1c
70,946
def remove_arena_env_prefix(env): """Remove ARENA_ENV_PREFIX from a env (possibly a grid_search). """ env = dcopy(env) if is_grid_search(env): if is_all_arena_env(env): for i in range(len(env["grid_search"])): env["grid_search"][i] = remove_arena_env_prefix( ...
63c3f23af41583e2c941f154a9347b204a4ed400
70,947
from scipy.ndimage import convolve1d def move_nansum_filter(arr, window, axis=-1): """ Moving sum (ignoring NaNs) along specified axis using the filter method. Parameters ---------- arr : array_like Input array. window : int The number of elements in the moving window. axi...
e53a0b48326a34f2faf9af000ea5fbff027c7ded
70,949
def dict_raise_on_duplicates(ordered_pairs): """Reject duplicate keys.""" d = {} for k, v in ordered_pairs: if k in d: # raise ValueError("duplicate key: %r" % (k,)) pass else: d[k] = v return d
b1b539b137f70291332f949339501cc5b8e35397
70,950
import torch def get_packed_sequence_info(packed): """Get `batch_sizes` and `sorted_indices` of `PackedSequence`. Args: packed (object): Packed sequences. If it contains multiple `PackedSequence`s, then only one of them are sampled assuming that all of them have same `batch_si...
f3540bfe63d5ef72ecb1df20e09dd249310508b7
70,951
import textwrap def multisample_vcf(): """Return string with multi-sample VCF""" return textwrap.dedent( """ ##fileformat=VCFv4.3 ##contig=<ID=20,length=62435964,assembly=B36,md5=f126cdf8a6e0c7f379d618ff66beb2da,species="Homo sapiens",taxonomy=x> ##FORMAT=<ID=GT,Number=1,Type=S...
f7190d79580cba75a906aa06d29850bf32acf8b2
70,952
def ouverture_image(largeur, hauteur): """ génère la balise ouvrante pour décrire une image SVG des dimensions indiquées. Les paramètres sont des entiers. Remarque : l’origine est en haut à gauche et l’axe des Y est orienté vers le bas. """ balise = "<svg xmlns='http://www.w3.org/2000/svg' v...
da53a8d8e45df8d54bb63dcf8f88b2465af486aa
70,954
def get_pp_id(pp_id: PowerPlantIDT) -> PowerPlantID: """ Unify format of provided power-plant identifier. """ if isinstance(pp_id, PowerPlantID): return pp_id elif isinstance(pp_id, tuple) or isinstance(pp_id, list): return PowerPlantID( pp_id=int(pp_id[0]), inv_id=-1...
56183f811e21539ee3ef3682e11149809725c0c8
70,955
def productversion_details(request, productversion_id): """Get details snippet for a productversion.""" productversion = get_object_or_404( model.ProductVersion, pk=productversion_id) return TemplateResponse( request, "manage/productversion/list/_productversion_details.html", ...
cd196e9bee29d30088c6569c08d3cec5cb15f9a2
70,957
import numpy def gen_doc_embedding(model, text): """ :param model: :param text: :return: 向量 [float] 注意它不能保证是float32 因为float32在python中是不存在的 当前实际值是 numpy.array(dtype=float32) """ words = [x for x in jieba.lcut(text) if x not in stopwords] # print(words) # vec = model.infer_vector...
80777131a367b4f3bda3d9a7c5963776c80fc40a
70,958
def not_found_error_handler(e: Exception) -> Response: """ Error handling function for HTTP 404 (NOT FOUND); raised when a nonexistent resource is requested :param e: exception instance :return: JSON response object """ # noinspection PyUnresolvedReferences return json_response( ...
1b1c7559d9a4631c1fc70e84a4e465075243d022
70,959
import math def get_box_transformation_matrix(box): """Create a transformation matrix for a given label box pose.""" tx,ty,tz = box.center_x,box.center_y,box.center_z c = math.cos(box.heading) s = math.sin(box.heading) sl, sh, sw = box.length, box.height, box.width return np.array([ ...
f7a175180c7baa8918dd4d66e1fa6035fe8c5f1d
70,960
def create_model( input_shape=(224, 224, 3), conv_list=[(2, 64), (2, 128), (3, 256), (3, 512), (3, 512)], dense_list=[4096, 4096, 1000], kernel_size=3, strides=1, pool_size=2, dropout_rate=0.1, output_activation='sigmoid', layer_activation='relu'):...
47841d07f7257726639b50ac14cca865938b46df
70,961
def _forward_one_ova(tr_class_idx, multi_ova, test_x, verbose): """Perform forward on an OVA classifier. Parameters ---------- tr_class_idx : int Index of the OVA classifier. multi_ova : CClassifierMulticlassOVA Instance of the multiclass OVA classifier. test_x : CArray ...
12b9fc29cbfa531465ad9c4e88d3b7c3bd2d2dad
70,962
def GetMappingByKeyName(key_name): """Returns a str used to uniquely identify a mapping.""" return RunSiteMap.get_by_key_name(key_name)
f3106def7ef6830ce5adad7ea6853c56965e36e4
70,963
def bot_has_role(item: int) -> AC: """Similar to :func:`.has_role` except checks if the bot itself has the role. This check raises one of two special exceptions, :exc:`.ApplicationBotMissingRole` if the bot is missing the role, or :exc:`.ApplicationNoPrivateMessage` if it is used in a private messa...
b75c96f8b119610abf9d6992e2bbd46a32e4d983
70,964
def rotate_vector_with_rpy(orientation_rpy, vec): """Rotate a vector with a given rpy orientation (roll, pitch, yaw)""" quat = convert_rpy_to_quat(orientation_rpy) return rotate_vector_with_quaternion(quat, vec)
af1b726dec5571e0a914f01d5ea79630dfe9a3c7
70,965
import torch def signed_scaled_shift(x, x_ref, dev='cpu', topology='torus', iters=1000, lr=1e-2, learn_scale=True): """ Shift trajectory, with scaling, reflection and translation. Shift trajectories to be as close as possible to each other, including switches in sign. :param np.array th...
e423828ef900e0ba9cb1616b69c4e72f17876abb
70,966
def theoretical_arrhenius( data_arrhenius, loaded_files, column_t_name, column_r_name, theoretical_p_list, ): """Function that calculates r^2, T0, R0 parameters for theoretical p values from user's input. Args: data_arrhenius (list): list of DataFrames with calculated data for each ...
191843b1c083966200a2469e00442ccbc1dcc2be
70,967
def LHS(n,loc,upc,dist): """ Latin hypercube sampling. Parameters: n: integer; size of desired sampling loc: scalar; lower bound of desired distribution upc: scalar; upper bound of desired distribution dist: string; either 'uniform' or 'normal' Returns: lhs:...
b7d65c64573ea4825850e4c306ec50a11c1bf885
70,968
def list_size_reducer(reduction_factor, your_list): """_summary_ Parameters: reduction_factor (int): _description_ your_list (list): _description_ Returns: reduced_list (_type_): _description_ """ # input type checking assert type(reduction_factor) == int, 'reduction_fact...
0ed7dbff4a0b27146ffa1f44ce9e517bc4c632b0
70,969
from typing import Union def create_doc_from_template( template_url: str, service_account_key: Union[str, dict], copy_title: str = None, **template_vars, ) -> str: """Create a doc and render it from the template Google document.""" # Step 1: Define the transaction requests = [] for key...
297b57770812b524cc754cb2d091a38034c667fd
70,970
def optimize_helix_simple(n_particle_bb, sigma, epsilon, sidechain=True, DE_popsize=50, pdbfile='LJ_helix.pdb', plotfile='LJ_helix.pdf'): """ Optimize backbone particle positions along a helix and helical radius, vertical rise, with equal spacing of particles. :param n_particle_bb: Number of ba...
d1886bff0b621c71a48569de91986486e1ecda07
70,971
from terracotta.expressions import evaluate_expression from typing import Sequence from typing import Mapping from typing import Tuple from typing import BinaryIO def compute(expression: str, some_keys: Sequence[str], operand_keys: Mapping[str, str], stretch_range: Tuple[Number, Nu...
0a64618cea50fab5e69c288c9453df969275bbbd
70,972
def bad_neighbours(values): """ Maximize the values choosen from a circular list such that no two values are neighbours. See: http://community.topcoder.com/stat?c=problem_statement&pm=2402&rd=5009 for problem statement and test cases. Params: values: list, of integers Returns: ...
2410ca896bb36198e3df4a68de88d932a05b0c61
70,973
import re def convert_parameters(child, text=False, tail=False, **kwargs): """ Get child text or tail :param child: :param text: :param tail: :return: """ p = re.compile(r'\S') # Remove empty info child_text = child.text if child.text else '' child_tail = child.tail if chil...
de9ba60931516c7a51c5dd7411c914a110295fb2
70,974
def VectorObserver(vector, ofdate): """Calculates the geographic location corresponding to an equatorial vector. This is the inverse function of #ObserverVector. Given a geocentric equatorial vector, it returns the geographic latitude, longitude, and elevation for that vector. Parameters -----...
aaf663ec398014d43e1df14707c2b7931fbc925f
70,975
def QDA_g(x, means, covariances): """ Determines the label of observation x using the K estimations of the mean and covariance matrix of each cluster using Quadratic Discriminant Analysis decision rule. Parameters ---------- x : m-dimensional vector ...
18346f75dbe4979269801b909ca767a2ed130ccc
70,976
def window(timeColumn, windowDuration, slideDuration=None, startTime=None): """Bucketize rows into one or more time windows given a timestamp specifying column. Window starts are inclusive but the window ends are exclusive, e.g. 12:05 will be in the window [12:05,12:10) but not in [12:00,12:05). Windows can...
e18b030d6938f1e4bceef914e7bc4a4dfc2782f5
70,978
import requests import json def request_data(url: str, where_clause: str = "1=1") -> dict: """ Requests data from the ArcGIS api and retuens the response in JSON format. """ params = { "referer": "https://www.mywebapp.com", "user-agent": "python-requests/2.9.1", "where": where...
61ce82eb38f48805d62cdf8c9927f2607411281e
70,979
def get_node_array(node, repo_path, name): """Retrieve a numpy array from a node.""" return utils.load_numpy_array_from_repository(repo_path, node.uuid, name)
fb526b429f6b7a09f7c9a7d3baab4377fcd2ea9d
70,980
import struct def _apple_bundle_version_impl(ctx): """Implementation of the apple_bundle_version rule.""" build_label_pattern = ctx.attr.build_label_pattern capture_groups = ctx.attr.capture_groups if (build_label_pattern and not capture_groups or not build_label_pattern and capture_groups): ...
763f57a850618de70d4c1a63f0f7f6c49f5afbcc
70,981
def Sqrt(x): """Square root function.""" return x ** 0.5
e726dfad946077826bcc19f44cd6a682c3b6410c
70,982
def create_json_dataset(dic, sample_rate, window_size): """Creates JSON file for Voice Activity Detection. Data are chunked in shorter clips of duration window_size""" sessions_iteration = dic.keys() example_counter = 1 json_dataset = {} for sessions in sessions_iteration: speech_timings...
23cd1afd1f1fa009567127eccc0e7e3253bb15a0
70,983
def get_xml_root(): """ Gets the root of the arxiv xml tree and returns it.""" xml_filepath = '/home/ashwath/Files/arxiv-cs-all-until201712031.xml' # xml_filepath = 'D:\\Coursework\\HiWi\\arxiv-cs-all-until201712031.xml' doc = etree.parse(xml_filepath) root = doc.getroot() return root
146e5436f494b24b5933fb9bf7bb3a96dda6ff5d
70,984
import math def _slerp(leds_xyz, n_led): """Interpolate positions from the xyz positon of the first and last LED leds_xyz: np.array of shape(2,3) n_led : total n LED on the stripe""" p0, p1 = leds_xyz[0], leds_xyz[1] omega = math.acos(np.dot(p0/np.linalg.norm(p0), p1/np.linalg.norm(p1))) s...
b05bbfa7caa642c7d741d166cc4fa7ec21f64f50
70,985
def hello(friend_name): """Says 'Hello!' to a friend.""" return "Hello, {}!".format(friend_name.title())
706c5a2d3f7ebdf9c7b56e49bb0541655c191505
70,986
import random import string import pathlib import requests import shutil def proxy(): """Proxies requests to the given OpenFaaS url """ error = False url = request.cookies.get("openfaasurl") if url is not None: url = unquote(url) url = urljoin(url, "function/") url = urlj...
85f29542f3cb0f6e508222bd37a55443f7f2a672
70,989
def _get_story_duration(story_tag): """ Return the sum of the text time and media time, or return None if not found """ try: metadata = story_tag.find('mosExternalMetadata') payload = metadata.find('mosPayload') except AttributeError: return 0 try: return float(p...
df7f90eb6a02c0e8f9e6deaa45770fdc03c79a50
70,990
from sklearn.preprocessing import LabelEncoder def plot_decision_function(fitted_classifier, range_features, ax=None): """Plot the boundary of the decision function of a classifier.""" feature_names = list(range_features.keys()) # create a grid to evaluate all possible samples plot_step = 0.02 xx...
cbd792fe0af8f8032c5bb3ea2753c73be61414d7
70,991
import numpy def array2image(arr, mode): """NumPy array to PIL Image""" arr = arr.swapaxes(1,2).swapaxes(0,2) arr[arr < 0] = 0 arr[arr > 255] = 255 arr = numpy.fix(arr).astype(numpy.uint8) return Image.fromstring(mode, arr.shape[1::-1], arr.tostring())
9231df1d2d7310830545631e0fb953f8a66cec89
70,992
def default_file_reader(filename, varname, land): """ Read data from a netCDF file and return it in an array with shape (NTIME,NLAND). Parameters ---------- filename : str Input netCDF filename. varname : str Name of input variable in the netCDF file: e.g., "tas", "pr", etc...
2f1583d8bcd41c9c2072a5869dbc13e5dd94a5e5
70,993
import requests from typing import Optional from typing import Tuple from typing import Sequence from typing import Mapping from typing import Any import base64 import binascii def list_results( http_session: requests.AuthorizedSession, operation_id: str, page_size: int = 0, page_token: Optional[str] ...
c80d0ad57e6f32550be33995a694736f914531c1
70,994
def spectralGraphPartition23(A, Bin='bNG', L=1.0, finetune=False, n_cutoff=4): """ """ # Prep work if Bin == 'bNG': B = lambda v, A, indx: bNG(v, A, indx, L) elif Bin == 'bRandUni': B = lambda v, A, indx: bRandUni(v, A, indx, L) else: err_msg = 'Invalid specification for...
5d0a33081686c07c04fd1b7203606a05345b6ac7
70,995
import signal def prominant_curvature_features(local_curvatures, show_plot=False,min_prominance=0.1,min_width=5,dist_bwt_peaks=10): """Obtain prominant (peaks) local curvature This function finds peaks for a given list of local curvatures using scipy's signal module. Args: local_curvatures:(Arr...
964945c2f19b0349f08e0a292cd8a3d4fb1db715
70,996
def cached(s): """ **Deprecated**, use :func:`cachedio` instead, where ``backend="memory"``. Usage as follows: .. code-block:: python @cached("20170101") def get_daily(*args, **kws): return xa.get_daily(*args, **kws) Automatically cache the result in memory and avoid refe...
d3dbf99701392f98bb570fc053ecf11bd85dc33b
70,997
def query_renumber(args): """ Gets renumber information from user """ if args.station_name is None: args.station_name = raw_input('Station name for which to renumber: ') args.date = cm_utils._query_default('date', args) return args
b939c5dc3b93e007c5d0f9c1804fe10e38b81ccf
70,998
from re import T def xentropy_loss(x, y, epsilon=1e-6): """ cross-entropy loss """ fx = T.softmax(x) y = T.one_hot(y, np.max(y)+1) xentropy = - np.sum(y * np.log(fx+epsilon))/len(y) return xentropy
4a27e1a4d3ca6387f5ca85ccf80a2be1e42b1bec
70,999
def NamesOfDeclaredExtraKeyFlags(): """Returns the list of names of additional key flags for this module. These are the flags that became key for this module only as a result of a call to DeclareExtraKeyFlags() above. I.e., the flags declared by module_bar, that were not already declared as key for this mod...
d8debc09e829720f64bd6eff3a314689a329f930
71,000
def generate_text_input_data(input_shape): """Generates training data and target labels. # Arguments input_shape: input shape in the following format(num_samples, x, y) # Returns numpy arrays: 'x_train, y_train' where the value of the arrays are booleans. """ x_train = np.random.choice...
3cbc6165b19013e48133f613cce0d95de0002d2e
71,001
def find_paths(prior_path, selected_small_cave): """Finds all paths starting with the prior path and ending on end.""" # This will return some duplicates known_paths = [] for next_node in cave_network[prior_path[-1]]: if next_node == "end": known_paths += [prior_path + [next_node]] ...
8c3983dbaee3b17301e16cd5657b886f1a6dbee6
71,002
import json import requests def get_resource_metadata(request): """ Gets resource metadata and aggregations. This function retrieves a given resource's metadata to display in the resource info tab. It will also get a list of available """ return_obj = {} # -------------------- # # ...
647e575ad05e94b306f5e784dd8050867cd9ecfa
71,003
def has_valid_args(args): """Determine whether the arguments passed are valid or not. Keyword arguments: args -- arguments passed (program name skipped) """ return len(args) == 4 and not has_wrongly_positioned_args(args)
969c62ee734bf864db069109d663eacd861d3e80
71,004
import copy import test def setup_rt(hostname, nodename, virt_resources=_VIRT_DRIVER_AVAIL_RESOURCES, estimate_overhead=overhead_zero): """Sets up the resource tracker instance with mock fixtures. :param virt_resources: Optional override of the resource representation ...
ba8c11bd4ba75ba1d7dec1f1ef062d06eead510b
71,005