content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import random def random_guesser_v1(passage): """Takes in a string and returns a dictionary with 6 keys for the binary values representing features of the string, and another six keys representing the scores of those features. Note: for the scores, 0 represents no score, while -1 represents '?' Arguments --------- passage: string to be converted to dictionary with feature scores. """ features_dict = {} features = ["is_accountability", "is_unobjectivity", "is_inaccuracy", "is_fact-basedness", "is_influential", "is_opinionated"] features_score = ["score_accountability", "score_unobjectivity", "score_inaccuracy", "score_fact-basedness", "score_influential", "score_opinionated"] for i in range(len(features)): features_dict[features[i]] = random.randrange(2) features_dict[features_score[i]] = random.randrange(-1, 4) return features_dict
b2759839fcdd59d36aa2bf6643750970affc77a1
28,042
def min_max_dates_dict(min_max_dates): """Calculates dates needed by the pipeline, starting from min and max dates. Generates dictionary of dates needed for the calculation starting from a tuple containing min_date and max_date from the input logs. Args: min_max_dates: Tuple containing min_date and max_date for the input data. Returns: Dictionary containing info related to dates needed for the calculation. """ min_date, max_date = min_max_dates tot_days = (max_date - min_date).days if round(tot_days * 0.05) < 30: cohort_days = 30 else: cohort_days = round(round(tot_days * 0.05) / 30) * 30 return { 'min_date': min_date, 'max_date': max_date, 'total_days': tot_days, 'half_days': round((tot_days / 2) + 0.1), 'cohort_days': cohort_days }
14b99c9dd6096131d0d18f77da73a5c1c8d5f885
69,572
def calculate_compensated_moment(moment_sample, x_sample, interp_gap, interp_reference, beta): """ Calculates the compensated moment for a measurement of a sample. """ return moment_sample - interp_reference(x_sample) + (beta * interp_gap(x_sample))
c370dae8b5d5bfb7a4f60b5dbdbedffb4e70a3f2
495,849
def convertir(T: list) -> int: """ T est un tableau d'entiers, dont les éléments sont 0 ou 1 et représentatn un entier écrit en binaire. Renvoie l'écriture décimale de l'entier positif dont la représentation binaire est donnée par le tableau T. """ n = 0 for i in range(len(T)): n += T[i]*2**(len(T)-i-1) return n
74a38f5bcb7f09fe18c09306d0c168d259fb3dc1
242,102
def graph_ready(f): """No-op decorator that explicitly marks a function as graph-ready. Graph-ready functions are assumed to not need any conversion. Args: f: Any callable. Returns: f itself. """ setattr(f, '__pyct_is_compile_decorator', True) return f
742c60dd90658fdcd9f09a601015736b6029746e
146,097
def _get_binding(pdb_filename): """ Get binding mode of pdb file. x if none. e.g. 11as_r_u.pdb would give u """ if "_u" in pdb_filename: return "u" elif "_b" in pdb_filename: return "b" else: return "x"
177273f3eb69498f760050e9c366859527082c24
100,753
def CheckDoNotSubmitInFiles(input_api, output_api): """Checks that the user didn't add 'DO NOT ' + 'SUBMIT' to any files.""" keyword = 'DO NOT ' + 'SUBMIT' # We want to check every text files, not just source files. for f, line_num, line in input_api.RightHandSideLines(lambda x: x): if keyword in line: text = 'Found ' + keyword + ' in %s, line %s' % (f.LocalPath(), line_num) return [output_api.PresubmitError(text)] return []
2c347ef3497335ae0b33128e9a9d60c36cc65017
110,838
def example(a: int, b: int) -> int: """ Returns the sum of a and b, except one or both are 0 then it returns 42. :param a: The first operand :type a: int :param b: The second operand :type b: int :returns: The conditional sum :rtype: int .. testsetup:: from <%= rootPackage %>.<%= mainModule %> import example >>> example(1, 2) 3 >>> example(0, 4) 42 """ return a + b if a != 0 and b != 0 else 42
aac4b49706753f40390277d9c19de08323e96799
61,449
from typing import List def split_into_lists(input_list: List, target_number_of_lists: int) -> List[List]: """ Evenly splits list into n lists. E.g split_into_lists([1,2,3,4], 4) returns [[1], [2], [3], [4]]. :param input_list: object to split :param target_number_of_lists: how many lists to split into :returns: list of lists containing original items """ quotient, reminder = divmod(len(input_list), target_number_of_lists) return [input_list[i * quotient + min(i, reminder):(i + 1) * quotient + min(i + 1, reminder)] for i in range(target_number_of_lists)]
daf9bcad6d86d3654c36bca15f1c9943acb21159
679,270
def bulk_docs(docs, **kwargs): """Create, update or delete multiple documents. http://docs.couchdb.org/en/stable/api/database/bulk-api.html#post--db-_bulk_docs :param list docs: The sequence of documents to be sent. :param kwargs: (optional) Arguments that :meth:`requests.Session.request` takes. :rtype: (str, str, dict) """ if ("json" not in kwargs) or (not isinstance(kwargs["json"], dict)): kwargs["json"] = {} kwargs["json"]["docs"] = docs return "POST", "_bulk_docs", kwargs
00aa6fc07f507bba63ea044f3addeba2c77fdc18
141,478
import requests import logging def get_reply(session, url, post=False, data=None, headers=None, quiet=False): """ Download an HTML page using the requests session. Low-level function that allows for flexible request configuration. @param session: Requests session. @type session: requests.Session @param url: URL pattern with optional keywords to format. @type url: str @param post: Flag that indicates whether POST request should be sent. @type post: bool @param data: Payload data that is sent with request (in request body). @type data: object @param headers: Additional headers to send with request. @type headers: dict @param quiet: Flag that tells whether to print error message when status code != 200. @type quiet: bool @return: Requests response. @rtype: requests.Response """ request_headers = {} if headers is None else headers request = requests.Request('POST' if post else 'GET', url, data=data, headers=request_headers) prepared_request = session.prepare_request(request) reply = session.send(prepared_request) try: reply.raise_for_status() except requests.exceptions.HTTPError as e: if not quiet: logging.error("Error %s getting page %s", e, url) logging.error("The server replied: %s", reply.text) raise return reply
4baa985db090d0f88762c8f6cfadff084f2b88ad
4,738
def read_layout(f_name): """ Read a layout (symbols assigned to key positions) from a file. Args: f_name (str): File name of the layout. Returns: The symbols accumulated in a list of lists representing the key placement. Example: The layout file might look like this: a b c d e f g h i j This function returns [['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['h', 'i', 'j']]. """ layout = [] with open(f_name) as f: for line in f: line = line.strip() layout.append(line.split()) return layout
837bada7134b34f64b16951dd21c1ac01a561561
344,094
def net_label_styler(net_label: str) -> str: """Returns the stylised net_label to make CE unified and ET/Voyager less verbose. Assumes that ET's declared as 'ET_ET1','ET_ET2','ET_ET3' in network_spec. Args: net_label: Network label, e.g. 'A+_H..A+_L..V+_V..K+_K..A+_I'. """ return ( net_label.replace("CE2", "CE") .replace("ET_ET1..ET_ET2..ET_ET3", "ET_E") .replace("Voyager", "Voy") )
42ac5259c4025658bafab7793a5d7311662196c0
235,275
def _val_in( val_0, magnitude ): """ Returns magnitude with the sign such that abs(val_0 + mag2) < abs(val_0) If mag < 0, does the opposite. If abs(mag) > 1, may result in an overshoot. """ if val_0 < 0: pass elif val_0 > 0: magnitude = -magnitude else: # Because one cannot draw closer to 0 if one is already there: if magnitude > 0: magnitude = 0 # And since we don't want d to be always negative: else: magnitude = -magnitude return magnitude
b1962196508ec95a4a41c504bdf146dd9735cca3
358,981
def isMultiPolygonal(fire): """ return true if the object is a MultiPolygon """ return True if fire["geometry"]["type"] == "MultiPolygon" else False
c30f885a41b418450030340a9ed15281d902c173
144,769
def is_no_cache_key_option(number): """Return ``True`` iff the option number identifies a NoCacheKey option. A :coapsect:`NoCacheKey option<5.4.2>` is one for which the value of the option does not contribute to the key that identifies a matching value in a cache. This is encoded in bits 1 through 5 of the *number*. Options that are :func:`unsafe<is_unsafe_option>` are always NoCacheKey options. """ return (0x1c == (number & 0x1e))
aad8173794ae13fe885316f8048d66e547addc7b
653,114
import hmac import hashlib def signature(params, shared_secret): """ Calculate the digital signature for parameters using a shared secret. Arguments: params (dict): Parameters to sign. Ignores the "signature" key if present. shared_secret (str): The shared secret string. Returns: str: The 32-character signature. """ encoded_params = "".join([ f"{key}:{params[key]}" for key in sorted(params.keys()) if key != "signature" ]) hasher = hmac.new(shared_secret.encode('utf-8'), encoded_params.encode('utf-8'), hashlib.sha256) return hasher.hexdigest()
c2c93f477ebe5145edaf99a62ba5caa37b32b859
446,077
import six def FormatTagSpecifications(resource_type, tags_dict): """Format a dict of tags into arguments for 'tag-specifications' parameter. Args: resource_type: resource type to be tagged. tags_dict: Tags to be formatted. Returns: A list of tags formatted as arguments for 'tag-specifications' parameter. """ tags = ','.join('{Key=%s,Value=%s}' % (k, v) for k, v in six.iteritems(tags_dict)) return 'ResourceType=%s,Tags=[%s]' % (resource_type, tags)
9db57935ea724a7334b98a5160f0eb09f6325ded
622,927
def init_bytearray(payload=b'', encoding='utf-8'): """Initialize a bytearray from the payload.""" if isinstance(payload, bytearray): return payload if isinstance(payload, int): return bytearray(payload) if not isinstance(payload, bytes): try: return bytearray(payload.encode(encoding=encoding)) except AttributeError: raise ValueError("payload must be a str or bytes") return bytearray(payload)
71cf2c6df77aa341ba2ec1f5f8ac11855b448295
219,759
def str_to_bytes(input_str): """Convert string to bytes. """ return input_str.encode()
da623777a875fe2deb2cb9189c06c89453139617
554,358
def convert_rgb_tuple(tuple_256): """Convert R,G,B Decimal Code from 8-bit integers to [0, 1] floats. E.g. (255, 247, 0) -> (1., 0.9686... , 0.) representing a specific yellow colour, namely #FFF700 in Hex(ademical). """ return tuple(float(rgb_int) / 255 for rgb_int in tuple_256)
1748c6207b58d68ace9e947359cd686964ceb207
47,812
import re def printable(text): """ Convert text to only printable characters, as a user would see it. """ ansi = re.compile(r'\x1b\[[^Jm]*[Jm]') return ansi.sub('', text).rstrip()
653fbbdd2e03d6c43cd26b6823ba6a3c22dcbd18
443,929
import re def affinity_locality_predicate(write_affinity_str): """ Turns a write-affinity config value into a predicate function for nodes. The returned value will be a 1-arg function that takes a node dictionary and returns a true value if it is "local" and a false value otherwise. The definition of "local" comes from the affinity_str argument passed in here. For example, if affinity_str is "r1, r2z2", then only nodes where region=1 or where (region=2 and zone=2) are considered local. If affinity_str is empty or all whitespace, then the resulting function will consider everything local :param affinity_str: affinity config value, e.g. "r1z2" or "r1, r2z1, r2z2" :returns: single-argument function, or None if affinity_str is empty :raises: ValueError if argument invalid """ affinity_str = write_affinity_str.strip() if not affinity_str: return None matchers = [] pieces = [s.strip() for s in affinity_str.split(',')] for piece in pieces: # matches r<number> or r<number>z<number> match = re.match("r(\d+)(?:z(\d+))?$", piece) if match: region, zone = match.groups() region = int(region) zone = int(zone) if zone else None matcher = {'region': region} if zone is not None: matcher['zone'] = zone matchers.append(matcher) else: raise ValueError("Invalid write-affinity value: %r" % affinity_str) def is_local(ring_node): for matcher in matchers: if (matcher['region'] == ring_node['region'] and ('zone' not in matcher or matcher['zone'] == ring_node['zone'])): return True return False return is_local
349858a8737def11c0f57be546638b4631fa4290
296,181
import requests def download_from_url(url: str, timeout=None): """ Download file from the URL. :param url: URL to download. :param timeout: timeout before fail. """ try: response = requests.get(url, allow_redirects=True, timeout=timeout) except requests.exceptions.SSLError: print('Incorrect SSL certificate, trying to download without verifying...') response = requests.get(url, allow_redirects=True, verify=False, timeout=timeout) if response.status_code != 200: raise OSError(str(response)) return response
4d4e9058bb3a093fb3bcf6aa0e6e3e3107a89f92
175,527
def make_draws(dist, params, size=200): """Return array of samples from dist with given params. Draw samples of random variables from a specified distribution, dist, with given parameters, params, return these in an array. Parameters ---------- dist: Scipy.stats distribution object Distribution with a .rvs method params: dict Parameters to define the distribution dist. e.g. if dist = scipy.stats.binom then params could be: {'n': 100, 'p': 0.25} size: int, optional (default=200) The number of random variables to draw. Returns ------- Numpy array: Sample of random variables """ return dist(**params).rvs(size)
795db03cc6697a6e6d84aa0cd2a54cc719714368
383,363
def digits_are_unique(n): """Returns whether digits in n are unique (and no 0)""" digits = set([int(d) for d in str(n)]) if 0 in digits: return False return len(str(n)) == len(digits)
9d2363808e6f8d038d047bc279a89e3de0a93fce
156,004
from pathlib import Path def valid_hostapd_config() -> str: """Get a valid hostapd config to compare.""" hostapd_config_path = Path("tests/data/hostapd/config.txt") return hostapd_config_path.read_text(encoding="utf-8")
893d2801525a2365a0abfd31b0ca43e654e9b9c8
608,475
def find_shortest_path(orbit_graph, obj_start, obj_end, path=[]): """Find the shortest path between the start and end objects in a graph This code is copied from the Python Patterns - Implementing Graphs essay at https://www.python.org/doc/essays/graphs. It is gratefully re-used under the PSF license. Parameters ---------- orbit_graph : dict A dictionary containing every planet (object) as keys, and the list of objects that they connect to (either orbiting or being orbited by) for the values. obj_start : str The name of the starting object obj_end : str The name of the end object path : list Objects that must be traversed in the path from obj_start to obj_end, Default: [] Returns ------- shortest : list The shortest path between two objects. This path contains both the start and end objects. """ path = path + [obj_start] # If the start object is the same as the end object then return the path # right at the start! It will be 1 element long. if obj_start == obj_end: return path # If the start object is not in the graph then return None if obj_start not in orbit_graph: return None # We're going to find the shortest path here, start by calling it None shortest = None # Step through the nodes from the start object for node in orbit_graph[obj_start]: # If the node is not in the path then call **this same function** to # find the shortest path between that object and the end object! # pass the path we've created to that function. if node not in path: newpath = find_shortest_path(orbit_graph, node, obj_end, path) # If we find a new path compare it to the length of the shortest # path. If it is shorter then replace "shortest" with this new path if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest
90114ce973b233a63b47fa5599785309716874b7
335,366
import six import time def retry(ExceptionToCheck, tries=3, delay=2, backoff=2): """ Retry decorator published by Saltry Crane. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ """ def deco_retry(f): def f_retry(*args, **kwargs): mtries, mdelay = tries, delay try_one_last_time = True while mtries > 1: try: return f(*args, **kwargs) try_one_last_time = False break except ExceptionToCheck: six.print_("Retrying in %s seconds" % str(mdelay)) time.sleep(mdelay) mtries -= 1 mdelay *= backoff if try_one_last_time: return f(*args, **kwargs) return return f_retry # true decorator return deco_retry
7a9a35fb64e41535188323adb678c9eafeadc3c3
443,449
def add_versions(nodes, versions): """ In Dutch rechtspraak.nl data, an version can have an annotation. :param nodes: list of node objects :param versions: list of versions :return: list of nodes """ count_version = {} count_annotation = {} for item in versions: id0 = item['id'] val = item['hasVersion'] count_version[id0] = count_version.get(id0, 0) + 1 if val.lower().find('met annotatie') >= 0: count_annotation[id0] = count_annotation.get(id0, 0) + 1 for node in nodes: node['count_version'] = count_version.get(node['id'], 0) node['count_annotation'] = count_annotation.get(node['id'], 0) return nodes
a2fe192246f07a698095d908962586098358a801
114,891
from typing import Any def has_column(table: Any, name: str) -> bool: """ Helper function for determining if a table has a column, works with h5py, pytables, and pandas """ if hasattr(table, "cols"): return hasattr(table.cols, name) return name in table
89a55c55c11dbcef4ed8aa77b045d1c61b677d39
204,144
def get_name_and_versions_to_delete(chart_response, keep=2): """ Get name and unused versions from chart api response. Please see test if confusing about the input and output. If less than 1 to keep, return empty empty to delete :param chart_response: api response of charts :param keep: number of versions to keep. default only keep one :return: Dict(str, list) contains chart name and versions """ name_and_versions = dict() if keep < 1: return name_and_versions for k, v in chart_response.items(): name_and_versions[k] = list() count = 0 for value in v: if count >= keep: name_and_versions[k].append(value['version']) else: count += 1 return name_and_versions
ba0f5ac95be3624829a3e9331f72c0ffb0ff1ad7
264,847
def atomic_masses() -> dict: """ Function which returns the atomic and molecular masses. Returns ------- dict Dictionary with the atomic and molecular masses. """ masses = {} # Atoms masses["H"] = 1.0 masses["He"] = 4.0 masses["C"] = 12.0 masses["N"] = 14.0 masses["O"] = 16.0 masses["Na"] = 23.0 masses["Na_lor_cur"] = 23.0 masses["Na_allard"] = 23.0 masses["Na_burrows"] = 23.0 masses["Mg"] = 24.3 masses["Al"] = 27.0 masses["Si"] = 28.0 masses["P"] = 31.0 masses["S"] = 32.0 masses["Cl"] = 35.45 masses["K"] = 39.1 masses["K_lor_cut"] = 39.1 masses["K_allard"] = 39.1 masses["K_burrows"] = 39.1 masses["Ca"] = 40.0 masses["Ti"] = 47.9 masses["V"] = 51.0 masses["Fe"] = 55.8 masses["Ni"] = 58.7 # Molecules masses["H2"] = 2.0 masses["H2O"] = 18.0 masses["H2O_HITEMP"] = 18.0 masses["H2O_main_iso"] = 18.0 masses["CH4"] = 16.0 masses["CH4_main_iso"] = 16.0 masses["CO2"] = 44.0 masses["CO2_main_iso"] = 44.0 masses["CO"] = 28.0 masses["CO_all_iso"] = 28.0 masses["CO_all_iso_Chubb"] = 28.0 masses["CO_all_iso_HITEMP"] = 28.0 masses["NH3"] = 17.0 masses["NH3_main_iso"] = 17.0 masses["HCN"] = 27.0 masses["C2H2,acetylene"] = 26.0 masses["PH3"] = 34.0 masses["PH3_main_iso"] = 34.0 masses["H2S"] = 34.0 masses["H2S_main_iso"] = 34.0 masses["VO"] = 67.0 masses["VO_Plez"] = 67.0 masses["TiO"] = 64.0 masses["TiO_all_Exomol"] = 64.0 masses["TiO_all_Plez"] = 64.0 masses["FeH"] = 57.0 masses["FeH_main_iso"] = 57.0 masses["OH"] = 17.0 return masses
c476014c415986ba40a11fd943d3867d140a6fdd
461,945
import six def subclasses_of(class_, it, exclude=None): """Extract the subclasses of a class from a module, dict, or iterable. Return a list of subclasses found. The class itself will not be included. This is useful to collect the concrete subclasses of an abstract base class. ``class_`` is a class. ``it`` is a dict or iterable. If a dict is passed, examine its values, not its keys. To introspect the current module, pass ``globals()``. To introspect another module or namespace, pass ``vars(the_module_or_namespace)``. ``exclude`` is an optional list of additional classes to ignore. This is mainly used to exclude abstract subclasses. """ if isinstance(it, dict): it = six.itervalues(it) ignore = [class_] if exclude: ignore.extend(exclude) class_types = six.class_types ret = [] return [x for x in it if isinstance(x, class_types) and issubclass(x, class_) and x not in ignore]
61c1973a5870977dd47a77ff00f31ba5f59a8cd9
293,546
def int_to_bin(x, w, lsb_last=True): """ Converts an integer to a binary string of a specified width x (int) : input integer to be converted w (int) : desired width lsb_last (bool): if False, reverts the string e.g., int(1) = 001 -> 100 """ bin_str = '{0:{fill}{width}b}'.format((int(x) + 2**w) % 2**w, fill='0', width=w) if lsb_last: return bin_str else: return bin_str[::-1]
a3b31614bc464408a8b476b3a8b7a73fb566169a
506,466
import re def raw_seconds_short(string): """Formats a human-readable M:SS string as a float (number of seconds). Raises ValueError if the conversion cannot take place due to `string` not being in the right format. """ match = re.match(r'^(\d+):([0-5]\d)$', string) if not match: raise ValueError(u'String not in M:SS format') minutes, seconds = map(int, match.groups()) return float(minutes * 60 + seconds)
8c77c00737638dcaa512f161c805eb42bde4b8f0
180,257
def strip_space(text, n): """strip n spaces of every line in text""" lines = ( i[n:] if (i[:n] == ' ' * n) else i for i in text.splitlines() ) return '\n'.join(lines)
21d85454bf6985f2a1e9a337e7bbf5bce96d35ca
345,036
def get_product_from_prokka_fasta_header(fasta_header: str) -> str: """ Grabs the gene portion of a .ffn or .faa fasta header """ contig, delim, product = fasta_header.partition(" ") return product
599cddcb449403880f6b1c2345043a909ff8a250
86,238
import torch def get_output_shape(model, in_chans, input_window_samples): """Returns shape of neural network output for batch size equal 1. Returns ------- output_shape: tuple shape of the network output for `batch_size==1` (1, ...) """ with torch.no_grad(): dummy_input = torch.ones( 1, in_chans, input_window_samples, dtype=next(model.parameters()).dtype, device=next(model.parameters()).device, ) output_shape = model(dummy_input).shape return output_shape
44420861d85e5a2dc79ca0a3e061f65fd1d3fb89
200,871
def get_all_SpeciesID(pro_seq): """ This function is used to get all the id from a fasta file :param pro_dir: :return: """ # pro_input = "/home/luhongzhong/ortholog_343/protein_align_s2_R/OG1587_aa_aligned.fasta" # OG_test = list(SeqIO.parse(pro_dir, "fasta")) OG_test = pro_seq all_OG_ID = [] for record in OG_test: # print(record.id) all_OG_ID.append(record.id) return all_OG_ID
8643870ddc4aada7368beef2b3a0770cd6aaf142
152,124
def add_two_ints(first_int, second_int): """ function to add two numbers together :param first_int: the first number to add together :param second_int: the second number to add together :return: sum of inputs, may be positive or negative :rtype: int """ return first_int + second_int
22160c395a19d53934448a4b287fd9ee591ac87a
202,044
def make_Hamiltonian(pauli_list): """Compute the Hamiltonian. pauli_list is a list of tuples [(coefficient, Pauli(v,w))] WARNING. This is exponential in the number of qubits. """ Hamiltonian = 0 for p in pauli_list: Hamiltonian += p[0]*p[1].to_matrix() return Hamiltonian
ab25e19d768a0db49fee74222ccbb3e8d4450ce7
246,515
def miles_per_gallon(start_miles, end_miles, amount_gallons): """Compute and return the average number of miles that a vehicle traveled per gallon of fuel. Parameters start_miles: An odometer value in miles. end_miles: Another odometer value in miles. amount_gallons: A fuel amount in U.S. gallons. Return: Fuel efficiency in miles per gallon. """ distance = end_miles - start_miles mpg = distance / amount_gallons return mpg
8484a81afa3498b0b09c15a5138e85637cee00e6
324,906
def _only(c): """Return only member of a singleton set, or raise an error if the set's not a singleton.""" assert len(c)==1,'non-singleton ' + repr(c) for elt in c: return elt
a4cb38483cca680bf2072f0ea5600c2603410053
242,760
def parse_property(name,value): """ Parses properties in the format 'name(;|\n)key=value(;|\n)key=value' Used by HDB++ config and archivers """ if '\n' in value: value = value.split('\n') elif ';' in value: value = value.split(';') else: value = [value] r = {'name': (value.pop(0) if '=' not in value[0] else name) } value = [v.strip().split('=',1) for v in value] r.update((v[0],v[-1]) for v in value) return r
6cd055a0d8f562b709e632d5b90c3e1e525f3650
437,306
def split_type_name(resource_type_name): """Split the type name of the resource Args: resource_type_name (str): the type_name of the resource Returns: tuples: type and name of the resource """ return resource_type_name.split('/')
5180d2a8b60b0586847a353d7b144c3e84bb2daa
321,509
def view_settings(state): """Get all data about the view state in neuroglancer: position, image zoom, orientation and zoom of the 3d view, and voxel size. Parameters ---------- state : dict Neuroglancer state as JSON dict Returns ------- view : dict Dictionary with keys: position, zoomFactor, perspectiveOrientation, perspectiveZoom, and voxelSize """ view = {} view["position"] = state["navigation"]["pose"]["position"]["voxelCoordinates"] view["zoomFactor"] = state["navigation"].get("zoomFactor", None) view["perspectiveOrientation"] = state.get("perspectiveOrientation", None) view["perspectiveZoom"] = state.get("perspectiveZoom", None) view["voxelSize"] = state["navigation"]["pose"]["position"]["voxelSize"] return view
3df21738922fb0e98d48c36678be1aa1174a3d25
151,706
def bson2string(bval: bytes) -> str: """Decode BSON UTF-8 string as string.""" return bval.decode('utf8')
9075e85572e6b4bb35ea56a30cd90e63a8e355d0
261,083
def normalize(p): """ Naive renormalization of probabilities """ S = sum(p) return [pr / S for pr in p]
40cf1f54a74d057d2f474a476ea9d30bc3340b07
599,229
def calc_bpm(beat_interval, sampling_freq): """Calculate instantaneous BPM from beat to beat interval Args: beat_interval: (int) number of samples in between each beat (typically R-R Interval) sampling_freq: (float) sampling frequency in Hz Returns: bpm: (float) beats per minute for time interval """ return 60 * sampling_freq * (1 / (beat_interval))
9722a514c46525a7ec8851a7042c99851e312807
374,663
def interpolate_real(r1, r2, t): """Linearly interpolate between two real color components.""" r1 = float(r1) r2 = float(r2) return r1 + t * (r2 - r1)
1be5307a16a96032072567648aec72df43075485
208,414
import csv def read_elsys_file(fn): """Reads an Elsys CSV file and returns a list of dictionaries containing key info for each sensor. """ recs = [] with open(fn, newline='') as csvfile: reader = csv.DictReader(csvfile, delimiter=';') for row in reader: recs.append(dict( model = row['SKU'], dev_eui = row['EUI'], app_eui = row['AppEUI'], app_key = row["AppKey"] )) return recs
8ad0270b0bfb1e28a677122744092718fb3220d3
293,134
def get_optimal_step_size_and_momentum_parameters(sketch, fixed, momentum, n, d, m): """ As defined in: 1. Jonathan Lacotte, Mert Pilanci, Optimal Randomized First-Order Methods for Least-Squares Problems (https://arxiv.org/abs/2002.09488) 2. Jonathan Lacotte, Mert Pilanci, Faster Least Squares Optimization (https://arxiv.org/pdf/1911.02675.pdf) Args: sketch: Sketching matrix used fixed: Whether sketching matrix is redrawn at every turn momentum: Whether heavy-ball is used or not n: Number of rows of data matrix d: Number of columns of data matrix m: Sketch size Returns: step size and momentum parameter """ if sketch == 'SRHT': if fixed: if momentum: alpha = m / d step_size = (2 * (alpha - 1)) / (alpha + ((alpha ** 2 - alpha) ** 0.5)) # beta = ((alpha ** 0.5) - ((alpha - 1) ** 0.5)) / (alpha ** 0.5) + ((alpha - 1) ** 0.5) xi, gamma = m / n, d / n lambda_h = (((1 - gamma) * xi) ** 0.5 - ((1 - xi) * gamma) ** 0.5) ** 2 Lambda_h = (((1 - gamma) * xi) ** 0.5 + ((1 - xi) * gamma) ** 0.5) ** 2 # step_size = 4 / ((1 / Lambda_h)**0.5 + (1 / lambda_h)**0.5)**2 beta = ((Lambda_h ** 0.5 - lambda_h ** 0.5) / (Lambda_h ** 0.5 + lambda_h ** 0.5)) ** 2 else: beta = 0 step_size = 1 - d/m else: beta = 0 xi, gamma = m/n, d/n step_size = (xi - gamma)**2 / (xi**2 + gamma - (2 * gamma * xi)) else: if fixed: if momentum: beta = d / m step_size = (1 - beta) ** 2 else: beta = 0 step_size = (4 * m * d) / (m**2 + d**2) else: beta = 0 step_size = ((m - d) * (m - d - 3)) / (m * (m - 1)) return beta, step_size
2cf730c25e91046725dd51006641e1490a5c2dbb
400,937
def fix_label(label): """Splits label over two lines. Args: label (str): Phrase to be split. Returns: label (str): Provided label split over two lines. """ half = int(len(label) / 2) first = label[:half] last = label[half:] last = last.replace(' ', '\n', 1) return first + last
2b5e9202a0770f3c4c8324c672cd6e5656d0acb3
221,723
def render_template(template_name, context, environment): """Renders a jinja2 template""" template = environment.get_template(template_name) return template.render(context)
24b458a6ece91a59c51c8093c039dd554f5c7a36
263,193
def dBtoLinear(db): """Converts a log value to a linear value.""" return 10**(db/20);
120dd8b13cd4eb56de55cba86baa79bc1784cc2d
59,699
import inspect def is_generator(func): """Check whether object is generator.""" return inspect.isgeneratorfunction(func)
489321c7e197706d541596830aa3f18b6fb01901
654,279
def mangle_sheet_name(s: str) -> str: """Return a string suitable for a sheet name in Excel/Libre Office. :param s: sheet name :return: string which should be suitable for sheet names """ replacements = { ':': '', '[': '(', ']': ')', '*': '', '?': '', "'": '"', "\\": "" } for x, y in replacements.items(): s = s.replace(x, y) return s
742728e243c0bb9e9ed0d2af1c5224c20a544f25
605,700
import requests def request_page(url: str) -> requests.Response: """ This function makes a request to the webpage to be scraped Args: url (str): Url of the page to be scraped Returns: page (requests.Response): Object containing the server's response to the HTTP request """ headers= {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36"} page= requests.get(url, headers= headers) if page.status_code != 200: print("Error processing request") return page
33ff9e500d33dfcca06807e036130f12ff14d7fd
466,976
def generate_url(date: str) -> str: """ generate a url for the download, given a date string in format YYYY-mm-dd""" base_url = 'https://www.rollingstone.com/charts/albums/' url = base_url + date + '/' return url
4ed337c82ddfaa03c34560250c22bbbadbb3ccb9
337,943
import struct def unpack_fp(fmt, fp, increment=True): """Unpacks a structure from a file, increment the position if set. """ if increment: return struct.unpack(fmt, fp.read(struct.calcsize(fmt))) else: pos = fp.tell() ret = struct.unpack(fmt, fp.read(struct.calcsize(fmt))) fp.seek(pos) return ret
c7b17fc3dd5e854241f15da808439f9bb5ae4f81
387,478
def makeProcessUrl(samweb, projecturl, processid): """ Make the process url from a project url and process id """ if not '://' in projecturl: projecturl = samweb.findProject(projecturl) return projecturl + '/process/' + str(processid)
d45ec5a5c8f5133afcf799ebb88ae7e3683dd087
528,344
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): """Return True if the values a and b are close to each other and False otherwise. (Clone from Python 3.5) Args: a: A float. b: A float. rel_tol: The relative tolerance – it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05. The default tolerance is 1e-09, which assures that the two values are the same within about 9 decimal digits. rel_tol must be greater than zero. abs_tol: The minimum absolute tolerance – useful for comparisons near zero. abs_tol must be at least zero. Returns: True if the values a and b are close to each other and False otherwise. """ return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
270be278b3865f5faebdf1bb436daa7bec90fb9c
45,699
import re def parse_portpin(name): """Finds the port name and number of a pin in a string. If found returns a tuple in the form of ('port_name', port_number). Otherwise returns `None`. """ m = re.search("P([A-Z])(\d+)", name) if m: port_name, port_number = m.groups() return (port_name, int(port_number))
84a5f701a2bed7317051589baacedd600810e257
493,506
def freestyle_table_params(rows, aging): """Returns parameters for OpenSQL freestyle request""" return {'rowNumber': str(rows), 'dataAging': str(aging).lower()}
f764202958acc29b4d21d481406ee029eedb28f6
678,199
def eliminate_none(data): """ Remove None values from dict """ return dict((k, v) for k, v in data.items() if v is not None)
d213b19d204716ae1f4c6db2103c5fe8a283ee5d
551,387
def transpose(data): """Transpose a data structure 1. dict data = {'2017-8': 19, '2017-9': 13} In: transpose(data) Out: [('2017-8', '2017-9'), (19, 13)] 2. list of (named)tuples data = [Member(name='Bob', since_days=60, karma_points=60, bitecoin_earned=56), Member(name='Julian', since_days=221, karma_points=34, bitecoin_earned=78)] In: transpose(data) Out: [('Bob', 'Julian'), (60, 221), (60, 34), (56, 78)] """ if type(data) == dict: # return list([*zip(*data.items())]) return list(map(tuple, zip(*data.items()))) elif type(data) == list: return list(zip(*data)) else: return None
8d734c288931123ddacbf5333bb744fdb9dc2622
521,832
import torch def create_init_scores(prev_tokens, tensor): """ Create init scores in search algorithms Args: prev_tokens: previous token tensor: a type tensor Returns: - initial scores as zeros """ batch_size = prev_tokens.size(0) prev_scores = torch.zeros(batch_size).type_as(tensor) return prev_scores
0da0f693041602ed7e79f4f114fedac317419875
572,056
def attack(decrypt_oracle, iv, c, t): """ Uses a chosen-ciphertext attack to decrypt the ciphertext. :param decrypt_oracle: the decryption oracle :param iv: the initialization vector :param c: the ciphertext :param t: the tag corresponding to the ciphertext :return: the plaintext """ c_ = iv + c p_ = decrypt_oracle(bytes(16), c_, c[-16:]) return p_[16:]
80106b2376a8fa2d30afe96e5a763d6153ed3936
37,624
def enumerate_possibilities(mesa, hand): """Finds all the way of adding to 15 using exactly 1 card from the hand, and any arbitrary number from the mesa. Args: mesa -- List of Card objects hand -- List of Card objects Returns: List of tuples, each representing a different possibility for adding up to 15. Example: [(card1, card2), (card1, card3, card4)] Example: >>> from quince.components.card import Card >>> card1 = Card(1, 'oro') >>> card2 = Card(9, 'espada') >>> card3 = Card(2, 'oro') >>> card4 = Card(4, 'copa') >>> card5 = Card(3, 'copa') >>> card6 = Card(2, 'basto') >>> card7 = Card(5, 'espada') >>> mesa = [card1, card2, card3, card4] >>> hand = [card5, card6, card7] >>> result = enumerate_possibilities(mesa, hand) >>> result == [(card5, card1, card2, card3), (card6, card2, card4), ... (card7, card1, card2)] True """ def find_permutation(card_pool, partial_sum, permutations): """Recursively find all permutations of card_pool and partial_sum which add to 15, and append each result to permutations """ # calculate the current sum of all cards in partial_sum current_sum = sum([card.info()[0] for card in partial_sum]) if current_sum == 15: # found a permutation, append it to permutations permutations.append(tuple(partial_sum)) if current_sum >= 15: # at or beyond target sum, so stop recursing return # for each remaining card in card_pool, see if there is a permutation # adding to the target, given the current partial_sum for card in enumerate(card_pool): remaining_cards = card_pool[card[0] + 1:] new_partial_sum = partial_sum + [card[1]] find_permutation(remaining_cards, new_partial_sum, permutations) permutations = [] # for each card in the hand, find all permutations that add to 15 for card in hand: find_permutation(mesa, [card], permutations) return permutations
38bd19f1022d70ae7f32cfcc98f4d0f5f381598e
510,072
def seconds_to_str(seconds): """ converts a number of seconds to hours, minutes, seconds.ms """ (hours, remainder) = divmod(seconds, 3600) (minutes, seconds) = divmod(remainder, 60) return "h{}m{}s{}".format(int(hours), int(minutes), float(seconds))
edaa063c1d5423c0404a41e83f1a1419891e685a
34,763
def events_flatten(events): """ Combines all overlapping events in an ordered sequence of events """ if len(events) <= 1: return events else: a = events[0] b = events[1] if a.intersects(b): return events_flatten([a.join(b)] + events[2:]) else: return [a] + events_flatten(events[1:])
985dcb9a5da172c05a07a180110ba7c7de1c4fc7
423,750
from re import findall from pathlib import Path from typing import Dict def _check_site(filepath: Path, site_code: str, gc_params: Dict) -> str: """Check if the site passed in matches that in the filename Args: filepath: Path to data file site: Site code gc_params: Dictionary of GCWERKS parameters Returns: str: Site code """ site_data = gc_params["sites"] name_code_conversion = {value["gcwerks_site_name"]: site_code for site_code, value in site_data.items()} site_code = site_code.lower() site_name = findall(r"[\w']+", str(filepath.name))[0].lower() if len(site_code) > 3: raise ValueError("Please pass in a 3 letter site code as the site argument.") try: confirmed_code = name_code_conversion[site_name].lower() except KeyError: raise ValueError(f"Cannot match {site_name} to a site code.") if site_code != confirmed_code: raise ValueError( f"Mismatch between code reasd from filename: {confirmed_code} and that given: {site_code}" ) return site_code
62c6bf7e72a56cc894214c3570f256a7e8db6471
317,916
def _clean_roles(roles): """ Clean roles. Strips whitespace from roles, and removes empty items. Args: roles (str[]): List of role names. Returns: str[] """ roles = [role.strip() for role in roles] roles = [role for role in roles if role] return roles
d52b568f8a2d756f53f0b51307578f4d4afdcd08
667,334
import torch def binary_accuracy(prediction, target): """Calculates accuracy between two classes using probabilities Parameters ---------- prediction : torch.Tensor or torch.autograd.Variable Vector of probabilities of class 1 target : torch.Tensor Vector containing the class indices 0 or 1 """ if isinstance(prediction, torch.autograd.Variable): prediction = prediction.data predicted_classes = torch.gt(prediction, 0.5) return torch.mean(torch.eq(predicted_classes, target.byte()).float())
4f101992de444af744c06b361146feeee917b682
636,874
def does_contain(stackstrings, ss): """ Check existence of stackstring in list. :param stackstrings: list of all recovered stackstrings :param ss: new stackstring candidate :return: True if candidate already in stackstring list, False otherwise """ hashable_ss = (ss.fva, ss.s, ss.written_at) for s in stackstrings: hashable = (s.fva, s.s, s.written_at) if hashable == hashable_ss: return True return False
01dd5b3f92ceb1eb8ca5cb048e61f988164603df
512,351
def iou(bbox_1, bbox_2): """ Get IoU value of two bboxes :param bbox_1: :param bbox_2: :return: IoU """ w_1 = bbox_1[2] - bbox_1[0] + 1 h_1 = bbox_1[3] - bbox_1[1] + 1 w_2 = bbox_2[2] - bbox_2[0] + 1 h_2 = bbox_2[3] - bbox_2[1] + 1 area_1 = w_1 * h_1 area_2 = w_2 * h_2 overlap_bbox = (max(bbox_1[0], bbox_2[0]), max(bbox_1[1], bbox_2[1]), min(bbox_1[2], bbox_2[2]), min(bbox_1[3], bbox_2[3])) overlap_w = max(0, (overlap_bbox[2] - overlap_bbox[0] + 1)) overlap_h = max(0, (overlap_bbox[3] - overlap_bbox[1] + 1)) overlap_area = overlap_w * overlap_h union_area = area_1 + area_2 - overlap_area IoU = overlap_area * 1.0 / union_area return IoU
5a08958265d5afbb7891d408bed6c7f3e5b27f3f
410,218
def sequential_search(target, lyst): """ in() 顺序搜索 Returns the position of the target item if found, or -1 otherwise. :param target: :param lyst: :return: """ position = 0 while position < len(lyst): if target == lyst[position]: return position position += 1 return -1
9a686606dd70b95568a016f4155c6b9ae55efca0
655,157
def class_name(cls): """ Return class name given a class instance. """ return cls.__name__
8e4b6a32cc7b1d9fd0e9d4bab9df3091da77b0cd
489,790
def listify(s): """ Converts s into a list if not already. If s is None, an empty list will be returned. """ if s is None: s = [] elif isinstance(s, (set, tuple)): s = [i for i in s] elif not isinstance(s, list): s = [s] return s
1b44b3b3a041b3df5d6cfbd08394e421b3c6e831
687,035
def compute_tf(document, term, type='raw'): """ This function computes the raw term-frequency (TF) for a given document and term. :param document: array of terms (list object) :param term: single term :param type: Type of TF calculation to use, default is 'raw'. Other options are 'augmented' and 'boolean' :return tf: raw term frequency of term in the document """ assert (type in ['raw', 'augmented', 'boolean']), "The parameter 'type' is not recognized. Please enter 'raw', 'boolean' or 'augmented' as it's value." tf = 0.0 if type == 'raw': tf = float(document.count(term)) if type == 'boolean': tf = float(term in document) if type == 'augmented': tf = 0.5 + ((0.5 * float(document.count(term))) / float(max([document.count(x) for x in document]))) return tf
41065eab5b8b2aba2d5c805668f6ce6c5a185f5b
276,721
from typing import Counter def breakdown_structure(connection_counter: Counter, rules: dict) -> Counter: """breaksdown the polymer structure and add new elements Args: connection_counter (Counter): Initial count of each connection rules (dict): Rules how to break down each connection Returns: Counter: new polymer structure represented by the number for each pairs Examples: >>> breakdown_structure(Counter(AB = 1), {"AB":"C"}) Counter({'AC': 1, 'CB': 1}) >>> breakdown_structure(Counter(AB = 1, BC = 4), {"AB":"C", "BC":"A"}) Counter({'AC': 5, 'BA': 4, 'CB': 1}) """ new_counter = Counter() for poly_pair in connection_counter: new_counter[poly_pair[0] + rules[poly_pair]] += connection_counter[poly_pair] new_counter[rules[poly_pair] + poly_pair[1]] += connection_counter[poly_pair] return new_counter
279b375cd23f1957f2c9d8454bf5f405143d9103
271,440
def NameAndAttribute(line): """ Split name and attribute. :param line: DOT file name :return: name string and attribute string """ split_index = line.index("[") name = line[:split_index] attr = line[split_index:] return name, attr
7595f51d728c5527f76f3b67a99eccd82fb9e8b7
12,500
def _force_list(val): """Ensure configuration property is a list.""" if val is None: return [] elif hasattr(val, "__iter__"): return val else: return [val]
0f1f6bc48bbe68007549015d1602b9e8bc4561d9
416,058
def hasValidKey(dict, key): """ Return True if key is in dict and not None, False otherwise. """ return key in dict and dict[key] is not None
438ca30f1b133be80389abf8304cd24b09fce1d8
16,624
def StringLiteral(str): """Convert string to string literal.""" literal = '"' + str.replace('\\', '\\\\').replace('"', '\\"') + '"' return literal.encode('utf8')
6132ffd563b5be3c024dd0eadbffbdb6dbe5a448
456,486
def to_bytes(x): """Convert an integer to bytes.""" return x.to_bytes(2, 'big')
49eb15a37cbbc2dc235a84931b4518082a56fe67
179,181
def fromHex( h ): """Convert a hex string into a int""" return int(h,16)
ffae24cdade04d3ab4098f13643098dff2c69ef2
25,459
def set_availability_zone(radl, zone): """ Modify RADL to set availability zone """ radl_new = '' for line in radl.split('\n'): if line.startswith('system'): line = line + "\navailability_zone = '%s' and" % zone radl_new = radl_new + line + '\n' return radl_new
df1b0e46ea0c3aa97bb2c2b70dc44d99b7489983
359,566
import string import random def generate_string(number, chars=string.ascii_lowercase+string.digits): """Generate a string.""" return ''.join(random.choice(chars) for _ in range(number))
5517cb92930652dcaf9f15dd5d5bcd7c9fc378ec
159,580
def k_min(l, k): """ Gets the k smallest elements in a list and their indices. """ enum_l = list(enumerate(l)) l_s = sorted(enum_l, key=lambda v: v[1]) k_mins = l_s[:k] return tuple(map(list, zip(*k_mins)))
99cd944b1594595d23be75c7b8fca3fd31875bbb
225,794
import math def get_bearing(compass_device): """Return the vehicle's heading in radians. When thw world's +ve x is on the left and +ve y is on top, angle is 0. Angle increases clockwise.""" if compass_device is not None: compass_data = compass_device.getValues() radians = math.atan2(compass_data[2], -compass_data[0]) while radians > math.pi: radians -= 2*math.pi while radians < -math.pi: radians += 2*math.pi else: radians = 0.0 return radians
b000460dd19a24834dbba34790e6fbaad45c18af
300,143
def _ExtractCommentText(comment, users_by_id): """Return a string with all the searchable text of the given Comment PB.""" commenter_email = users_by_id[comment.user_id].email return '%s %s %s' % ( commenter_email, comment.content, ' '.join(attach.filename for attach in comment.attachments if not attach.deleted))
7c372eb15805ca3f47b54c32ba9afb64208815dc
686,649
def FUNCTION_TO_REGRESS_TEMPLATE(x, a, b, c): """ A simple function to perform regression on. Args: x: A list of integers. a,b,c: Coefficients """ return (x[0] * a/2) + pow(x[1], b) + c
46f53a3d2a7e6729f51439a355991103dcbc03c2
18,236
def require(*modules): """Check if the given modules are already available; if not add them to the dependency list.""" deplist = [] for module in modules: try: __import__(module) except ImportError: deplist.append(module) return deplist
88df83cd33d8bddea63e4d2fbfb4d8351a3c23b1
1,331
import functools import builtins import logging def requires_ipython(fn): """Decorator for methods that can only be run in IPython.""" @functools.wraps(fn) def run_if_ipython(*args, **kwargs): """Invokes `fn` if called from IPython, otherwise just emits a warning.""" if getattr(builtins, '__IPYTHON__', None): # __IPYTHON__ variable is set by IPython, see # https://ipython.org/ipython-doc/rel-0.10.2/html/interactive/reference.html#embedding-ipython. return fn(*args, **kwargs) else: logging.warning( 'Method "%s" is a no-op when invoked outside of IPython.', fn.__name__) return run_if_ipython
f826621ff8a89720c932f1f396b746ae6aef4e64
664,174
def get_s3_url(s3_client, bucket, key, expires_in=604800): """ Generate signed URL for specified object key in bucket """ signed_url = s3_client.generate_presigned_url( 'get_object', Params={ 'Bucket': bucket, 'Key': key }, ExpiresIn=expires_in ) return signed_url
1a90988077a938e13aad7fb4195478735cfc9bd0
157,743
def VerifyNonNegativeGems(gems): """Returns that all gem values are nonnegative.""" return all(count >= 0 for count in gems.values())
6beb0c19f502249f49864edcaf7af8d0d3c57946
286,045
def optional_one(query): """Like calling one() on query, but returns None instead of raising NoResultFound. """ results = query.limit(1).all() if results: return results[0] return None
07e71ff5505452e248804799755504c54d22ed03
145,452
def N2_depolarisation(wavelength): """ Returns the depolarisation of nitrogen :math:`N_2` as function of wavelength :math:`\lambda` in micrometers (:math:`\mu m`). Parameters ---------- wavelength : numeric Wavelength :math:`\lambda` in micrometers (:math:`\mu m`). Returns ------- numeric Nitrogen :math:`N_2` depolarisation. Examples -------- >>> N2_depolarisation(0.555) # doctest: +ELLIPSIS 1.0350291... """ wl = wavelength N2 = 1.034 + 3.17 * 1.0e-4 * (1 / wl ** 2) return N2
22e0ccd1bc668594a381578ff85504f534b22084
436,049