content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def get_score(word): """Score a given word.""" if len(word) == 4: return 1 else: score = len(word) if len(set(word)) == 7: score += 7 return score
c48ffc666e1219ec7b19aeb3343a04de95e048bb
558,797
def start_first_monday(df): """Slices the dataset keeping data dated after the first monday available Parameters: ----------- df : Pandas DataFrame the original dataset Returns ----------- df : Pandas DataFrame the corresponding dataset """ first_date_gap = df.iloc[0].gap_in_day next_monday_gap = first_date_gap + (4 - first_date_gap % 7) % 7 df0 = df[df['gap_in_day'] >= next_monday_gap] return df0
493e2ff6bc2da3a69f9cfca698d9fc0bb5f35f0f
202,853
def squared(value: int) -> int: """Returns the squared value""" return value * value
73cfb3e7c7fdfb2bf99296861dc243c5c92cb67e
255,315
def text(item): """ Get the text from the tweet """ if 'text' in item: return item['text'] return None
1451d0933c65b5c09eb8a39eb882162af335cb57
600,784
def append_from(session, data, page): """ Collect paginated data.""" r = session.api_request(page) url_next = r["links"]["next"] if url_next: append_from(session, data, url_next[len(session.base_url):]) data.extend(r["data"]) return data
05100d0f6d10d3851a99a30528d75ba5510f9a21
430,784
def factor_out_twos(n): """ Returns the tuple (d,s) such that n = d*(2**s) for the smallest value of d """ d = n s = 0 while d % 2 == 0: s += 1 d //= 2 return d,s
76ed2fa981673098afd66239eca960607e96d7e9
615,873
def write_string(fid, s): """ Write *s* as a null terminated string to *fid*. """ fid.write(s + '\0') return fid
3e7f00279272da79003ed76db5b4028e1b0b5727
454,219
def hash_djb2(s, seed=5381): """ Hash string with djb2 hash function :type s: ``str`` :param s: The input string to hash :type seed: ``int`` :param seed: The seed for the hash function (default is 5381) :return: The hashed value :rtype: ``int`` """ hash_name = seed for x in s: hash_name = ((hash_name << 5) + hash_name) + ord(x) return hash_name & 0xFFFFFFFF
1f110277c1da36acfa1c336664e78eb867fa6e97
562,016
def _set_coords(ds, varname): """Set all variables except varname to be coords.""" if varname is None: return ds if isinstance(varname, str): varname = [varname] coord_vars = set(ds.data_vars) - set(varname) return ds.set_coords(coord_vars)
b6f94e9e8022dccfb6dfab078203c624f6c8bf3a
558,158
def filterArchitecture(results, architecture): """ Restrict the list of results based on given architecture """ filtered_results = {} for name, res in results.items(): filtered_values = [] for value in res: if architecture is "x86": # drop aarch64 results if ("armband" not in value['build_tag']): filtered_values.append(value) elif architecture is "aarch64": # drop x86 results if ("armband" in value['build_tag']): filtered_values.append(value) if (len(filtered_values) > 0): filtered_results[name] = filtered_values return filtered_results
a909932f1761d0278627c91498e8631f50ada380
303,300
from typing import List def _ternary_search(array: List[int], value, low: int, high: int) -> int: """ The implementation detail of the recursive implementation of ternary search. :param array: is the array to search. :param value: is the value to search for. :param low: is the lower bound of the partition. :param high: is the upper bound of the partition. :return: the index of the value, or -1 if it doesn't exist. """ if high < low: return -1 # Ternary search has two middle pointers. partition_size = (high - low) // 3 middle_1 = low + partition_size middle_2 = high - partition_size if value == array[middle_1]: return middle_1 if value == array[middle_2]: return middle_2 if value < array[middle_1]: return _ternary_search(array, value, low, middle_1 - 1) if value > array[middle_2]: return _ternary_search(array, value, middle_2 + 1, high) return _ternary_search(array, value, middle_1 + 1, middle_2 - 1)
f07a81c640ef9bafe31f01c72bf7ce5af6d30604
634,063
def solution(nums: list) -> list: """ This function sorts the passed in array of numbers. """ if nums is None: return [] return sorted(nums)
e8f44a4ce4b8eede0533329bc9c89ba9e2f0006d
415,864
def length(x): """ Returns the length of x :param x: the time series to calculate the feature of :type x: pandas.Series :return: the value of this feature :return type: int """ return len(x)
461d11ba6ca91b7ab6e7029ea7fe09fe4f78da1c
567,946
def create_garage_parking(data): """Create garage parking feature.""" data['Posti_garage'] = (data['Posti auto'] .str.extract(r'(\d).*garage\/box') .astype('float') .fillna(0)) return data
82ad85660b78584565adbbd5fe8ab38e435a1bf7
495,441
def return_timings(data, trial_type): """ Finds all trials matching the string 'trial_type', retrieves onset in seconds, and returns them as a list. """ data = filter(lambda d: trial_type in d[0], data) onsets = [] for trial in data: onsets.append(trial[5]) return onsets
f1c4ae2013287b85b603dd9b90affb0ab01f7fdd
283,605
from datetime import datetime def convert_iso_time(isotime): """Will convert an isotime (string) to datetime.datetime""" return datetime.strptime(isotime, '%Y-%m-%dT%H:%M:%S.%fZ')
49c60216ac664899614a82ac0fdaaa1731fbaafb
215,171
def FixateInputShape(input_params, batch_size, target_max_seqlen=None, source_max_seqlen=None): """Adjusts the input_params so that it always produces fixed shaped output. Sets p.target_max_length to target_max_seqlen and p.source_max_length to source_max_seqlen if set. Only keep items in bucket_upper_bound that is <= max_seqlen where max_seqlen is source_max_seqlen if given; otherwise, target_max_seqlen. Args: input_params: The input params. batch_size: The input generator should always output the batch size. target_max_seqlen: Every batch should produce samples with this sequence length, and samples are padded to this length. Use input_params.bucket_upper_bound[-1] if not set. source_max_seqlen: Same effect as target_max_seqlen but for source if set. Returns: input_params itself. """ p = input_params # Pad to fixed length, since otherwise the infeed queue can't be set up, # because the shape won't be known statically. # # Limit memory by throwing away large sequences. if not target_max_seqlen: assert p.bucket_upper_bound target_max_seqlen = p.bucket_upper_bound[-1] if source_max_seqlen: p.bucket_upper_bound = [ x for x in p.bucket_upper_bound if x <= source_max_seqlen ] if not p.bucket_upper_bound: p.bucket_upper_bound = [source_max_seqlen] else: p.bucket_upper_bound = [ x for x in p.bucket_upper_bound if x <= target_max_seqlen ] if not p.bucket_upper_bound: p.bucket_upper_bound = [target_max_seqlen] p.bucket_batch_limit = [batch_size] * len(p.bucket_upper_bound) p.pad_to_max_seq_length = True if source_max_seqlen: p.source_max_length = source_max_seqlen p.target_max_length = target_max_seqlen if hasattr(p, 'pad_and_set_target_shape'): p.pad_and_set_target_shape = True # Because every batch is padded to the max sequence length and has the same # batch size, they are shardable. p.remote.shardable_batch = True return p
9034b08e73b6fdded41420f36167f099fade58fb
64,738
import logging def make_log_metric(level=logging.INFO, msg="%d items in %.2f seconds"): """Make a new metric function that logs at the given level :arg int level: logging level, defaults to ``logging.INFO`` :arg string msg: logging message format string, taking ``count`` and ``elapsed`` :rtype: function """ def log_metric(name, count, elapsed): log_name = 'instrument.{}'.format(name) if name else 'instrument' logging.getLogger(log_name).log(level, msg, count, elapsed) return log_metric
8d99e00284b21d192a741d2cc0f7b1a2c40b18e2
137,561
from datetime import datetime def is_naive_datetime(dt: datetime): """判断 datetime 对象是否带有时区。 如果没有时区,在任何时候该对象都应该被当作本地时区对待。 """ return dt.tzinfo is None
cb7be80d98f08740978d1aa58cf8255d688cae95
267,487
import json def read_config(file_path): """Read JSON config.""" json_object = json.load(open(file_path, 'r')) return json_object
ed2feb5f23afbdee20573db847f4b7d5615fb6ce
550,184
def load_header(file: str): """Check if the graph is directed, bipartite, weighted.""" directed, bipartite, weighted = False, False, True with open(file, 'r', encoding='utf-8') as f: row = f.readline() if 'bip' in row: bipartite = True if 'unweighted' in row: weighted = False if 'asym' in row: directed = True return directed, bipartite, weighted
e91665878d01a9f460b32d542066f6c27add96db
327,186
def u4(bytes): """ Convert a little endian Ublox U4 type to a native integer """ if len(bytes) != 4: raise ValueError('Need exactly 4 bytes') return int(bytes[0]) + \ int(bytes[1]) * 256 + \ int(bytes[2]) * 65536 + \ int(bytes[3]) * 16777216
ab446bc02500ad9eba94b8b6bc9de689cf334e57
234,186
def my_tokenizer(s): """ Split a string s by spaces. Parameters ---------- s : The string. Returns ------- s.split() : A list with the resulting substrings from the split """ return s.split()
db2e0e637d087c1c5ed7813ef1f3903656d3eab2
310,278
def decode_data(data, table): """ Decode data with precalculated table """ dec = [] for i in range(0, len(data), 16): dec.append(table[data[i:i+16]]) return bytes(dec)
2351ece8066e1335d172c760d271f2a1a5f47922
479,595
def OnlyIfDescendedFrom(tag_names): """Decorator that only executes this visitor if we have the named ancestor. If one of the specified parent tag names is in the tree above us, run the decorated function. Otherwise, continue down the tree by using the default visitor, as if the decorated function didn't exist. """ def CalledOncePerDefinition(func): def CalledOncePerInvocation(self, *args, **kwargs): if self.IsDescendedFrom(tag_names): return func(self, *args, **kwargs) else: return self.visit(*args, **kwargs) return CalledOncePerInvocation return CalledOncePerDefinition
bfc502191beb09863ed70219dd842ad3b927663f
244,257
def node_pos_formatter(node): """ Returns a terminal node's original token. """ return node.text
2886fea43ad06d81e60f29be3c90fba7060e385e
607,559
def sort_and_dedup(input_list: list): """Sorts a list alphabetically and remove duplicates. Return tuple""" seen = set() seen_add = seen.add input = sorted(input_list) # sort uniques = [x for x in input if not (x in seen or seen_add(x))] output = tuple(uniques) return output
7eb7314d7cd8039479755aee2fc775ef760a508a
461,333
def yields_from_gronow_2021_tables_3_A10(feh): """ Supernova data source: Gronow, S. et al., 2021, A&A, Tables 3/A10 He detonation + Core detonation Five datasets are provided for FeH values of -2, -1, 0 and 0.4771 We use four intervals delimited by midpoints of those values. """ if feh <= -1.5: return [2.81e-2, 9.85e-6, 4.23e-9, 1.25e-7, 5.72e-3, 1.85e-6, 3.29e-4, 1.10e-1, 7.14e-2, 1.76e-2, 7.85e-1] elif -1.5 < feh <= -0.5: return [2.81e-2, 9.72e-6, 4.21e-9, 1.16e-6, 5.72e-3, 2.08e-6, 3.38e-4, 1.10e-1, 7.15e-2, 1.76e-2, 7.85e-1] elif -0.5 < feh <= 0.239: return [2.75e-2, 2.74e-5, 3.87e-9, 1.71e-5, 5.82e-3, 7.58e-6, 3.30e-4, 1.10e-1, 7.01e-2, 1.68e-2, 7.62e-1] elif 0.239 <= feh: return [2.45e-2, 8.64e-6, 3.65e-9, 3.46e-5, 5.99e-3, 1.01e-5, 2.94e-4, 1.10e-1, 6.46e-2, 1.49e-2, 6.91e-1]
16704acc8c5b04ab30e36374ee35af5c979125a8
549,806
def isint(intstr): """ Checks if a string is an integer. Args: intstr (str): A string Returns: bool """ try: int(intstr) return True except ValueError: return False
2d989ec51f64c7e622198ba8bdeceeecbddce2f0
253,633
def fresh_dict(m, ignore_underscore_fields=True): """ Returns a dict representation of the current (unsaved) state of Model M. Like django's built-in Model.__dict__, except that seems to use the stored (i.e. old) rather than new/unsaved values. In other words, if you change some of M's values but haven't yet saved them, FRESH_DICT will return the unsaved versions, whereas django's __dict__ will return the saved values. If IGNORE_UNDERSCORE_FIELDS, throws out fields that start with an underscore. """ d = {} for fieldn in [f.name for f in m._meta.fields]: if ignore_underscore_fields and fieldn.startswith('_'): continue d[fieldn] = getattr(m, fieldn) return d
e7f4c6177d3702e3025e2117e43e09671e2c03da
378,549
def parse_fasta (lines): """Returns 2 lists: one is for the descriptions and other one for the sequences""" descs, seqs, data = [], [], '' for line in lines: if line.startswith('>'): if data: # have collected a sequence, push to seqs seqs.append(data) data = '' descs.append(line[1:]) # Trim '>' from beginning else: data += line.rstrip('\r\n') # there will be yet one more to push when we run out seqs.append(data) return descs, seqs
4dea579720f43f348389e53751c0308f1c493296
26,968
def getSegsIgnore(oracleSplitSegs, collars): """ This function returns a list of the segment times to ignore based on the input collar sizes. Note that each collar defined as a start collar size and an end collar size, though both can be the same. Inputs: - oracleSplitSegs: ground truth segments all iterations have reduced it to non-overlapping segments with a constant number of speakers in each segment - collars: list of start collar sizes and end collar sizes in seconds, form "[0.25, 0.25]" Outputs: - segsIgnore: the list of segment times to ignore, form: "[[1270.14, 1270.64], [1274.63, 1275.88], ...]" """ segsIgnore = [] for index, collar in enumerate(collars): segsIgnore.append([]) for row in oracleSplitSegs: segsIgnore[index].append([row['tbeg'] - collar[0], row['tbeg'] + collar[1]]) segsIgnore[index].append([row['tend'] - collar[0], row['tend'] + collar[1]]) return segsIgnore
b5bfbbc25539f58e7e6de1299c4562ea4df5d70b
199,242
def calculate_benefit_cost_ratio(region, country_parameters): """ Calculate the benefit cost ratio. """ cost = ( region['network_cost'] + region['spectrum_cost'] + region['tax'] + region['profit_margin'] ) revenue = region['total_revenue'] if revenue > 0 and cost > 0: bcr = revenue / cost else: bcr = 0 return bcr
2c820f3cc758bf22355983dac8950df380168dc9
242,577
def par_insertion(pairs, chars, rules, steps): """ Apply steps of par insertion to the polymer template. :param pairs: template pairs :param chars: counter of characters :param steps: number of required steps :return: pairs, chars """ for _ in range(steps): for (a, b), value in pairs.copy().items(): insertion = rules[a + b] pairs[a + b] -= value pairs[a + insertion] += value pairs[insertion + b] += value chars[insertion] += value return pairs, chars
9058ce6aa1626d22bd9eaca0e613fdfcdd51d264
583,363
def _rshift_nearest(x, shift): """Given an integer x and a nonnegative integer shift, return closest integer to x / 2**shift; use round-to-even in case of a tie. """ b, q = 1 << shift, x >> shift return q + (2 * (x & b - 1) + (q & 1) > b)
cb6fa2a2d65367766adab37e05534990dfe3b2a6
656,373
def touchforms_error_is_config_error(touchforms_error): """ Returns True if the given TouchformsError is the result of a form configuration error. """ error_type = touchforms_error.response_data.get('error_type', '') return any([s in error_type for s in ( 'XPathTypeMismatchException', 'XPathUnhandledException', 'XFormParseException', )])
359fc7bfa195c5adadeec3d230408a892827b8a8
611,338
def get_data_source(name): """Guesses data source from file name. If the name contains 'terr' then we guess terrestrial data, otherwise we assume satellite. Arguments ========= name : str File name Returns ======= int 0 if satellite, 1 if terrestrial """ if name.find('terr') != -1: # terrestrial return 1 else: # assume satellite return 0
2ac0915327805320474a94cb6b9189e7c7041440
343,638
import traceback def format_traceback(sys_exc_info): """Formats traceback.""" return "".join(traceback.format_tb(sys_exc_info[-1])).rstrip()
1e6f3b3cf90b49d0757216fbc30dc6c94ff5d197
340,005
import random import string def generate_random_string(len: int): """ Creates a randomly generated string of uppercase letters Args: len (int): The desired length Returns: random_string (str) """ return ''.join(random.choices(string.ascii_uppercase, k=len))
5414ecb7a6e212379000e43fef07e4642c0e63a0
17,329
def _ply_header(num_vertices, num_faces, use_vertex_colors=False): """ Return a string representing the PLY format header for the given data properties. """ hdr_top = """ply format ascii 1.0 comment Generated by Brainload """ hdr_verts = """element vertex %d property float x property float y property float z """ % num_vertices hdr_vertex_colors = """property uchar red property uchar green property uchar blue property uchar alpha """ hdr_face = "element face %d\nproperty list uchar int vertex_indices\n" % num_faces hdr_end = "end_header\n" if use_vertex_colors: hdr_elements = [hdr_top, hdr_verts, hdr_vertex_colors, hdr_face, hdr_end] else: hdr_elements = [hdr_top, hdr_verts, hdr_face, hdr_end] return ''.join(hdr_elements)
40d7b12a1006be4cfa634f887c1054ddb30bb145
391,603
def get_contacts(filename): """ Function to get all the name and email IDs of contacts in separate lists :param filename: File containing contact list :return: lists containing names and emails """ names = [] emails = [] with open(filename, encoding='utf-8') as contacts_file: for contact in contacts_file: names.append(contact.split()[0]) emails.append(contact.split()[1]) return names, emails
83518c828ee5da909cf7765ac4cc59fc65f97330
161,995
def index1(b, i, k): """Magic index1 function. Takes a bitstring k and inserts bit b as the ith bit, shifting bits >= i over to make room. """ retval = k lowbits = k & ((1 << i) - 1) # get the low i bits retval >>= i retval <<= 1 retval |= b retval <<= i retval |= lowbits return retval
d5fa14ed1f11d8b1636f6e842b64dd7d2d9ede68
538,103
def format(self, ndigit="", ftype="", nwidth="", dsignf="", line="", char="", **kwargs): """Specifies format controls for tables. APDL Command: /FORMAT Parameters ---------- ndigit Number of digits (3 to 32) in first table column (usually the node or element number). Initially defaults to 7. ftype FORTRAN format types (initially defaults to G): G - Gxx.yy. xx and yy are described below. F - Fxx.yy E - Exx.yy nwidth Total width (9 to 32) of the field (the xx in Ftype). Initially defaults to 12. dsignf Number of digits after the decimal point (yy in F or E format) or number of significant digits in G format. Range is 2 to xx-7 for Ftype = G or E; and 0 to xx-4 for Ftype = F. Initially defaults to 5. line Number of lines (11 minimum) per page. Defaults to ILINE or BLINE from the /PAGE command. char Number of characters (41 to 240, system-dependent) per line before wraparound. Defaults to ICHAR or BCHAR from the /PAGE command. Notes ----- Specifies various format controls for tables printed with the POST1 PRNSOL, PRESOL, PRETAB, PRRSOL, PRPATH, and CYCCALC commands. A blank (or out-of-range) field on the command retains the current setting. Issue /FORMAT,STAT to display the current settings. Issue /FORMAT,DEFA to reestablish the initial default specifications. For the POST26 PRVAR command, the Ftype, NWIDTH, and DSIGNF fields control the time output format. This command is valid in any processor. """ command = f"/FORMAT,{ndigit},{ftype},{nwidth},{dsignf},{line},{char}" return self.run(command, **kwargs)
4c01afdccc4066005a4db7d523ef1d13ccf74b36
634,616
def _is_match_one(sub_string_list, src_string): """ Whether the sub-string in the list can match the source string. Args: sub_string_list (list): The sub-string list. src_string (str): The source string. Returns: bool, if matched return True, else return False. """ for match_info in sub_string_list: if match_info in src_string: return True return False
baa41ca9e8ab1d800d87862edece77f41ec649c1
219,722
import torch def all_or_none_accuracy(preds, targets, dim=-1): """ Gets the accuracy of the predicted sequence. :param preds: model predictions :param targets: the true targets :param dim: dimension to operate over :returns: scalar value for all-or-none accuracy :rtype: float32 """ preds_max = preds.data.max(dim=dim)[1] # get the index of the max log-probability assert targets.shape == preds_max.shape, \ "target[{}] shape does not match preds[{}]".format(targets.shape, preds_max.shape) targ = targets.data return torch.mean(preds_max.eq(targ).cpu().all(dim=dim).type(torch.float32))
4e46720996a383b601f7de332945182971f53988
681,596
import logging import requests def news_API_request(covid_terms: str = "Covid COVID-19 coronavirus"): """ This function get the news from the news API according to the given keywords. :arg covid_terms (str): Keywords of the news that you want to get :return: Json file: A json file containing the news that you get """ logging.info("getting the news with the keywords: " + covid_terms) base_url = "https://newsapi.org/v2/everything?" api_key = "f59ef4d22d7540f39636e99e44b9d0e6" keywords = "Covid&COVID-19&coronavirus&" language = "en&" sort = "publishedAt&" full_url = base_url + "qInTitle=" + keywords + "sortBy=" + sort + "language=" + language + "apiKey=" + api_key r = requests.get(full_url) return r.json()
bc9fa9d117e92ec5a14ce3ecd2f73966fc86b37d
424,745
def collect_default_successors(start_state): """ Collect the default successor states. NOTE: The start state also evaluated as a successor! NOTE: This function is necessary for expression validation! :param start_state: the start state of the searching :return: the set of default successor states """ processable_states = {start_state} default_states = set() visited_states = set() while processable_states: state = processable_states.pop() if state not in visited_states: if state.node.is_default(): default_states.add(state) elif not state.node.is_matchable(): processable_states.update(state.find_successor_states()) visited_states.add(state) return default_states
740ef64fc848b2a76d1bf82594acaea5db549b02
571,344
def bigend_2_int(p_bytes): """ Convert bigending bytestring to int """ l_ix = 0 l_int = 0 while l_ix < len(p_bytes): l_b = int(p_bytes[l_ix]) l_int = l_int * 256 + l_b l_ix += 1 return l_int
5c51a3752eec30804ab45185fb51c70be240a5b6
19,906
def is_eulerian_tour(graph, tour): """Eulerian tour on an undirected graph :param graph: directed graph in listlist format, cannot be listdict :param tour: vertex list :returns: test if tour is eulerian :complexity: `O(|V|*|E|)` under the assumption that set membership is in constant time """ m = len(tour)-1 arcs = set((tour[i], tour[i+1]) for i in range(m)) if len(arcs) != m: return False for (u, v) in arcs: if v not in graph[u]: return False return True
bafb2e64802b613b024f7da740c2489443e8acef
392,606
def get_max_value(li): """Return the largest value from a list.""" m = li[0] for value in li: if value > m: m = value return m
3f208bd33fb057901b1d89f8161bb22ddd7e88a6
362,642
def lcg_generator( state: int, multiplier: int = 1140671485, addend: int = 12820163, pmod: int = 2 ** 24, ) -> int: """ Performs one step in a pseudorandom sequence from state (the input argument) to state the return value. The return value is an integer, uniformly distributed in [0, pmod). See https://en.wikipedia.org/wiki/Linear_congruential_generator """ state = (multiplier * state + addend) % pmod return state
486438504a3c177b5e9fdc508857dcd349da76a0
144,260
def _preprocess(statement: str): """Preprocess the input statement.""" statement = statement.strip() # Replace any occourance of " with '. statement = statement.replace('"', "'") if statement[-1] != ";": statement += ";" return statement
48faedb198d937c8efbd655820510df147b11be2
580,361
def remove_padding(X,pad_value): """Convience function used to remove padding from inputs which have been padded during batch generation""" return X[X!=pad_value]
968de77558270bad4858db63374eb2c2e7a1148c
57,965
def get_end_of_line_character(view): """Return the EOL character from the view's settings.""" line_endings = view.settings().get("default_line_ending") if line_endings == "windows": return "\r\n" elif line_endings == "mac": return "\r" else: return "\n"
f8f4b45b187d9780671f1848ca25c63c93876a22
451,619
def gerrit_check(patch_url): """ Check if patch belongs to upstream/rdo/downstream gerrit, :param patch_url: Gerrit URL in a string format :returns gerrit: return string i.e 'upstream'/'rdo'/'downstream' """ if 'redhat' in patch_url: return 'downstream' if 'review.rdoproject.org' in patch_url: return 'rdo' if 'review.opendev.org' in patch_url: print("We don't have ability to hold a node in upstream") return 'upstream' raise Exception(f'Unknown gerrit patch link provided: {patch_url}')
93039f8b11e2359d05984d84953f3d7e05663bef
234,128
from typing import Any def py_is_not_none(x: Any) -> bool: """Check if x is not None.""" return x is not None
064976648b101a2ae2f0593f2e92149a79a73f42
495,383
def mul(X, varX, Y, varY): """Multiplication with error propagation""" # Direct algorithm: Z = X * Y varZ = Y**2 * varX + X**2 * varY # Indirect algorithm won't ensure floating point results # varZ = Y**2 # varZ *= varX # Z = X**2 # Using Z to hold the temporary # Z *= varY # varZ += Z # Z[:] = X # Z *= Y return Z, varZ
92f4d24a8f370525062b8826fc1ec8cffaec0bbe
262,908
def compute_score_seq(seq, score_matrix, pval_mat, min_score, scale, width, offset): """ Score a sequence using a processed motif scoring matrix ---- Parameters: seq (str) : sequence to score score_matrix (np.ndarray) : scoring matrix pval_mat (np.ndarray) : matrix used to compute P-values using a DP-algorithm (Staden, 1994) min_score (int) : lowest score in the scoring matrix scale (int) : scale used during motif processing width (int) : motif width offset (int) : offset used during motif processing ---- Returns: score (np.double) : sequence score pvalue (np.double) : sequence score P-value """ score = 0 seq_len = len(seq) assert seq_len == width # score the current sequence for i in range(width): nuc = seq[i] if nuc == 'N': score = min_score break # we don't go further elif nuc == 'A' or nuc == 'a': score += score_matrix[0, i] elif nuc == 'C' or nuc == 'c': score += score_matrix[1, i] elif nuc == 'G' or nuc == 'g': score += score_matrix[2, i] elif nuc == 'T' or nuc == 't': score += score_matrix[3, i] # end if # end for assert score >= min_score # get the p-value for the obtained score tot = pval_mat.sum() pvalue = (pval_mat[score:].sum()) / tot # retrieve the log-likelihood score logodds = (score / scale) + (width * offset) score = logodds assert pvalue > 0 assert pvalue <= 1 return score, pvalue
eda48309e6778e231a0fb22a907680659cf7082d
460,009
import itertools def _get_common_blocks(dp_block_sizes, dp_ids): """Return all pairs of non-empty blocks across dataproviders. :returns dict mapping block identifier to a list of all combinations of data provider pairs containing this block. block_id -> List(pairs of dp ids) e.g. {'1': [(26, 27), (26, 28), (27, 28)]} """ blocks = {} for dp1, dp2 in itertools.combinations(dp_ids, 2): # Get the intersection of blocks between these two dataproviders common_block_ids = set(dp_block_sizes[dp1]).intersection(set(dp_block_sizes[dp2])) for block_id in common_block_ids: blocks.setdefault(block_id, []).append((dp1, dp2)) return blocks
027ac3625e21ab70de8bd656ed2e625236c12fbb
90,488
import torch def roi2bbox(rois): """Convert rois to bounding box format. Args: rois (torch.Tensor): RoIs with the shape (n, 5) where the first column indicates batch id of each RoI. Returns: list[torch.Tensor]: Converted boxes of corresponding rois. """ bbox_list = [] img_ids = torch.unique(rois[:, 0].cpu(), sorted=True) for img_id in img_ids: inds = (rois[:, 0] == img_id.item()) bbox = rois[inds, 1:] bbox_list.append(bbox) return bbox_list
6ea7850a6d32bee2254599871dfb9d9db14e4136
349,000
import re def urlReg(msg): """Try to match an url.""" m = re.match('^.*(https?://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)', msg) if m: return m.group(1) return
4199486959cbc32a241f5b378d9a4ba887c1ebc3
477,241
def snp_count(vcf, chromosome, start, end): """ Count the number of snps in the window. :param vcf: vcf, a vcf file with SNPs and their genomic positions :param chromosome: str, Chromosome name :param start: int, Start position of the sequence :param end: int, End position of the sequence :return: int, number of snps in the vcf window """ snp_count = vcf.sample_variant(str(chromosome), int(start), int(end)) snp_count = sum(1 for item in snp_count) return snp_count
c18f52662f96d3013452c4884f506901e9da146b
73,153
def add_one(number): """A function that adds one to the number given and returns it""" return number + 1
84c9f4a5de79c1d7232c922875fcbeab4f9fee43
527,409
def is_palindrome(phrase): """Is phrase a palindrome? Return True/False if phrase is a palindrome (same read backwards and forwards). >>> is_palindrome('tacocat') True >>> is_palindrome('noon') True >>> is_palindrome('robert') False Should ignore capitalization/spaces when deciding: >>> is_palindrome('taco cat') True >>> is_palindrome('Noon') True """ new_phrase = phrase.replace(" ", "").lower() counter = 0 while counter < len(new_phrase)-counter-1: if new_phrase[counter] != new_phrase[len(new_phrase)-counter-1]: return False counter= counter+1 return True
af277bc5aad18ed08cf48b523b0f08b84ad4ff0e
394,760
def add(x, y): """The sum of two bits, mod 2.""" return (x + y) % 2
9c12cbcfd1f693942232c8f8c20fe4e58e21cb85
273,658
def synset_to_wnid(synset): """ Converts synset to wnid. Synset is a wordnet node object""" return synset.offset()
ba68060b66ab6cd12edd7322ed091b4b5244112e
604,369
def str2bins(string): """ Parses string as a list of floats, comma separated as in: "1.2,3,6,7" -> [1.2, 3.0, 6.0, 7.0] """ return [float(s) for s in string.split(",")]
c670cc045155ebaa1b8ca9a3a098e7ae4837a7bb
258,626
def schedule_1_amount(responses, derived): """ Return the amount as defined in schedule 1 for child support """ try: if derived['show_fact_sheet_b'] or derived['show_fact_sheet_c']: return derived['guideline_amounts_difference_total'] else: return float(responses.get('payor_monthly_child_support_amount', 0)) except ValueError: return 0
33fefc60fc8cb49941b2edaea518c4a57022a946
607,495
def get_class_name(obj): """ A simple template tag to retrieve the class name of an object. :param obj: an input object """ return obj.__class__.__name__
261de168f63336517838e868294c0b177c9e628b
265,219
def player_attr_by_id(roster, player_id, attribute): """Returns the attribute of a player given a roaster and a player_id. Args: roster (dict): Team roster (returned from API) player_id (str): Player unique identifier (IDXXXXXXX) attribute (str): Attribute from roster dictionary. Returns: string: Attribute of the person requested. """ new_player_id = player_id.replace("ID", "") for roster_item in roster: person_id = str(roster_item["person"]["id"]) person_attr = roster_item["person"][attribute] if person_id == new_player_id: return person_attr
caf17c0802b1b32fb32bf8397be80dc3baac7016
252,741
def space_indentation(s): """The number of leading spaces in a string Args: s: str. The input string. Returns: int. The number of leading spaces. """ return len(s) - len(s.lstrip(' '))
9bc74fc261f7f53d073dfc95ca76ba1ee9db90a4
586,648
def normalize_slice(s, total): """ Return a "canonical" version of slice ``s``. :param slice s: the original slice expression :param total int: total number of elements in the collection sliced by ``s`` :return slice: a slice equivalent to ``s`` but not containing any negative indices or Nones. """ newstart = 0 if s.start is None else max(0, s.start + total) if s.start < 0 else min(s.start, total) newstop = total if s.stop is None else max(0, s.stop + total) if s.stop < 0 else min(s.stop, total) newstep = 1 if s.step is None else s.step return slice(newstart, newstop, newstep)
f4f204a3ec0a3da4c4a5b33d27330a2445454597
521,291
def _get_first_last(details): """ Gets a user's first and last name from details. """ if "first_name" in details and "last_name" in details: return details["first_name"], details["last_name"] elif "first_name" in details: lst = details["first_name"].rsplit(" ", 1) if len(lst) == 2: return lst else: return lst[0], "" elif "last_name" in details: return "", details["last_name"] return "", ""
2a2ef17441c4243c5e58b74567709b9acb52e01f
118,368
def tag_key(tagname: str) -> int: """ Convert a tagname ("w.YYYY.NN" or "w.YYYY.N") into a key for sorting. "w_2017_1" -> 201701 "w_2017_01" -> 201701 "w_2017_10" -> 201710 etc. """ return int(tagname.split("_")[1]) * 100 + int(tagname.split("_")[2])
91f3559519299ced3952a430dfdc166a42997d0b
54,945
from typing import Any def is_options_list(options_list: Any) -> bool: """ Checks whether the given value is an options list. :param options_list: The value to check. :return: True if it is an options list. """ return ( isinstance(options_list, list) and all(isinstance(element, str) for element in options_list) )
51908a901a39d82ae85f49455eca51b5d0176bb7
492,095
def extract_chat_id(body): """ Obtains the chat ID from the event body Parameters ---------- body: dic Body of webhook event Returns ------- int Chat ID of user """ if "edited_message" in body.keys(): chat_id = body["edited_message"]["chat"]["id"] else: chat_id = body["message"]["chat"]["id"] return chat_id
382435ac01dd502f52ad2a5e300830f13cca533d
237,442
def pretty_print_time(time, message=None): """Pretty print the given time""" days = time.days hours, remainder = divmod(time.seconds, 3600) minutes, seconds = divmod(remainder, 60) if message is not None: print(message) print(f'\t {days} days, {hours} hours, {minutes} minutes, {seconds} seconds') # Print out fractional days things have been in this state total = days + hours/24. + minutes/(24.*60) + seconds/(24.*3600) return f"{total:.1f}"
366caa41f110b984508376cf957d5050a04955e7
670,679
def isHexDigit(s): """ isHexDigit :: str -> bool Selects ASCII hexadecimal digits, i.e. '0'..'9', 'a'..'f', 'A'..'F'. """ return s in "0123456789abcdefABCDEF"
527295b72c56000654b40ffd42f4b2480be3cfad
331,910
def get_crashreport_key(group_id): """ Returns the ``django.core.cache`` key for groups that have exceeded their configured crash report limit. """ return u"cr:%s" % (group_id,)
484fcd0140fdadadebd5faea01e420d39ed66992
67,229
import copy import itertools def cartesian_exp_group(exp_config, remove_none=False): """Cartesian experiment config. It converts the exp_config into a list of experiment configuration by doing the cartesian product of the different configuration. It is equivalent to do a grid search. Parameters ---------- exp_config : str Dictionary with the experiment Configuration Returns ------- exp_list: str A list of experiments, each defines a single set of hyper-parameters """ exp_config_copy = copy.deepcopy(exp_config) # Make sure each value is a list for k, v in exp_config_copy.items(): if not isinstance(exp_config_copy[k], list): exp_config_copy[k] = [v] # Create the cartesian product exp_list_raw = ( dict(zip(exp_config_copy.keys(), values)) for values in itertools.product(*exp_config_copy.values()) ) # Convert into a list exp_list = [] for exp_dict in exp_list_raw: # remove hparams with None if remove_none: to_remove = [] for k, v in exp_dict.items(): if v is None: to_remove += [k] for k in to_remove: del exp_dict[k] exp_list += [exp_dict] return exp_list
2a2d3b9f78ec680ac4c39150195fee154e001aeb
330,284
def addText(text, endIndex, namedStyleType, requests): """Adds requests to add text at endIndex with the desired nameStyleType. Returns new endIndex. Args: text (String): text to add endIndex (int): Current endIndex of document. Location to add text to namedStyleType (String): desired namedStyleType of text requests (list): list of requests to append requests to Returns: int: new endIndex after adding text """ # Finds new end index by incrementing endIndex by the length of the text # plus 1 for the automatically appended '\n' newEndIndex = endIndex + len(text) + 1 # Appends requests to add text, and then request to change namedStyleType # as desired requests.extend([ # Add text, including a '\n' at the previous line to create a new paragraph # Note that a '\n' will automatically be appended to the end of the text { 'insertText': { 'location': { 'index': endIndex - 1 }, 'text': '\n' + text } }, { 'updateParagraphStyle': { 'range': { 'startIndex': endIndex, 'endIndex': newEndIndex }, 'paragraphStyle': { 'namedStyleType': namedStyleType }, 'fields': 'namedStyleType' } } ]) return newEndIndex
476e1b40d16fa5cbea81933e9ef72318cd770488
481,202
from operator import xor def otp(m, k): """ Encrypts m using key k as a one-time pad. This simple returns the xor of each corresponding message and key bit. """ assert len(m) == len(k) return [xor(mm, kk) for mm, kk in zip(m, k)]
ac3b4aa10487b61a7f127a8999a09d30b26922e5
411,122
def combine_by_append(vector1, vector2): """ Combines two lists by appending them. :param vector1: list of values :param vector2: list of values :return: a list created by appending vector1 to vector2 """ return vector1 + vector2
1376c70613b4e8df7628062f20bc58759ddddb92
359,585
def calculate_velocities(cartesians, timestep=1): """ Calculate velocities at each timestep given Cartesian coordinates. Velocities at the first and last point are extrapolated. :param cartesians: Cartesian coordinates along trajectory :param timestep: time step between frames in units of fs, default=1 :return: velocities """ velocities = [] for i in range(0, len(cartesians)): if i == 0: velocity = (cartesians[i + 1] - cartesians[i]) / timestep elif i == len(cartesians) - 1: velocity = (cartesians[i] - cartesians[i - 1]) / timestep else: velocity = (cartesians[i + 1] - cartesians[i - 1]) / 2 * timestep velocities.append(velocity) return velocities
ab38b3745b0cd36887924e491e143e99053a197d
254,470
def longest_common_prefix(seq1, seq2): """ taken from https://www.quora.com/What-is-the-easiest-way-to-find-the-longest-common-prefix-or-suffix-of-two-sequences-in-Python :param seq1: first string :param seq2: second string :return: the prefix """ start = 0 while start < min(len(seq1), len(seq2)): if seq1[start] != seq2[start]: break start += 1 return seq1[:start]
79dbaf1e0ef4859bb7b0e525c09d0273b4dbf590
99,325
from typing import OrderedDict def duplicate_word_removal(data: list) -> list: """ Removes duplicate words :param data: The list of dictionaries of the form :type: [{"Header":"", "Header_keywords": [], "Paragraph_keywords": [], slides:[int]}] :return: The list of dictionaries with duplicate keywords removed of the form :rtype: [{"Header":"", "Header_keywords": [], "Paragraph_keywords": [], slides:[int]}] """ for dictionary in data: ordered_headers = list(OrderedDict.fromkeys(dictionary['Header_keywords'])) dictionary['Header_keywords'] = ordered_headers ordered_paragraph = list(OrderedDict.fromkeys(dictionary['Paragraph_keywords'])) dictionary['Paragraph_keywords'] = ordered_paragraph return data
d07eb32ce09284db33a5d2787195afe20ca34184
419,891
def Clamp(num, a, b): """ Returns ``a`` if ``num`` is smaller than or equal to ``a``, ``b`` if ``num`` is greater than or equal to ``b``, or ``num`` if it is between ``a`` and ``b``. Parameters ---------- num : float Input number a : float Lower bound b : float Upper bound """ return min(max(num, a), b)
2b66d62f8f795ecb4907436cb5c09b150abe9438
123,560
def np_shape(matrix): """ Function to calculate the shape of a numpy.ndarray Returns the matrix shape """ return matrix.shape
411fb27eae62839a8fc87c577bc7ec8c86bdf0c0
379,225
def calculate_evaluation_metrics(confusion_matrix): """ Calculates the evaluation metrics of the model. :param confusion_matrix: The confusion matrix of the model. :return: dictionary, with the metrics of the model. """ metrics = dict() metrics['precision'] = confusion_matrix.get('TP', 1) / ( confusion_matrix.get('TP', 1) + confusion_matrix.get('FP', 1)) metrics['recall'] = confusion_matrix.get('TP', 1) / ( confusion_matrix.get('TP', 1) + confusion_matrix.get('FN', 1)) metrics['f1_score'] = 2 * metrics['precision'] * metrics['recall'] / (metrics['precision'] + metrics['recall']) return metrics
d2c3ea5b75529d4ae324f22350bf4d65c89fbf7c
120,086
def select_single_mlvl(mlvl_tensors, batch_id, detach=True): """Extract a multi-scale single image tensor from a multi-scale batch tensor based on batch index. Note: The default value of detach is True, because the proposal gradient needs to be detached during the training of the two-stage model. E.g Cascade Mask R-CNN. Args: mlvl_tensors (list[Tensor]): Batch tensor for all scale levels, each is a 4D-tensor. batch_id (int): Batch index. detach (bool): Whether detach gradient. Default True. Returns: list[Tensor]: Multi-scale single image tensor. """ assert isinstance(mlvl_tensors, (list, tuple)) num_levels = len(mlvl_tensors) if detach: mlvl_tensor_list = [ mlvl_tensors[i][batch_id].detach() for i in range(num_levels) ] else: mlvl_tensor_list = [ mlvl_tensors[i][batch_id] for i in range(num_levels) ] return mlvl_tensor_list
1a389d8ff836fb08f5e5519ec5dd9336d031ec54
621,326
def str2bits(str_in): """ Convert string input to bits. :param str_in: input string :return: bits array """ result = [] for c in str_in: bits = bin(ord(c))[2:] bits = '00000000'[len(bits):] + bits result.extend([int(b) for b in bits]) return result
f006773e74b17445258436d5581058349a1572ec
386,754
def nchannels(I): """ Return the number of color channels of the image `I`. """ D = len(I.shape) if D == 2: return 1 elif D == 3: return I.shape[-1] else: raise ValueError("Unrecognized image array shape {}".format(I.shape))
acab605144a9378ec2adcf719aeb5a65a18f30ee
259,382
def proxy_request_method(request): """Parametrized fixture changing request method (GET / POST / PATCH / ...). """ return request.param
a78fd8002e78332644387066a72cb62ff5ea2a4f
166,437
def depad(data): """Removes padding characters from the end of b64u encoded strings""" return data.rstrip('=')
5ac4f34c54e5f9fa7f008c14419b3bd3bb5b6cfd
279,411
def num2col(col_int: int) -> str: """ Convert an Excel column index to a string e.g. 1 == "A", 27 == "AA" e.t.c. """ if not isinstance(col_int, int): raise ValueError("Invalid data type supplied. Must supply an integer") col_str = "" while col_int > 0: col_int, remainder = divmod(col_int - 1, 26) col_str = chr(65 + remainder) + col_str return col_str
251f2b0d645a4485233873457c025faae79cfdf3
500,375
def split_container(path): """Split path container & path >>> split_container('/bigdata/path/to/file') ['bigdata', 'path/to/file'] """ path = str(path) # Might be pathlib.Path if not path: raise ValueError('empty path') if path == '/': return '', '' if path[0] == '/': path = path[1:] if '/' not in path: return path, '' # container return path.split('/', maxsplit=1)
53b0d1164ecc245146e811a97017f66bb1f032a7
9,941
def _getvaluefrombuffer(buf, loc): """Returns a requested value from buffer. Function is called recursively. Parameters ---------- buf : dict Buffer object loc : list List of strings with the requested location within buf Returns ------- ret : object Reqested value in buf at position loc""" if len(loc) > 1: return _getvaluefrombuffer(buf.__dict__[loc[0]], loc[1:]) if not hasattr(buf, loc[0]): raise RuntimeError("Requested <field> does not exist.") return buf.__dict__[loc[0]]
09bddb0713c6cd900d450e7b960a6f06b69f656a
170,041
def hex_to_RGB(hexstr): """ Convert hex to rgb. """ hexstr = hexstr.strip('#') r, g, b = int(hexstr[:2], 16), int(hexstr[2:4], 16), int(hexstr[4:], 16) return (r, g, b)
7084907ff084229fd2b4656aa301ca72a80d2fab
15,350
from typing import Union from typing import Mapping from typing import Any from functools import reduce import operator def map_reduce(key_path: Union[str, list[str]], mapping: Mapping[str, Any]) -> Any: """Reduce a mapping, returning a value from an arbitrarily deep hierarcy. The result of calling this function is the same as successively subscripting each key in the `key_path`, starting from `mapping`. Parameters ---------- key_path : str or list[str] A collection of sequential child keys into `mapping`. May be given as either a list of strings or a single string with dots (``.``) delimiting keys. mapping : Mapping[str, Any] The mapping to subscript. Example ------- The following lines are equivalent: map_reduce('foo.bar.baz', things) # Is the same as: map_reduce(['foo', 'bar', 'baz'], things) # Is the same as: things['foo']['bar']['baz'] """ if isinstance(key_path, str): key_path = key_path.split('.') return reduce(operator.getitem, key_path, mapping)
5b4d35b724e99d9360ce48984adc28b3d5a02cde
248,481
def get_latest_docdata_payment(payment): """ Get the latest docdata payment (DocDataPayment) for given payment (DocDataPaymentOrder). """ if payment.docdata_payments.count() > 0: return payment.docdata_payments.order_by('-created').all()[0] return None
a462257fe33130e2e49bba218fbd1e38933ee1ad
338,808