content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _strip_outliers(w, max_value=1e4, n_devs=5): """Removes work values that are more than 5 (n_devs) standard deviations from the mean or larger than 1E4 (max_value). Parameters ---------- w : list(float) List of works max_value : int, default=1E4 Work values larger than this will ...
6a51005f95587e444c77ab1d4e77d0f9e9a1ea64
665,116
def add_train_args(parser): """Add training-related arguments. Args: * parser: argument parser Returns: * parser: argument parser with training-related arguments inserted """ train_arg = parser.add_argument_group('Train') train_arg.add_argument('--n_batch', ...
578c279a32bbfda96bcbfae9e58631788a2a67da
665,118
import os def list_files(directory): """Returns a list of absolute paths to all files in |directory| and its subdirectories.""" all_files = [] for (root, _, files) in os.walk(directory): for filename in files: all_files.append(os.path.abspath(os.path.join(root, filename))) retu...
ee3142412743ae5d8e2ad0466e78ae46cd087443
665,119
def get_node_attrs(node_id, node_label, attrs_var): """Query for retreiving node's attributes.""" query = ( "MATCH (n:{} {{ id: '{}' }}) \n".format( node_label, node_id) + "RETURN properties(n) as {}\n".format(attrs_var) ) return query
b36c55bdeb50a7a703cc1971c857590e7f403208
665,120
import hashlib def compute_n_hashings(string, n): """Iterate n times the hashing funciton given a string value (password) :param string: the value on which to iterate the hashing function :type string: string :param n: number of iterations to apply :type n: int :return: None :rtype: None ...
648ed6d4e6e909db01a635ab059a876b3f8b70b5
665,121
import hashlib def verify_password(hash_value, clean_value): """ verifies hash_value with string :param hash_value: :param clean_value: :return: """ if hashlib.md5(clean_value.encode()).hexdigest() == hash_value: return True return False
7ff6e63d4d0820773033dd6c063f7767bdb87a5a
665,122
from typing import Union from typing import List import json def parse_issues_json_string(issues_json: Union[str, bytes]) -> List[str]: """ Parses a JSON string containing GitHub issues into a list of issue titles. Note: The issue data must contain the `title` field. :param issue_json: Issue data en...
d1db99e0fcc7ec9d9a2a67e4b81f475db57f3c94
665,123
def find_duplicates(list_of,name_of): """ """ duplicates=[] duplicates=set([x for x in list_of if list_of.count(x) > 1]) if (len(duplicates)>0): print("duplicate "+name_of+" index found") print(duplicates) return duplicates
abc9350ddae69f40989ed42d59458e786962f252
665,124
def map_from_columns(df, key_col, val_col): """Return a dict mapping keys in the key_col to values in the val_col of the passed spark dataframe""" cols = df.select(key_col, val_col).toPandas() return dict(cols.to_numpy())
8bdeedc1716a6eb6a63a0d4a7711b50489105e8b
665,125
def female_filter(variable): """ Simple function to know the gender by name ending. If name ends with 'a' - it is female's name. """ return variable[-1].lower() == 'a'
0747583f13aeeacc522bf8a7d246625796a45504
665,126
def digital_channel_ids(): """Returns list of digital channels used in the experiment.""" line_fmt = 'Dev1/port0/line{0:02d}' line_ids = [line_fmt.format(n) for n in range(5, 31)] return line_ids
3171635c66a1fcd4680debeedc1802254df8a066
665,127
import os import random def get_raw_file(): """ Get the raw divider file in a string array. :return: the array :rtype: str """ with open("{0}/dividers.txt".format( os.path.abspath(os.path.dirname(__file__)) ), mode="r") as file_handler: lines = file_handler.readlines() ...
2f52d45c152f101a25ff93cbf7a9d21e230c3b1e
665,128
import json def read_config_file(config_filename): """Reads configuration parameters from the specified JSON file.""" # Strip comments while keeping line numbers. config_str = "" with open(config_filename, "r") as f_in: for line in f_in: line = line.rstrip() comment_pos = line.find("//") ...
67a89c89ab44732a6535548181f0d3edd2179a0e
665,129
def is_prime(number): """ Check if the number is a simple :param number: :return: """ if number == 1: return False for x in range(2, number): if number % x == 0: return False else: return True
a33d9975cacd4569d8ba38f608b4e268e9c12254
665,130
def cleanString(s): """ takes in a string s and return a string with no punctuation and no upper-case letters""" s = s.lower() for p in "?.!,'": # looping over punctuation s = s.replace(p,'') # replacing punctuation with space return s
4e77343b661f8230cf52681e015246bf67a22163
665,132
def title_case(sentence): """ Converts enetered string into the title_case Parameters ----------- sentence : string string to be converted into sentence case Returns ------- title_case_sentence : string string in TITLE CASE Example ------- >>>title_case('Th...
8cef40ec1f14f78fa4211aaf896b9b2426a0682e
665,133
from typing import List import collections import heapq def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: """ >>>Implementation of Dijkstra's algorithm using priority queue This is basically a greedy way to find the shortest distance: We start from the...
b9344195f9bc2ddbed338006f9dad52ecfa83947
665,134
def makeCd_from_vec(vecCd,nDims,n_neurons): """ convert between vector and matrix forms of C and d""" C = vecCd[:nDims*n_neurons].reshape(nDims,n_neurons).T d = vecCd[nDims*n_neurons:] return C,d
d5360fdcbe88433c7c03b6ede0e0061deff04330
665,135
import json def load_json_fixture(fixture_path): """ Loads a fixture file, caching the most recent files it loaded. """ with open(fixture_path) as fixture_file: file_fixtures = json.load(fixture_file) return file_fixtures
34312784cb849466884753666b5d22b4c808961d
665,136
def by_bases(bases): """基族Dにより与えられた集合が独立か否か判定する関数を返す関数 Args: bases: 基族D Returns: 与えられた集合Xが独立か否か判定する関数 True if ∃B ∈ D, X ⊆ B False otherwise """ return lambda X: any(X <= B for B in bases)
94807b365b8e85186356cc6de31c9d6ff36abb98
665,138
import numpy def slidingDotProduct(query, ts): """ Calculate the dot product between a query and all subsequences of length(query) in the timeseries ts. Note that we use Numpy's rfft method instead of fft. Parameters ---------- query: Specific time series query to evaluate. ts: Time series to...
88668309e729edc9942f5f3fad80087d9a3b4c8b
665,139
def compute_position(positions, total, index, length): """ used to compute the position where the bar will be put """ return positions - total / 2 + length / 2 + index * length
f5663404a5d6aef79efaf55c0c3800e291738966
665,140
import hashlib def _validate_file(fpath, md5_hash): """ Validate a file against a MD5 hash. Parameters ---------- fpath: string Path to the file being validated md5_hash: string The MD5 hash being validated against Returns --------- bool True, if the file ...
87677b38205e18c5656e4c660ea1d141e5d3d0b8
665,141
def get_root(graph): """ Search for the root node by finding nodes without inputs. """ # Find root node roots = [] targets = [t for ts in graph.values() for t in ts] for src in graph: if src not in targets: roots.append(src) if len(roots) > 1: raise ValueErro...
2d0e425b791335e0b90e34b3f1f403fe00f4a92e
665,142
def shift_left(my_list): """ the function "shift_left()" gets a list and return a new list that is shift left/ :param my_list: the list that the func get :type my_list: list :return new_list: the shift left list :rtype: list """ new_list = [my_list[1], my_list[2], my_list[...
6cba57a82aed45462f04d00d57ac08e9066ae5bc
665,143
def _clamp_window_size(index, data_size, window_size=200): """Return the window of data which should be used to calculate a moving window percentile or average. Clamped to the 0th and (len-1)th indices of the sequence. E.g. _clamp_window_size(50, 1000, 200) == (0, 150) _clamp_window_size(300...
49f744813f928506c41344c20f6e2b20f54faa17
665,144
def main(name='world', kind='Hello'): """ name: Who is the message for? kind: What kind of message should be given to name? """ return '{0} {1}!'.format(kind, name)
78006dbe0572335c73f58278f4f4d1d3ebf503ba
665,145
from datetime import datetime def utc_timestamp_to_datetime(timestamp): """ Converts timestamp (seconds) to UTC datetime :type timestamp: float | int :rtype: datetime """ return datetime.utcfromtimestamp(round(timestamp))
568c45c0f2c447832707246e9b9fd3d0d1274c2d
665,146
def usafe_filter(entity): """Returns the URL safe key string given an entity.""" return entity.urlsafe
9f5a86e61940e31be51eb09c6e250ebb12401d5f
665,147
from pathlib import Path import os import pkg_resources def get_archives_root(pkg: str = __name__) -> Path: """Get the data directory for test archives.""" path = os.path.join("data", "archives") return Path(pkg_resources.resource_filename(pkg, path))
d1b7541b382d674c6c510c9809976fab33e1b38b
665,148
def transform_input(x, image_inverse_transform=None): """ Accepts input image batch in #BCHW form :param x: input image batch :param image_inverse_transform: an optional inverse transform to apply :return: """ if image_inverse_transform is not None: x = image_inverse_transform(x) ...
6800300a0e9ee560eff4bebc8d1af5ab60f2e387
665,149
import torch from typing import Union def normalise_coords(coords: torch.Tensor, shape: Union[tuple, list]) -> torch.Tensor: """Normalise actual coordinates to [-1, 1] Coordinate locations start "mid-pixel" and end "mid-pixel" (pixel box model): Pixels | 0 | 1 | 2 | | | | ...
fe6820caad41320023b20e52674d3401c4b88fca
665,150
def get_neighbor_expression_vector(neighbors, gene_expression_dict): """Get an expression vector of neighboring genes. Attribute: neighbors (list): List of gene identifiers of neighboring genes. gene_expression_dict (dict): (Gene identifier)-(gene expression) dictionary. """ expressions ...
cfbf3365169af9ba33345bce64de636b5703d3a0
665,151
import sys import platform def get_cpu_bitness(): """Returns the number of bits in the CPU architecture as a str: 32 or 64. Unless someone ported python to PDP-10 or 286. OSX or Windows, we don't care about userland, we report the bitness of the kernel. On other platforms (Linux), we explicitly want to re...
862217e5f1e35084e73e2c12674ef1afb4954dd5
665,152
import torch from pathlib import Path from typing import Dict from typing import Any def load_checkpoint(path_to_checkpoint: Path, use_gpu: bool = True) -> Dict[str, Any]: """ Loads a Torch checkpoint from the given file. If use_gpu==False, map all parameters to the GPU, otherwise left the device of all p...
1c76eed4edb742365aabffaa3312d8aeb65d31f2
665,153
import json def load_abi_strings(source_file: str): """ Loads abi strings from json files :param source_file: :return: """ with open(source_file, 'r') as f: abi_string = json.load(f) return abi_string
f8a4e0c09b0e015e626295d49c9b1aece26e37b9
665,154
import warnings import time def warn_and_continue(exn): """Call in an exception handler to ignore any exception, isssue a warning, and continue.""" warnings.warn(repr(exn)) time.sleep(0.5) return True
a8297d5ceb064bd494f18a0a0a54e83c70229692
665,155
def is_leading_low(x, j): """Return True if bit ``j`` is the lowest bit set in ``x``.""" return x & ((1 << (j+1)) - 1) == 1 << j
cbdfd49dbea663ef0856f62be4b2445bb1ca435d
665,156
import re def colFromRegex(referenceList, regex): """ Return a list created by mapping a regular expression to another list. The regular expression must contain at least one capture group. Parameters ---------- referenceList : list-like A list to derive new values from. regex : str ...
f2f973830dee94a01a133cde345e569ac9ef27bf
665,157
def tuple_from_sequence(*args): """ Construct a tuple from a sequence (not list!) of objects EXAMPLES:: >>> from openmath.convert_pickle import tuple_from_sequence >>> tuple_from_sequence(1, 2, 3) (1, 2, 3) >>> tuple([1, 2, 3]) (1, 2, 3) """ return tuple(arg...
88ce18251c4e1fa9f536a82628c5c14bb553dac4
665,158
import unittest def suite(): """ Creates the test suite for all packages except turtle (which is graphical) """ modules = ( 'test_testcase', 'test_strings','test_tuples','test_colors', 'test_geom','test_filetools','test_urltools','test_modlib', 'test_turtle') # Been ...
e37604f90c30a196a8822eb827bb36ac0a814750
665,159
def computeBounds(bounds, length, numStrings, numOnes): """Using the appropriate bound, computes the value of that bound for given parameter values.""" results = [] for b in bounds: raw_bound = b(length, numOnes, numStrings) scaled = (raw_bound/numStrings)*100 results.append(sca...
aca26b632850a56059137ce8a14eebb28efa00be
665,160
def returns_minus_base(returns, b, masks): """ Subtract optimal baseline from returns :param returns: returns from each step on or for whole trajectory. Size: batch_size x 1 :param b: Optimal baseline per time step for every trajectory. Size: length_time_horizon :param masks: indicate the final step...
5d2432d087adf250ffacb5d4ae6a4ea6628efdf1
665,161
import os def make_test_module(): """ A function with side-effect of creating a python module for containing tests at the root of a project. """ if os.path.exists('./test'): return None # If there is a test module present # at the target location, exit. os.mkdir('./test') ...
1b929a3f7fd8e2e689ee4a5a8f8b277ce6a28183
665,162
def delta(a, b): """ Kronecker delta function """ return 1 if a == b else 0
2f419de404d984b4ffaddc6e9a5c163722f885d4
665,163
def preprocess_sentence(s): """ 每个句子首尾加上标识符 s: " "连接的分词 """ s = 'start' + s + 'end' return s
0f428d8dd11b7a043a986f08c1bac80cfc9085bd
665,164
def policy_rollout(env, agent): """Run one episode.""" observation, reward, done = env.reset(), 0, False obs, acts, rews = [], [], [] while not done: env.render() obs.append(observation) action = agent.act(observation) observation, reward, done, _ = env.step(action) ...
9dd1fe588b6f1c78d54e2bc534e411791ba51420
665,165
import ntpath def StripPathToFile( path ): """ Strip a file path down to the last folder/file name. """ head, tail = ntpath.split(path) return tail or ntpath.basename(head)
f98f87827b779599c0e84ba88c189cea05961c9d
665,166
from typing import Any def truebool(val: Any | None) -> bool: """Return `True` if the value passed in matches a "True" value, otherwise `False`. "True" values are: 'true', 't', 'yes', 'y', 'on' or '1'. """ return val is not None and str(val).lower() in ("true", "t", "yes", "y", "on", "1")
39fce4719a25175b67f211426374ef98c087175a
665,167
def redis_prime_logic__style_1_Domain(redis_client, dbDomain, redis_timeouts): """ primes the domain, returns the certificate :param redis_client: :param dbDomain: The :class:`model.objects.Domain` to be primed :param redis_timeouts: REDIS KEY PREFIXES: d1: domain c: certifica...
203f654dd348782caaa9e09c059613aa5d1e595b
665,168
def decode_num(element) -> int: """ Decode an integer from its byte equivalent """ if element == b'': return 0 big_endian = element[::-1] if big_endian[0] & 0x80: negative = True result = big_endian[0] & 0x7f else: negative = False result = big_endia...
20b1d2cb15e9cb8fda0f55f7836ec820417fd070
665,169
def parser_json(): """Return a /parser response.""" return { "parsers": [ { "lastRun": "2018-04-30 11:52:33", "lastKnownError": "", "hasForecast": True, "uid": 11, "hasHistorical": False, "descrip...
71a56a8bed188127bcb7a6b2a17d7cc58557cc5b
665,170
import re def _compute_m(input): """ _comput_m - function to compute the measure m of a stem based on the alternate vowel-consonane sequences Inputs: - input : str Words to be stemmed Outputs: - input : str ...
c6eb6763191d459071662fcdd9f9630585278186
665,172
def calcular_cambio(cambio: int) -> str: """ Cambio a retornar Parámetros: cambio (int): Valor a retornar al comprador Retorno: str: Cadena de caracteres que indica cuántas monedas de cada denominación se deben retornar (usando la menor cantidad de monedas posible). """ c500 =...
f309bf43de6f1b4f38cb8a0b38d0d98a3df706d7
665,173
from typing import Dict from typing import Optional def smp_converge(men_engage: Dict[str, Optional[str]], women_engage: Dict[str, Optional[str]]) -> bool: """Return True if there exists a couple that are unengaged.""" return None in men_engage.values() or None in women_engage.values()
731eb1faae978db88ca48766e4796ea321a6a0d3
665,174
def ev_connector_tf(dataframe, type_list): """ Creates new columns to describe each station connector types Attributes ------------------- dataframe: DataFrame the DataFrame to deal with type_list: list all connector types Return ---------------------- dataframe: D...
43b60a758514725d15f541a83a0c0371825664e4
665,175
import torch def _logaddexp(a, b, mask): """compute the log sum exp, to avoid the situation of add to inf values""" output = torch.zeros_like(a) # find the mask to output b when a contain -inf values out_put_b_mask = torch.isinf(a) & (a < 0) # find the mask to output a when b contain -inf values ...
28ffcceaf7fbb2b0204fa31c5b181a33834bc4b1
665,176
def build_feature_dict(args, examples): """Index features (one hot) from fields in examples and options.""" def _insert(feature): if feature not in feature_dict: feature_dict[feature] = len(feature_dict) feature_dict = {} # Part of speech tag features if args.use_pos: f...
ab64a6012298881a6a33b088923197d6992df156
665,177
def calculate_clipping(cfg, scale): """ Helper function for calculating lo and hi. Args: -- cfg: configuration file for model -- scale: scale for lo, hi. If lo, hi in [0,255], scale is 1. If lo, hi in [0,1], scale is 1/255 Returns: -- LO, HI: list, lower bound and upper bound of each chann...
287f5ec588723e6f4bfe39c40f7fb501df78d161
665,178
def get_attr(f, name): """ Try to access the path `name` in the file `f` Return the corresponding attribute if it is present """ if name in list(f.attrs.keys()): return(True, f.attrs[name]) else: return(False, None)
ad645d2e199fff19697f7bf7d05a4d4769d2c7c9
665,179
from datetime import datetime def format_timestamp(time_string): """Return the timestamp as a formatted string.""" return datetime.strptime(time_string, '%Y%m%d%H%M%S').isoformat().replace('T', ' ')
815952e232777e44c1b711333d1d49e2354688a9
665,180
def nested_compare(t, u): """ Return whether nested structure of t1 and t2 matches. """ if isinstance(t, (list, tuple)): if not isinstance(u, type(t)): return False if len(t) != len(u): return False for a, b in zip(t, u): if not nested_compare(...
469336042fdd37822e4cc1dde53cdde24bbc96a7
665,181
def get_bbox(img, bbox): """ API expects bbox as [ymin, xmin, ymax, xmax], in relative values, convert to tuple (xmin, ymin, xmax, ymax), in pixel values """ width, height = img.size bbox_px = (0, 0, width, height) if bbox: bbox_px = ( int(bbox[1] * width), int(bb...
96f7c94f8c7b07db510f26fa1dec6695d4c4f275
665,182
def interval_union(intervals): """ Returns the union of all intervals in the input list intervals: list of tuples or 2-element lists """ intervals.sort(key=lambda x: x[0]) union = [intervals[0]] for i in intervals[1:]: if i[0] <= union[-1][1]: # overlap w/ previous if ...
e63eaaf7fdb63e478dad34734c772f2b8b22c791
665,183
import base64 def base64_from_image(image_path): """ Encodes an image in base64 (> str) """ image = open(image_path, 'rb') image_content = image.read() image.close() return(base64.b64encode(image_content).decode('ascii'))
9ffed7f8c746b7dcca0290e9021601f0f8a836c6
665,184
def checkText(text): """ 检查文本是否为英文 """ text = text.replace(' ', '') for i in range(len(text)): if not text[i].isalpha(): return False return True
63576fb8add769278bbca07005c15cd3a2e34f5b
665,185
def check_choice(variants: list): """variants is variants of user choice choice: 'Ваш выбор: {variant}' error: 'Некоректные данные!'""" variants = [str(elem) for elem in variants] while True: try: answer = input('Ваш выбор: ') if answer in variants: re...
77fa613d6f097cc8df175a048e9d63baf5fe0664
665,186
def _choose_most_important_network(properties, network): """ Use the `_network_importance` function to select any road networks from `all_networks` and `all_shield_texts`, taking the most important one. """ prefix = network.prefix all_networks = 'all_' + prefix + 'networks' all_shield_texts...
070b80fac1abf17d996a3cb8aff945871d5ffcb1
665,187
import os def is_testing(): """Whether or not the testing routes should be added?""" return os.environ.get('MLCOMP_TESTING') == '1'
699d5afaa7d074e5ad23572c290db6e6f56fe509
665,188
def cluster(d): """ Utility function """ clusters = {} for key, val in d.items(): clusters.setdefault(val, []).append(key) return clusters
499b8a1f9816cdd9f9ed4bdb8063c395bab731ab
665,189
def preprocess_proxy(proxy): """fix proxy list to IPAddress,Port format from dictionary to ipaddress,port Parameters ---------------- proxy : dict proxy details form the proxy json file Returns --------------- dict constaining keys ipaddress and port for the proxy """ ...
482145c8179a79e8323df261213c05bcb408680f
665,190
import pickle import dill def maybe_dill_loads(o): """Unpickle using cPickle or the Dill pickler as a fallback.""" try: return pickle.loads(o) except Exception: # pylint: disable=broad-except return dill.loads(o)
0691a174b5e22cbce5f9830407795a66d9081db3
665,191
def allcap_differential(words): """ Check whether just some words in the input are ALL CAPS :param list words: The words to inspect :returns: `True` if some but not all items in `words` are ALL CAPS """ is_different = False allcap_words = 0 for word in words: if word.isupper(): ...
7023fe036484eeb980f2a948aa2a0f980655a1a2
665,192
def format_gender(gender): """ Maps gender from Lookit v1 to current gender, assuming "other or prefer not to answer" mapping to na """ gender_mapping = {'male': 'm', 'female': 'f', 'other or prefer not to answer': 'na'} return gender_mapping.get(gender, '')
7253f7ac6a1ed84c879b168b48d516a3f9b56101
665,194
from datetime import datetime def format_bybit_candle_timestamp(timestamp: datetime) -> float: """Format Bybit candles timestamp.""" return int(timestamp.timestamp())
b7052e01145200df7951daa24703797d2f64a621
665,195
def calc_kappa2(T_K): """ Calculates kappa2 in the PWP equation. Calculates kappa2 in the PWP equation, according to Equation 7 in Plummer, Wigley, and Parkhurst (1978) or Equation 6.14 of Dreybrodt (1988). Parameters ---------- T_K : float temperature Kelvin Returns ------- ...
60bf05880002bc796bc91081b1cfa9126ebb0f17
665,196
from typing import Union import math def truncate_to_block(length: Union[int, float], block_size: int) -> int: """ Rounds the given length to the nearest (smaller) multiple of the block size. """ return int(math.floor(length / block_size)) * block_size
cbcd3cfcb2bf32c0cc7d4f00a1b3d5d741113d7d
665,197
def help_intent_handler(handler_input): """Handler for Help Intent.""" # type: (HandlerInput) -> Response # 多言語応答データを取得 lang = handler_input.attributes_manager.request_attributes["_"] speech_text = lang['HELP_MSG'] reprompt = lang['ASK_MSG'] handler_input.response_builder.speak(s...
6b19cab09d60a8d92397c7e28356ac9b173b1072
665,198
import requests from bs4 import BeautifulSoup def GetHTML(url="https://demo.entitysport.com/"): """Downloads the homepage structure""" # Attaching headers for browser compatibility. headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Ch...
f28e21f8810b378efc88f4a01a2f4268d0a2494b
665,199
def not_caught_by_spamhaus(log_data): """ Returns a dict like log_data but with IPs that were found in zen.spamhaus.org removed. """ return {ip: lists for ip, lists in log_data.items() if "zen.spamhaus.org" not in lists and len(lists) >= 1}
d7e3914dd491f7c4126f17a75fc61bcd51db7c1d
665,200
def construct_path(u,v,discovered): """Use the discovered dictionary from depth-first search to reconstruct a path from node u to node v. """ path = [] # Deal with empty case if v not in discovered: return path # build list of edges # that connect v to u, # then r...
049fd09509765c64ff347f33fffda4719e8d34eb
665,201
import torch def vstack_params(params,new_params): """ Stacks vertically for each key in params, new_params """ assert params.keys() == new_params.keys() res = {k: torch.vstack([params[k], new_params[k]]) for k in params.keys()} return res
2afadfccfd0b54223c531c65aa33ab95e1f37238
665,202
def get_all_keys(dictionary): """ Method to get all keys from a nested dictionary as a List Args: dictionary: Nested dictionary Returns: List of keys in the dictionary """ result_list = [] def recrusion(document): if isinstance(document, list): for list_i...
c161689d060cde21b953ba5cb13ea23ecfea7a99
665,203
def merge_sorted_arrays2(array1, array2): """ if array1_index >= len(array1) => add the rest of array2 to new_array else if array2_index >= len(array2) => add the rest of array1 to new_array else if array1[0] >= array2[0] => new_array.append(array1[0]) array1_index += 1 ...
a666dcdbd560eb760f2cb7a742822cbddd34d90f
665,204
import torch def _cross_squared_distance_matrix(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: """ Pairwise squared distance between two (batch) matrices' rows (2nd dim). Computes the pairwise distances between rows of x and rows of y :param x : 3-D float Tensor :shape: (batc...
1d78e1c34f1333ac4264c4bab0a676305e79c517
665,205
def find_parent_fnames(var): """ Find full names of parents, recursively. These names will be forbidden in the subsequent resolution to make sure there's no back branch in the constructed DAG. """ names = [var.fname] # No self-referential if var.parent: names.append(var.parent.fnam...
e0b32984275a80b14851bba9ecb357a4628d1d54
665,206
import math def sector(angle, radius, rad=False): """Finds the area of a sector of a circle""" if rad: angle = math.degrees(angle) return (angle / 360) * (math.pi * (radius ** 2))
7adcef08a8164eda7f401ddfa2acc7afaae5479e
665,207
def disambiguate_language(text, assumed_languages, db): """ Some Wiktionary links simply point to a term without specifying what language it's in. In that case, we have to guess. The possible languages are: - The language of the Wiktionary it's in - The language of the other term in th...
ba7f17c468f3be7a07295daa5c6f3f944d8edb99
665,208
from typing import Iterable from functools import reduce def _digits_to_number(digits: Iterable[int]) -> int: """ Gives the number given by its digits, e.g. [1, 2, 3] -> 123 """ return reduce(lambda x, y: x * 10 + y, digits)
10b21394452652658efc5726d73d8e7f7f24c5da
665,209
def form_assignment_string_from_dict(adict): """ Generate a parameter-equals-value string from the given dictionary. The generated string has a leading blank. """ result = "" for aparameter in adict.keys(): result += " {}={}".format(aparameter, adict[aparameter]) return resul...
ea37f0ab0de0e66b4bd3c8745d0d18ed77d1143e
665,210
import cProfile import pstats import resource import os def ProfileRunValidationOutputFromOptions(feed, options): """Run RunValidationOutputFromOptions, print profile and return exit code.""" # runctx will modify a dict, but not locals(). We need a way to get rv back. locals_for_exec = locals() cProf...
0bedbdacd8a8904713d102f6a09b83114df16588
665,211
import os def prepare_epoch_result_directory(result_dir: str, epoch: int) -> str: """Creates a result directory named by the epoch on the filesystem. Args: result_dir (str): The root result directory. epoch (int): The epoch number. Returns: str: The path to the epoch result direc...
577d1d5ec07ecc9b413e60a31fca99fe9bc3c755
665,213
def tobytes(value): """implicitly try to convert values to byte strings mainly for python 2 and 3 compatibility""" if not isinstance(value, bytes): value = value.encode('utf8') return value
b611d900e5adcbe9bf46e1f2bdcf7ffe6ea5b87c
665,214
def params(): """ Parameters p to create query arg commands, used in the liquid format of: {{ p }} """ return ["remote_addr", "http_method", "uri", "host", "remote_addr"]
1e2b89b6d7f21f51943302cabdf28a7ae6680496
665,215
def train_pred_step(X, y, X_pred, model, metric): """[summary] Parameters ---------- X : [type] [description] y : [type] [description] X_pred : [type] [description] model : [type] [description] metric : [type] [description] Returns ------...
a1bf9d4869f669b476abfd42f0cb66d87f3012a6
665,216
def iff( a, b, c ): """ Ternary shortcut """ if a: return b else: return c
f9b01653abd384bd9f942e0fe15fa3b8d396603e
665,217
def searchkit_aggs(aggs): """Format the aggs configuration to be used in React-SearchKit JS. :param aggs: A dictionary with Invenio facets configuration :returns: A list of dicts for React-SearchKit JS. """ return [ {"title": k.capitalize(), "aggName": k, "field": v["terms"]["field"]} ...
7ea577c4503cf8b9b8f9a1b6f396712477040260
665,218
def pre_process_data(full_file_lines): """ I group all the possible configurations in a dictionary the key is MACHINE + BENCHMARK + LOG HEADER :param full_file_lines: :return: dictionary that contains the grouped benchmarks """ grouped_benchmarks = {} for i in full_file_lines: ...
d40e19f4e7e992d7cd1775f516a7fc038e3b059f
665,219
def parse_argparser(parser): """Parse the argparser. Parameters ---------- parser : argparse.ArgumentParser Returns ------- dict """ args = parser.parse_args() config = vars(args) return config
ba7ea0623039f491405b49976569a7b1a680c47f
665,220
from datetime import datetime def calculate_age(year): """ get profileform birthday_year field submited data and calculate current age, then return age """ birthday_year = year today = datetime.now() date = today.date() current_year = date.strftime("%Y") age = int(current_year)...
66c0123f18ac6147b74f4e99e9918d5ee850befa
665,221