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 '...
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_dat...
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]...
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: ...
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...
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 spli...
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. :...
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 ...
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: ...
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 ( ...
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 alr...
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 o...
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: ...
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' pa...
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....
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...
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: ...
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 Dis...
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. ...
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...
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['...
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 ve...
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 ...
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 cl...
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**...
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 ...
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 = torc...
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_...
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() ...
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 i...
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 = {'nam...
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...
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: (f...
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(di...
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 Sq...
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...
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 = { ':': '', '[': '(', ']': ')', '*': '', '?': '', ...
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 ...
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))) ...
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 ...
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 (po...
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), M...
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_si...
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 """ ...
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 pos...
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: ...
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 GCWER...
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 """ ...
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)...
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 ...
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 positio...
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 'b...
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 Ret...
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(co...
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.at...
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__',...
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': ke...
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 ----...
22e0ccd1bc668594a381578ff85504f534b22084
436,049