content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import hmac def is_valid_digest(hash_a: str, hash_b: str) -> bool: """Compares two hashes using `hmac.compare_digest`.""" return hmac.compare_digest(hash_a, hash_b)
e2901c596761c6a221d60aaee1d32e8abd0fad42
627,962
def all_visible_subclasses(klass): """ Returns all reachable subclasses of the supplied class, presumably a BaseModel subclass. """ def helper(klas, result): subklases = klas.__subclasses__() if len(subklases) > 0: result.update(subklases) for subklas in subklase...
a12464d35ec824ab94371020f4527b3ac912c4e9
627,963
def binomial_coeff(n, k): """Compute the binomial coefficient "n choose k". n: number of trials k: number of successes returns: int """ # Just put all three return possibilities into one statement. Could use parentheses if it # seems clearer. return 1 if k==0 else 0 if n==0 else binomi...
50f2c319a4ba316d43bb37cf8fc65df31d6dbb1b
627,964
def upper_repl(match): """ Convert mask-special tokens to real special tokens """ return " [" + match.group(1).upper().replace('-', '_') + "] "
91e359e85195aa6b586681fcfde3839008414493
627,965
def max_area(height): """ Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container ...
a6110253ae6cad5042bfda600d86fea101d64edc
627,966
def acroname(name): """ Returns a three letter acronym given a podcast title """ if not len(name): return name # return empty string right back word_list = name.split() # first, trim npr label from some podcasts if 'NPR' == word_list[0]: word_list = word_list[1:] if name.star...
dcd27ac058a0a9bdc70200d99194fdbee9563d05
627,967
def to_camel_case(source: str) -> str: """Converts the specified source string from snake_case to camelCase.""" parts = source.split("_") prefix = parts.pop(0) suffix = "".join([p.capitalize() for p in parts]) return f"{prefix}{suffix}"
b3a9345265bf0b9de6667edb4402b59a6a46da81
627,969
def cast(x, dtype=None): """ Casts a tensor to a new type. Parameters ---------- x : tensor A Tensor or SparseTensor or IndexedSlices of numeric type. It could be uint8, uint16, uint32, uint64, int8, int16, int32, int64, float16, float32, float64. dtype : dtpye The dest...
51808a09dea94772a367ecfb9c86f838356303df
627,970
def fullscan_policy(obs): """ A policy function that generates only fullscan data. """ valid_actions = obs['valid_actions'] ms1_action = len(valid_actions) - 1 # last index is always the action for MS1 scan return ms1_action
39172e8a421d485d790c01c14407a623026d5422
627,971
def az_to_phi(az): """Transforms azimuth (angle from north towards east) to phi (angle from x-axis towards y-axis) for simtel array coordinate systems Parameters: ----------- az: float Returns: -------- ...
817c2a3f583f6ab3d3a258e056c639cad3a24d54
627,972
def pair_interactions(x): """Pair interacting nodes""" split_line = x.split() pair = "{0}_{1}".format(split_line[0], split_line[3]) return pair
6be7c03bf070b01f20ba183f9a7e89029717c497
627,973
from typing import List import shlex def split_run_args(command: str) -> List[str]: """Splits a shell command string into arguments.""" return shlex.split(command)
30ba93669684e69a03a84031bb4a7ca0a5cb4963
627,974
def _generate_struct_header(ctx, metadata, encryption): """Transpile XLS IR into C++ source.""" library_name = ctx.attr.library_name or ctx.label.name generic_struct_h = ctx.actions.declare_file("%s.generic.types.h" % library_name) specific_struct_h = ctx.actions.declare_file("%s.types.h" % library_name...
25e2c0a621ba6288e3363c9405303bb658f0c266
627,975
import six def _cell(item, column, key, fmt): """Constructs a value in table cell.""" if key is None: key = column if isinstance(key, six.string_types): keys = [key] else: keys = key raw_value = None for k in keys: if k in item and item[k] is not None: ...
4b26276eeb9e5550ebaeb643b7fb5f30ca55e0e1
627,976
import requests def get_K2_campaign_fov(): """ K2 campaign FOV footprint in json format Source: https://keplerscience.arc.nasa.gov/k2-fields.html """ url = "https://raw.githubusercontent.com/KeplerGO/K2FootprintFiles/master/json/k2-footprint.json" footprint_dict = requests.get(url).json() ...
f79df5b07882226ef3de9a88437a6272feaedb58
627,977
def without_empty_values(iterable): """Return a copy of ``iterable`` with all ``empty`` entries removed. """ try: return {k: v for k, v in iterable.items() if (hasattr(v, "__len__") and len(v) > 0) or not hasattr(v, "__len__")} except AttributeError: return type(iterable)((v for v in ite...
cca8edea9666bb02c3e1b2a4953c392ba00b4f1b
627,978
import os def file_is_image(filename) -> bool: """ Tests whether a filename corresponds to a supported image (jpg, jpeg, ico, png, gif). File suffix is used (i.e. no content analysis is performed). arguments: filename -- filename or a path returns: True if file is image else False ""...
431f13956e816f212b42fbe19de63cc2c56094fa
627,979
def epoch(x_train, y_train, x_test, y_test, clf): """Results for a single epoch""" clf.fit(x_train, y_train) train_loss = clf.loss_ train_err = 1.0 - clf.score(x_train, y_train) val_err = 1.0 - clf.score(x_test, y_test) clf.warm_start = True return [train_loss, train_err, val_err]
a8d918b247034827153de0ef411989dec3d18b97
627,980
def file_key(entry): """ For a PlaylistEntry, return a path. """ if entry.remote: return entry.remote.path return entry.path
aafc3772a8b327f6e5d23195691ecdddd6186f86
627,981
import pathlib import yaml def read_yaml_data(data_filename: str, names=None) -> dict: """Read in a YAML data file as a dictionary""" data_path = pathlib.Path(data_filename) try: with data_path.open('r', encoding='utf-8') as fp: yaml_data = yaml.safe_load(fp) except FileNotFoundErr...
7614df406f673caee9e13517fb2eaf410750bbfd
627,982
def filter_folder_path(path): """ This function will filter out \\..\\ or \\ at the begining. Also if path becomes empty, . will be used """ local_search_path = path local_search_path = local_search_path.replace('\\..\\', '\\') local_search_path = local_search_path.replace('/../', '/') if local_sear...
ccc228f5160b6dd7bcf9cc4478635edd8feddef4
627,983
import math def prime_check(num): """ Checks if a single number is prime. A simple function, not a speedy solution. """ if num == 1: return False upper_bound = int(math.sqrt(num) + 1) for n in range(2, upper_bound): if num % n == 0: return False return True
bad4e607392bf5030f65202ff7f252f0391123d7
627,984
import re def filter_subs(subs, pattern): """Returns a list of subtitles who's text contains the given regex pattern""" ret = [] for sub in subs: if re.search(pattern, sub.text, re.MULTILINE): ret.append(sub) return ret
aee3b85323daeffcdbe2795c35640b24be7e499f
627,985
def get_ids_from_individual(individual): """Gets the ids from a given individual Args: individual (CPPN): The individual to get the ids from. Returns: tuple: (inputs, outputs, connections) the ids of the CPPN's nodes """ inputs = [n.id for n in individual.input_nodes()] outputs...
587d3a0f031bdb113676a65892b3027b7567a436
627,986
def _get_conv_shape_1axis( image_shape, kernel_shape, border_mode, subsample, dilation=1 ): """This function compute the output shape of convolution operation. Copied and simplified from theano (2020/11/08): https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/abstract_conv.py Parameters ...
dac0c8b6fa10c85698601457dca59e858e057c61
627,987
def get_gaze_point_mm(limbus): """ Returns intersection with z-plane of optical axis vector (mm) """ # Ray-plane intersection x0, y0, z0 = limbus.center_mm dx, dy, dz = limbus.normal t = -z0 / dz x_screen_mm, y_screen_mm = x0 + dx * t, y0 + dy * t return x_screen_mm, y_screen...
adbab3ded16cbe4a9d469b7eaaf6c0c7481ed61f
627,988
def clean_data(keys, data, default="-"): """ cleans the data in order to archive the correct format Args: data: keys: (list) default: (any character) Example: >>> clean_data([{'keybla': 1}, {'keybums': 2}], ['keybla', 'keybums']) ... = {'keybla': 1, 'keybums': de...
26f7ac064146ebcf9be641389b54d56a21946335
627,989
import os def cmd_exists(cmd): """ Given a command name, checks to see if it exists on the system, return True or False """ return os.system("type " + str(cmd)) == 0
f1826b20fe3b96a56633891aaee7e6d38553e49c
627,990
def data_reordering_identical(dfModIndex_to_order, dfSummaries_to_order, dfIsDisc_to_order, dfTimes_to_order, dfSummaries_ordered): """ Reordering of the reference table columns according to the order of a second one. This function reorders the columns of the simulated data (s...
7b217cf69f3b358013fbc93a7b5792e365925335
627,991
def get_input_from_kvp(datainputs): """Get execute DataInputs from URL (key-value-pairs) encoding """ inputs = {} if datainputs: for inpt in datainputs.split(";"): (identifier, val) = inpt.split("=") # add input to Inputs inputs[identifier] = val retur...
d1ae77a97bd70d183f9d914d2933b2b6e38fa779
627,992
def end_of_string_doc(editor, start_line): """ Find where a docstring ends, beginning with `start_line` and working forward """ for i in range(start_line, len(editor.lines)): if editor.lines[i].endswith(('"""', "'''")): return i return None
7151f35fd7004e6233065c37a66cd699c87c7c60
627,993
def oppgaver_med_feil(data): """Sammenligner avgitt svar med riktig svar returnerer liste med indeksene til svarene som er feil. Parameters ---------- data : list En list med dictionarys Returns ------- list En list med indeksene til de spørsmålene som er besvart feil. ...
52c762cd34f4f402a2bc7e16e6daa5353ab03ce8
627,996
def dict_to_str(d, val_sep=' ', item_sep=' '): """Convert dict to string""" str_list = [f'{k}{val_sep}{v}' for k, v in d.items()] s = item_sep.join(str_list) return s
69631f17a9c07659d1cbdc70c3b397710fb0b58f
627,997
def identity(x): """Identity function: return the given argument unchanged""" return x
bfd4adbffcc67512e22396957a92fa31de727e8e
627,998
def comment_prep(content): """ Prepares the comment so we can have sme basic context. """ # same comment structure, so we'll just do it in a function text = "Imgur link: " + content text += "\n\n\n------\n" text += "This action was performed by a bot. Message +/u/arrivance for further deta...
01f606ce3a9fcf389e8c75cbdc66335dfd17a5e0
627,999
def _normalize_integer_rgb(value): """ Normalize ``value`` for use in an integer ``rgb()`` triplet, as follows: * If ``value`` is less than 0, convert to 0. * If ``value`` is greater than 255, convert to 255. Examples: >>> _normalize_integer_rgb(0) 0 >>> _normalize_integer_rg...
48204a8af4c345c5599e563a84d2a1a2d129de79
628,000
def to_unicode(obj): """ Convert the input Byte string to a Unicode string. The input object must be a Byte string. """ return obj.decode("utf-8")
8752f48600f7454fe0b4b1d4f7923bc93218c1f2
628,002
def check_enum(val, candidates, name): """ Checks the specified val is in the specified candidates. """ if val not in candidates: message = \ "{0} can not be used for {1}. " \ "Available values are {2}." \ .format(val, name, candidates) raise ValueErro...
b18c88206f2207f82bb0e1a408ff40eaa343b170
628,003
async def leave_comment(gh, issue_comment_url: str, message: str, token: str): """ Leave comment in issue or pull request :param gh: object with actions :param issue_comment_url: api string :param message: comment :param token: GitHub token :return: response """ data = {'body': messa...
cdcddeaef04cf3667cc861d44bd69180a8e49b34
628,004
import re def is_sudoku_option(value: str) -> bool: """validate the number is a integer between 1-9""" return bool(re.match(r"^[1-9]$", value))
e9f6c53c00d02f9ffa6c7ab2fac5a4812db3f38a
628,005
def get_partial_index(df, start=None, end=None): """Get partial time index according to start and end Parameters ---------- df: pd.DatFrame or pd.Series start: str, optional, e.g., '2000-01-01' end: str, optional, e.g., '2017-08-31' Returns ------- pd.DatetimeIndex """ if s...
17b2426ae29eb5ba9a10a1d672bc9b954c69f504
628,006
import time def timing(func): """ Function decorator for timing a function, not good for recursion. """ def wrap(*args): time1 = time.time() ret = func(*args) time2 = time.time() dbg = func.func_name, (time2 - time1) * 1000.0 print("%s function took %0.3f ms" % ...
f613db3c5981041a9b7afb10bd6479c52488c450
628,007
import re from functools import reduce def template_render(template, model): """ A simple template render. Example: >>> model = { ... "name": "lyc", ... "foo": { ... "bar": "hello" ... } ... } >>> template = "{{foo.bar}} {{ name }}" >>> template_render(t...
26ace34be309d29c567aaa76aa043c02cf96e72a
628,008
import string def remove_punct(user_input): """The remove_punct function gets rid of all punctuation from the string. Parameters ---------- user_input : string Input received from user Returns ------- output_list : string User's input with removed punctuation "...
d0dd09294436e076f376f15f4030d4d49838fcdd
628,009
import os def prepend_home_dir(filename): """ Prepends the home directory to the given filename if it doesn't already contain some kind of directory path. """ return os.path.join(os.environ['HOME'], '.ssh', filename) if '/' not in filename else filename
f39deacf66498f83b182db2d07c9f00c4458b883
628,011
import os def get_external_ip(): """ It get current external IP address """ return os.environ.get('SHIP_EXTERNAL_IP', '')
92c3cb8fb79312b2de2a64840b04c05121d7d5e4
628,012
import sys def get_module(name): """Get a module by its name. If it's not already loaded, it imports it. """ if name not in sys.modules: try: __import__(name) except ImportError: pass return sys.modules.get(name)
f703c51ce65d6a8cca49f1be1d18b52625a6ef0c
628,013
def list_validator(lens=[]): """[summary] This method used to chek the input list sould have 9 elements This method is only for saftey check purpose. Args: lens (list, optional): [input element list]. Defaults to []. Returns: [Boolean]: [True or False] """ return Tru...
0b78af04cf3791a55dc72b3c31e69f8fc744854a
628,014
import math def primes_list(lower, upper): """Problem 39: A list of prime numbers Parameters ---------- lower : int The lower bound of the prime numbers to return upper : int The upper bound of the prime numbers ro return Returns ------- list of int A list of ...
2b668af4e86f6131ec93e4a694b6bdc0579a4a5d
628,015
def describe_nunique(df): """ describe method including nunique for numeric descriptions """ df_described = df.describe(include='number').T df_described['unique'] = df.select_dtypes(include='number').nunique() return df_described[['count', 'unique', 'mean', 'std', 'min', 'max', '25%', '50%', '75...
b4a8da079f8897a2eef99d80b501262ae1e62cf4
628,016
import re def clean_html(text): """ Remove html tags from text and convert a small set of html-encoded symbols :param text: string with html markup :return: text without html markup """ if text: clean_text = re.sub('<[^<]+?>', ' ', text) clean_text = clean_text.strip() ...
52db990dfe5abdb5be28aa9ede0025fd4413dd89
628,017
def get_surrounding_text(text, sub_start, sub_end=None, distance=25): """ Looks for the substrings, 'sub_start' and 'sub_end' variables in 'text' and return a new substring with a number equal to 'distance' characters in the left of 'sub_start' position and in the right of 'sub_end' position if they exi...
c5ad4a80940260ca591b7974ef9a37441140be78
628,018
def drop_systematics(blocks, systematics): """Drop a systematic from a set of blocks. Parameters ---------- blocks : list(str) All TRExFitter blocks. systematics : list(str) Name of the systematic to drop. Returns ------- list(str) Blocks without desired systema...
9dcc86d39fdc8a4a7deb583d4d4afd25cc5e620b
628,019
def pg_version(conn): """ Returns the PostgreSQL server version as numeric and full version. """ num_version = conn.get_pg_version() conn.execute("SELECT version()") full_version = list(conn.get_rows())[0]['version'] return dict(numeric=num_version, full=full_version)
18e1dd309ea1aa08cb53eef994402668cca16d04
628,020
def list_large_age_diff(gedcom): """ US34: List all couples who were married when the older spouse was more than twice as old as the younger spouse """ age_diff = [] for family in gedcom.families: husband = gedcom.individual_with_id(family.husband_id) wife = gedcom.individual_wit...
8229c7d723ad437f06b257f448238c8b6beca453
628,022
def session_status(connection): """Checks Intelligence Server session status. Args: connection: MicroStrategy REST API connection object Returns: Complete HTTP response object. """ response = connection.session.get(url=connection.base_url + '/api/sessions', ...
f70355a5b81c29115a0725fa5a746accf7eadfb4
628,023
def iseven(x): """is the number x an even number?""" return x%2 == 0
5700285b86d2a9d62cc444f752ae5d959c982aba
628,024
import re def normalize(name: str) -> str: """일러 이름 정규화 Arg: name(str): 일러 이름. 경로와 확장자 없어야함 Return: name(str): 깔끔하게 바뀐 일러이름. """ return re.sub("^Pic_", "pic_", name)
cd377c3f1a0e274868020451645fcd422200ffe9
628,025
def get_problem(): """Specifies a problem to run TF-Coder on. Edit this function!""" # A dict mapping input variable names to input tensors. inputs = { 'rows': [10, 20, 30], 'cols': [1, 2, 3, 4], } # The single desired output tensor. output = [[11, 12, 13, 14], [21, 22, 23, 24], ...
1ac03d2df8fc6f0a749e016762b64e5e92d9c128
628,027
import os def get_verification_dir(sim_root): """ Gets the folder for data used for verification etc. """ return os.path.join(sim_root, "verification")
b3c92b0b920e09f3957688519d481446f1221de2
628,028
def getValueTryRemoveTailZero(float_num): """ try to remove .0 from an float number, 2.00 -> 2 keep other float as it was, 2.02 -> 2.02 :param float float_num :return float/int """ int_num = int(float_num) if int_num == float_num: return int_num return float_...
aef0ced52fa74236760ccc54996e59fea086f292
628,029
def merge_value_range_fields(nmdc_objs: list, tx_attributes: list, **kwargs) -> list: """ Takes each nmdc object (either a dict or class instance) and merges two attributues into a single attribute separated by a "-". Additionaly, the has_minuimum_numeric_value and has_maximum_numeric_value attrubut...
c201a79fbdf75e4dacebbe101b33f4d327f81c3b
628,030
def factorial_2(n, acc=1): """ Stuff in loop """ while True: if n < 2: return 1 * acc return factorial_2(n - 1, acc * n) break
1aabe36033b61b839d68057b0f516723fd774796
628,031
def nan2zero(data): """ Replace NaNs and negative values by zeros """ return [val if val>0 else 0 for val in data]
066e16ebd5c4c3fa827f84d5b89901da03eea241
628,032
def plot_kwargs(kwargs): """ Specializes proc_kwargs for plots. """ plt_args = {'alpha': None, 'color': None, 'linestyle': None, 'linewidth': None, 'marker': None, 'markersize': None, 'label': None ...
1b951424ff6a583b15414c5deafc7223f04801ea
628,033
import re def flatMapFunc(document): """ document[0] is the document ID (distinct for each document) document[1] is a string of all text in that document You will need to modify this code. """ documentID = document[0] words = re.findall(r"\w+", document[1]) return [(f'{v} {documentID}...
b4d259109f566f895d47e0cb0a72d2d5f220bfc1
628,034
def validate_ipv4_addr(ipstring): """Ensure that string is a valid IPv4 address in decimal.""" pieces = ipstring.split('.') if len(pieces) != 4: return False try: return all(0<=int(p)<256 for p in pieces) except ValueError: return False
3cbfe322ef7c66ee95b0b17e7bcda566295014c2
628,035
def render_sunset(data, query, local_time_of): """sunset (s) Local time of sunset""" return local_time_of("sunset")
9a19d3693556d545ed99af757203f2fad8abb0a6
628,036
def to_dojo_data(items, identifier='id', num_rows=None): """Return the data as the dojo.data API defines. The dojo.data API expects the data like so: {identifier:"whatever", items: [ {name:"Lenin", id:3, ....}, ] } The identifier is optional. """ ret = {'items':items} ...
dab7fda1cf2ae577c71dba38d38f1f591ad0431b
628,037
from collections import defaultdict def convert_tab_to_dict(response): """Convert tab response to dictionary.\n Response is a string made of rows with two tab separated columns.""" if not type(response) == type("hola"): print("The argument is not a string.") return {} result = default...
b402b2104933e24aad3ec5bbda5efa608bf48c49
628,038
def next_word_plus_register_value(c, code): """[next word + register]""" v = "c.m[0x%04X + c.r[0x%01X]]" % (c.m[c.pc], code-0x0F) c.pc += 1 return v
d4f2fb4cb12e88ddb09036d3711b4891b0be6506
628,039
def clean_release_name(name): """Strip dirty characters out of release names. The API will match against clean names.""" chars = ['#', '@', '$', '%', '^', '§', '¨', '©', 'Ö'] for c in chars: name = name.replace(c, '') return name.replace('_', ' ').replace('.', ' ').replace('-', ' ')
f7e7ed652492c155e5ca3713dba335daa5d5f0b3
628,040
def _get_member_groups(get_member_group_func, identifier, security_enabled_only): """Call 'directoryObject: getMemberGroups' API with specified get_member_group_func. https://docs.microsoft.com/en-us/graph/api/directoryobject-getmembergroups """ body = { "securityEnabledOnly": security_enabled_o...
72491f91382439120079d39cab881b1b51707488
628,041
def model_to_dict(instance, fields=None, exclude=None): """ Return a dict containing the data in instance. This differs from django.forms.model_to_dict by containing non-editable fields and relation values being the related objects instead of pk of those objects. :param instance: Model instanc...
bf08b6eead47ede0923c76ac984219490f44dc91
628,042
import sys def weighted_median(a, weights): """Weighted median of a 1-D numeric array.""" order = a.argsort() a = a[order] weights = weights[order] midpoint = 0.5 * weights.sum() if (weights > midpoint).any(): # Any point with the majority of total weight must be the median ret...
d1d9d615067742ba6381f5a90c3981bd8682ea26
628,043
import hashlib def key_to_md5(key): """ convert bibtex-key to shortened md5-sum to avoid special characters in the keys :param key: bibtex-key of an article :return: converted key, first six characters of the key md5-sum """ m = hashlib.md5() m.update(key.encode('utf-8')) hd = m.hexdig...
be1c3e592a5dfccd481c9223c468c0416d2fc664
628,044
def get_num_common_grams(delete, insert, q=5): """ Returns the number of common words in given delete and given insert.""" delete_grams_freqs = delete.get_q_grams_freq(q) insert_grams_freqs = insert.get_q_grams_freq(q) common_grams_freqs = delete_grams_freqs & insert_grams_freqs return sum(common_gr...
34390c776e90ab249e4db659e1284d6d08e0cf93
628,046
import random def generate_shuffle(dic): """ Given a dictionary, shuffle the keys """ keys = list(dic.keys()) return (random.sample(keys, len(keys)))
02a621426936f8b389bf0faf4d1062d97a63d0c9
628,047
from typing import Dict from typing import Optional def local_paths_from_manifest_item( item: Dict, imgs_s3key_prefix: str, textract_s3key_prefix: Optional[str] = None, imgs_local_prefix=None, textract_local_prefix=None, ) -> Dict: """Translate Textract+image manifest S3 URIs to local paths ...
4b2cbe37f2255f371fccb9dab4fa741afa876e3f
628,048
def dic_partiel(n): """retourne un dictionnaire partiel de mot de taille n correctement parenthese""" if n <= 0: return [""] elif n == 1: return ["()"] sub_list = dic_partiel(n-1) new_list = [] for word in sub_list: new_list.append(word + "()") new_list.append("(...
f2e9bed41f7dd49975ae5eb81edb132f661d8e31
628,049
def unbreakable_input(): """ Ignore keyboard interrupts and return value (used in configuration dialog) """ while True: try: data = input() except KeyboardInterrupt: continue break return data
77e2ad57f29edc544d59e0e04fe699bd43f88c43
628,050
def url(host, port): """ Return the URL where the server can be reached. """ return 'wss://{}:{}'.format(host, port)
5f6c51c218a376b3868ecea9f86256eb146b34bc
628,051
def extract_argument(arguments, prefix, remove=True): """Extract argument from arguments.""" for argument in arguments[:]: if argument.startswith(prefix): if remove: arguments.remove(argument) return argument[len(prefix):] return None
06084be10e21fce2817d0189418a2307b6ae85f7
628,052
import numpy as np def hash_collision_probability(a, h, g): """ Compute probability of hash collision for signed random projects (aka SimHash) See: Similarity Estimation Techniques from Rounding Algorithms (Charikar 2002) Args: a: Cosine similarity (pearson correlation) between vectors/data p...
36bd99733fdd986c468cc3875b497317d5d43adc
628,053
import argparse def parser(): """Parse arguments and set configuration parameters.""" parser = argparse.ArgumentParser( description="Relocate duration datasets" ) parser.add_argument( "--root-path", default=None, type=str, required=True, help="Root direc...
6d4c913e9a5495f0c59f00c5059e963c96f80103
628,054
def aiolib(request): """Support asyncio only. Disable uvloop on tests it brokes breakpoints.""" return request.param
277d5572a1ca014d73995983dabff41ee44b1b29
628,055
import torch def collate_fn(batch): """ Dataloader中会用到这个函数 用来整理这个批次中每张图像中对应的object的数量 """ imgs, labels, paths, sizes = zip(*batch) batch_size = len(labels) imgs = torch.stack(imgs, 0) max_box_len = max([l.shape[0] for l in labels]) labels = [torch.from_numpy(l) for l in labels] fil...
fc870ff8f9209187d6109776585555c42a21ded8
628,056
import random def random_ip(*args): """ :return: """ return ".".join(map(str, (random.randint(0, 255) for _ in range(4))))
2e527d377d004292784c77d42788b791893ff434
628,057
def get_error_messages( response ): """ Builds a string based on the error messages in the payload Args: response: The response to print Returns: The string containing error messages """ # Pull out the error payload and the messages out_string = response.dict["error"]["mes...
2104ee4a243b3a778d53b5129885d74dfd8f9d01
628,058
import os def readAndDeleteFile(fileName): """ read data from file provided, and delete it when done return the contents as a string """ res = '' with open(fileName,'r') as f: res = f.read() os.remove(fileName) return res
a2c870bc164c7ac3321b2700183b061e38fc8cb8
628,059
import click def provision_with_option(func): """Add a provision-with option.""" return click.option('--provision-with', metavar='PROVISIONER', help='Specific provisioner to run on the machine.', default=None)(func)
73d360c6574124e67f35ed64df72631a35c411fc
628,060
def _add_markers(figure_data, molecules, plot_type="scatter3d"): """ Add markers on the plot graph. :params figure_data: the graph data :params molecules: list of selected molecules :params plot_type: plot type (scatter3d, histogram2d, scatter) :returns: plotly graph trace list """ dru...
8930960fe3c4212c315a3236dede9e4665d127bc
628,062
def make_svtStatus(svt, mstSvtLimit, spoiler=False): """ サーヴァントのステータスを作成 """ hp = [s["hpMax"] for s in mstSvtLimit if s["svtId"] == svt["id"] and s["limitCount"] == 4][0] atk = [s["atkMax"] for s in mstSvtLimit if s["svtId"] == svt["id"] and s["limitCount"] ...
aaa96634d75bea3ee957c4642741a6a6c0e6fab4
628,063
def subtract(a, b): """Calculates the subtraction of b from a. :param a: The first operand of the subtraction. :param b: The second operand of the subtraction. """ return a - b
6b453eff9fc4b32922cd1155ec8d62d0bcc9c804
628,064
def centerpoint(geolocations): """ :param geolocations: array of arrays in the form of [[longitude, latitude],[longitude,latitude]] :return: average latitude and longitude in the form [latitude, longitude] """ lats = [] lngs = [] for lon, lat in geolocations: lats.append(lat) ...
0e236080c31a51ba919ffb2fb25fc2c3062c6807
628,065
def _check_lesson_is_empty(parsed_lesson): """ Checking lesson for being empty Args: parsed_lesson (dict): Parsed lesson Return: bool: True if parsed_lesson['info'] have any content except whitespaces, else False """ return not parsed_lesson['info'].strip()
7976561eba0542cdd9b4a356c25c88e0e2c82472
628,066
import logging import csv def read_header(filepath): """Read header line of CSV file. INPUT: filepath: Full pathname of CSV file OUTPUT: i: First row of CSV file """ logging.info("Reading header for {0}".format(filepath)) with open(filepath, "r") as f: reader = csv.re...
0b07849a7190b307fc2d3e6f6fc4d3505320ba4d
628,067
def get_revoke_key(revoke_statement): """ Create the key from the revoke statement. The key will be used as the dictionnary key. :param revoke_statement: The revoke statement :return: The key """ splitted_statement = revoke_statement.split() revoke_privilege = splitted_statement[1] ...
0001bc2d14569bef8acbd799487450af1cf337f7
628,068
from typing import List import random def hexacolors(size: int) -> List[str]: """Retorna una lista de colores (hexadecimal). :param size: Tamaño de la lista de colores :size type: int """ return [ "#"+"".join(random.choices("0123456789ABCDEF", k=6)) for _ in range(size) ]
74beb56b12ad040fe75c471e23a3864eca327a18
628,070
def summarizing(sentences, similarity_scores, n_summary_sentences): """ Given similarity scores of clean_sentences with original_query, the function extracts the clean_sentences with the top n scores as the summary. """ sorted_sentences = {} j = -1 orders = similarity_scores sort_orders = so...
ef700efa4919f983cfaf3cbce9f3456360b06de3
628,071