content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def create_dead_recover_reactions_model( vaccination_states, non_vaccination_state, virus_states, areas, ): """Create death and recover reactions for the model. Parameters ---------- species : list of strings List containing the names of all species. vaccination_states : li...
bbab9c5ccbb1d1e7dba50ff3637b6966cc5e86d6
354,699
def is_member(user, group): """Checks if the user object is a member of the group or not.""" return user.groups.filter(name=group)
c50ea4ee7a40a6a78811c8b0d40a57dd93e0897c
415,460
from typing import Dict from typing import Any def mk_ehvi_default_optimizer_options() -> Dict[str, Any]: """Makes a copy of dictionary for generic default optimizer options for EHVI-based acquisition function, used when optimizer options for a given acquisition function are not registered. NOTE: Ret...
e7a05d0bad1857b162ba078b1550e438a552b4f8
150,285
def _loop_action_in_command_line(command_line: str) -> bool: """Does the command line contain a loop statement Args: command_line (str): The command line to test. Returns: bool: True if there's a loop in this command line. """ return any( word in command_line.split() for wo...
8cf6c17805dc25be41ecbc32664bd396d13e3df1
643,925
def vlan_range_to_list(vlans): """Converts single VLAN or range of VLANs into a list Example: Input (vlans): 2-4,8,10,12-14 OR 3, OR 2,5,10 Returns: [2,3,4,8,10,12,13,14] OR [3] or [2,5,10] Args: vlans (str): User input parameter of a VLAN or range of VLANs Returns: l...
739c4213516cc4bbce486cde3206b81db523b94e
434,700
def _sum(array): """ Recursively find the sum of array""" if len(array) == 1: return array[0] else: return array[0] + _sum(array[1:])
a9897f996e22bdf9738c6f64a1807d191b2647ef
522,398
def round_safe(value, precision): """Standard `round` function raises TypeError when None is given as value to. This function just ignores such values (i.e., returns them unmodified). """ if value is None: return value return round(value, precision)
5f1ee265cec3e249e599318cfa10ce0e8ef5ca6e
385,337
import math def multiply(int1, int2): """ An implementation of the Karatsuba algorithm for integer multiplication. Returns product of int1 and int2. """ # Base case if (int1 < 10 and int1 > -10) or (int2 < 10 and int2 > -10): return int1 * int2 # Set up strInt1 = str(int1) ...
da4ca6d0e96420283542d335f37762c35f1c397a
659,352
def limit_to_bounding_box(df, coords): """ Drop rows with coordinates outside of the bounding box. """ min_lat, max_lat, min_lon, max_lon = coords df = df[df['LAT'] < max_lat] df = df[df['LAT'] > min_lat] df = df[df['LON'] < max_lon] df = df[df['LON'] > min_lon] return df
cc76cbe7bad15e60fe68fd32e664481298db2b53
207,019
def call_vtk(obj, method, args=None): """ Invoke a method on a vtk object. Parameters ---------- obj : object VTK object. method : str Method name. args : None ot tuple or list Arguments to be passed to the method. If None, the method is called with no arguments....
ebff1ca9e5881e1a4fa5e17a9b766d3bb2fed030
229,697
def oucru_convert_dtypes(tidy, columns=[]): """Helper method to apply convert_dtypes. Helper method to apply convert_dtypes() to a specific set of columns which might or might not be included in the DataFrame. Parameters ---------- tidy: pd.DataFrame The DataFrame columns: list...
af0c5576a19d922e465d5e460055dee0142845e5
361,629
def match_to_int(match): """Returns trace line number matches as integers for sorting. Maps other matches to negative integers. """ # Hard coded string are necessary since each trace must have the address # accessed, which is printed before trace lines. if match == "use-after-poison" or match ==...
c2daab64bc4a2ae258b7ac6152a949b48d8d7906
679,348
import hashlib def get_sha256(string): """Get sha256 of a string. :param: (string) the string to be hashed. :return: (string) the sha256 of string. """ return str(hashlib.sha256(string).hexdigest())
17db82f505405f5edc636c70c5e074b4ffb7daa4
459,318
def is_vertex_field_name(field_name): """Return True if the field's name indicates it is a non-root vertex field.""" return field_name.startswith('out_') or field_name.startswith('in_')
0d19000a3f34cd78677b41e52cdeee835186888b
587,561
def s_curve(CurrTime, Amp, RiseTime, StartTime=0.0): """ Function to generate an s-curve command Arguments: CurrTime : The current timestep or an array of times Amp : The magnitude of the s-curve (or final setpoint) RiseTime : The rise time of the curve StartTime : The time that the...
19c198dd823b4fd5d4c382bcb76249aa2e438638
126,212
def to_bool(value: str) -> bool: """ Converts a string argument to the bool representation (or throws a ValueError if the value is not one of '[Tt]rue' or '[Ff]alse'. """ if value in ["True", "true", True]: return True if value in ["False", "false", False]: return False raise...
579df9985701e8081e8c753206c72d2c0afc6851
585,981
import math def convert_bytes(size): """Make a human readable size.""" label = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB') try: i = int(math.floor(math.log(size, 1024))) except ValueError: i = 0 p = math.pow(1024, i) readable_size = round(size/p, 2) return '{}{}'....
b4b070e85d31c0c607422667aa7f79bc0c21bcfc
647,594
from datetime import datetime def recast_timestamp(ms: int): """Recast millisecond epoch offsets to DateTime""" try: return datetime.fromtimestamp(ms / 1000.0) except TypeError: return None
6d89074ad13e7eb0e96949b8463015fda1124e45
73,874
import copy def confusion_matrix(y_true, y_pred, labels): """Compute confusion matrix to evaluate the accuracy of a classification. Args: y_true(list of obj): The ground_truth target y values The shape of y is n_samples y_pred(list of obj): The predicted target y values (parallel ...
a836ac91173ba61857bc1f2cd33b888976ebc32d
539,246
def FirstSignificant(pvals, thresh): """Given a list of temporal p-values for peptide phoshorylation changes return the time point at which the peptide is first significant or 'Not significant' """ for t in range(len(pvals)): if pvals[t] <= thresh: return str(2**(t+1)) return...
f181c930a68cd632cce82592901ec5e7a1c9fa04
304,628
def flatten(list_of_lists:list[list])-> list: """flatten list of lists Args: list_of_lists (list[list]): list of lists Returns: list: list """ return [item for sublist in list_of_lists for item in sublist]
3579023bdf103cf6942c8bbe1c681319b2ce386d
268,022
from typing import Dict def build_item(hex_color: str, frequencies: Dict, html_colors: Dict) -> Dict: """ :param hex_color: '000000' :param frequencies: {'000000':0.3, 'FFFFFF':0.2, ... } :param html_colors:{'000000':{'name':'Black', 'hex':'000000', 'r':0, 'g':0, 'b':0}, ...} :return: {'color':{'n...
9b0d4b123c26d5e8cae0517f837c405d4411cadf
510,635
def cantor_pairing(a, b): """ A function returning a unique positive integer for every pair (a,b) of positive integers """ return (a+b)*(a+b+1)/2 + b
1b2c93165a333594efdc198a91145d9eeef5fbb1
475,999
def get_child_schema(self): """An optional function which returns the list of child keys that are associated with the parent key `docs` defined in `self.schema`. This API returns an array of JSON objects, with the possible fields shown in the example. Hence the return type is list of lists, because this plugin ret...
4d91ff18ab8e3f6cec5610169dc6d52e7a647960
25,052
def is_int(in_obj): """ Checks if the input represents an integer and returns true iff so """ try: int(in_obj) return True except ValueError: return False
4e5837e136932d70c65e55b5f5959e61c0c89619
329,484
def xywh_to_xyxy(box): """Convert xywh bbox to xyxy format.""" return box[0], box[1], box[0]+box[2], box[1]+box[3]
53b31a43cfee6bb5efdf7875af66d21e2657ee1e
231,769
def get_class_by_name(name: str) -> type: """ Returns type object of class specified by name Args: name: full name of the class (with packages) Returns: class object """ components = name.split('.') mod = __import__(components[0]) for comp in components[1:]: mod = getat...
23f55bffc3c78b2cd0e922760a1968871e76b468
157,724
def get_end_pos(cls, start_pos, dimensions, left=False, up=False): """ calculate the end position if were to build an array of items :param cls: Type :param start_pos: (int, int) :param dimensions: (int, int) :param left: bool: default builds rightward :param up: bool: default builds downwar...
a03b45f7137e835a8709da933a7a7e4f509f8569
655,690
def _clean_scale(scale): """Cleanup a 'scaling' string to be matplotlib compatible. """ scale = scale.lower() if scale.startswith('lin'): scale = 'linear' return scale
5e67783ae6f8b9df704c3b2e7f68dcd3b6c9e47d
656,764
def num_to_uix(n): """Convert number to subscript character. Args: n (int): Single-digit number Returns: str: The Unicode superscript for the letter at the number. """ return "ᵃᵇᶜᵈᵉᶠᵍʰⁱ"[n]
7a942cf22b9f3068741414d5dcfcdfc52bae37f0
556,430
def _check_if_StrNotBlank(string): """ check if a sting is blank/empty Parameters ---------- Returns ------- : boolean True if string is not blank/empty False if string is blank/empty """ return bool(string and string.str...
e5de1d902f8e3931d23e04c6ba825b17d90e8d1d
10,553
def dummy_decorator(func): # noqa: D401 """Dummy property decorator, to test if chained decorators are handled correctly.""" return func
3cc6c14b387a9a81283ca26c802792e008e6cf72
609,447
def get_role_part(rawsource): """Helper function to get role name from the instruction. Args: rawsource: Role raw text. Example: :role:`text` -> :role:` """ return rawsource[:rawsource.find('`') + 1]
3e1c46ef3e8b2e58782b10ec59cdc447bacc76a4
105,607
def _parse_ports(ports_text): """ Handle the case where the entry represents a range of ports. Parameters ---------- ports_text: str The text of the given port table entry. Returns ------- tuple A tuple of all ports the text represents. """ ports = p...
eb6eed9a5f8ea91d448be9c0eede9f5b258cf358
687,432
def get_book_title(soup): """ Return book title""" return soup.find('h1', attrs={'class': 'bookTitle'}).get_text()
7b18b5fdcb82216ffdc1fff5a92ae5b70856cdd1
328,232
def remove_granular_connector_edges(inner_g_strongly_connected): """ Removes granular connector edges from graph Args: inner_g_strongly_connected (NetworkX MultiDiGraph): strongly_connected street network graph Returns: inner_g_strongly_connected (NetworkX MultiDiGraph): strongly_connect...
eab9010996e58fd9ca5ec6074323da357f5e1a19
461,927
from functools import reduce from operator import getitem def get_key_by_path(tree, keys): """ Function to get keys from a tree by path. Parameters ---------- tree : dict Instance containing the keys keys : Multiple Key to be extracted Re...
abefed035673905f67db6b292b1f0b6aa9027d6e
343,618
import functools def skippable(*prompts, argument=None): """ Decorator to allow a method on the :obj:`CustomCommand` to be skipped. Parameters: ---------- prompts: :obj:iter A series of prompts to display to the user when the method is being skipped. argument: :obj:`str` ...
879106f4cc0524660fb6639e56d688d40b115ac4
1,464
def get_files_from_drive(drive_service, name=None, substring_name=None, mime_type=None, custom_metadata=None, parent_id=None, trashed=False, result_fields=["name", "id"]): """Gets files from Google Drive based on various search criteria Arguments: drive_service -- a Google Drive service name -- name of file(s) b...
1499296106a19f26b9ed2d685392cc6ae615461b
435,703
def rc_str(dna): """Reverse complement a string """ complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'} ks = list(complement.keys()) for k in ks: complement[k.lower()] = complement[k].lower() return ''.join([complement[base] for base in dna[::-1]])
8508078209b1136f8405608bae331a877e13c9dc
395,238
def find_duplicates(iterable): """Find duplicate elements in an iterable. Parameters ---------- iterable : iterable Iterable to be searched for duplicates (i.e., elements that are repeated). Returns ------- set Repeated elements in `iterable`. """ # modifie...
b5d5bc6b85cd2cfafe3bd0f88ef2daa0e28e538e
63,166
import ipaddress def max_usable_hosts(addr): """ compute total number of client connections that can be made with a given network """ return ipaddress.ip_network(addr).num_addresses - 2
2d6ebf39b700bdc618d0abfca1c389f8dd760a18
209,381
def relative_deviation(simulated, observed, threshold): """Return the relative deviation of a simulated value from an observed value.""" try: 1 / observed except ZeroDivisionError: observed = 0.00001 dev = abs(simulated - observed) / observed if dev > threshold: return (True...
84559c29b2b3e8f87aa55ca7fbd42ad69fcb0409
198,885
def has_valid_fastq_extension(file_location): """ Determines whether or not the passed file location has a valid FASTQ or GZIP'd FASTQ file extension. ARGUMENTS file_location (str): the location of the file to check RETURNS valid (bool): whether or not the file location has a valid FAS...
89603a0868ad2dc28cabc92a08503c8b7b40b654
503,431
def unset_bit(string: int, pos: int) -> int: """Return bitstring with the bit at the position unset Args: string (int): bit string pos (int): position in the bit string Returns: int: string with the pos bit set to 0 """ return int(string) & ~(1 << pos)
10c3ae77a19a9323758e5679f358c0f55c19c962
616,765
def get_ckpt_filename(node_name, epoch): """Returns the checkpoint filename. Args: node_name: A string. The name of the node. epoch: An integer. The checkpoint epoch. Returns: ckpt_filename: A string. The filename of the checkpoint. """ return node_name + '.' + str(epoch)
5f72a924503ae7ae33cd912ad72495118fde2f6e
484,327
def unbind(instance_id, binding_id): """ Unbind an existing instance associated with the binding_id provided DELETE /v2/service_instances/<instance_id>/service_bindings/<binding_id>: <instance_id> is the Cloud Controller provided value used to provision the instance <binding_i...
bd43f393a10a9114b44d125f97271293ba483fdd
187,316
def cluster_vertical(P): # Used in form_segment_(). """ Cluster P vertically, stop at the end of segment """ if len(P['down_fork_']) == 1 and len(P['down_fork_'][0]['up_fork_']) == 1: down_fork = P.pop('down_fork_')[0] # Only 1 down_fork. down_fork.pop('up_fork_') # Only 1 up_fork. ...
d2bbd35795c349985e9d1a28c6a5b9e5476ce2f0
209,684
def get_not_downloaded_isbns(all_isbns, downloaded_isbns): """ Identifiy ISBNs, which haven't been downloaded @params: all_isbns - Required : all isbns (pd.Series) all_isbns - Required : already downlaoded isbns (pd.Series) @returns: to_download : isbns to download (list) ...
f92f11e3b9ac47eacd50c79a436ee4e5ce3260f1
423,914
import base64 def embed_mp4(filename): """Embeds an mp4 file in the notebook.""" video = open(filename, 'rb').read() b64 = base64.b64encode(video) tag = ''' <video width="640" height="480" controls> <source src="data:video/mp4;base64,{0}" type="video/mp4"> Your browser does not support the vid...
ba41e6f7518e26dc6781eb2f321b301863896b41
232,025
def _map_channels_to_measurement_lists(snirf): """Returns a map of measurementList index to measurementList group name.""" prefix = "measurementList" data_keys = snirf["nirs"]["data1"].keys() mls = [k for k in data_keys if k.startswith(prefix)] def _extract_channel_id(ml): return int(ml[len...
d6d83c01baec5f345d58fff8a0d0107a40b8db37
4,806
def _request_get_json(response): """ Get the JSON from issuing a ``request``, or try to produce an error if the response was unintelligible. """ try: return response.json() except ValueError as e: return {"error": str(e)}
1b6a6d823c23f036ef3c2a06ed3a421544797bc5
83,249
from typing import Tuple import textwrap def prep_for_xml_contains(text: str) -> "Tuple[str]": """Prep string for finding an exact match to formatted XML text.""" # noinspection PyRedundantParentheses return (textwrap.indent(textwrap.dedent(text), " ",),)
1d3170c41f1688a853b91784b5f6f17465d885f7
141,913
import random def filter_random_values(n, df, col_name): """ Filter randomly chosen part of DataFrame. :param n: Sample size :param df: Pandas DataFrame. :param col_name: DataFrame column name :return filtered DataFrame """ # check if sample size is lower than 1 assert n < 1 # ...
b8730c0251a7bdb1a501b92ab450bdb6c1b8d9b8
340,465
import hashlib def get_file_hash(filepath): """Reads the file and returns a SHA-1 hash of the file. Args: filepath: String of the path to the file to be hashed Returns: String: The SHA-1 hash of the file. """ hasher = hashlib.sha1() blocksize = 65536 with open(filepath, "rb") as f: buf = f....
af966bca8125adbd48a36b3ada3e5226bdfd890c
577,401
from typing import List from typing import Set from typing import Dict def get_samples_in_studies(samples: List[str], studies: Set[str], sample_to_study: Dict[str, str]) -> List[str]: """ Find which samples from the list were generated by the given studies...
2990853024b9006df27b002d98705db55e94ed30
567,092
def norm_whitespace(s: str) -> str: """normalize whitespace in the given string. Example: >>> from hearth.text.utils import norm_whitespace >>> >>> norm_whitespace('\tthere\t\tshould only be one space between \twords. ') 'there should only be one space between words.'...
0f1194008abfececff6ed72181e28e7204e63713
335,510
from pathlib import Path def read_scanners(filename: Path) -> list[list]: """Read the raw scanner inputs. Args: filename (Path): filename Returns: list[list] scanned beacon positions for each scanner """ result = [] with filename.open("r") as file: for line in file: ...
4c189882b8e141fde9c67e26b3a0b15b3def90c0
265,876
from typing import Any from typing import Iterable def get_config_name_for_args(*args) -> str: """ Get a name string by concatenating the given args. Usage:: >>> get_config_name_for_args("123456", None, "+remindme") '123456__None__+remindme' >>> get_config_name_for_args("123456", None, ("a_t...
1a389888f09b35e7f4188d29fc1411c78b1ac3e3
331,011
def oif_axis_size(oifsettings): """Return dict of axes sizes from OIF main settings.""" scale = {'nm': 1000.0, 'ms': 1000.0} result = {} i = 0 while True: try: axis = oifsettings[f'Axis {i} Parameters Common'] except KeyError: break size = abs(axis['En...
8488e440898e5cd649261d67370b662ceddd5934
377,142
def is_nova_server(resource): """ checks resource is a nova server """ return ( isinstance(resource, dict) and "type" in resource and "properties" in resource and resource.get("type") == "OS::Nova::Server" )
c412455c6a22f3ac1b1eb074caeec70d54bf0fbd
89,083
def get_kappa(searchers: dict): """Retrieve kappa from each searcher and return as list""" kappa_list = [] for s_id in searchers.keys(): s = searchers[s_id] kappa_list.append(s.kappa) return kappa_list
899ebd8b9ca6259f253e380e8000e33550d838b2
594,192
def rgb2gray(rgb_img): """ Parameters ---------- rgb_img : numpy array with shape as (3, X, Y) image to convert in gray Returns ------- gray_img , the grayscale image """ gray_coef = [0.2989, 0.5870, 0.1140] r = rgb_img[0] / 255 g = rgb_img[1] / 255 b = rgb_img[...
d6b582253eed18c1810f584bda815a7b98f74ec4
645,274
def to_snake_case(field: str) -> str: """Return string converted to snake case (e.g. "Given Name" -> "given_name").""" return "".join("_" if c == " " else c.lower() for c in field)
833a107f3a6c9b24a44d47c73851c7e2ce0ffb38
95,473
import functools def repeat(num): """ decorator for repeating tests several times """ def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): for _ in range(num): f(*args, **kwargs) return wrapper return decorator
070b301b2ea47ab72e183d0fcfcbb60a0c34b52e
474,655
import operator import math def unit_vector(vec1, vec2): """ Return a unit vector pointing from vec1 to vec2 """ diff_vector = map(operator.sub, vec2, vec1) scale_factor = math.sqrt( sum( map( lambda x: x**2, diff_vector ) ) ) if scale_factor == 0: scale_factor = 1 # We don't have an actu...
79e2cff8970c97d6e5db5259801c58f82075b1a2
704,506
from typing import Mapping from typing import Union from typing import List def map_params_to_arg_list(params: Mapping[str, Union[str, float, int]]) -> List[str]: """Method to map a dictionary of params to a list of string arguments""" arg_list = [] for key in params: arg_list.append(str(key) + "=...
17fed9dd821abd5e6e3a9664ae6713cacec35d4f
565,284
from typing import OrderedDict def dict_sort(dic, by="value", topk=None, reverse=True): """ Sort dictionary by key or value Params ====== dic (dict) : Input dictionary by (str) : String indicating the sorting procedure (value = sort by value, key = sort by key) t...
4590f8d703f7ac733a2833189905806e057cb25d
506,930
def read_lines(file_name): """ Read lines from given file and return as list """ with open(file_name, 'r') as fobj: lines = fobj.readlines() return lines
d5fbf26b61029a6cfd1738b8d3f44b71bbf6e0a2
646,561
def parse_float(v: str) -> float: """Parse float type. :param v: An environment variable to parse. :type v: :class:`str` :return: A float type value :rtype: :class:`float` .. versionadded:: 0.5.6 """ return float(v)
e52b78808fa41f2190495c31ca0981cd9b34fbbb
220,028
def prune(d): """If possible, make the multi-valued mapping `d` single-valued. If all value sets of `d` have exactly one member, remove the set layer, and return the single-valued dictionary. Else return `d` as-is. """ if all(len(v) == 1 for v in d.values()): return {k: next(iter(v)) f...
b0c60b00a5bd47d248f558db6d96b8569b9e94bb
670,384
def get_top_pb_type(element): """ Returns the top level pb_type given a subelement of the XML tree.""" # Already top-level parent = element.getparent() if parent is not None and parent.tag == "complexblocklist": return None # Traverse while True: parent = element.getparent() ...
fefe2cb04612c3ab5ed99f7dc6ec774ce990b320
306,757
from math import log2 def human_readable_file_size(size): """ Returns a human readable file size string for a size in bytes. Adapted from https://stackoverflow.com/a/25613067) """ _suffixes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'] # determine binary order in steps of size 10 # (c...
171b9039885222c6d17edd923b9d9e5fa17e2933
427,334
from functools import reduce from operator import getitem def _get_by_path(tree, keys): """ 访问tree(config:json)结构的,所有keys项 (为了设置新配置,要访问旧配置时使用) Access a nested object in tree by sequence of keys. :param tree: (config:json) :param keys: keys项 :return: (json的k:v) """ """ getitem...
d55ef3f41061a7323adfd8434e239c3f8febb120
262,843
def maneuverToDir(str: str) -> int: """ maps dubins curve action to an interger {-1, 0, 1} Paramters --------- str: str dubins curve action Returns ------- int L -> 1, R -> -1, S -> 0 """ if str == 'L': return 1 if str == 'R': return -1 r...
a70d65f89c20e281eae6b69443a9bdc9fbe04eb1
56,677
async def index(): """ Index of the Metadata Repository Service that redirects to the API documentation. """ return "Index of the Metadata Repository Service"
6e8f751c2a92a764362aa19c03803b7db843905b
257,619
import random def generate_trip_data(num_existing_trips, num_trips, num_destinations): """Generates a list of tripData to be inserted into the database. Keyword arguments: num_existing_trips -- number of trips in the evolutions num_trips -- number of trips being created by the script num_d...
f44de12397bb90d3ef5e8184c5eb9bccfa1f5270
346,710
import torch def safe_power(x, exponent, *, epsilon=1e-6): """ Takes the power of each element in input with exponent and returns a tensor with the result. This is a safer version of ``torch.pow`` (``out = x ** exponent``), which avoids: 1. NaN/imaginary output when ``x < 0`` and exponent has a frac...
c384c43482fd9cba4957b115555c58f1c6fa50ce
689,830
def mocked_compute_cell_size(data_dict, by_image): """Mocks compute cell size so we don't need to create synthetic data with correct cell size""" X = data_dict['X'] constant_val = X[0, 0, 0, 0] # The default resize is 400. We want to create median cell sizes that divide evenly # into that number wh...
656d879ca962aa45bd18ab0ba1aba045c48f29bd
179,876
def degree(G, nbunch=None, t=None): """Return the degree of a node or nodes at time t. The node degree is the number of edges adjacent to that node. Parameters ---------- G : Graph opject DyNetx graph object nbunch : iterable container,...
cb2f47a453051a6021444486b16e9f238dcadda4
350,215
def get_pkg_name(req): """Return the name of the package in the given requirement text.""" # strip env markers req = req.partition(';')[0] # strip version req = req.partition('==')[0] req = req.partition('>=')[0] return req
f82fc633d2d089485e7873ba3b31c93b3df9c734
145,984
def _models_count_all_function_name(model): """Returns the name of the function get the number of models in the database""" return '{}_count_all'.format(model.get_table_name())
22ea542e640e1b53fefe22d467c2dd852203b8a9
635,919
def lagrange2(N, i, x, xi): """ Function to calculate Lagrange polynomial for order N and polynomial i [0, N] at location x at given collacation points xi (not necessarily the GLL-points) """ fac = 1 for j in range(-1, N): if j != i: fac = fac * ((x - xi[j + 1]) / (xi[i ...
c37284ac5a8446484d625b1f41c0f67381a3b5d6
431,725
def semPad(ver: list[str], length: int) -> list[str]: """Pad a semver list to the required size. e.g. ["1", "0"] to ["1", "0", "0"]. Args: ver (list[str]): the semver representation length (int): the new length Returns: list[str]: the new semver """ char = "0" if ver[-1] == "*": char = "*" return ver +...
6e794fddc961d16c5f24ba66624360ec13394739
584,848
def tstr_to_float(tstr): """ Convert time from 12-hour string (with AM/PM) to agenda-compatible float. :param tstr: 12-hour time string :returns: Float like: 8.0 for '8:00AM' """ afloat = float(tstr.rstrip("APM").split(":")[0]) if "PM" in tstr and tstr.split(":")[0] != "12": afloat ...
df063e6fdac8cc60457ed70dbfebdb9ac51e77b4
161,745
def telescopic_direct(L, R, n, limits): """Returns the direct summation of the terms of a telescopic sum L is the term with lower index R is the term with higher index n difference between the indexes of L and R For example: >>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b)) -1/(b + 2) - ...
1a902ade1c58867e2ad2ee4e1adc8ae1eb03f861
402,583
def sindex(i,j,qi,qj): """ Returns the location of {i,j} in the set {{0,0},{0,1},...,{0,qj-1},...{qi-1,qj-1}}. """ return int((i * qj) + j)
489d5046611311d29f9c87344013468585e71c66
194,681
def _check_name_should_break(name): """ Checks whether the passed `name` is type `str`. Used inside of ``check_name`` to check whether the given variable is usable, so we should stop checking other alternative cases. Parameters ---------- name : `Any` Returns ------- ...
4e6981fa840b89bf69a1a0e6c6401b1e2387e17d
18,115
def encode_remainining_length(remaining_length): # type: (int) -> bytes """Encode the remaining length for the packet. :returns: Encoded remaining length :rtype: bytes """ encoding = True encoded_bytes = bytearray() encoded_byte = 0 while encoding: encoded_byte = remaining_l...
ddb7ea7f98753375a8f5d817f4f07d23c09f83f4
393,147
def chain(*args): """Applies a list of chainable update transformations. Given a sequence of chainable transforms, `chain` returns an `init_fn` that constructs a `state` by concatenating the states of the individual transforms, and returns an `update_fn` which chains the update transformations feeding the ap...
74643ddf7d88e05640c9549048ddd19f9616c2c2
687,461
from tempfile import mkdtemp def create_temporary_directory(prefix_dir=None): """Creates a temporary directory and returns its location""" return mkdtemp(prefix='bloom_', dir=prefix_dir)
b2a1ddeb8bcaa84532475e3f365ab6ce649cd50c
14,705
import re def _get_data_glob(data): """ Construct a glob expression from the data expression """ return re.sub(r'{[^{}]*}', '*', data)
b4add01693f3147849dc14f642d2acdd09c962c1
67,418
def collection_2_sentence(list_str): """ Given a container (list or set) of strings with the names of cities, states or any string (elements), returns a string where each element is listed in a sentence Note: returned objects should be in alphabetical order Ex1: {"LIVERPOOL"} -> LIVERPOOL Ex2:...
56326ed61cdc3356ea25d6a3df899869d62ad5d7
442,629
def is_inline(tag): """ A filter function, made to be used with BeautifulSoup. Makes sure the tag is `inline`, or has both data-inline-type and at least one of data-inline-{id,ids,filter} attributes. """ check_type = lambda attr: attr[0] == 'data-inline-type' check_attrs = lambda attr: att...
ad207188de13c487c420d84645f460b175a16e88
123,025
def gcd(a, b): """ gcDen(a, b) -> number A traditional implementation of Euclid's algorithm for finding the greatest common denominator. """ while b > 0: a, b = b, a % b return a
3e484c53dec87c0932d55f63ab734cdde44efb5f
289,111
def strip_whitespace(string: str) -> str: """ Strip leading and trailing whitespace from a string """ if string[-1] == " ": string = "".join(string.rstrip()) if string[0] == " ": string = "".join(string.lstrip()) return string
9de016e162b45e3b444610008eab996cfdcfb198
605,938
def xor(b1, b2): """xor takes two byte buffers and returns their XOR combination, b2 can be shorter in length than b1, if so b2 will repeat""" l = len(b1) if len(b2) > l: raise ValueError("Xor does not accept b2 longer than b1, " "args len(b1)=%d, len(b2)=%d" % (len(b1),...
28a2f342fef30411c13d0a4fa26ea7feaec18d32
273,938
from pathlib import Path def get_genbank_paths(folder): """Generate a collection of paths to GenBank files in a specified folder.""" if not Path(folder).is_dir(): raise ValueError("Expected valid folder") valid_extensions = (".gb", ".gbk", ".genbank") return [ file for file in Path(fol...
31b3dde450c4c5182d9ec9718d1bdc70901b738b
604,698
import random def create_random_string(length): """Create random string from a character set. Parameters ---------- length : int Size of the expected string. Returns ------- str Random string. Notes ----- String is created from unambiguous letters...
03473c24cd954d464ddd9fafa5ce760e61675553
282,487
def internal_params_1D( pixels_per_clock: int, window_width: int, image_size: int, output_stride: int, origin: int ): """Calculate "internal" parameters of linebuffer based on user parameters. This includes the window_count (number of total windows outputted), the parallelism (width of ...
625897c740c7d0fd39eeb0d4f306963b53170621
304,879