content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def set_parallel(n_core): """ Set parallel. This helper function decides whether the analysis should be run in parallel based on the number of cores specified. :param n_core: An integer; specifies the number of cores to use for this analysis. :return: A boolean; whether analysis should be run in p...
92d6ae54c7620303a4c6b644b81b3bcc16e185cd
546,431
def lower(tokens): """Lower-case all tokens of a list""" return [token.lower() for token in tokens]
1488a793ad74cc200c810fff47e068a00a762e0d
338,841
import yaml def load_repositories(repos_file): """ Load repository yaml """ if repos_file: try: file_descriptor = open(repos_file, 'r', encoding='utf-8') except IOError as error: print("Error: open file {} failed", repos_file, error) return None ...
d3f1ae60407f3c9eeebc9ca5326fa753e166c2ba
638,425
from pathlib import Path def get_output_filepath(filepath): """Returns a new output filepath based on a given filepath. Given filepath: /Users/max/Desktop/video.mp4 Returned filepath: /Users/max/Desktop/video_blurred.mp4 Args: filepath (str): Path to an existing file Returns: str...
f63bc2ae127647e8cb3b8a9a969f87077262540d
258,898
def _extract_hostname(url: str) -> str: """Get the hostname part of the url.""" if "@" in url: hn = url.split("@")[-1] else: hn = url.split("//")[-1] return hn
316310e703954dc6b3a995e8b523dbb549a3e9ca
309,193
def eval_acc(results, is_print=False): """ :param results: np.array shape of (N, 2) [pred, label] :param is_print: print eval score :return: score """ acc = (results[:, 0] == results[:, 1]).sum() / results.shape[0] * 100 if is_print: print('*****************') print('ACC Po...
2071437521ce8a13d1efc5618b9ca745b6664bf7
492,414
def identity(*args): """ Identity function :param args: Splat of arguments :type args: ```tuple``` :return: First arg if len(args) is 1 else all args :rtype: Union[Tuple[Any, Tuple[Any]]] """ return args[0] if len(args) == 1 else args
565efa7ab8994accdbc0d4cd27e7762818ab953f
393,241
def package_time(date_dict): """Package a time/date statement in a standardised form.""" return {"time_value": date_dict}
6c4097e162091e3992fa6ef57e83093cf0788c46
670,688
def create_pair(n): """ Create a pair of n-digit integers, from 1-up and from 9-down. """ one = 0 two = 0 up = 1 down = 9 num_digits = 0 while num_digits < n: one = 10 * one + up two = 10 * two + down up += 1 if up == 10: up = 1 dow...
04ab585ef8ddaa113aafd958cfefe9ad4778aba7
485,047
def sql2dict(queryset): """Return a SQL alchemy style query result into a list of dicts. Args: queryset (object): The SQL alchemy result. Returns: result (list): The converted query set. """ if queryset is None: return [] return [record.__dict__ for record in queryset]
c55fa18773142cca591aac8ed6bdc37657569961
707,916
import difflib def diff_output(expected: str, actual: str) -> str: """ Compares the expected and actual outputs of a command Args: expected: desired output actual: STDOUT captured from command Returns: str: diff output """ # files read in are converted to "universal"...
cce18472d064196739fcfa0ea7a6a98256c5c20d
576,436
def uniqify(name: str, other_names: list) -> str: """Return a unique name with .xxx suffix if necessary. Example usage: >>> uniqify('hey', ['there']) 'hey' >>> uniqify('hey', ['hey.001', 'hey.005']) 'hey' >>> uniqify('hey', ['hey', 'hey.001', 'hey.005']) 'hey.002' >>> uniqify('hey'...
2fcbe5180b2206e7fcab3540126bdf50d2fd16d2
280,308
import collections def parse_bv_keywords(section): """Grab the keywords in a BrainVision section, and create a dictionary. Args: section: a section starts with [xxx], and contains lines of key=value Returns: A dictionary of keys and values from this section. """ section = section.split(']', 1)[1] ...
72e4423ae4f87fddc34e695c99bb3e83dc8b9512
337,577
import torch def _compute_stacked_offsets(sizes, repeats): """Computes offsets to add to indices of stacked tensors (Tensorflow). When a set of tensors are stacked, the indices of those from the second on must be offset in order to be able to index into the stacked tensor. This computes those o...
4f981d196adc4462acfc8428e0d781b15f80756a
289,432
def ib_error(code): """Given an error code, return the error text. """ error_strings = [ \ "System error", \ "Function requires GPIB board to be CIC", \ "No Listeners on the GPIB", \ "GPIB board not addressed correctly", \ ...
3531c21efbe293f1bc15a786d9a64b7c4f9744d8
277,224
import random def get_sampled_frame_number(total_frame_number: int, sample_rate: int): """ Sample frame numbers randomly according to the sample rate. :param total_frame_number: total frame number of target video :param sample_rate: sampling rate for frame :return: list of sampled frame number ...
037c1e131a66869918965f3034933dea36c5531b
521,500
def convert_metadata(old_metadata): """ Convert model metadata from old format (with camel-case parameter group names) to new format. Args: old_metadata (dict): Model metadata in old format Returns: new_metadata (dict): Model metadata in new format """ model_metadata = old_met...
18a5b62dbf361bb414f04853cee61d1920467785
332,413
def max_or_none(iterable): """ Returns the max of some iterable, or None if the iterable has no items Args: iterable (iterable): Some iterable Returns: max item or None """ try: return max(iterable) except ValueError: return None
6d123df136e427d54525306439930dc560a0cf05
577,604
def get_random_elements(faker, elements): """ Generate random unique sorted elements using elements :param faker: Faker Library :param elements: List of elements :return: Random unique elements value sorted """ result = faker.random_elements( elements=elements, unique=True,...
7008d2aea430f720bf34ed217f2ed88ca677c106
565,576
def _find_sub_list(sublist, full_list): """ Args: - sublist is a list of words that are supposed to be found in the full list. - full list is a list of words that is supposed to be searched in. Returns: - List of tuples with the form (first_index_of_oc...
2f3c0ba416a4f1beaf03681f0361b766823667fb
258,698
def mean_hr_bpm(num_beats, duration): """Average heart rate calculation This is a simple function that converts seconds to minutes and divides the total number of beats found by the total minutes in the strip. :param num_beats: a single integer of the number of total beats in a strip :param durati...
83eb5433cec77f9294e1310410e3e06ed1b1eda9
677,402
def ff_decimal_rounder_uncommon(ls_fl_num2format=[0.0012345, 0.12345, 12.345, 123.45, 1234.5, 123456.789], dc_round_decimal={0.1: 4, 1: 3, 100: 2, float("inf"): 0}, verbose=False): """Decimal rounding function with conditional formatting by number size...
b83472401c401332e7c727cb95cebaa74973e4b1
454,830
def memoize(func): """A decorator to cache the return value of func. Args: func: function to decorate Returns: wrapper: decorated function """ cache = {} def wrapper(args): try: return cache[args] except KeyError: cache[args] = func(args...
c3068fa4b723dc8e8ee767433fc55f078c8acb63
260,714
import math def ssr(precinct, seed): """ Sum of Square Roots (SSR) pseudorandom function from Rivest, 2008: http://people.csail.mit.edu/rivest/Rivest-ASumOfSquareRootsSSRPseudorandomSamplingMethodForElectionAudits.pdf Input: precinct number (as an integer) and seed (a string of 15 digits) >>> ss...
c180cd2725474f2b2a9cea0e4747a19952dd4d9a
208,844
from typing import Dict from typing import Any def can_local_namespace_access_route( local_namespace: str, route_obj: Dict[str, Any], ) -> bool: """Can this local namespace access the given route?""" for protection in route_obj['namespace-access']: if protection['namespace'] == local_n...
a12447621a803e0bc0cdf208c0870548aef65d74
357,429
def numfmt( num, fmt="{num.real:0.02f} {num.prefix}", binary=False, rollover=1.0, limit=0, prefixes=None, ): """Formats a number with decimal or binary prefixes num: Input number fmt: Format string of default repr/str output binary: If True, use divide by 1024 and use IEC binary...
837b271860e065bfd1e811e5f3ca16040f3ea663
470,305
def datetime_to_iso(date): """ convert a datetime object to an ISO_8601 formatted string. Format of string is taken from JS date to string """ return date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
29768984b64f1c66c5d9ee809058d352927c5658
593,660
def interpret_field(data): """ Convert data to int, if not possible, to float, otherwise return data itself. Parameters ---------- data : object Some data object Returns ------- data : int, float or same data type as the input Return the data object casted as an int, ...
4e32d7a7574c5564a0a76fc4ce0dc600bcaceded
520,858
def pluralize(count, item_type): """Pluralizes the item_type if the count does not equal one. For example `pluralize(1, 'apple')` returns '1 apple', while `pluralize(0, 'apple') returns '0 apples'. :return The count and inflected item_type together as a string :rtype string """ def pluralize_string(x): ...
1e980ca625f93611b37de797efcfb4f3afb8c7ea
245,310
def stringToLengthAndCombo(combo_string): """Creates a tuple of (attribute, value) tuples from a given string. Args: combo_string: string representation of (attribute, value) tuples. Returns: combo_tuple: tuple of (attribute, value) tuples. """ length = len(combo_string.split(';'))...
51a71a967e5c14df10c3df848bf8655ee853334f
300,761
def polygonArrayToOSMstructure(polygon): """ polygonArrayToOSMstructure(polygon) With a polygon array gets structure of poly for OSM sql. Parameters ---------- polygon : Array Array that contains the poligon separated [[lat,long], [lat', long'], [lat'', long''], ...] same as [...
61c3debcf4b8ff47eca574fd1bb94a0cde52dbf5
86,512
def fpr(fp: int, tn: int) -> float: """False Positive Rate computed from false positives and true negatives.""" return fp / (fp + tn) if fp + tn else 0.0
455610e45cad46e56dae87a71f0ec842763cbc05
645,046
def ifN(v, d): """Return value if value is not None else default""" return v if v is not None else d
fb3ccd6def31f35a53e968510141e4d389a21f5d
146,604
import torch def make_target(label, label_to_ix): """Turn target labels into a numeric vector where each label has a unique index""" return torch.LongTensor([label_to_ix[label]])
33b8f92868d1de685154cda236de4bbe53a9df70
623,030
from pathlib import Path def res_get(res, attr: Path, **kw): # pylint: disable=redefined-outer-name """ Get a node's value and access the dict items beneath it. The node value must be an attrdict. """ val = res.get("value", None) if val is None: return None return val._get(attr, ...
eeb5615b253d2a55333714f328e7245bb8a202b7
344,312
def ngrams(seq, min_n, max_n): """ Return min_n to max_n n-grams of elements from a given sequence. """ text_len = len(seq) res = [] for n in range(min_n, min(max_n + 1, text_len + 1)): for i in range(text_len - n + 1): res.append(seq[i: i + n]) return res
af71c95d5c240da78061f481e8068619a4071393
268,727
from typing import Any def get_full_name(obj: Any) -> str: """Returns identifier name for the given callable. Should be equal to the import path: obj == import_object(get_full_name(obj)) Parameters ---------- obj : object The object to find the classpath for. Returns ---...
6f83f808f8c4d226b1d26365adc75f5cb6c4e28f
15,087
def flip_keypoints(keypoints): """ Flipped keypoints horizontally (x = -x) """ for i, k in enumerate(keypoints): keypoints[i, 0] = -keypoints[i, 0] return keypoints
2da5e0b3fc2fde35a49b8615fd3fbe8f63fec3f3
101,178
def create_kmers(seq,kmer_size): """ Create a set of kmers from a sequence. """ return [seq[i:(i+kmer_size)] for i in range(len(seq)-kmer_size+1)]
5fbdcf9c7e9802eed2d491c7b1c40f2c7c7a9f2e
353,057
def json_parts(json_line): """ Checks for "label" and "description" components of Json command. PArameters: json_line (str): The Json command being passed into the function. Returns: Arr [Bool, Bool]: Is there a label command? Is there a description comman...
168f6cd064b7f443539b3cd8a187a7234085ef7b
692,084
def udfize_lambda_string(expression: str): """Given an expression that uses 'input' as a parameter, return a lambda as a string.""" return "lambda input: ({})".format(expression)
bdcc542568702e91f60400ef25f86df9d4847563
91,889
def noop(value, param=None): """A noop filter that always return its first argument and does nothing with its second (optional) one. Useful for testing out whitespace in filter arguments (see #19882).""" return value
babd4941efdff8fa67df07a5dd3d86da210b91c2
101,677
import torch def add_gaussian_noise(tensor, mean=0.1, std=1., device='cpu'): """Function that add noise to a given tensor. Args: tensor: An input tensor mean: Gaussian noise mean std: Gaussian noise std device: device used to store tensor Returns: tensor: A new tensor with added noise "...
2e3cd8c500d064497ffbc0aa2476a670d2179043
339,960
def _create_gauss(*, mu, sigma, numspikes, prng): """Create gaussian inputs (used by extgauss and evoked). Parameters ---------- mu : float The mean time of spikes. sigma : float The standard deviation. numspikes : float The number of spikes. prng : instance of Rando...
6c0e6b1c9bbd778e8b447baf5524dfd5f56778ee
308,394
def div_scaler(X, divider): """ Divides the input by the divider """ return X.astype("float32") / divider
53dd469ac2d988eadd048af21cb452418c7fc111
498,552
def strip_hash_bookmark_from_url(url): """Strip the hash bookmark from a string url""" return (url or '').split('#')[0]
c31f569b147d4e9bd74e932856b1a2e168e05bb3
666,194
def getClassLabel(file): """ This method extracts the class label from a given file name or file path. The class label should either be the file name without ending numbers or the folder in which the file is located @param file: The file name or the file path @returns the class label...
cc604a09aed4067fc8e9a71d774822dbc409a736
55,099
def make_object(row, names, constructor): """Turns a row of values into an object. row: row of values names: list of attribute names constructor: function that makes the objects Returns: new object """ obj = constructor() for name, val in zip(names, row): func = constructor.con...
36755906bfa415c09b3cf738c1c9873d61d03fe3
264,097
import six def equals_lf(line): """ Return True if line (a text or byte string) equals '\n'. """ return line == ('\n' if isinstance(line, six.text_type) else b'\n')
4a70e39970f0869319346806ae95159b3293e549
135,739
def mul_point(p, m): """ multiply point p by m """ sp = [] for i in range(3): sp.append(p[i]*m) return sp
6f9cbe000476ee46d8cce842112d463f8e70ef92
354,569
def to_hsl(color: tuple) -> tuple: """Transforms a color from rgb space to hsl space. Color must be given as a 3D tuple representing a point in rgb space. Returns a 3D tuple representing a point in the hsl space. Saturation and luminance are given as floats representing percentages with a precisio...
725cd35cb9ae83d635ba5d2b477afdeb3c1bd37c
110,922
def switch(*args): """:yaql:switch Returns the value of the first argument for which the key evaluates to true, null if there is no such arg. :signature: switch([args]) :arg [args]: mappings with keys to check for true and appropriate values :argType [args]: chain of mapping :returnType: a...
c0d152b4004866826c4892a1340865b79feefa2c
696,194
def calc_bin_cov(scaffolds, cov): """ calculate bin coverage """ bases = sum([cov[i][0] for i in scaffolds if i in cov]) length = sum([cov[i][1] for i in scaffolds if i in cov]) if length == 0: return 0 return float(float(bases)/float(length))
19b23824a96afd287a5a2bc55f249b624b81781a
363,968
from pathlib import Path def is_subpath(parent_path: str, child_path: str): """Return True if `child_path is a sub-path of `parent_path` :param parent_path: :param child_path: :return: """ return Path(parent_path) in Path(child_path).parents
6852efb5eede8e16871533dca9d0bf17dd7454bb
683,030
def calc_last_time_active(xml_element, filename): """ Calculate the absolute time (in EPOCH) when an event was active for the last time. :param xml_element: The element containing an lastTimeActive attribute :param filename: A filename where the name contains digits only, representing the creation time ...
8b084647e0cf09eeec99230ac7fcac18d62ac047
472,170
def get_cum_returns(returns, compound=True): """ Computes the cumulative returns of the provided returns. Parameters ---------- returns : Series or DataFrame, required a Series or DataFrame of returns compound : bool True for compounded (geometric) returns, False for arithmetic...
89b39cdae9e1cd8e0ebd5547c46a6795a2d45954
469,216
def create_sample_db(ntables): """ Create a python description of a sample database """ rv = {} for i in range(1, ntables + 1): rv["table%s" % i] = { "columns": [ { "name": "id", "type": "integer", "use_s...
c49f583b4e7f58f1bbb7ad05902c1fc9010bd35c
7,242
def _request_meta(request): """ Extract relevant meta information from a request instance """ meta = {"ip_address": request.META["REMOTE_ADDR"]} if "HTTP_USER_AGENT" in request.META: meta["user_agent"] = request.META["HTTP_USER_AGENT"] if hasattr(request, "session") and request.session.s...
7dcb84a16513902ceeba415ff7b0870fee4dc3c7
141,476
def sanitize(string): """Sanitizes the string Args: string (str): input string Returns: str: sanitized string """ sanitized = string.replace('"', '').replace("'", "") return sanitized
b96845220d376fd278a63118f77a27b78f568565
78,662
def parse_story_file(content): """ Remove article highlights and unnecessary white characters. """ content_raw = content.split("@highlight")[0] content = " ".join(filter(None, [x.strip() for x in content_raw.split("\n")])) return content
350774af9ba5341f8869039fb99018be951365af
81,545
def getFiducialPositions(fiducialNode): """ Extracts positions from input fiducial node and returns it as array of positions Parameters ---------- fiducialNode : vtkMRMLMarkupsFiducialNode FiducialNode from which we want the coordinates Returns ------- List of arrays[3] of fiducial positions """ ...
9f42c8bf3208400b1ee6a85506e63f1f14f2def5
451,036
def get_cu_mask(total_count, active_cu): """ Returns a compute-unit mask as a binary string, with a single compute unit set. """ a = ["0"] * total_count a[active_cu] = "1" return "".join(a)
8a5190959993f56bcc6e29f76329014d25218899
246,923
def get_need_types(app): """ Returns a list of directive-names from all configured need_types. **Usage**:: from sphinxcontrib.needs.api import get_need_types all_types = get_need_types(app) :param app: Sphinx application object :return: list of strings """ needs_types = g...
db3b74b43bb09fe70038b2c0707fa76219c0f565
415,906
import difflib def elements_equal(e1, e2, ignore={}, ignore_trailing_whitespace=False, tidy_style_attrs=False, exc_class=ValueError): """ Recursively compare two lxml Elements. Raise an exception (by default ValueError) if not identical. Optionally, ignore trailing whitespace after block e...
061c3de64f118c54d2e09d5e990c36d952b59237
279,994
def getGridMarker(location, grid): """Return marker in grid at given location""" return grid[location[0]][location[1]]
28952b0e179534809ea6fa08b977a596312655fc
603,977
def get_src_attrs(placeholder, image, slick=False): """ :param placeholder: url of static image :param image: url of real image :param slick: slick carousel requires `data-LAZY`, semantic-ui uses `data-SRC` attribute :return: src attribute with temporary static placeholder image, real image will be ...
ba749518c0a98ff220fa820783c2ac7f5657274a
252,323
def bitwise_and_2lists(list1, list2): """ Takes two bit patterns of equal length and performs the logical inclusive AND operation on each pair of corresponding bits """ list_len = len(list2) return_list = [None] * list_len for i in range(list_len): return_list[i] = list1[i] & list2[i...
832b9a745eb157d2ae97c620994337c6f44b734e
615,037
def object_belongs_to_module(obj, module_name): """ Checks if a given object belongs to a given module (or some sub-module). @param obj: Object to be analysed @param module_name: Name of the module we want to check @return: Boolean -> True if obj belongs to the given module, False otherwise ...
9528c6be37c5cc4b067d95131c0ee0b376c455cc
372,374
def interpreted_value(slot): """ Retrieves interprated value from slot object """ if slot is not None: return slot["value"]["interpretedValue"] return slot
513e27b42d3762694fc4d9a1f0456b2ea6790724
298,980
def _make_rv_params_variable(rv, **params): """ Wraps the random variable rv, allowing it to accept time-dependent parameters. """ if any(callable(x) for x in params.values()): return lambda t: rv( **{k: (x(t) if callable(x) else x) for k, x in params.items()}) ...
a497962b67f88a9bc01855e695d17a0aceaa8958
49,124
def readable_timedelta(days): """To get the number of weeks and days in given nuber of days""" number_of_weeks = days // 7 #To get number of weeks number_of_days = days % 7 # To get number of days return('{} week(s) and {} day(s)'.format(number_of_weeks, number_of_days))
5be929ebb108192540648dbd2af980a009437ad7
91,138
def add_frame(img, c, b=40): """Add a colored frame around an image with color c and thickness b """ img = img.copy() img[:, :b] = img[:b, :] = img[:, -b:] = img[-b:, :] = c return img
63b00fd6e47347baf49c28a38b74829aef158b98
104,330
import configparser def parse_prep(prepname, prepfile): """Gets parameters from specified prep name and config file.""" preps = configparser.ConfigParser() preps.read(prepfile) return preps[prepname.upper()]
c7e6dca45c8bb544f87ffcecb23e247a7940e194
374,805
def countPxlsPerClass(data, label_col = "Label"): """ Counts amount of pixels per class label Parameters ---------- data: numpy.dataframe dataframe containing data label_col: str ( optional) name of label column Examples --------) >>> countPxlsPerClass(data, "Label_...
c23fbb1e11a816297fa577b701288903c93791af
561,088
import re def camel_to_snake_case(in_str): """ Convert camel case to snake case :param in_str: camel case formatted string :return snake case formatted string """ return '_'.join(re.split('(?=[A-Z])', in_str)).lower()
a905bd2007fcaafed1e811a48c5fe14831e77631
686,249
def remote_raw_val_from_db_val(db_val: bytes) -> str: """Retrieve the address where a grpc server is running from a remote db value Parameters ---------- db_val : bytes db value assigned to the desired remote name Returns ------- str IP:PORT where the grpc server can be ac...
05bbe6397e0fdbd4b04a79c5ecc697f9b3a759fb
195,768
def get_seq_middle(seq_length): """Returns relative index for the middle frame in sequence.""" half_offset = int((seq_length - 1) / 2) return seq_length - 1 - half_offset
a5c115627b71dd1e3de9d1a57ab2d37cba972e7f
546,572
import json import requests def sendTelegramMessage( body: str, apiKey: str, chatId: str, disableNotifications: bool = True ) -> bool: """ Send a Telegram message using the REST api. Docs: https://core.telegram.org/bots/api#sendmessage """ headers = {"Content-Type": "application/json"} d...
49358ce9d626e9f4beceeff963b3294f8727a932
468,552
def get_col(model, attribute_name): """Introspect the SQLAlchemy ``model``; return the column object. ...for ``attribute_name``. E.g.: ``get_col(User, 'email')`` """ return model._sa_class_manager.mapper.columns[attribute_name]
a2e81d77e3f0b7c796b3cbc65b0b792049dcf8af
71,200
def parse_ls_tree_line(gitTreeLine): """Read one line of `git ls-tree` output and produce filename + metadata fields""" metadata, filename = gitTreeLine.split('\t') mode, obj_type, obj_hash, size = metadata.split() return [filename, mode, obj_type, obj_hash, size]
0c32b850ed5951bcf888194894682ad9aab10e2c
341,539
def parent(n: int) -> int: """Return the index of the parent of the node with a positive index n.""" return (n - 1) // 2
b2b9451d00124665fd7443b6fe663f24ba6d7fc7
680,812
def determine_paired(args) -> bool: """ Determine whether we should work in paired-end mode. """ # Usage of any of these options enables paired-end mode return bool( args.paired_output or args.interleaved or args.adapters2 or args.cut2 or args.pair_filter ...
3a79f44fe6bfc59f15b81bb765745abba3ca1277
570,697
def is_number(s): """ Returns True if the string s can be cast to a float. Examples: is_number('1') is True is_number('a') is False is_number('1a') is False is_number('1.5') is True is_number('1.5.4') is False is_number('1e-6') is True is_number('1-6'...
a3249fc4ff413353894e7dd2153d2428e5f8b405
511,477
import math def latlon2tms(lat,lon,zoom): """ Converts lat/lon (in degrees) to tile x/y coordinates in the given zoomlevel. Note that it doesn't give integers! If you need integers, truncate the result yourself. """ n = 2**zoom lat_rad = math.radians(lat) xtile = (lon+ 180.0) / 360.0 *...
f4c238ad3af7635f6a812021cc38744a73a0a437
631,003
import re def get_thesis_description(thesis): """ The description exists in two parts: one that is shown and one that is hidden (must be expanded to see). The structure of the second part varies, and thus we must make the way of extraction generic. Return: The entire description of a give...
46db952a928b85767cde573830e7808f9af20276
170,533
import torch def calculate_dihedrals(p, alphabet): """Converts the given input of weigths over the alphabet into a triple of dihederal angles Args: p: [BATCH_SIZE, NUM_ANGLES] alphabet: [NUM_ANGLES, NUM_DIHEDRALS] Returns: [BATCH_SIZE, NUM_DIHEDRALS] """ sins = torch.s...
381add4de653ba30b1049248666296520530a539
625,103
def _getHierBenchNameFromFullname(benchFullname): """ Turn a bench name that potentially looks like this: 'foodir/bench_algos.py::BenchStuff::bench_bfs[1-2-False-True]' into this: 'foodir.bench_algos.BenchStuff.bench_bfs' """ benchFullname = benchFullname.partition("[")[0] # strip any...
c9bbc6882f2c702a110d1b81b8c47eace72409b9
60,731
def splitIssue(str, delim): """ Converts issue string (separated by delimiter) into issue array """ if((str == str) & (str is not None)): return(str.split(f"{delim} ")) else: return([])
f8b2062ffa76ee940ce17f208cae5a2226778c14
514,594
def get_localized_name(name): """Returns the localizedName from the name object""" locale = "{}_{}".format( name["preferredLocale"]["language"], name["preferredLocale"]["country"] ) return name['localized'].get(locale, '')
efa32f51bf89d1f2262a225dcfb13ea3ae2fedbc
648,509
def parse_team_links(response): """Parse the links to individual teams from a franchise page to get injury reports.""" years = response.css('th[data-stat=year_id] a::text').getall() links = response.css('th[data-stat=year_id] a::attr(href)').getall() # Injury reports are only available from 2009 on...
a12b90e69330c977c6f4ab2e0313c80238ab1967
595,765
def url_file_name(url: str) -> str: """ Extract file name from url (last part of the url). :param url: URL to extract file name from. :return: File name. """ return url.split('/')[-1] if len(url) > 0 else ''
38ea970f26f439119ad8bb8312ff9e393bf7e431
629,384
def arrayCheck(nums): """ Function to find a sequence 1, 2, 3. Given a list of integers, return True if the sequence of numbers 1, 2, 3 appears in the list somewhere. Args: nums (Array): Array of integer """ for i in range(len(nums)-2): if nums[i] == 1 and nums[i+1] == 2 a...
22b871e12e49fbd215ca517ff1071d38f06c26cc
625,685
def traverse_map(input_map, right=3, down=1): """Travel down the input map by heading right and down a fixed amount each iteration. The map consists of clear ground '.', and trees '#'. The map repeats to the right infinitely. Get the number of trees that would be encountered travelling from the top ...
9844c795581e285f26e81258f19381efb0a705ba
636,047
def _custom_formatargvalues( args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value)): """Copied from inspect.formatargvalues, modified to place function argumen...
644568f56f51f1287790b472693dd08b80f8728f
128,850
def wrap_lines(lines, width=80, sep=' ', ellipsis="...", force_ellipsis=False, rjust_ellipsis=False): """ Wraps given list of lines into a single line of specified width while they can fit. Parts are separated with sep string. If first line does not fit and part of it cannot be displayed, or there are other lines t...
ecf2dac1c693687b19c058f13187ba1a4968c0de
54,911
def calculate_weight_per_week(data) -> float: """Reads a list that stores a week's worth of data to calculate and return average weight per week""" total = 0 day = len(data) for index, weight in enumerate(data): total += weight[2] return total / day
5a5cd9adc1a127deba9d8fe46fbcbe4ba365f5e5
373,292
def _get_ipaddr(req): """ Return the ip address for the current request (or 127.0.0.1 if none found) based on the X-Forwarded-For headers. """ if req.access_route: return req.access_route[0] else: return req.remote_addr or '127.0.0.1'
5f9d2af65428f752aa998346c6eb10b359ad8032
85,765
def substr_match(a, b): """ Verify substring matches of two strings. """ if (a is None) or (b is None): return False else: return a in b
9b98d14b6ec5f2ab433eea92d377b5e1477fef64
13,535
from typing import Callable from typing import Any import inspect async def maybe_coroutine(func: Callable, *args, **kwargs) -> Any: """Allows running either a coroutine or a function.""" if inspect.iscoroutinefunction(func): return await func(*args, **kwargs) else: return func(*args, **kw...
8ac38b41863aa73fdd4534032d45d3a2f56770d2
259,412
def _footer(settings): """ Return the footer of the Latex document. Returns: tex_footer_str (string): Latex document footer. """ return "\n\n\end{tikzpicture}\n\end{document}"
a1d8d884e1a5e028ec2139f68f8a499b460785b6
547,682