content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def spin_energy(J = -2, mu = 1.1, k = 1, state = [1,-1,1,-1]): """Computes the energy of some spin configuration. Note, all lists should be in the format of a sequential list where 1 is spin up and -1 is spin down :param J: Ferromagnetic constant, defaults to -2 :type J: int or float :p...
cb717dabd238b55f5bf6ff393bb8c1fd5b955c92
628,192
def parse_reference(reference): """ Helper function, parses a 'reference' to document name and anchor """ if "#" in reference: docname, anchor = reference.split("#", 1) else: docname = reference anchor = None return docname, anchor
06a9ff5a6c0e211f636093800b80b2e72f8630b4
628,194
import torch def torch_cat_dicts(L): """Concatenates a list of dictionary of torch tensors L = [{k: v1}, {k: v2}, ...] to {k: [v1; v2]} """ d = {} if L: K = L[0].keys() cat_fns = [torch.hstack if L[0][k].ndim == 0 else torch.cat for k in K] for cat_fn...
4bff7805f09170dcee91f7103bd6a4013db1f4ef
628,196
def partition_games(df, frac=0.7): """ Returns a 2-tuple of arrays containing the indices. The first are the indices in the dataframe that correspond to the first <frac> games of each season. The second are the indices that correspond to the last <1-frac> games of each season. Assumes that the g...
f6d84bcbdc1b651c27976c1241144f1666dbd119
628,199
from typing import Optional from typing import Any def safe_ith(arr: Optional[list], ind: int, default: Any = None) -> Optional[Any]: """Performs safe index access. If array is None, returns default.""" if arr is not None: return arr[ind] return default
26b2f6ab8779461efb0400bda8b7c5c35d5f9fea
628,202
def decode_report_item_id(report_id): """Provided with a DOM report item id return the report_item id in the database""" return int(report_id.replace("reportItem", "").split("-")[1])
e3a6304f9bdfa1d9b3238a265b54a3240f9a592c
628,204
def count_refs_in_mapping( references, mapping ): """Count the number of references in the mapping""" count = 0 for r in references: if r in mapping: count += 1 return count
cde74f6bc17615946caf151b156f3f076a826095
628,207
def to_list(val): """ Method for casting an object into a list if it isn't already a list """ return val if type(val) is list else [val]
c087b7cee3ed633da959d3c77ada38f7a1cc13e8
628,208
import random def random_seq(size, nucleotides="ACTG"): """Generate a random nucleotide sequence of length `size` and composition `nucleotides` Parameters ---------- size : int length of desired sequence nucleotides : str, optional string of nucleotides to use in sequ...
694e5136330db21342fef8ac7de8174cc2245dae
628,209
def convert(seconds): """ Convert seconds to (seconds, minutes, hours, remainder_seconds) """ r = seconds s = r % 60 m = (r - s) % (60*60) h = (r - s - m) % (60*60*60) return s, int(m/60), int(h/(60*60)), r - (s + m + h)
bd91005a7677f959d1e59a15505e08facdde2825
628,212
def dup_mul_term(f, c, i, K): """ Multiply ``f`` by ``c*x**i`` in ``K[x]``. Examples ======== >>> R, x = ring("x", ZZ) >>> R.dmp_mul_term(x**2 - 1, ZZ(3), 2) 3*x**4 - 3*x**2 """ if not c or not f: return [] else: return [cf * c for cf in f] + [K.zero]*i
bfb4c67f26ed6d1929aea4e889cc0fb172d1ef34
628,215
def pull_pairs(flat): """Return a Iterable of pairs of adjacent items in another Iterable `flat` should be of even size: `len(list(flat)) % 2 == 0` >>> list(pull_pairs([1, 2, 3, 4])) [(1, 2), (3, 4)] """ it = iter(flat) return zip(it, it)
fefb989b406e776d2b8f83057cbabfa4171b51b2
628,225
def sizes_execpt(inp, dim): """return all except the specified dimension indices""" return [s for d, s in enumerate(inp.shape) if d != dim]
936ef2366eaa6bc32671e1c541a885cc44f833b1
628,227
def _find_neighborhoods_ids(input_list, neighborhoods_df): """ Read in a list of names of neighborhood names. Returns a list of neighbhorhood ids Args: input_list: a list containing the names of the neighborhoods in the treatment group. neighborhoods_df: a dataframe containi...
71ec994ce2e4fe28ec20a1e5604eea4159f8c172
628,228
def slowest_speed(speed_list): """ Compute the derived speed by finding the slowest object in the speed_list. :param speed_list: A list of objects with a speed_mb attribute. :returns: Speed as an integer. """ speed_mb = 0 if speed_list: for obj in speed_list: if not spee...
d7021efbc4d5d897233cf1e1948a14e4a6b73596
628,229
def world2pixel(x,y,w,h,bbox): """Converts world coordinates to image pixel coordinates""" # Bounding box of the map minx,miny,maxx,maxy=bbox # world x distance xdist=maxx-minx # world y distance ydist=maxy-miny # scaling factors for x,y xratio = w/xdist yratio = h/ydist # Calculate x,y pixel co...
381c053cec430f4eeb58a5fdef1a7978ec104cbe
628,230
def dominating_set(G): """ Finds a greedy approximation for a minimal vertex cover of a specified graph. At each iteration, the algorithm picks the vertex with the highest degree and adds it to the cover, until all edges are covered. :param G: networkx graph :return: vertex cover as a list of ...
b1e446d2dd338d6e84a98543b6de33c6c86be836
628,232
def convert_iob_to_iobes(iob_tags): """Converts a sequence of IOB tags into IOBES tags.""" iobes_tags = [] # check each tag and its following one. A None object is appended # to the end of the list for tag, next_tag in zip(iob_tags, iob_tags[1:] + [None]): if tag == 'O': io...
edd195dc30650542e3542a270b47ee4d6bcdcbb8
628,233
def getTitlePerks() -> list: """ Get the list of perks to look for in the job description :return: list - list of perks """ perkList = ["Why you'll like working here", 'Benefits', "The top five reasons our team members joined us (according to them)", "What’s in it fo...
6dae31ce2ed55fab41ad495067ff0cdca4372bb0
628,237
import operator def max_element (elements, ordered = None): """ Returns the maximum number in 'elements'. Uses 'ordered' for comparisons, or '<' is none is provided. """ if not ordered: ordered = operator.lt max = elements [0] for e in elements [1:]: if ordered (max, e): ...
465684f0437416470b5544b94d5bc7bb4989e958
628,238
def prid(obj, show_cls=False): """Get the id of an object as a hex string, optionally with its class/type.""" if obj is None: s = 'None' else: s = hex(id(obj)) if show_cls: s += str(type(obj)) return s
12b00c07c075b0b9ff4ad7f1d0a2deabb1fa2af3
628,240
def extract_seq_pseudo_label_from_submission(submission_df, rna_seq_id, pred_cols=None): """ Each Kaggle's OpenVaccine submission csv file can be used to make a pseudo label. OpenVaccine submission format is explained here: https://www.kaggle.com/c/stanford-covid-vaccine/overview/evaluation Exampl...
72ff4c68bf45d5e5a4a4cfd5f2d1c6146b248858
628,242
def calculate_point_triplet_orientation(coordinate_1, coordinate_2, coordinate_3): """ Returns a value that represents the negative sine of the angle created by connecting coordinate_1 to coordinate_2 to coordinate_3. If this connection occurs in a clockwise fashion the value will be negative, counterc...
b478c38af7ba37a84dc4ecff1af81a26f911463c
628,243
from typing import Union from typing import List def create_column_statement(name: str, data_type: str, nullable: bool, constraints: Union[List, None] = None, **kwargs) -> str: """Function for generatin...
0b1b199f7f700a73ab69f98745e57ecf3b39a345
628,245
def _MergeProguardConfigs(proguard_configs): """Merging the given proguard config files and returns them as a string.""" ret = [] for config in proguard_configs: ret.append('# FROM: {}'.format(config)) with open(config) as f: ret.append(f.read()) return '\n'.join(ret)
af65bdb4b5063b47d8876862a544fcfefd27ec37
628,246
def scoped_logger_name(module_name: str, config_name: str = "maestral") -> str: """ Returns a logger name for the module ``module_name``, scoped to the given config. :param module_name: Module name. :param config_name: Config name. :returns: Scoped logger name. """ if config_name == "maest...
c9d3add60b9e01956692b4c3e9ce4efff474503b
628,251
def op_help(oper, left_op, right_op): """Helper method does math on operands and returns them""" if oper == '+': return left_op + right_op elif oper == '-': return left_op - right_op elif oper == '*': return left_op * right_op else: return left_op / right_op
5f52ea03cc05679fd2882170e39babb864094150
628,257
import pickle def serialize(x): """Return a pickled object.""" return pickle.dumps(x)
c3debbc8df9b457879a784344ab7885b95b9ecd3
628,259
def preload(pytac_lat): """Load the elements onto an 'elems' object's attributes by family so that groups of elements of the same family can be more easily accessed, e.g. 'elems.bpm' will return a list of all the BPMs in the lattice. As a special case 'elems.all' will return all the elements in the latt...
b65c6950442bf3afd55f1b3cc5c67529170c3b69
628,260
def list_to_csv(parlist, sep=", "): """Returns a csv string with elements from a list.""" result_str = "" for par in parlist: result_str += str(par) + sep return result_str[:-len(sep)]
86b816790f982f9133661a8c4e775a7e13209aed
628,266
import importlib def load_command_class(name): """ Given a command name, returns the Command class instance. All errors raised by the import process (ImportError, AttributeError) are allowed to propagate. """ module = importlib.import_module(f's2e_env.commands.{name}') return module.Comman...
43359285196ce8ab8f68423fea0429df341feaae
628,268
def build_datasets_by_publisher_query() -> str: """Build query to count datasets grouped by publisher.""" return """ PREFIX dct: <http://purl.org/dc/terms/> PREFIX dcat: <http://www.w3.org/ns/dcat#> SELECT ?organizationNumber (COUNT(DISTINCT ?dataset) AS ?count) FROM <https://datasets.fellesdatakatalog.digdir.n...
6c1dfdbc3bad0da05d12a0aecfa3118ff6d8558a
628,273
def update_list(content, new_values): """Update a list with additional or new values.""" new_content = content[:] if content else [] new_values = [x.strip() for x in new_values.split(",")] if isinstance(new_values, str) else new_values or [] for value in new_values: if value == "-": ...
553b6b134fd57827c52df4e0ac80acb321530d24
628,278
def checkColumns(board: list) -> bool: """ Returns True if there is no repeating numbers in the columns. """ for i in range(len(board[0])): column = [] for line in board: if line[i].isnumeric(): column.append(line[i]) if len(column) != len(set(column))...
8f4c974fef412f6a791cf7b525ddb15edea64c77
628,282
def f(z): """ A function of metallicity Z, which we will set as the yield of Sr from core-collapse supernovae. """ return 3.5e-8 * (z / 0.014)
c86494dd24a4b3525ab0357eff538d66b169700c
628,285
def GetMessageFromQueue(session, queueurl, delete_after_receive=False): """Get message from the queue to process :param session: Session to use for AWS access :type session: boto3.session.Session :param queueurl: URL of the queue from which to receive messages :type queueurl: str :param delete_after_receiv...
04d28777329fd6ca85936e827c41b46b0c444b5f
628,296
def offset_api_limit(sp, sp_call): """ Get all (non-limited) artists/tracks from a Spotify API call. :param sp: Spotify OAuth :param sp_call: API function all :return: list of artists/tracks """ results = sp_call if 'items' not in results.keys(): results = results['artists'] ...
6dcbcf33e4a47fba5dbd832bcf4fb7cfb5898fa7
628,304
from typing import Callable def make_normalization_function(min_value: float, max_value: float, scope=(0, 1)) -> Callable: """ Minimax normalization :param min_value: Min value in data :param max_value: Max value in data :param scope: Normalization range :return: normalization function ""...
2414bb7172cff411e461f4255f7c7d69bf6b8d9e
628,310
import requests def request(url, input_file, token, include_words=False): """ :param input_file: Input object :param url: Endpoint url :param token: X-Inferuser-Token :param include_words: Include Mindee vision words in http_response :return: requests response """ input_file.file_objec...
bed43f7888d0d7f6a06641b02d5984cfe2879107
628,313
def xml_get_attrs(xml_element, attrs): """Returns the list of necessary attributes Parameters: element: xml element attrs: tuple of attributes Returns: a dictionary of elements """ result = {} for attr in attrs: result[attr] = xml_element.getAttribute(attr) ...
77911646f3624dc089475927a8b1e14abd9caef7
628,315
from typing import Dict def _get_api_headers(token: str) -> Dict: """ Return authorization header with current token. Parameters ---------- token : str Azure auth token. Returns ------- Dict A dictionary of headers to be used in API calls. """ return { ...
c8761da1ba2c36825b1a73bd236196a125d1bdfd
628,316
def arg_cond_req_or(args_array, opt_con_req_dict): """Function: arg_cond_req_or Description: Checks a dictionary list array for options that require one or more options to be included in the argument list. Arguments: (input) args_array -> Array of command line options and values. ...
b691b92eeaae063dd25e80f5db7b0ed795ea8519
628,318
def fanout(w): """ Get the number of places a wire is used as an argument. :param w: WireVector to check fanout for :return: integer fanout count """ _, dst_nets = w._block.net_connections() if w not in dst_nets: return 0 all_args = [arg for net in dst_nets[w] for arg in net.args] ...
3ce96c3eab252d0b34c13c346cb9acfbaf34c618
628,319
def get_tree( graph, root, prop, mapper=lambda x: x, sortkey=None, done=None, dir="down" ): """ Return a nested list/tuple structure representing the tree built by the transitive property given, starting from the root given i.e. get_tree(graph, rdflib.URIRef("http://xmlns.com/foaf/0.1/P...
345d5023d1342d58ed9f644d78a1bc7908726bbd
628,320
def get_file_contents(file_path): """ Get expected result from file. """ try: with open(file_path, 'r') as f: # remove string literals (needed in python2) and newlines return f.read().replace('\r', '').strip() except OSError as e: raise e
4debf6b82eed7f4c1ee5e747efb7c4a8ce33fcda
628,321
def endswith_xFFxD9(data): """ Checks whether the given data endswith `b'\xD9\xFF'` ignoring empty bytes at the end of it. Parameters ---------- data : `bytes-like` Returns ------- result : `bool` """ index = len(data) - 1 while index > 1: actual = data[index] ...
9be0913e7226ff64938e083f19990f8521d01873
628,322
def infix(formula: str, arg: int): """ evaluation of infix expression :param formula: bytebeat formula :param arg: time argument :return: int: computation result """ characters = formula.replace("t", str(arg)).replace("/", "//") try: return eval(characters) except...
7bee7c4711b20b91502b934607752cfa7022dd85
628,324
import requests def get_list_nab() -> list: """ Get list of possible time series to retrieve from the Numenta Anomaly Benchmark: https://github.com/numenta/NAB. Returns ------- List with time series names. """ url_labels = 'https://raw.githubusercontent.com/numenta/NAB/master/labels/combi...
2dc0bc54c274f2208a2303826a394401d44e6ffc
628,325
from typing import Dict def first_subset_second(first: Dict, second: Dict) -> bool: """ Return true if first is a subset of second, false otherwise. :param first: first dict :param second: second dict :return: true if all elements in first are in second, and are mapped to same value,...
0f05340b8ba92f088d547837d8fd12c03933ccac
628,326
def mean(items): """ Calculates arithmetic mean. Returns zero for empty lists. """ return float(sum(items)) / len(items) if items else 0
a01271032bb9b7b2a1f9e305edf95b08da58e810
628,329
from datetime import datetime def _build_date(date, kwargs): """ Builds the date argument for event rules. """ if date is None: if not kwargs: raise ValueError('Must pass a date or kwargs') else: return datetime.date(**kwargs) elif kwargs: raise Val...
b298683842e3e2d24e04d9c6a03d09debee62ac6
628,330
def parse(puzzle_input): """Parse input""" return [int(line) for line in puzzle_input.split()]
e870a59298d44991e5fb82d5de432613e5078ebd
628,332
import six def to_utf8(string): """ Encode a string as a UTF8 bytestring. This function could be passed a bytestring or unicode string so must distinguish between the two. """ if isinstance(string, six.text_type): return string.encode('utf8') return string
393d902e34f11b46317c5ef4d9501cfc725f0cb8
628,341
import gzip def reader(fname): """Returns correct file object handler or reader for gzipped or non-gzipped FastQ files based on the file extension. Assumes gzipped files endwith the '.gz' extension. """ if fname.endswith('.gz'): # Opens up file with gzip handler return gzip.open ...
6d24474fb51b9902888c13d4341cf0b25fcbf104
628,342
import torch def one_hot_encoding(input_tensor, num_labels): """ One-hot encode labels from input """ return torch.eye(num_labels, device=input_tensor.device)[input_tensor]
ce878d1dbc1f5802a4a8059a586d14bc1e9d342a
628,343
def check_type(lp): """ check the type of the launchpad :param lp: launchpad object :return: name of launchpad type """ if lp.Check(0, "pro"): print("Launchpad Pro") return "Pro" elif lp.Check(0, "mk2"): print("Launchpad Mk2") return "Mk2" else: ...
acf8b349d0bd8858b0445d74b6eb9ea3bca582ce
628,347
def edits0(word): """ Return all strings that are zero edits away from the input word (i.e., the word itself). """ return {word}
7f4a4d1ce4584dc66443eabe8999722351e815e6
628,348
def greet_all(greeting: str, names: list) -> list: """Return a list of strings that consist of the greeting messages for each person in names. The format of each greeting message is '<greeting>, <name>', where greeting is the given greeting and <name> is an element of <names>. The returned list should...
03303a15e5f8ac807f8e630fc3210d611bd7af1d
628,352
def idx_word(idx, nlp): """ Returns the token/word at the specified index of the spaCy model. :param idx: The index to query. :param nlp: The spaCy model. :return: Word at the index in the vocabulary. """ hash_code = nlp.vocab.vectors.find(row=idx) if len(hash_code) == 0: return '<UNK>' return nlp.vocab.stri...
5cc53f5869c247ce8759583e63aae2ea1ef3e216
628,354
def get_entity_from_bio(tokens, entitys): """ Get {word:entity} from bio labeled sequence,. Only accept BIO schema. inputs: tokens: A B C D E F entitys: B-GPE I-GPE B-PER I-PER O O return: {'AB': 'GPE', 'CD': 'PER'} """ word2entity = {} left = 0 r...
817de1c0d696682cc119cf5e2fe550c103838729
628,357
def all_same_suit(card_set): """ Determines whether the cards in the given collection are all of the same suit. """ return all(card.suit == card_set[0].suit for card in card_set[1:])
8069c8809b788fc754f0d2720947b03c513653cb
628,361
def lorenz(in_, t, sigma, b, r): """Evaluates the RHS of the 3 Lorenz attractor differential equations. in_ : initial vector of [x_0, y_0, z_0] t : time vector (not used, but present for odeint() call) sigma : numerical parameter 1 b : numerical parameter 2 r : numerical parameter ...
f4b9758be3a0f956f2b27fbb389dfcb2fb6edbfc
628,362
from typing import Sequence from typing import Dict def get_masks(counterfactuals: Sequence[Sequence[str]], vocab_to_indices: Dict[str, Sequence[int]]): """Returns masks indicating if counterfactual tokens are in original sentence. Args: counterfactuals: The tokens of the input's counterfactual...
504d4f9e3fba844c4d2496c47003e34fd54b8752
628,365
def zscore(raw, mean, stddev): """Returns the zscore (standard score) of a value""" zscore = (raw - mean) / stddev return zscore
545e3354105c021dc537dcd80013f074b311f71b
628,369
def get_filter_list(table): """Get the filter list and number of filter in a table.""" filters = set(table['filter']) return filters, len(filters)
347e623dc82a74453bfd82524946ff5be9db28b6
628,371
def approximate_index(dataset, findvalue): """ Return index value in dataset, with optimized find procedure. This assumes a `dataset` with continuous, increasing values. Typically, these are timestamps. :param list dataset: a continuous list of values (f.e. timestamps) :param int findvalue: the value,...
98e8720ee3cf7e175ba0df69cf4f3671f4b52ecb
628,375
def _find_qubit_id(cmd): """Find qubit id in openqasm cmd.""" left = [] right = [] for i, j in enumerate(cmd): if j == '[': left.append(i) elif j == ']': right.append(i) if len(left) != len(right): raise ValueError(f"Parsing failed for cmd {cmd}") ...
78082b69c932d0ad78f491e002d9c5a1665c622c
628,377
def get_upload_path(instance, filename): """ Construct the path to where the uploaded config file is to be stored. """ configtype = instance.config_type.lower() # sanitize the filename here.. path = 'export/config/{0}/{1}'.format(configtype, instance.filename) return path
76c4f0fef08c649cd482c33e2891984d214169a7
628,378
from functools import reduce def compute_product_string(product_string): """Takes `product_string` and returns the product of the factors as string. Arguments: - `product_string`: string containing product ('<factor>*<factor>*...') """ factors = [float(f) for f in product_string.split("*")] ...
ebd2a7e57529dc24960a29b5406634830f30bf83
628,380
def get_battery_energy_full(battery_id): """ Get the maximum energy stored in the battery :param battery_id: Battery ID/Number e.g. BAT0 :return: maximum energy (int) """ with open(f'/sys/class/power_supply/{battery_id}/energy_full') as f: battery_percentage = int(f.read()) return b...
7465c89a91680d746a35d6f5db0dd27c652e9e39
628,381
def _GetTestSubPath(key): """Gets the part of the test path after the suite, for the given test key. For example, for a test with the test path 'MyMaster/bot/my_suite/foo/bar', this should return 'foo/bar'. Args: key: The key of the TestMetadata entity. Returns: Slash-separated test path part after...
c792a606d54b10f67bbb270964be319135500bf5
628,382
def get_string_without_quotes(str): """ Helper function to return a string without the quotes :param str: Input String :type str: String :return: String with quotes replaced :rtype: String """ return str.replace('"', '')
56f4dc56d82b0dae01f93fcb0ea405f6b0e3ccac
628,385
def property_type(value): """ Return the type for given value in Neo4j land. """ if isinstance(value, str): return "string" elif isinstance(value, int): return "int" elif isinstance(value, float): # Nb. Python floats are double precision return "double" elif ...
7c037c2ad310b8c0a30823b10eda10a5c3f5f37f
628,388
def pivotCombinedInventories(combinedinventory_df): """Create a pivot table of combined emissions. :param combinedinventory_df: pandas dataframe returned from a 'combineInventories..' function :return: pandas pivot_table """ # Group the results by facility,flow,and compartment combinedi...
71d56bd546b5990c7b2658f0616ebaf8ed6f472f
628,390
def fahrenheit_to_celsius(temperature): """Covert from Fahrenheit to Celsius :param temperature: degree understood to be in Fahrenheit NOTE: Fahrenheit to Celsius formula: °C = (°F - 32) x 5/9 First subtract 32, then multiply by 5, then divide by 9. """ return (temperature - 32) * 5.0 / 9.0
cc054b90d17c7d9850e2762181b86a6c54719142
628,394
def ranges_overlap(min1, max1, min2, max2): """ :param min1: :param max1: :param min2: :param max2: :return: return True if the 2 ranges overlap (edge inclusive), else False """ if min1 <= max2 and min2 <= max1: return True return False
ec531bf2303e1d7a36d55a6ba9be8fac00fb65e4
628,396
import copy def recursive_postprocessing(filter_, condition, replacement): """Recursively descend into the query, checking each dictionary (contained in a list, or as an entry in another dictionary) for the condition passed. If the condition is true, apply the replacement to the dictionary. Param...
2a639a621100ab7c23222c26a8944ea223b5b6d1
628,397
import bisect def find_between(a, low, high): """Finds all elements of a between low and high. Simple binary search algorithm using the bisect module. Searches the array a for all elements between low and high. Useful for finding mergers that occur between time t1 and t2. Arguments: a {...
40596dfbb4d99c7b9988fbf22c787eaf22a94f6a
628,399
def get_attribute(element, attribute, default=0): """ Returns XML element's attribute, or default if none. """ a = element.getAttribute(attribute) if a == "": return default return a
84406553069b9c300d6ea188d970f554cd7ee424
628,400
import zlib import random def find_credit_grade(email): """Returns the credit grade of the person identified by the given email address. The credit grade is generated randomly using the email as the seed to the random number generator. The credit grade can be either A, B, C, D, E, F or G. ""...
254cafd9db80219b4ea4725af76c89365e32c646
628,402
def _factor2(n): """Factorise positive integer n as d*2**i, and return (d, i). >>> _factor2(768) (3, 8) >>> _factor2(18432) (9, 11) Private function used internally by the Miller-Rabin primality test. """ assert n > 0 i = 0 d = n while 1: q, r = divmod(d, 2) ...
52c2a627636f07e4b8fe6028b705051cf2565a4a
628,404
def ConsensusMotif(sequence_set): """Find the consensus motif for the input sequence set.""" k = len(sequence_set[0]) matrix = [[0] * k for i in range(4)] # Initiate a zero-filled nested list. for col, colbases in enumerate(zip(*sequence_set)): for row, letter in enumerate('ACGT'): ...
4d0dc206ddad3dd3b701e332f9f7bad3fe1975a2
628,408
import logging def cartesian_goals(x, y): """ Use a cartesian coordinate system to calculate goals from given X and Y values. :param x: x cartesian coordinate :param y: y cartesian coordinate :return: cartesian derived base, fibia, and tibia servo goal values """ # Convert 2D X and Y ...
9bb73b628967ab171d654f4d6e50d6055e8b6023
628,409
def has_overlap2(label1,label2): """ Returns TRUE if the two labels overlap Otherwise returns FALSE """ label1,label2 = label1.lower(),label2.lower() labeloverlaps = {"pron-subj":{'pron-obj': '1', 'copula': '2', 'present_marker_deletion': '4', 'lexical': '6', 'dem_pro': '9', 'gender': '14', 'mar...
45e183a8636db73312b6b0c4f94c6f8a478e357c
628,410
import pathlib def _get_artefacts_count_of_bootstrap_nodes(_: pathlib.Path) -> int: """Returns number of network bootstrap nodes. """ return 3
7c03491c47161fc65474bc39a59e3a8b6ecf34f2
628,411
def pattern(vals: list) -> str: """ Return a regex string from a list of values """ return f"^({'|'.join(map(str, vals))})$"
08a26c2d4abd890a1dc96a58a9814e6f5d02b85f
628,417
def isHidden(path_): """Hidden files are files which names starts of dot symbol. This method returns True if file is hidden or False otherwise.""" return path_[0] == '.'
3314929857660e491467d35190e355ffc67c8b17
628,418
def to_root_latex(s): """ Converts latex expressions in a string *s* to ROOT-compatible latex. """ return s.replace("$", "").replace("\\", "#")
775459ec73270d22fb4797fa4062711d34b58d58
628,424
def _lstrip(source: str, prefix: str) -> str: """ Strip prefix from source iff the latter starts with the former. """ if source.startswith(prefix): return source[len(prefix) :] return source
0782647c439cafe9d1036c8d6541ac5377991e2c
628,425
def format_time(function_name, time, nb_iterations, timeout): """ Provides a nicely formatted string given a function name, a time of execution and the number of iterations. Args: function_name (str): The name of the function that was executed. time (float): The time it took for the fun...
c8d28e1835ce9a8d36a1a1ba2dd436c676a56910
628,427
def _index_keys(columns): """ Take all the key columns and build a list of possible index tuples that can arise from them. For example, given the following schema: "varId|dbSNP,gene" these are the possible index key lists: [['varId', 'gene'], ['dbSNP', 'gene']] """ keys = [k.split...
ee7cb47b0abe6936ba7f5cfd720a4e92854a0d90
628,431
def zigzag(n): """ Produce a list of indexes that traverse a matrix of size n * n using the JPEG zig-zag order. Taken from https://rosettacode.org/wiki/Zig-zag_matrix#Alternative_version.2C_Translation_of:_Common_Lisp :param n: size of square matrix to iterate over :return: list of indexes in t...
d20e0466c30301278a5727b5f3975286969c9a11
628,437
def file_to_str(fname): """ Read a file into a string PRE: fname is a small file (to avoid hogging memory and its discontents) """ data = None # rU = read with Universal line terminator with open(fname, 'rU') as fd: data = fd.read() return data
f89dce69a8f39d6d98a3cc9f70d684a1ac9d52bf
628,439
from typing import Any def is_primitive_type(arg_type: Any) -> bool: """Check if the input type is one of `int, float, str, bool`. Args: arg_type (typing.Any): input type to check. Returns: bool: True if input type is one of `int, float, str, bool`. """ try: return isinst...
288b4e425f65b428ca33164fbc5aeb891eb39ad9
628,441
def _parse_range(r): """ Parse an integer sequence such as '0-3,8-11'. '' is the empty sequence. """ if not r.strip(): return [] res = [] for piece in r.strip().split(","): lr = piece.split("-") if len(lr) == 1 and lr[0].isdigit(): res.append(int(...
2cbd53453cb98a2c2f4d5799c159ffec762fc009
628,443
def normalize_list_params(params): """ Normalizes parameters that could be provided as strings separated by ','. >>> normalize_list_params(["f1,f2", "f3"]) ["f1", "f2", "f3"] :param params: Params to normalize. :type params: list :return: A list of normalized params. :rtype list "...
3c837def00e2c543b33b6829d157e9b3f0699f19
628,446
def normalize(img, radius=1): """ Normalize image to L2 norm of radius """ img = img - img.mean(-2, keepdim=True).mean(-1, keepdim=True) norms = img.pow(2).sum(-2, keepdim=True).sum(-1, keepdim=True).sqrt() return img / norms * radius
0dc92bc66d6d9e19d62455e66fbd2cbf09f0535e
628,447
def get_rerole_stats(rerole_ops): """ Gets a summary of information about the rerole operation. """ stats = {'base': {}, 'team':{}} users = {'base': {}, 'team':{}} for (user, role_spec) in rerole_ops: to = role_spec[:2] per_team = role_spec[2] if len(per_team): ...
33c922ef88ebec52d522f8c3a0d802e2c745034c
628,451
def count_params(model, trainable=True): """ Count number of parameters in pytorch model (optional: only count trainable params) """ if not trainable: return sum(p.numel() for p in model.parameters()) else: return sum(p.numel() for p in model.parameters() if p.requires_grad)
30be6a99ab63b1b2ef71b740009520a39bf1a05c
628,453
def prepare_params(sort=None, filter=None, params=None): """ Prepares the different parameters we want to send as the query in a request :param sort: str The sorting (used in list commands issued to the DNSimple API) :param filter: dict The filtering (used in list commands issued to the...
b4d97173ba3e4777a843ff332dae1b33c22204ae
628,455