content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def lsum (inlist): """ Returns the sum of the items in the passed list. Usage: lsum(inlist) """ s = 0 for item in inlist: s = s + item return s
24907db4a001b66974adb9702e816b531cf78d84
625,451
def numToDigits(num, places): """Helper, for converting numbers to textual digits.""" s = str(num) if len(s) < places: return ("0" * (places - len(s))) + s elif len(s) > places: return s[len(s)-places: ] else: return s
897aa092e725aae6902a2cb1e0b3eede7149a2c2
625,452
def splitBy(s, fn): """functional style""" lst, t = [], s while t: h, t = fn(t) lst.append(h) return lst
4f24a7d5c47d17bdfd30c43436c62585dd10ecb7
625,453
import re def ucfirst(word): """Uppercase the first letter in a string and error if string starts with an digit Args: word (str): the word Raises: Exception Returns: (str) """ if len(word) <= 0: return "" if not re.match('^[a-zA-Z]', word): r...
b2f0d5a6747499b6227c573f21d728b2c5f1be73
625,454
def calc_speed(player): """ player slippi Port Given a player we compute its current speed return speed """ speed=(player.leader.post.position.x-player.leader.pre.position.x, player.leader.post.position.y-player.leader.pre.position.y) return speed
c1f2245921dae4b358765f0f15d88047165aa542
625,455
def TETChromaticScale(frequency, octaveDivider): """creates an even tempered scale with a given starting frequency and a number for how many divisions you want the octave to be divided into. Returns an Array""" i = 0 scale = [] while i < octaveDivider: i += 1 note = round(frequency *...
c01dc7a3e1dbbf2a146327dfbc6d73fb877259b6
625,456
def get_arg_dict(func, args, kwargs): """ Возвращается параметры функции func в виде единого словаря """ args_names = list(func.__code__.co_varnames[:func.__code__.co_argcount]) try: if args_names[0] == 'self': args_names.pop(0) except: pass return {**dict(zip(args_names,...
b5ff7a2ee31e73bb965c9dd8f7358c67dd6d6790
625,457
def affected(constraint_qs): """Filter constraints, keeping only those to be updated""" # The constraints were renamed in the UI in commit 16699 on 2019-09-03. # This was between meetings 105 and 106. Assuming this migration and # the new conflict types are in place before meeting 111, these # are t...
23ee17da7ba42cbeda7b181a5c24897ec723aef4
625,458
import re def querySpecificity(queryObj={'tk': '^我們$', 'pos': 'N%', 'tk.regex': True}): """Score a token object for specificity. Parameters ---------- queryObj : dict A token object in a list returned by :py:func:`.tokenize`. Returns ------- float A point indicati...
e62c0d0571dc519bb0f0b9e085665d8f4f410b69
625,459
def fillna_by_column(df,same_column_name): """ 填充经过关联后 带有_x和_y的同名字段, 用右边填充左边的数据 :param df :param same_column_name """ df_copy = df.copy() column_x = same_column_name+'_x' column_y = same_column_name+'_y' df_copy[column_x] = df_copy[column_x].fillna(df_copy[column_y]) del df_copy[column_y] df_copy = df_co...
b4008f41750784fb3998540689bba6efa9194209
625,460
def GetParentNodeWhereTrue(node_id, tree, stop_function): """walk up in gene tree and stop where stop_function is true. The walk finishes at the root. returns tuple of node and distance. """ node = tree.node(node_id) distance = 0 while node.prev is not None: if stop_function(node...
bdc79abd5a8171f821102e5d8f74f95952a5157b
625,461
def setBit(num, n): """ Return num with the nth bit set to 1. """ # Make a mask of all 0s with the nth bit set to 1. mask = 1 << n return num | mask
42ec57a67b37171171ef929c5355e3de368ec63c
625,462
import time def display_timestamp(t): """Takes a Unix timestamp as a an arg, returns a text string with '<unix timestamp> (<equivalent time>)'.""" return '%s (%s)' % (t, time.strftime('%d/%m/%Y %H:%M', time.gmtime(t)))
e5a435ec39afc114d532846a01b407c5cfad2df2
625,464
def create_valid_bigquery_field_name(field_name): """ Clean up / prettify field names, make sure they match BigQuery naming conventions. Fields must: • contain only -letters, -numbers, and -underscores, • start with a -letter or ...
413b62566f0f1034335f43237229f02195947368
625,465
def uniq(iterable, key=lambda x: x): """ Remove duplicates from an iterable. Preserves order. :type iterable: Iterable[Ord => A] :param iterable: an iterable of objects of any orderable type :type key: Callable[A] -> (Ord => B) :param key: optional argument; by default an item (A) is discarded ...
219cba5494198fc806b503e9000a7e491fe2a7c5
625,466
def conv1x1(mb, input, in_planes, out_planes, stride=1): """1x1 convolution""" return mb.Conv(input, in_planes, out_planes, k=1, stride=stride, bias=True)
724625a9a1e1087064bb9f33d6b83ec67e0c359e
625,467
def make_cached_ssd_store_options( cache_budget_mb, persistent_path, capacity=None, size_factor=1, physical_block_size=512, host_cache_budget_mb=0, ): """make SSD use GPU and host as cache store_options param of MultiTableEmbedding. If cache_budget_mb > 0 and host_cache_budget_mb > 0, use GP...
fd701a01ceca0efff3efb9ac27e46d683f67eb1a
625,468
import re def is_match(regex, string, ignore_case=False): """Check if regex matches string.""" regex_flags = re.DOTALL if ignore_case: regex_flags = re.DOTALL | re.IGNORECASE return re.match(regex, string, regex_flags) is not None
52b7efb1569531f1e0b1e5717f021d5e2b08e924
625,469
def classify_token(w): """ Function for feature augmentation. Improves the network's results by generating the information that will be fed into the feature-augmentend embedding layer Parameters ---------- w : str Word Returns ------- str Class to which a token ...
78757650191388204e942ac02a4950316bbefd6d
625,470
import os import sys def running_script_name(): """Return the name of the currently executing python script.""" return os.path.basename(os.path.realpath(sys.argv[0]))
0397bf84e9ba7a14140be9a8922db6433955e2b1
625,471
def _get_global_variable_names(name, tuple_path): """Get the global variables names for ground truth. Args: name: Python `str`. Name of the sample transformation. tuple_path: Tuple path of the part of the ground truth we're saving. See `nest.flatten_with_tuple_paths`. Returns: mean_name: Varia...
33b02ca0907f5e5d2a026cf1a56811107c38025c
625,472
def _parse_file_move(file_move): """Return the (old_filename, new_filename) tuple for a file move.""" _, old_filename, new_filename = file_move.split() return (old_filename, new_filename)
02815dde04578fcc63cb5033bb29729d4dfb9fd1
625,473
import hashlib def getETag(data): """Gets the ETag for the specified data. Args: data: The data for which the ETag should be generated. """ md5 = hashlib.md5() md5.update(data) return md5.hexdigest()[-16:]
db7578c74551f5c507c3d7c0bcbf3cab2768ff1e
625,474
import sqlite3 def total_items_count(): """Queries and prints the total items.""" conn = sqlite3.connect('rpg_db.sqlite3') curs = conn.cursor() query = 'SELECT COUNT (*) FROM charactercreator_character_inventory;' result = curs.execute(query) total_items = result.fetchall() return print('...
5b3655f8722b26fb6bc9bf99bf5e51a4f5450293
625,476
def njoiner(inbox, n=None, join=""): """ String joins and returns the first "n" inputs. Arguments: - n(``int``) [default: ``None``] All elements in the inbox smaller then this number will be joined. - join(``str``) [default: ``""``] String which will join the elements of the ...
1541c192bb379657027ef93eebd2c01287756df8
625,477
import traceback def format_exception(e): """ Format the traceback of the exception ``e`` in a string. """ elements = traceback.format_exception(type(e), e, e.__traceback__) return ''.join(elements)
f83ccb7da334e24c90887412211c1ca9eba1e66d
625,478
def joinRects(rect1, rect2): """ 计算包含 `rect1` 和 `rect2` 的最小 `rect` 坐标 """ return [min(rect1[0], rect2[0]), min(rect1[1], rect2[1]), max(rect1[2], rect2[2]), max(rect1[3], rect2[3])]
ebb9893171cbed6a82970279efb774e07f158d2f
625,479
def comp_market_value(price, vol_list, admin_fee_list): """ return current market value of this stock, after deducting selling admin fees """ return sum(price * i[0] - i[1] for i in zip(vol_list, admin_fee_list))
17b306afcef257370c5b2ba5cd9d54829f300c30
625,481
def est_majeure(nom: str, prenom : str, age: int) -> bool: """ Renvoie True si la personne est majeure, ou False sinon. Précondition : nom != "" and prenom != "" and age > 0 """ return age >= 18
eebd9d58c8280e8ce857a753b2108eb3e5ea5c0c
625,482
def optimizerModel2wts(model): """Convert an optimizer model file into a flat weight vector.""" wts = [] with open(model) as f: for line in f: wts.append(float(line.partition(' ')[2])) return wts
6960ed9172a72190bf11c9e1ea7e8eaf98ee18ec
625,483
import socket def create_socket(host, port): """creates and returns socket""" connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.connect((host, port)) return connection
1ff580d40cd8d1987e58b0c69895012ae1badc9d
625,484
def get_objects(conn, script_params): """ File the list of objects @param conn: Blitz Gateway connection wrapper @param script_params: A map of the input parameters """ # we know script_params will have "Data_Type" and "IDs" since these # parameters are not optional data_...
e9734670abdc7b7eecb6841e0ba16f8c487abddd
625,485
def convert_wavelength_vacuum2air(wavelength_vacuum): """ Convert vacuum wavelength to air wavelength Parameters ----------- wavelength_vacuum: float Vacuum wavelength in Angstroms Returns -------- float Air wavelength in Angstroms """ sigma2 = (1e4/wavelength_va...
c6448f8043c4cc1b603743cf12a766edeefdbbef
625,486
def getEventsList(objectsList=[]): """create an event list from the schedules of the objects provided""" events_list = [] # list to hold the events of the system for object in objectsList: if object.schedule: for record in object.schedule: if not record["entranceTime"] i...
e5f9831def112eb48fe949ab9978dd3541bb7503
625,487
def add_stoichiometry(stm, rxns, rctnids, obfunc): """Add stoichiometry information to matrix""" for r in rxns: rid = r.getId() rctnids.append(rid) for sp in r.getListOfReactants(): species_name = sp.getSpecies() # Be sure to skip boundary compounds if...
e0c179c7d335dc1d6411c010c231da7c1938c7b3
625,489
def get_largest_hand(hands): """ Iterate through a list of hands found in an image and return the largest hand found. :param hands: A list of hands found in an image. :return: The largest hand found. """ if hands is None or len(hands) < 1: return None largest_hand_so_far = hands[0] ...
e4866d06362845d2541c9d104baf6500f61b19c9
625,490
def is_sorted( s, strict = True ): """Test if a sequence is sorted""" prev_elem = None for x in s: if prev_elem != None and x < prev_elem or ( x == prev_elem and strict ): return False prev_elem = x return True
174e0824e45964fd41027e08801e54b9c260cb1b
625,491
def jarFlags(target, source, env, for_signature): """If we have a manifest, make sure that the 'm' flag is specified.""" jarflags = env.subst('$JARFLAGS', target=target, source=source) for src in source: contents = src.get_text_contents() if contents[:16] == "Manifest-Version": ...
86bb957daf44dbe163e60df753baf60bd8f2bbbe
625,492
import csv def loadcsv(file_path, header=False, ignore_empty_line=False, **kwargs): """CSV version of loadtxt""" lines = [] with open(file_path, 'r') as infile: for each in csv.reader(infile, **kwargs): if ignore_empty_line and not each: continue lines.appen...
e06f43810b00f4513a2bbd26bdcded9109eb2e6a
625,493
def test_clone_scoping(): """ test_clone_scoping """ print("run python test_clone_scoping") def f(x, y): def h(z): # No dependency on f, so not nested and not cloned return z * z def g(z): def gg(): return z + z # Depends on ...
bfec4dfc9f358677a47fb7f295b747466ef69216
625,494
from PIL import Image def _to_pil_rgb_image(image): """Returns an PIL Image converted to the RGB color space. If the image has an alpha channel (transparency), it will be overlaid on a black background. :param image: the PIL image to convert :returns: The input image if it was already in RGB mode, o...
b4590b12f38899ca5552805287fc753d050079a8
625,495
def fim(entrada, contador): """ Verifica o fim do arquivo :param entrada: string que representa o arquivo que está sendo analisado :param contador: inteiro utilizado para determinar a nova posição na string :type entrada: str :type contador: int :return: retorna se é o final da string :r...
144b82fdca57eb131bd48f18f436cc15f01a7958
625,497
def _combine_overlapping_cities_hashed(my_list): """If two cities' markers overlap, combine them into a single entry. Explanation: Use latitude and longitude rounded to N_DIGITS to create a PKEY for each city. Rounding will cause nearby cities to have the same PKEY. Largest city chosen: As SQL queries m...
69b5a9abbdec8547fe28256b721b94f7cdb6cc07
625,498
def to_unicode(data): """ Get a string and make it Unicode @zc00l """ out = "" for char in data: out += char + "\x00" return out
90891ff255f33e8d231774f00986f86aeb65f164
625,499
def get_bfield_name(name): """Sanitize the name of bitfields.""" return name.replace(' ', '') + 'Bits'
8df32b8b6f0eb439ac8f3cf9e8fb7810324e854b
625,500
def canonical_shape_copy(shape): """ A shape is in canonical form when the mininums of x, y & z are zero. """ mins = [min(pt[dim] for pt in shape) for dim in range(3)] new = [tuple(pt[dim] - mins[dim] for dim in range(3)) for pt in shape] return tuple(sorted(new))
db379ea6200271e419ba1de4666d9e76182e1579
625,501
def two_way_quick_sort(array, low, high): """ Sort array in ascending order by quick sort :param array: given unsorted array :type array: list :param low: starting index of array to sort :type low: int :param high: ending index of array to sort :type high: int :return: sorted array ...
f60e6fcdd5f51968eb0d59965c94f08fcd584c0b
625,502
def get_refdes(anno_record): """ Build and return a reference designator from the subsite, node and sensor fields in record supplied. """ subsite = anno_record.get('subsite', None) node = anno_record.get('node', None) sensor = anno_record.get('sensor', None) if node is None: return subsi...
d210ef0a57214c04d8f72348fca9d40388d19d29
625,503
def replace_param(context, **kwargs): """ """ d = context["request"].GET.copy() for k, v in kwargs.items(): d[k] = v for k in [k for k, v in d.items() if not v]: del d[k] return d.urlencode()
836713ae6e8282716694a0fe7130da356e55fc27
625,504
def _is_comment(line): """ Assert if line is a comment or a line to ignore. Expects striped lines. """ is_comment = \ line.startswith('#') \ or not bool(line) return is_comment
04494ee84fff24a6a88e0d4838a3bcd351cffee9
625,505
def calc_3d_bbox(xs, ys, zs): """Calculates 3D bounding box of the given set of 3D points. :param xs: 1D ndarray with x-coordinates of 3D points. :param ys: 1D ndarray with y-coordinates of 3D points. :param zs: 1D ndarray with z-coordinates of 3D points. :return: 3D bounding box (x, y, z, w, h, d)...
5e4f2c6197addae67816844f6764b16c031d3d29
625,506
def Transforme_DataFrame_fichier(DataFrame, extension, chemin = None): """ Transforme un dataframe en le format selectionné, c'est à dire : - csv - json - array Pour l'option csv, on précisera un chemin permettant d'enregistrer le fichier. Pour les autres, on obtiendra des ob...
1acec8725886b82e1fb86fdb8619a1de9108c8e2
625,507
def rivers_with_station(stations): """D - Returns a set with the names of the rivers with a monitoring station""" set_of_rivers = set() #a set contains only unique elements so river names are not repeated for station in stations: set_of_rivers.add(station.river) #just adds river name to th...
ade71b4cf3f6d2f32748e01f8db56edf02d9fd06
625,508
import hashlib import os def sha1sum(filename, blocksize=65536): """Calculate the SHA1 hash of that file""" hasher = hashlib.sha1() if not os.path.exists(filename): return with open(filename, 'rb') as f: for block in iter(lambda: f.read(blocksize), b''): hasher.update(block...
f69d30df315b1ee2110ac5d430519880637ec3f5
625,509
def add_mask_if_none(f, clip, *a, **k): """ Add a mask to the clip if there is none. """ if clip.mask is None: clip = clip.add_mask() return f(clip, *a, **k)
bc277aaacf175299dd95856ecccb1b2476e52dfd
625,510
import torch def just_return_it(args, data, seed, size): """ Because the label in cifar dataset is int So here it will be transfered to a torch tensor """ return torch.tensor(data, dtype=torch.float)
0352d4ba8c2f09b61752e3785d21c8ed4749cdc2
625,511
from pathlib import Path def add_stem_suffix(p: Path, s: str) -> Path: """ eg. ("/path/to/file.ext","-suffix") -> ("/path/to/file-suffix.ext")""" return p.parent / Path(p.stem + s + p.suffix)
18f0741bb73bd77b4585b450d84bb9e6c54ebd13
625,512
def build_raw_github_url(state, datestring, raw_filename): """ Generate a URL to a raw result file hosted on GitHub Args: raw_filename: Raw filename of an election result file. Returns: String containing a URL to the raw result file on GitHub. """ tpl = "https://raw.githubuser...
784fe425b7e95946a23279cf232d606fc905724b
625,513
def compare_version(lhs, rhs): """Compare two versions. Parameters ---------- lhs : tuple tuple of three integers (major, minor, patch) rhs : tuple tuple of three integers (major, minor, patch) Returns ------- int Returns 0 if lhs and rhs are equal, 1 if lhs is bigger than rhs, otherwise...
fd61215efa578b31d4c14502b16b8793a3fa7a28
625,514
import torch def pair_wise_loss(x, y, delta_v = 0.5, delta_d = 1.5): """ :param x: [b, c] :param y: [b, c] :return: pair_wise_loss, float. """ b, c, _, _ = x.shape center = (x + y) / 2 # [b, c, 1, 1] # dist = 0.5 * ((x - center).norm(dim=1) + (y - center).norm(dim=1)) # loss = 0.5...
216ebf7d9062364cc516c6e132fc25a713706b7a
625,515
def default_to_list(value): """ Ensures non-list objects are add to a list for easy parsing. Args: value(object): value to be returned as is if it is a list or encapsulated in a list if not. """ if not isinstance(value, list) and value is not None: value = [value] el...
128709c0d999cd80d0009d4aec31c2ec34755493
625,516
def akon(data): """ AKON - Request data """ return data
a166fbab5dd4475f192ff168a6f24d1192bb2fd8
625,517
def _to_list(obj): """Make object into a list""" return [obj] if not isinstance(obj, list) else obj
acdc52335a4e536446d6d1ff7666ce8122f98011
625,518
import functools import time def timed(func): """ Time the execution of a wrapped function and print the output :param func: Function to be wrapped :return: function to be wrapped """ @functools.wraps(func) def wrap(*args, **kwargs): start = time.perf_counter() func(*args,...
3b85277f928064fed081165d5925b13f447e7860
625,520
def keepLargestInterval(intervals, keys=False): """ If keys=False, Intervals dictionary must have the following structure: intervals{strain: [genelist1], [genelist2], [genelist3], ... } Else, the structure must be intervals{strain: {ID1: [genelist1]}, {ID2:[genelist2]}, {ID3:[genelist3]}, ... }""" ...
f79232b10e1443dd9141df2aebdadb982e159747
625,521
def shorten_task_names(configs, common_task_prefix): """ Shorten the task names of the configs by remove the common task prefix. """ new_configs = [] for config in configs: config.task_name = config.task_name.replace(common_task_prefix, "") new_configs += [config] return new_conf...
b73ce8be7adece6da1f6ed218f3d78c52c5b1d94
625,522
def percentile(n): """Create function that calculates percentile for list""" return lambda xs: sorted(xs)[int(len(xs)*n)]
6760213cfd57e8d93948c4215bb0d7785a25860a
625,524
from typing import Set def _extract_args(input_str: str) -> Set[str]: """Extract the argument names from a string representation of a lambda function. Args: input_str: The string to be inspected. Something like 'x, opt=5:". Returns: The argument names from the `input_str`. Something like...
cdfe59dbee131490cb940560417b0202302d27f6
625,525
def _sanitize_jobname(jobname): """ e.g. '/dev/sdb' -> 'dev_sdb' """ jobname = jobname.replace("/", "_") if jobname.startswith("_dev_"): jobname = jobname[5:] return jobname
f30f47e9f5d2d5ab10e52d4ad9b6947ca374836c
625,526
import logging def get_by_uid(api, uid): # type (ApiClient, str) -> dict(str) """Get a user by uid Args: api: the ApiClient instance to use for requests uid: uid to fetch Returns: a Lumapps Feed instance """ logging.info("getting user by uid %s", uid) result = api...
000ee8ca261563aa5ac8f36d2ba974b385436669
625,527
from typing import Sequence from typing import Any from typing import Tuple from typing import Optional def validate_provided_image_paths(image_paths: Sequence[Any]) -> Tuple[Optional[str], bool]: """Given a list of image_paths (list length at least 1), validate them and determine if metadata is available. ...
b50f9114d9f940943f61f4b8f85e0125673769c2
625,529
def get_sequence_keys(directory): """Recursively get all key sequences of a dict. :param dictionary: dict object for which key sequences will be extracted :return: list containing all key sequences. """ keys_paths = [] def get_files(directory, prefix=[]): if type(directory) is dict: ...
e525ccff56d168467d2e3ab39b7198ced93623b7
625,530
from typing import Union from typing import Optional from datetime import datetime def epoch_to_timestamp(epoch: Union[int, str]) -> Optional[str]: """Converts epoch timestamp to a string. Args: epoch: Time to convert Returns: A formatted string if succeeded. if not, returns None. ""...
910049acef550f638d5d8bcb50a21209fd5fff30
625,531
def parse_timestamp(my_dt): """ Param my_dt (datetime.datetime) like status.created_at Converts datetime to string, formatted for Google BigQuery as YYYY-MM-DD HH:MM[:SS[.SSSSSS]] """ return my_dt.strftime("%Y-%m-%d %H:%M:%S")
439e446bb6ac0ef0b7f3a49bb333868304cbb4b8
625,532
def get_supported_pollutants_dict(): """ Return the dict that maps the supported-pollutants numeric notations and their associated textual notations. Returns ---------- dict Notes ---------- While each pollutant has a different numeric notation, there are pollutants that have the same ...
b7e7332529479af0354c0552ace30c2851c6a470
625,534
def chooseHighestFromTuple(arr): """ Pick the id of the highest element of a list of tuples of the form (id, key), where they key determines which value is the highest :param arr: The array of elements :return: A tuple of the form (id, key) of the element with the highest key """ high = ...
58a0a8606149dd8ba579d663ed6451f2fabb9bd0
625,535
def replace_string(metadata, field, from_str, to_str): """Replace part of a string in given metadata field""" new = None if from_str in metadata[field]: new = metadata[field].replace(from_str, to_str) return new
8ab2a22bd6623217deda59d54044c6bdfa9a3d21
625,536
def mean_clone_size_fit(times, rlam): """For the single progenitor models (for progenitor cells only)""" return 1+rlam*times
9bd0a313f95c25696152b0af0ff3c7dd3fcb3e2d
625,537
def great_circle_pole_pts(lon_p, lat_p): """Find two orthogonal points on the great circle from its polar axis. Parameters ---------- lon_p: float Polar axis west longitude (degree). lat_p: float Polar axis latitude (degree). Returns ------- float West longitude...
fc479bc75a623ff752b19e24fe164d885c3d251e
625,538
import random def partition(nums, left, right): """ function partition(a, left, right, pivotIndex) pivotValue := a[pivotIndex] swap(a[pivotIndex], a[right]) // 把pivot移到結尾 storeIndex := left for i from left to right-1 if a[i] <= pivotValue swap(a[storeIndex], a[i]) ...
31a93eb8a15a684f466a1724a5566b9186e0381a
625,539
def _mkUniq(collection, candidate, ignorcase = False, postfix = None): """ Repeatedly changes `candidate` so that it is not found in the `collection`. Useful when choosing a unique column name to add to a data frame. """ if ignorcase: col_cmp = [i.lower() for i in collection] can_cmp...
6c9d840104b91134ac8a623e3ed85aad967e6a65
625,543
def _assertable(queryset, list_item='name'): """ From a Django queryset return a list of one attribute that can be passed to an assert statement. The default model attribute to compare is name. :param django.db.models.query.QuerySet queryset: :returns: A list of the specified attrributes from each ...
9cd93aff431e3ea9779b228b3319b1891df726a3
625,544
def tokens_to_indexes(data_csv, tokenizer): """Convers tokens to indexes using bms.Tokenizer.""" data_csv['Tokens_indexes'] = \ data_csv['Tokens'].progress_apply(tokenizer.text_to_sequence) data_csv['Tokens_len'] = data_csv['Tokens_indexes'].apply(len) return data_csv
41595cbe745ef84a74203181cb0b9194ea8c15c7
625,545
def complex_mul(Ar, Ai, Br, Bi, conjugate_a=False, conjugate_b=False): """ C = A * B """ if conjugate_a: Ai = Ai.neg() if conjugate_b: Bi = Bi.neg() Cr = Ar.mul(Br) - Ai.mul(Bi) Ci = Ai.mul(Br) + Ar.mul(Bi) return Cr, Ci
646218dc7ce06b6adddd0b4d0393e207c67d02df
625,546
import torch def create_loss_function(loss_name): """ Create a loss function from its name by creating a wrapper to the corresponding torch.nn.functional function (e.g. torch.nn.functional.mse_loss for 'MSE') and preparing the targets if necessary. Args: loss_name: The name of the loss functi...
4e6ef2b4d7dd3c5ad1142e987252826adaaccc4b
625,548
def generate_config(context): """ Entry point for the deployment resources. """ project_id = context.env['project'] policy_get_name = 'get-iam-policy-{}'.format(project_id) policy_add_name = 'add-iam-policy-{}'.format(project_id) policy_remove_name = 'remove-iam-policy-{}'.format(project_id) p...
f33b64d2d5bb00eb67dd7860e8d51d8e85893bef
625,549
from bs4 import BeautifulSoup def __parsePageFilings(page_parsed: BeautifulSoup) -> list: """Function to extract filings from a parsed HTML EDGAR listings page. Arguments: page_parsed {BeautifulSoup} -- Parsed HTML for filing extraction. Returns: list -- Structured list of dictio...
1f533d3a1bfce1a543aaf1d5a74075b213356f02
625,551
def webUrlsPool(page_num): """ 根据得到的网页总数,构造并返回所有符合搜索标准的网页url列表 params: page_num:根据初始url获得的网页页数 """ pageUrls = [] page_num = int(page_num) for i in range(1,page_num + 1): url = 'https://search.51job.com/list/070300%252C020000,000000,0000,00,9,99,%25E6%2595%25B0%25E5%25AD%2597%...
e1ddd42d28b17c5ca463e9d3aa3b5b2ee883467c
625,552
import sys def calculate_coverage(geneloc, fmins, fmaxes): """ This is to report the percent coverage of a gene on its ends due to partial matches to two different assembly contigs. Since each end could map to more than on contig, only the longest match on each end is considered. """ gene...
2785188df1efbe91e4dadbdc08dcc71402c31bc0
625,553
def convert_process(x): """ Converts process column in wikipedia transistor count table to numeric. """ # NANs are floats if isinstance(x, float): return x else: return x.replace('nm', '').replace(',', '').strip()
2bd43bdd1b952602087ee74aaf9ef11179ec06ac
625,554
import ntpath def _get_file_name(file_path): """ :param file_path: File name including path. :type file_path: str :return: File name. :rtype: str """ file_name = ntpath.basename(file_path) return file_name
56908f433655157b54f82f3ba225e3dd6d998617
625,555
import re def read_fb_file(fb_fname): """Return the total number of simulations covered by the folder from a fb file. The actual simulation is written by Matlab. The first part of the simulation code is to provide the total number of simulations the code will calculate. The function read the outp...
9d7b2da89f548809a3927cfb79d70ce0525832b1
625,556
def _parse_cudklys_table(table): """ Right now we basically just want a list of device names, eventually this might actually do something useful. """ splits = [row.split() for row in table] return {'CUDKLYS:LI{0}:{1}'.format(ele_name[3:5], ele_name[6:8]): 0 for (_, ele_name, _, _, _, _, _) in s...
69213a834d8fa799b34f966b83f614c39721e20b
625,557
import sys def is_linux(): """ Check if the system is linux. :return: True if the system is linux. """ return sys.platform.lower().startswith('linux')
2784b2e17b8982df0bdcfdf7660b55fbb4b4396e
625,558
def fusion (dict_base,dict_suite) : """ Cette fonction prend deux dictionnaire, ajoute tout les élément du deuxième a la fin du premier sauf si l'élément est déjà présent """ for res in dict_suite["results"]: dict_base["results"].append(res) dict_final=dict_base.copy() return dict_final
e47ff8ae3ebd30801575bbe34b0d2b846a4c58d5
625,559
def get_file_contents(file_path): """Return a string containing the file contents of the file located at the specified file path """ with open(file_path, encoding="utf-8") as f: file_contents = f.read() return file_contents
4e00422c05de3b90e3457b8d468514957c28b5f3
625,560
from datetime import datetime def get_timestamp_str(): """ Get a string containing current time stamp. """ now = datetime.now() date_time = now.strftime("%Y-%m-%d_%H-%M-%S") timestamp = date_time return timestamp
6499758cca2234abf252dfd2a20cbfc87bfde38f
625,561
def get_disp(localqc_table, regions, bg=1): """ Find localQC bins for each region :param localqc_table: Table of localQC regions :param regions: List dictionary of regions :param bg: Background threshold :return: """ # Group regions by chromosome regions_chrm =...
71da467c21bef08e97ce5060b27eb7825a6711e8
625,562
def find_faces_at_index(layer_qs, coord_val, index): """Find all the faces that intersect `coord_val` along `index` Example Slice a list of faces along the x-axis so that you can tell where to fill the shape in, by drawing lines across the polygon. """ return [face for face_q in layer_qs for fa...
da2e4c24da0dde66b6c40b0ff552840995b3a51e
625,565
def is_password_parameter(data_model, source_type: str, parameter: str) -> bool: """Return whether the parameter of the source type is a password.""" # If the parameter key can't be found (this can happen when the parameter is removed from the data model), # err on the safe side and assume it was a password...
60694ef889f9f2ed7afe069196391beab15dd6d8
625,566