content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def netInputIndex(s, current, x, y): """ Helper function for gameToNetInput. Get the index of the list to update :param s: The piece at the position being looked at :param current: The currently selected piece, None if no piece is selected :param x: The x coordinate of the position being looked at ...
b87688d50ac96d9bf243c3c452b1f3378b08d01d
649,354
def get_missing_face_hierarchical_keywords(iptc_data, face_list=None): """Checks if keywords need to be added for faces. Returns the keywords that need to be added.""" missing_keywords = [] if face_list == None: face_list = iptc_data.region_names for name in face_list: # Look for ...
db7698eb9c1a72ef9a7714a5e3e3e03c315c8277
649,355
import os def get_file_size(filename): """Returns the file size from filename. """ return os.stat(filename).st_size
75e7dd80efa0e853a8a8cf69a61051f601e0553e
649,356
def find_period(traj): """Find approximate period of oscillation using the last two peak event times in voltage""" try: evs = traj.getEventTimes('peak_ev') return evs[-1] - evs[-2] except: return 0
f66c210d2d3d60c62c027a3329e7aa3bd0f7cf93
649,358
import re def vmatch(regex, instr, wstrip=False): """ safely match and extract ffmpeg version infos """ rrx = re.match(regex, instr, re.I |re.S |re.M) if rrx: if wstrip: return rrx.groups()[0].replace(' ', '') else: return rrx.groups()[0] else: r...
98ce55e027c6719e008ed8a0b326ef575f12fca0
649,359
from importlib import import_module def load(name): """ ロケールモジュールをロード @param name: モジュール名 @return: モジュール """ module_path = __name__.split(".") module_path.append(name) return import_module(".".join(module_path))
e40f45169abc506acb6f8dc48db545f111d538f0
649,361
def dB2gain(dB): """Convert dB to multiplicative gain""" return 10.0**(dB/20.0)
bf20d65d124e42c4f1453b18bc17e6aef75a4678
649,362
from datetime import datetime def to_unixtime(t): """Return float of total seconds since Unix time.""" return (t - datetime(1970, 1, 1, 0, 0, 0)).total_seconds()
4e0d70e0283bacd2ec025432113e5004778e23d5
649,363
from pathlib import Path from typing import List def read_filelist(filepath: Path) -> List[str]: """ Read a list of files from a file (one file per line). Lines beginning with # are ignored :param filepath: The path of the file containing filenames :return: A list of filenames as strings """ a...
2c08fd7f7885c52dee6e523746d55d9b9ef88828
649,364
from typing import List from typing import Tuple def subdivide_range(rg: int, divider: int) -> List[Tuple[int, int]]: """ """ nbins = rg // divider if not rg % divider == 0: nbins += 1 ranges = [] last_upper = 0 for i in range(nbins - 1): ranges.append((last_upper, last_up...
27bceb464fc5b7d6ac75459b6422321f4a6d0c68
649,365
def get_curve_function(n) : """Programmatically create a curve function for fitting n gaussian""" funcstring = "def curve_function(x, {}) : ".format(", ".join("mu{i}, sigma{i}, A{i}".format(**{"i":i}) for i in range(1,n+1))) funcstring += "\n\treturn np.sum([" + ",".join("A{i}*np.exp(-(x-mu{i})**2/2/sigma{i...
2621007de891f9fd67568c0af9e6bee22fbba9f7
649,366
def getSeqLens(fastaf): """Return a table with length in kilobases for each seq in fastaf.""" lenout = {} curRec, curLen = None, 0 with open(fastaf) as ff: for line in ff: line = line.strip() if len(line) == 0: continue if line[0] == '>': ...
b52958a82c2f6b8edea4177303c936fa2dc956ad
649,368
import json def make_series_key(key, tags, attributes): """Utility function for making a series key POST body, used mainly for the series creation API endpoint. :param string key: the series key :rtype: string""" return json.dumps({'key': key, 'tags': tags, 'attributes': attributes})
3a8c5a94e10472a9d82d6857eba9ec8376eaebce
649,369
def _get_macro_edge_reversal_conflicts_with_existing_descriptor( reverse_base_class_name, reverse_target_class_name, existing_descriptor ): """Return a (possibly empty) list of reversal conflicts relative to an existing macro edge.""" errors = [] if reverse_base_class_name != existing_descriptor.base_cl...
b41a0cef1c4e295f8748cd6babe8a13c1938e546
649,370
def generate_db_url(user, password, host, db_name, protocol = "mysql+pymysql"): """ Utility function for generating database URL This function generates a database URL with the mysql and pymysql protocol for use with pandas.read_sql() Parameters ---------- user : str The username for the...
173e4c130145f3ab47489331adb0668438a912bf
649,371
def _env_to_bool(val): """ Convert *val* to a bool if it's not a bool in the first place. """ if isinstance(val, bool): return val val = val.strip().lower() if val in ("1", "true", "yes", "on"): return True return False
4cb6e5d1fbf4b79b4e8c0f4a57b24c0ed65d7c23
649,372
from typing import Union def maybeint(string: str) -> Union[str, int]: """ Try to cast a string to a int :param str string: to cast :return: int(string) or string in case cast fails """ try: return int(string) except ValueError: return string
187d2366332e45cade255566f467f500e71a4c7c
649,373
def dict_invert_mapping(conv): """ input: dictionary of lists output: dictionary of values: keys """ ret = {v2: k1 for k1, v1 in conv.items() for v2 in v1} return ret
3860b11a3845372d7a38b3839054a3be49e8aa8a
649,374
def app_on_open_with_list(content, arg): """ Check whether a webapp resource is on current user's open-with list content: resource object arg: user object """ user_obj = arg res_obj = content result = res_obj.rlabels.is_open_with_app(user_obj) return result
9fed1819a076680917fcad5a4b8a9e83ae349ab4
649,375
import os def list_downloadable_sources(target_dir): """Returns a list of python source files is target_dir Parameters ---------- target_dir : string path to the directory where python source file are Returns ------- list list of paths to all Python source files in `target...
f771a5e8494e10f692f7a392ccc3f6ea3b98955d
649,376
def find_subset_match(iso_intervals, enst_intervals): """ Compares intervals produced by construct_start_stop_intervals to each other to find subset matches. Used for fuzzy matching of IsoSeq transcripts (iso_intervals) to existing annotations (enst_intervals) """ iso_l, iso_r = iso_intervals en...
af53cf793453356b1aab60fd3116610b8adc1268
649,377
import os def clearpvecs(): """ docstring """ def clearfolder(mydir): """ docstring """ #filelist = [ f for f in os.listdir(mydir)] for f in os.listdir(mydir): os.remove(os.path.join(mydir, f)) clearfolder("input") clearfolder("output") c...
90c925fc1ef9e0a946dd001aa2e7477e7f129383
649,379
import pickle def read_from_pickle(fn): """ Function to read data from a pickled file Parameters ---------- fn : str File directory. data : any type, but recommend dictionary data to read. Returns ------- data : same as data Read in this variable. """ ...
a8ba2d2ceeb9baa22fdcc3f62ed0ee21d69d2628
649,380
def extract_website(s): """Extract websites from scheduling information.""" websites = [] candidates = s.select('a[href^="http"]') for c in candidates: websites.append(c["href"]) return websites
713cbbb8cac5b455f2e6b94abfd7626253454ff9
649,381
import os def enumerate_images(root): """List all the png files starting from root and split them into test and training sets.""" training = [] test = [] for root, dirs, files in os.walk(root): for name in files: path = os.path.join(root, name) low_name = name.lower() ...
f9a11bc7b7bbce6cb63e3a86b0d9b7dec014ac9e
649,382
def generate_ctrlpts2d_weights(ctrlpts2d): """ Generates unweighted control points from weighted ones in 2-D. This function #. Takes in 2-D control points list whose coordinates are organized like (x*w, y*w, z*w, w) #. Converts the input control points list into (x, y, z, w) format #. Returns the ...
d72fd1c32a074dfb0b3b58e6db717ee7c96e46b9
649,383
def htons(x): """Convert 16-bit positive integers from host to network byte order.""" return (((x) << 8) & 0xFF00) | (((x) >> 8) & 0xFF)
3a46a9e2bc54bb4e77076065e7741a9e5ae3a0ed
649,384
def packageParameters(gK, gNa, gL, Cm, EK, ENa, EL, Vm_0, T): """ Takes all HH class parameters, packages and returns a dictionary class object; the keys are hardcoded in the Hodgkin Huxley class definition """ parameterDictionary = { "gK": gK, "gNa": gNa, "gL": gL, ...
ffd00bf45f579cae5d2758d5652c60753157aa28
649,385
def _get_bpf(fps: int, br: int) -> float: """ 根据帧率,码率获取每帧素数据量,单位和码率相同 :param fps: 帧率 :param br:码率 :return: 每帧数据量 """ return round(br / fps, 4)
26fdf7bdf709e6f75c6ad33a8c1230d951b85819
649,386
from typing import Sequence def _parse_info(lines:Sequence[str]) -> dict: """Parse info.txt and return dictionary with relevant data""" auto = lines[0] == "AUTO" yaw, pitch, roll = map(float, lines[1].split(" ")) fov = float(lines[5]) return dict( auto=auto, fov=fov, yaw=ya...
3ddbdf5c134837276729135e3f07244e8bf41f81
649,387
def project_nonneg(values, imag_eps=1e-10, real_eps=1e-10, real_trunc=0.0): """Check that values are real and non-negative :param np.ndarray values: An ndarray of complex or real values (or a single value). `values` is modified in-place unless `values` is complex. A single value is also accepte...
2db645bbf22039507bf813050ab8c36a80f79e9c
649,388
import six def get_allocated_inventory(ctx, rp, rcs=None): """Returns the list of resource classes for any inventory that has allocations against it, along with the total amount allocated. If `rcs` is specified, the returned list is limited to only those resource classes in `rcs` that have allocations...
ff8388b3e3017e964102cddf36711cb551594cb0
649,389
import sys def Import(modname): """Improved __import__ function that returns fully initialized subpackages.""" try: return sys.modules[modname] except KeyError: pass __import__(modname) return sys.modules[modname]
d0395dce0a54c21a637e33f5d8e447c81650cb83
649,391
def get_leaves_with_labels(tree): """ Return leaves in the tree, as well as their labels >>> from ptb import parse >>> t = parse("(4 (4 (2 A) (4 (3 (3 warm) (2 ,)) (3 funny))) (3 (2 ,) (3 (4 (4 engaging) (2 film)) (2 .))))") >>> get_leaves_with_labels(t) [('A', 2), ('warm', 3), (',', 2), ('...
384fa89e89da0de61acc338570344ac027feb488
649,392
import os def search_files(files_, dirs): """ :param files_: -> list :param dirs: -> list :return: """ new_dirs = [] for d in dirs: for f in os.listdir(d): if os.path.isdir(os.path.join(d, f)): new_dirs.append(os.path.join(d, f)) else: ...
3634f18886ad1603403fe54acab78ac148583739
649,394
from pathlib import Path def _parse_input_filepath(filepath): """ Parse input file path either from CLI argument or default file path. """ if filepath is None: root_dir = Path(__file__).resolve().parent.parent filename = root_dir / "data" / "input" / "definition.json" else: ...
e15410d0f72c9411f38595cbb5948ea591c7b49b
649,395
import re def filename_norm(f: str, s: str = "") -> str: """替换不符合文件名的字符 :param f: 文件名字符串 :param s: 替换后的字符 (1个字符) :return str """ t = r'|/\\:*?"><' s = s if s not in t and len(s) <= 1 else "" f = re.sub('[{}]'.format(t), s, f) return f
badeb49237a956ecf996dd6446e22d819a321d01
649,396
def as_dictionary_of_dictionaries(labels, means, cov_diags): """ Dictionary storing one dictionary of parameters per category. """ assert len(labels) == len(means) == len(cov_diags) all_params = dict() for label, mean, cov_diag in zip(labels, means, cov_diags): category_params = dict() ...
c355f5ac3d2e8429bcf54e2420cf19c6c5efdd68
649,397
import requests def request_api_key(username: str, email:str, description:str="I'd like to try it out.", referral_code: str="github_referred"): """ Request an api key Make sure to save the api key somewhere safe. If you have a valid referral code, you can recieve the api key more quickly. ...
d234401ad1661bc660e7886f679b02cfaf33d289
649,398
def check_true(answer, label): """ Check if a given answer matches the label :param answer: the probability output from the network :type answer: float :param label: the label integer as either a 1 or a 0 :type label: float :return: 1 if classification is correct, 0 if incorrect :rtype: ...
bf2ec6b3eab7a5c9cd6c0c5e5c1d3e7efd4b5223
649,399
import os import json import argparse def load_model_specs(model_dir): """Look for the model specifications in the given directory""" if model_dir is None: # get the latest modified dir in the default dir, raise an Error if there's none default_dir = "checkpoints" all_dirs = [os.path.j...
56ca65969ad17b5548edee022ba8264a471bc5c5
649,401
import os import re def parseBarcodes(path): """Takes input directory containing pairsam files and parses barcodes of the form ADAPTOR_SX, with ADAPTOR containing 6 letters and X being a number with one or more digits.""" barcodes = [re.findall(r"[A-Z]{6}\_S[0-9]+", i)[0] for i in os.listdir(path)] ...
61f59cd1915ab2cad93758bd374cb4b308a1dea6
649,402
def some(pred, coll): """ Returns the first element x in coll where pred(x) is logical true. If no such element is found, returns None. >>> fish_are_blue = lambda x: "blue" in x.lower() and "fish" in x.lower() >>> some(fish_are_blue, ... ["Red fish", "Green fish", "Blue fish", ...
7f40254ec6910b663c5cb3fc3b90062d1d886cc0
649,403
def new_scores(dim): """ Generates a new scores board """ scores = [] row = 0 while (row < dim): temp = [] col = 0 while (col < dim): temp.append(0) col += 1 scores.append(temp) row += 1 return scores
f2c1ed65f58ff4ad2b4be272f50f22d17248d91d
649,405
def get_snapshots_from_text(query_output): """ Translate expanded snapshots from `cali-query -e` output into list of dicts Takes input in the form attr1=x,attr2=y attr1=z ... and converts it to `[ { 'attr1' : 'x', 'attr2' : 'y' }, { 'attr1' : 'z' } ]` """ ...
f6bfb56329c04ee8e325b5bd82ea417901420a58
649,406
import string def encipher(current_text, keyword, config): """ encipher takes the current text, the keyword and the configuration object and it returns the ciphertext Assumptions on input: the current text and the keyword may be in any case, without whitespace Preprocessing: the text and the keyword ...
356334b2147f4b04021874c9dfb949c57f811220
649,407
import os import time def make_working_directory( test_filename ): """ directly executing a test script can be done but rm -rf * is performed; to avoid accidental removal of files, cd into a working directory """ d = os.path.join( 'tmpdir_'+os.path.basename( test_filename ) ) if not os.path.ex...
c2c78e95bc8b2a159edc218da594eb443f67bab9
649,409
def is_palindrome(s): """ (str) -> boolean Returns true if the argument is a palindrome else false >>> is_palindrome("noon") True >>> is_palindrome("later") False >>> is_palindrome("radar") True """ # converts (s) to lower case and assigns it to the variable word word = s.low...
f20c0e3d09cba689f55369b218981da17eb33742
649,411
def word_distance_check(topic, testword, similarity): """ perform word2vec cosine distance of testword from topic if distance greater than similarity, return False """ # connect to API service return True
24580443c720334789093deb10db7a830f201810
649,412
def check_equivalence(row, df): """Find equivalent indels stored in dataframe column Args: row (pandas.Series): A Series object column labeled 'indel_obj' df (pandas.DataFrame) Returns: str: see example below Example: indel objects are stored in 'indel_obj' column. S...
fe7c1761626c7bd0251204c3e9a3869bede68949
649,413
def mock_invalid_response(): """ Returns invalid mock labels and their probabilities :return: """ return "Internal server error"
caba363414faa86bbbac5c53f81ba87cbdc48db8
649,414
def __normalize_parameters_dict(dictionary): """ Combine namespaces and their node names into one key and remove the "ros__parameters" key. Return an empty dict if the "ros__parameters" key is not found. """ # Recursive function def normalize_parameters_dict(dictionary, keys, result_dict): ...
90caa48b4a73063040848ee05de1eaf45e697040
649,415
def xor(bytes1, bytes2): """ Xor two input bytes and return Input: `bytes1`, `bytes2`: bytes need to xor. Output: xor result """ return bytes([a ^ b for a, b in zip(bytes1, bytes2)])
ac898cf412bb48482d2919a213934262e9d7ecda
649,416
def _compute_cycle(prod): """Figure out an integer cycle that identifies this product.""" # Extended ones are easy if prod.afos in ["PTSD48", "PFWF38"]: return 21 if prod.outlook_type == "F" else 10 day = int(prod.afos[5]) if day == 3: # has to be convective return 8 # Day 2 are...
a8228866223f05bc06ad3e4a599a52e41f6bb597
649,417
from numpy import ones, vstack from numpy.linalg import lstsq def eq_line_2points(p1, p2): """ returns the y = mx + b equation given two points. :param p1: point 1, x and y coord :param p2: point 2, x and y coord """ x_coords, y_coords = zip(*[p1, p2]) A = vstack([x_coords, ones(len(x_coor...
fcb97759c6988c6b6ef80019da513bbecc071821
649,418
import random def get_random_filename(file_list): """ Gets a random filename from inside the ZipFile object, with the selected file extension :return: arbitrary filename of selected type (extension) """ file_extension = '.xml' filename_list = [x.filename for x in file_list if x.filename.en...
4dfadfba53c40130928ee88f866c078e1c326f20
649,419
def deplen(deps): """Compute dependency length from result of ``dependencies()``. :returns: tuple ``(totaldeplen, numdeps)``.""" total = sum(abs(a - b) for a, label, b in deps if label != 'ROOT') return (total, float(len(deps) - 1))
b6dda009daa4b2e4cc677e1e0b492cb163cb49b6
649,420
def packing(x, r=2): """Takes a BCHW tensor and returns a B(rC)(H/r)(W/r) tensor, by concatenating neighbor spatial pixels as extra channels. It is the inverse of nn.PixelShuffle (if you apply both sequentially you should get the same tensor) Example r=2: A RGB image (C=3) becomes RRRRGGGGBBBB (C=12) an...
cd314381d9f84b4694c312bdcba786753a789698
649,421
def gen_palette(palette: str): """Generates the corresponding palette function from `palettable`.""" palette_split = palette.split(".") palette_name = palette_split[-1] # https://stackoverflow.com/a/6677505 palette_func = getattr( __import__( "palettable.{}".format(".".join(pale...
f92ccd03af6e391425f97830441b12a98acb3cf3
649,422
import re def _set_value(str_text, str_line, val): """ This function search for str_line in str_text and overwrites the whole matching line with <str_line> str(val) """ str_text = re.sub('\n' + str_line + '.*', '\n' + str_line + str(val), str_text) r...
e732bd26bbdcad3eed0c60201affc348565a1a5e
649,423
import sys import csv def print_numpy_block(fn, data, header='', delim='&', axis=-1): """ Unformatted output for numpy arrays in 2D or 3D. axis == -1 means each line spans the last axis of data. axis == 0 means each line spans the first axis of data. """ if axis != 0 and axis != -1: ...
8d769f22f2d28449187e65c922435940d3de51b5
649,424
def get_iam_service_account_email(project_id, account_id): """ Return the service account email given the id and project id Args: project_id (str): Project Identifier where service account lives account_id (str): The account id originally provided during creation Returns: str: ...
d44073a7b14c6de2960027ac4d01a479388f6be3
649,426
def val_num_int(text): """ Permite validar el ingreso de un número Parameters ---------- text : str Texto del input `text`. """ while True : try: n = int(input(f"{text}: ")) return n except: print("Ha ocurrido un error, introduce b...
d4a2cc6d998b59008c3aa2839fb53a2369628bb5
649,427
def _pkgname_ui(ayum, pkgname, ts_states=None): """ Get more information on a simple pkgname, if we can. We need to search packages that we are dealing with atm. and installed packages (if the transaction isn't complete). """ if ayum is None: return pkgname if ts_states is None: ...
1b78f6cdeeae5d3417a5315bd64d75cea22bc529
649,428
def getSpecPath(baseName, baseDir, e0, nTraj): """ getSpecPath(baseName, baseDir, e0, nTraj) Generate a file path for Monte Carlo simulated spectrum Parameters ---------- baseName - a string. The base name for the simulation, Example: "bulkC" baseDir - a string. The path to the directory to write the s...
048589a726c5be83c681491eed1eb0c9cd616444
649,429
import os from glob import glob def get_last_checkpoint(directory): """Obtain the name of the last checkpoint in a directory.""" checkpoint = "" if (not os.path.isdir(directory)): return checkpoint # Doing a search this way will treat first any checkpoint files # with seven digits, an...
676c7d6f1b39741ba9b992f6f9433152869c8f80
649,430
def maximo(numero1, numero2): """Devolve o maior número""" if numero1 >= numero2: return numero1 else: return numero2
dfe172638a4578ecaed36c72bedd51374c356363
649,431
def adamic(brands, exemplars): """ Return the average Adamic/Adar similarity between a brand's followers and the followers of each exemplar. We approximate the number of followed accounts per user by only considering those in our brand set.""" print('adamic deprecated...requires loading all brands in me...
d8c0c7adbe25f8d19f37754249b5c1b552963468
649,432
import os def replace_home(filename): """replace $HOME with ~ in the directory and filename""" home = os.path.expanduser('~') return filename.replace(home, '~', 1)
99acc317a48960853ffac0b2d8a476a80d717c37
649,433
def mayan_tzolkin_date(number, name): """Return a Tzolkin Mayan date data structure.""" return [number, name]
8cfd4120ea76de36e824311f1afab752beed84a3
649,435
import numpy def CatmullRomSpline(P0, P1, P2, P3, nPoints=100): """ P0, P1, P2, and P3 should be (x,y) point pairs that define the Catmull-Rom spline. nPoints is the number of points to include in this curve segment. """ # Convert the points to numpy so that we can do array multiplication P0, ...
df580dec1c4b6d6963f59eccdf72750398008b26
649,436
import base64 import logging def filter_descriptors(descriptors, digests, flavor='unflavored'): """Filter out the invalid descriptors. :param descriptors: Descriptors to be filtered. :param digests: Digests from the consensus. :param flavor: Flavor of the descriptor. """ descriptor_digests = ...
28f9326bd39ee8b24cb059deb8edd1cd3d913676
649,437
def _ncpus_memory(length, loading=3, node_cpus=48, node_memory=192): """Determine the number of cpus for the MPI job.""" n_nodes = length // loading // node_cpus if n_nodes == 0: n_nodes = 1 n_cpus = n_nodes * node_cpus memory = n_nodes * node_memory if n_cpus > length: n_cpus...
2337d1ede8fa21d3737c0a32937c9c898bb37b95
649,438
from typing import Union def dollar_str_formatting(val: Union[int, float]) -> str: """ Format dollar figures into $val trillion, $val billion, etc. Parameters ---------- val: float revenue amount Returns ------- str formatted dollar figure """ val = abs(val) ...
3871bc043935a7578140748b6328068cf96240d5
649,439
def key( *args ): """ join the arguments in the format of donkey Arguments --------- args: list of string Examples -------- >>>key( 'a', 'b', 'c' ) 'a__b__c' """ return '__'.join( args )
9094dd19fd221073fe9cdac84a3616e71eb6fbcc
649,440
import string import secrets def new_salt(n=12): """Generate a new salt.""" salt_chars = string.ascii_letters + string.digits salt = [secrets.choice(salt_chars) for _ in range(n)] return "".join(salt)
bde968e1c5168b9ecb835b3c9c3a7a32fccdf6e5
649,441
def obtain_reverse_codes(mapped, dst): """ Given the list of desired dst codes and an extensive map src -> dst, obtain the list of src codes :param mapped: Correspondence between src codes and dst codes [{"o", "to": [{"d", "e"}]}] :param dst: Iterable of destination codes :return: List of origi...
a7a46d76791dd00e3364a936dab8e4d9a3601105
649,442
def leniter(iterator): """leniter(iterator): return the length of an iterator, consuming it.""" if hasattr(iterator, "__len__"): return len(iterator) nelements = 0 for _ in iterator: nelements += 1 return nelements
49e0ce9f204e77292b1bc2e6f0121eaff4212285
649,443
def calc_center_pos(city, nodelist): """ Calculates center position for nodes in nodelist Parameters ---------- city : object city object of pycity_calc nodelist : list (of ints) List of node ids Returns ------- pos : tuple Position tuple (x, y) """ ...
854d000c7ce11d149c9914016a8187ce459df162
649,444
def clean_data(df): """ Perform data cleaning on the disaster response dataset Arguments --------- df - the dataframe returned by load_data Returns ------- pd.DataFrame """ categories = df.categories.str.split(';',expand=True) # select the first row of the categories da...
a2873c4c812518b1dcd1dd41933e9bfc299dae5d
649,445
import torch def trilinear_composition(h_s, h_t, x, einsum=True): """ Trilinear composition as described in: STAMP: Short-Term Attention/Memory Priority Model forSession-based Recommendation Shapes: b: batch e: embedding l: longest sequence length v: vocabulary size Parameters ...
cbeeff88ad144f72d2774fb47a4a7951e2fd503c
649,446
def parse_depends(s, strip_multi_arch=True): # real signature unknown; restored from __doc__ """ parse_depends(s: str[, strip_multi_arch : bool = True]) -> list Parse the dependencies given by 's' and return a list of lists. Each of these lists represents one or more options for an 'or' dependency ...
4a92d57f58e7e3d0148e296ec1e56b15b5af41c3
649,447
def rolling_std(returns, window): """ Essa função calcula volatilidade a partir do cálculo da desvio padrão móvel. Args: returns (pd.Series): série de retornos para o qual o desvio padrão será calculado. window (int): janela móvel para cálculo do desvio padrão móvel; Returns: p...
b99bfc97c9fbdf8c6293e440f8bb0532380ebbba
649,448
def flatten_first_two(batch): """This is a helper function that is used in other sampler functions. It flattens the first two dimensions of each key entry in the batch, thus making the data flattened. """ # The data must be intact up to preprocess. # After that we are free. for key in batch:...
c25e3acc9d61423092279820c556a3e82106ff7d
649,449
def foo_4(x): """ test >>> foo_4(1) 1 >>> foo_4(5) 120 """ result=1 for i in range(1, x+1): result=result * i return result
9446e26d5865a0e6eac54f1de621717b214c4e1f
649,450
import os import stat import shutil def rmtree(path): """Remove the given recursively. :note: we use shutil rmtree but adjust its behaviour to see whether files that couldn't be deleted are read-only. Windows will not remove them in that case""" def onerror(func, path, exc_info): if not os...
25833e9a388632a2375412e2e634383aa92e8f8e
649,453
def is_getter(attribute): """ Test if a method is a getter. It can be `get` or `get_*`. """ return attribute.startswith('get')
0f03a45671866b09d9cfa23766a8a33c16760e5c
649,455
import functools def _memo(fn): """Helper decorator memoizes the given zero-argument function. Really helpful for memoizing properties so they don't have to be recomputed dozens of times. """ @functools.wraps(fn) def memofn(self, *args, **kwargs): if id(fn) not in self._cache: ...
c59bd3203a3929411f5262b682a406a7ad2529a2
649,456
def marginal_datatrace(dt, items=None, like=None, regex=None, drop=None, samples=None): """ Given a datatrace, this function generates a subsample of it. Args: dt (pandas.core.frame.DataFrame): result of MCMC run on DataFrame format. This contains the whole information of the evolution o...
88f9994836780dd6ea93d765c358346a0997a8c5
649,457
def verify_keyid_is_v4(signing_key_fingerprint): """Verify that the keyid is a v4 fingerprint with at least 160bit""" return len(signing_key_fingerprint) >= 160/8
407d1408bda5845c94ec15813a4132f7d9bef878
649,458
def update_parameters_with_momentum(parameters, grads, v, beta, learning_rate): """ Update parameters using Momentum -Because mini-batch gradient descent makes a parameter update after seeing just a subset of examples, the direction of the update has some variance, and so the path taken by mini-batch gradient desc...
fd9f1e2e5b7d9f1f36eb58bb00add1c42d4c21b2
649,460
def process_subtitle(data): """get subtitle group name from links """ result = {} for s in data: # pprint(data) # f = Subtitle(id=s['tag_id'], name=s['name']) # if not f.select(): # f.save() result[s["tag_id"]] = s["name"] return result
47a1cf4d3dcb50f5f7ea2fd54c6137b72fe7a6ef
649,461
def get_queuelisting_perspective(display): """Retrieve the QueueListing perspective. Args: display: the display containing the loaded perspective Returns: QueueListing: the loaded QueueListing perspective """ display._active_perspective = 2 return display.perspectives[2]
98568df298bde2050901a47743162f44a010698e
649,462
def dsigmoid(y): """ derivative of sigmoid in this function y is already sigmoided """ return y * (1.0 - y)
b9281203991e7547c313246bd43f20d02c164527
649,463
import os import glob def image_paths(dir_or_filename): """Given: * a directory path, * a path/file specification, * or a single image, return a list of paths to all images """ # Expand any "~" dir_or_filename = os.path.expanduser(dir_or_filename) if os.path.isdir(dir_or_filena...
123d6d8ecc2569c9bf59fb00182477b473ea395b
649,464
def __html__(self): """ Returns the html representation of a string. Allows interoperability with other template engines. """ return self
0e6ac6ff63c652a2aec82915a8b0f2a9aefc9dc5
649,465
def check_duration_index(cross): """Verify the duration location""" assert len(cross) > 0, \ '(ValueError) Coda fit line does not cross noise threshold' return None
83b8ced37baccd42d4222dd167ea4ba02332448d
649,466
import yaml def local_test_config(): """ Requires yaml file with local logging configuration example: --- NS_DBHOST: localhost NS_DBUSER: ns_test NS_DBPASSW: some_password NS_DBPORT: 5432 NS_DBNAME: ns_db LOGGLY_TOKEN: app_token LOG_HANDLERS: "console,file,loggly" """ ...
4c44427daa64ebf1616d50925f41494bc8998722
649,467
import pathlib import json def azure_test_dataset(): """ Retrieve a locally saved sample from the population as dataset to use for this test Return: JSON format of the test dataset """ this_file = pathlib.Path(__file__) json_path = this_file.parent.parent.joinpath("fixtures", "azure_ip_ranges....
3e0698a039526b8a9431cfe70ad7691ea1e9e9bd
649,468
import os import shutil def CreateHTMLdir(tmp_dir, html_display_files_dir): """ We create the HTML directory in the tmp dir. We need to copy baseline files from html_display_files_dir to this directory This is where the information for the HTML directory is decided (no config) Args: both a...
8234dedd07cc6f6aa3c7ffd5fe5bacffe0dee616
649,469