content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import asyncio import inspect def _is_coroutine(obj): """Check to see if an object is really an asyncio coroutine.""" return asyncio.iscoroutinefunction(obj) or inspect.isgeneratorfunction(obj)
c8dd0ee26d1aa9ff8218f3a07a47d8efa4865f4e
575,658
import socket def connect(host, port): """Connection Args: host(str): destination hostname port(int): destination port Returns: the created socket """ # IPv4 address family over TCP s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, por...
94aa6040a55489eb22e84f82809632e8c4c469ee
575,660
def handler(message_type): """ Decorator to mark a method as the handler for a specific message type. """ def _actual_decorator(decorated_function): decorated_function.__message_type__ = message_type return decorated_function return _actual_decorator
ad554520bd9cf6b22a08b2695eb66d1a0edac2c6
575,661
def _get_data_bundle_update_lock_name(data_bundle_name): """Return the lock key name for the given data bundle.""" return 'update:data_bundle:%s' % data_bundle_name
270cc9bba72935f300e0aa488bd5905984626227
575,662
import logging def get_columns_with_null_values(df): """ Purpose: Get Columns with Null Values Args: df (Pandas DataFrame): DataFrame to describe Return columns_with_nulls (dict): Dictionary where keys are columns with nulls and the value...
301d61835d7d0a3a73211bc593d32caba703e1bd
575,664
def order_cols(df, cols): """Put columns in cols first, followed by rest of columns""" rest = [col for col in df.columns if col not in cols] df = df[cols + rest] return df
269e9ecaf976e89af0784daf7052cfd3fe494e27
575,667
import random import math def random_erasing(img, probability=0.5, sl=0.02, sh=0.4, r1=0.3, mean=(0.4914, 0.4822, 0.4465)): """ Random erasing augmentation Args: img: input image probability: augmentation probability sl: min erasing area sh: max erasing area r1: erasin...
589784cf2a775f2bd2e31f325a512e94c1f3f0b5
575,669
def uniq(l: list) -> list: """Return unique elements from l""" return list(dict.fromkeys(l))
d96171b0eff66180222e1b48ee553aec4dda40da
575,671
import re def get_address_from(x): """Extract an address from a string if exists.""" return re.findall("0x[\\da-f]{64}", str(x))[0]
54c31e7524a1cd7d15674613937a2c8aeef68464
575,674
def monomial_div(a, b): """Division of tuples representing monomials. Lets divide x**3*y**4*z by x*y**2: >>> monomial_div((3, 4, 1), (1, 2, 0)) (2, 2, 1) which gives x**2*y**2*z. However >>> monomial_div((3, 4, 1), (1, 2, 2)) None x*y**2*z**2 does not divide x**...
be74af5150b826025fecf9cb5b640395ae70af81
575,678
def _GetEnvironmentVars(benchmark_spec): """Return a string containing HPCG-related environment variables. Args: benchmark_spec: benchmark spec Returns: string of environment variables """ return ' '.join([ 'NUM_GPUS=%s' % benchmark_spec.total_gpus, 'OMP_NUM_THREADS=%s' % benchmark_spec....
60d968b924376f738f0615638e50c71b0c66c09d
575,679
from typing import Dict from typing import Any import dataclasses def dataclass_quick_asdict(obj) -> Dict[str, Any]: """Extract dataclass to items using `dataclasses.fields` + dict comprehension. This is a quick alternative to `dataclasses.asdict`, which expensively and undocumentedly deep-copies every n...
c01fb3d9e7c32a3c637904a64817d88769900c52
575,682
def get_contents_of_file(path_and_file_name, remove_whitespace): """Return the given file contents, formatted for assertion. Keyword arguments: path_and_file_name -- full path to relevant file remove_whitespace -- remove new lines and spaces """ with open(path_and_file_name) as f: if re...
60692a2a413a5509dc1a5ff2a20933efb79e6b6e
575,687
import re def _fixup_cc_list(cc_value): """Fix up cc list separators and remove duplicates.""" # Copied from trac.ticket.model cclist = [] for cc in re.split(r'[;,\s]+', cc_value): if cc and cc not in cclist: cclist.append(cc) return ', '.join(cclist)
5d2ac464cddd4e24995633c666c2822b155cbabb
575,689
from pathlib import Path def make_wrapper_name(path: Path) -> str: """Return an escaped filename to be used in source wrappers. Reverses the order of parts from the original filepath for easier readability """ escaped = '_'.join(reversed(path.parts)) for char in '. /': escaped = escape...
0b82b5b22071a700103c07cf2d0d9cbfdf582de4
575,694
import torch from typing import Tuple def accuracy( y_pred: torch.Tensor, y: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: """ Given a tensor y_pred of logits, predict the accuracy with respect to the ground truth labels y :param y_pred: tensor of shape (batch_size, n_labels) :param y: tens...
b26472286dd6a466aee7365f8b6498c6a3bd1243
575,695
from unittest.mock import call def coverage(args=None, plain=None): """ Runs the tests and creates a coverage report. By default it creates a html report. With the argument --plain, it creates a plain report and fails under a certain amount of untested lines. """ if plain is None: pla...
71e5a6600377b88f5e7cfae97f54d232b06beabb
575,698
def dimensions(layers): """Returns the number of `weights + biases` of a neural net, given the layers. Args: layers (list): List of 'int' representing the size of each layer. Returns: int: The number of optimizable variables (`weights + biases`) """ sum = 0 for l in range(0, le...
e4e3d2072fd8681582cad3fd62db2351263a84d6
575,701
def set_union(A: int, B: int) -> int: """ Args: A: B: Returns: Examples: >>> bin(set_union(int("0001", 2), int("1110", 2))) '0b1111' >>> bin(set_union(int("0001", 2), int("0001", 2))) '0b1' """ return A | B
9c514ed6b20c073eb5bf12d5470bc0861a5a5c58
575,702
def join_app_version(appname,version,platform): """Join an app name, version and platform into a version directory name. For example, ("app-name","0.1.2","win32") => appname-0.1.2.win32 """ return "%s-%s.%s" % (appname,version,platform,)
a9b916d84f8df4082f77f4743333825cd119387a
575,706
def parse_number(string): """Takes a string and attempts to convert it to a number. This function simply removes commas and underscores from the string, and then tries to convert it to an int or a float. >>> parse_number('10') 10 >>> parse_number('1.4') 1.4 >>> parse_number('12,345')...
98ec40f0ed78af2700f37d525ed1b5d3d6b47b52
575,708
def _at_step_1_and_every_nth_step(period): """A function that's true at 1 and n when n % period == 0.""" if period is None: return lambda step_n: False def _at_1_and_periodically(step_n): return (step_n == 1) or (step_n > 0 and (step_n % period == 0)) return _at_1_and_periodically
fa1572778e7113cc61e90967ce00e70c8cdf368e
575,710
async def status(hub, ctx, name: str): """ Get a container's status CLI Example: .. code-block:: bash idem exec lxd.containers.status container01 """ container = await hub.tool.lxd.api.request(ctx, "containers", "get", name=name) if "error" in container: return container ...
d3c7739d7bee384dc0176b18379a33c6879d5d5a
575,713
import sh def modified_recipes(branch='origin/master'): """ Returns a set of modified recipes between the current branch and the one in param. """ # using the contrib version on purpose rather than sh.git, since it comes # with a bunch of fixes, e.g. disabled TTY, see: # https://stackoverf...
b9e01268b439cc411208c792a17ec728f917bf70
575,716
def find_best_protein(remaining, original, protein_column): """ Finds best protein in remaining graph based on number of peptides a protein matches to (# of edges a protein has). Choose max If there are proteins with an equal number of maximum matched peptides then those proteins compared to the ori...
15eac5a473effc4f8439c56cba9b3da6232c2cd7
575,717
def _pounds_to_kilograms(mass): """Convert mass lbs to kg""" return mass * 0.453592
d797b6ae4af8195fcdb9b9966a91ab51a603004e
575,720
from pathlib import Path def read_dependencies(txt_file: Path) -> list: """Read name of the required packages.""" with txt_file.open("r") as f: dependencies = [ line for line in f.read().splitlines() if not line.startswith('#') ] return dependencies
172585f126cb1d5d2c0af627f0bd885d71628741
575,722
def gccdicosnap(dicosnap,dicoedgeccm): """ Selects all time-stamped edges with nodes belonging to the maximal connected component. Parameters: dicosnap (dict): Dictionary indexed by timestamps, whose keys are edgelists for a given time-slice. dicoedgeccm (dict): Dictionary index...
5c9cb173eee2bffa2f82edbf03ed05f5e1a7d2f0
575,731
def bbox_from_planet_feature(planet_feature): """Extract the tile footprint from a planet feature Args: planet_feature (dict): planet feature to extract bbox from Returns: list: coords of the feature's bbox """ # it's a geojson polygon, so drill in coords = planet_feature['geo...
8ceb650720d6b0fa62c45bd6e1ada74c2df5e0dd
575,732
def velocities_to_moduli(rho, v_phi, v_s): """ convert velocities to moduli mainly to support Burnman operations :param rho: density in kg/m^3 :param v_phi: bulk sound speed in m/s :param v_s: shear velocity in m/s :return: K_s and G """ return v_phi * v_phi * rho, v_s * v_s * rho
0a13a3cb9cbdbeca54cafb502264213908d4848f
575,736
import math def sizeof_fmt(size, suffix='B'): """ Return a human-readable string representation of a filesize Arguments: size -- size in bytes """ try: size = int(size) except ValueError: return None if size <= 0: return '0 %s' % suffix size_name = ('', 'K...
ba8da544c29296e55aca30787026cb519bdbe75e
575,739
def save_model(network, filename): """ Save model """ network.save(filename) return None
b19c89fc70f0b6924af5b391807a95745457e33e
575,756
def plant_vertices(g): """ return the list of mtg vertices that represent plants """ return g.vertices(scale=1)
33094087a6387869a3852a4bfc5d2b45f7883415
575,769
def parse_bool(s): """Parse a string to a boolean. Parameters ---------- s : str String to parse Returns ---------- bool Examples ---------- >>> from misc import parse_bool >>> print(parse_bool('true')) True """ if s.lower() == 'true': return T...
391aa8bd05969642434417330033462e3bdc8735
575,778
def get_idx_time(deadline): """Return time-step indexing: T = {0,1...tau-1}, tau = deadline""" T_ = list(range(0, deadline)) return T_
1bbcd072ed4c6107c86bd9f4b425b83f03199249
575,779
def get_baseline_uri(region): """ Description: ----------- Compiles the container uri for the Baseline Processing Container based ont he region. :region: (str) Current AWS Region :return: Baseline Container URI. """ container_uri_format = ( "{0}.dkr.ecr.{1}.amazonaws.com/sa...
771c2f4d4166f8cc610d153552852967636616a2
575,781
def cc_iterable_len(cc_iterable): """Count the number of elements in an Iterable object. Args: cc_iterable: a CLIF-wrap of a subclass of the C++ Iterable class. Returns: integer count """ count = 0 while True: not_done, _ = cc_iterable.Next() if not not_done: break count += 1 r...
f9b649d760f812fb587ffc98de32df8316ef63ab
575,782
def _gke_op_poller_factory(service, project, zone): """Creates a function that polls a GKE operation. The value returned by a call to this function can be provided as the op_poller argument to _wait_for_operation. Args: service: a apiclient.discovery.Resource object for interacting ...
e4937e5153cbb1477e83e6f42e80763a6c746878
575,786
def imp_factor(b_curve): # Docstring """ Imperfection factor. Returns the imperfection factor for a given buckling curve. The values are taken from Table 6.1 of EN1993-1-1 [1] Parameters ---------- b_curve : {'a0', 'a', 'b', 'c', 'd'} [_] Name of the buckling curve as obtained ...
b1cd525b1562ad0185539f1f7bf20c523b6787c3
575,787
def extract_gp_layer_kwargs(kwargs): """Extracts Gaussian process layer configs from a given kwarg.""" return dict( num_inducing=kwargs.pop("num_inducing", 1024), normalize_input=kwargs.pop("normalize_input", True), gp_cov_momentum=kwargs.pop("gp_cov_momentum", 0.999), gp_cov_ridge_penalty=...
416097ab3ebe7f8980177862d18e2b0b24005918
575,789
def generate_citation(metadata_dict): """ Generate a citation from the other metadata. """ format_args = dict(metadata_dict) format_args["year"] = format_args.pop("updated_datetime").split("-")[0] format_string = "{creator}, {year}: {title}. {publisher}, {object_id}" return format_string.for...
c1336173b4106f8a17f1a84ced9c7b044e4e3f93
575,791
def empty_str_from(target): """ Produces a function that will turn a string into an empty string if it matches the given target. """ def func(raw): """ The function which will do the conversion. """ if raw == target: return None return raw r...
aaa754d61f1484e4119ed5611a5b4d14ef7bd293
575,792
def calc_video_kbitrate (target_size, length_secs): """Given a target byte size free for video data, this returns the bitrate in kBit/S. For mencoder vbitrate 1 kBit = 1000 Bits -- not 1024 bits. target_size = bitrate * 1000 * length_secs / 8 target_size = bitrate * 125 * length_secs bit...
e0d1a7d4b8f6fc3f4bc221e0c48b5b95851ee04a
575,794
def get_info(part): """Get info about the FPGA part. :param part: the FPGA part as specified by the tool :returns: a dictionary with the keys name, family, device and package """ name = part.lower() # Looking for the family family = None families = [ # From <YOSYS>/techlibs/xili...
2280c40532f411e65c81343ce56e7cd6b9261248
575,795
def is_weak_community(G, nodes): """ Checks whether the provided set of nodes form a weak community in the graph G. """ # precondition: nodes must be sorted subgraph = G.subgraph(nodes) degree = G.degree(nodes) indegree = subgraph.degree() tsum = sum(degree) insum = sum(indegree) ...
9fb2a8faa72bbdbd6e4feaf7b3ab75d012f082ce
575,796
import re def clean_name( name ): """ replaces non-alpha with underscores '_' and set the string to lower case """ return re.sub( '[^0-9a-zA-Z]+', '_', name ).lower()
b0bef4b4a728568ac3f63447671faa4f20fb007c
575,797
def getStateLabelsFromLineNo(line_no, n): """ Gets the indeces for labelling rho [i, j] from the line number of an array. Parameters: line_no (int): line number of an array e.g. position of a row in a matrix or column in rho_t n: the number of states in the system Returns: ...
fe8b9242abac3ba8cb89bee8dbba1e421b9ab74d
575,800
def _is_convertible_to_property(value): """ Check whether a value is convertible to a chemiscope property, i.e. if it is a string or something convertible to float. """ if isinstance(value, (bytes, str)): # string types return True else: # everything convertible to float ...
c703fbca9aaae8ebc1af9700d4c25fa588d9b0c8
575,802
def get_equipped_in_slot(actor, slot): """ Returns Equipment in a slot, or None. """ if hasattr(actor, 'inventory'): for obj in actor.inventory: if obj.equipment and obj.equipment.slot == slot and obj.equipment.is_equipped: return obj.equipment return None
68afd2af8fe7418756ba3b40cb40918be0559cd7
575,804
def byte_to_signed_int(x): """ Returns a signed integer from the byte :param x: Byte """ if (x & 0x80) >> 7 == 1: return -((x-1) ^ 0xff) else: return x
c3fda8f63e5702e80e422adbc2a9126d2d0a25e7
575,805
import itertools def get_combinations(keys, *lists): """ Make combinations from given lists Parameters ---------- keys : list Name of consequent columns (lists) lists : list of lists Values to combine Example -------- get_combinations( ["key1", "key2", "key3"...
26e54ab444d058c01553bbf57baf589ea4c98b91
575,809
def num_of_nonzero_elements(my_vector): """Returns the number of non-zero elements in a vector""" counter = 0 for element in my_vector: if element != 0: counter += 1 return counter
ad17c895a6c4b2c1435da8f33f2be94ae9ff9283
575,811
def spread(arg): """Return a flattened array.""" ret = [] for i in arg: if isinstance(i, list): ret.extend(i) else: ret.append(i) return ret
d6bc0f06a76326f19437c220c54282d179ef8c58
575,812
def is_cell_of_types(board, point, types): """ Searches cell type in the list and returns an index if found. :param board: Board instance. :param point: Point instance. :param types: list of cell types (enum). :return: index if found, otherwise it returns -1. """ try: index = typ...
423b666b7f80fda5eede3fbe92cf6588417e46b5
575,820
def filter_planes(feature_dict, removeDirection, percentile): """filter planes by the criteria specified by removeDirection and percentile Args: feature_dict (dictionary): planes and respective feature value removeDirection (string): remove above or below percentile percentile (int...
7612741debf983fd0976cc0afe8428120b2e6647
575,824
import json def load_json(filename, samples=100000): """ Loads the generated corpus from a json file by picking the first n samples, random chosing is not neccessary as the sampling process from a language model is random :param filename: str, filepath and name :param samples: int, number of documents...
686a4181abe94a0f4b2a1e25f5bb10cde38c3886
575,825
def know(possible_dates): """A person knows the birthdate if they have exactly one possible date.""" return len(possible_dates) == 1
53c445b1579b9a6ea72a0428a7b1c6b820e34e8c
575,826
def _CreateNodeConfig(messages, flags): """Creates node config from parameters, returns None if config is empty.""" if not (flags.location or flags.machine_type or flags.network or flags.subnetwork or flags.service_account or flags.oauth_scopes or flags.tags or flags.disk_size_gb or flags.use_ip...
a4b2d1e2ce5e5a328a3e9c5241e6c8684a8fad89
575,827
def pround(val): """Round a number with a precision determined by the magnitude.""" precision = 1 if val >= 100: precision = 0 if val < 1: precision = 3 return f"{val:.{precision}f}"
0478e2bb66c511d1298abf9c534502a52ed60f36
575,830
def get_zipfile_comments(zip_file): """ Get a dictionary of comments for each file in the zip as a dictionary in the form {}. """ return {i.filename: i.comment.decode('utf-8') for i in zip_file.infolist()}
991343f3769c1de90005ef05446cec88929f3227
575,833
def jsonable(hist): """Make a history dictionary json-serializable. :param hist: dictionary of lists of float-like numbers. """ out = {} for k, v in hist.items(): out[k] = list(map(float, v)) return out
78e8faf5f1607ce6c04005a722e6ecd0a546dfff
575,838
def adjust_lr(lr, lrd=10, log=None): """ Update learnign rate. :param lr: original learning rate. :param lrd: decrease ratio of learning rate. :param log: if log is not None, print the comments for changing learning rate. :return lr: adjusted learning rate. """ lr = lr / lrd pri...
87b19660fc0b76729a3791fbb7ac20ea6cb02612
575,844
def pass_through(*args, **kwargs): """ Used for testing, takes your arguments and passes them back for type testing. .. code-block:: python variable = "Test this comes back the way I sent it." response = net.pass_through(variable, peer='somepeer') :return: *args, **kwargs """...
efd5195f652bf8a18b4b1e7c867a9a9d71cd9bf5
575,846
def readKms(fin, out=None): """ Read kmers and compute sum for each locus. Use out=ARRAY to change ARRAY inplace. """ ndb = out is None if out is None: out = [] with open(fin) as f: idx = -1 for line in f: if line[0] == ">": idx += 1 ...
a89ecd235e564c85aa4bcfba7ce1862274eff4b9
575,848
def convert_to_unicode(input_string): """Convert input string to unicode.""" if isinstance(input_string, bytes): return input_string.decode('utf-8') return input_string
0c22440a0e7e83ae3a6878f3da0c4ea1928fe408
575,849
import yaml def parse_yaml(input_file): """Parse yaml file of configuration parameters.""" with open(input_file, "r") as yaml_file: params = yaml.safe_load(yaml_file) return params
04a185768036f9e4932d4e3171c999a60f4a9cb7
575,853
def _nth_root(value, n_root): """ Helper to computer the nth-root of the value. """ return value ** (1 / n_root)
8065b3a1f42b1eff6ada0f79fb9667482501f7e8
575,856
def get_gencode2ucsc(genomes): """ generate conversion dict for gencode's Ensembl-style names to UCSC-style names. Parameters ---------- genomes : dict the provider's genomes dict Returns ------- dict keys: Ensembl names, values: UCSC names """ # start with ...
e6b399e332cdbcb5dd73e4d229a483f21b0680f2
575,859
def ensure_raw(x): """Return raw tensor from x, unless it already is a raw tensor""" try: return x.raw except AttributeError: return x
401a73e9775a266161f3b50f2703cde949600968
575,867
from functools import reduce def deep_get(dictionary, keys, default=None): """Get values of nested keys from dict Args: dictionary(dict): Dict with nested keys keys(dict.keys()): "." separated chain of nested keys, ex "info.player.name" """ return reduce(lambda d, key: d.ge...
5948d710a7641d26695f4087707106969b156456
575,870
def filename_from_disposition(content_disposition): """ Gets a filename from the given content disposition header. """ filename_pos = content_disposition.index('filename=') if filename_pos == -1: raise Exception('"filename=" not found in content disposition file') return content_dispos...
309ee4bab6e5cf5825d038bd8414c53496e95fc9
575,872
def _update_french_non_int(value): """ Update non-int values like "X" or "-". """ if value == 'X': return 99 if value == '-': return -1 return value
1bb3fbce04753233b3ddc6297c0678d8a6069675
575,873
def complement(sequence): """Provides the complement in the 5' - 3' direction Assumption: reference consists of A, G, C, T only complement(str) --> str """ d = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} return ''.join(d[c] if c in d else c for c in reversed(sequence))
ed9246cc885278764c8de8863b2013168ba2178f
575,875
def GetOrdinal(number): """ Get Ordinal Gets the Ordinal of the given (int) number input 12 >> 12th 1 >> 1st 925 >> 925th 632 >> 632nd """ if type(number) != type(1): try: number = int(number) except: raise ValueError("Intergers only") l...
7f72eb55169c787563807707597d10bbb8b9c448
575,879
from pathlib import Path def strip_hostname(uri_path: str | Path) -> str: """ Strop the hostname from a URI path. For example, "fileserver.host.com:/full/path/of/dir_name" will be transformed to "/full/path/of/dir_name". Parameters ---------- uri_path : str or Path A URI path. ...
901650436f463b493be57b2c85901e24459f1c2c
575,880
def buildOpenPGPFingerprintHostname(uid): """ Build the hostname where the OpenPGP fingerprint should be stored in a text record if it has been published. Don't forget, it's always possible that the name will not exist. """ parts = uid.split('@', 1) hostname = parts[0] hostname += "._pk...
c8fab0b69c9c91b8a13f436dce4a9c7918339849
575,884
def getVideoIdFromEntry(entry): """Get video ID from a YouTube entry.""" return entry.id.text.split("/")[-1]
a922cd4220e31ccb43f179f3598867c59d2b5eaa
575,885
import torch def calc_advantages(rewards, values, dones, reward_discount, advantage_discount): """ Calculate advantages with Global Advantage Estimation Args: rewards: Rewards from environment values: State-values dones: Episode ended flags reward_discount: Discount factor ...
5de73335fd265ea4b450fce36829fe3d9a3b91d9
575,886
from pathlib import Path def force_create_dir(dir_name: str) -> Path: """ Creates a new directory with the given name to disk, returning the associated Path object. If `dir_name` already exists, an incremented number is appended until the new directory can be created. Raises: `OSError`: I...
d12e8c37a96b463b167692ea9a71cf877c352754
575,888
import re def check_email(email): """Check if email address is in a valid format. Checks if the email message is greater than 2 characters, contains an '@' symbol with text before it, text after it, a period, and some more text. Note: email addresses with only two characters between @ and . will fail...
b28df1e0be741aad536847f717702b239162b9a4
575,889
def autofocus(scope, z_start, z_max, range_mm, steps, speed=0.3, metric='brenner', metric_kws=None, metric_mask=None, metric_filter_period_range=None, return_images=False): """Run a single-pass autofocus. Parameters: scope: microscope client object. z_start: position to start autofocus ...
e7aadd813d70766149bc3d78e7b78b1943c24d13
575,891
def _format_warnings(message, category, filename, lineno, file=None, line=None): """ Warning formatter Args: message: warning message category (str): level of warning filename (str): path for warning output lineno (int): Where the warning originates Returns: Formatt...
2cc630b1a2e46e92d9832f31ed3809417fef4b79
575,892
def eaton(v, vn, hydrostatic, lithostatic, n=3): """ Compute pore pressure using Eaton equation. Parameters ---------- v : 1-d ndarray velocity array whose unit is m/s. vn : 1-d ndarray normal velocity array whose unit is m/s. hydrostatic : 1-d ndarray hydrostatic pr...
80abde12e6890e8ae1febd52a0e1e86a65128d78
575,896
def remove(s1,s2): """ Returns a copy of s, with all characters in s2 removed. Examples: remove('abc','ab') returns 'c' remove('abc','xy') returns 'abc' remove('hello world','ol') returns 'he wrd' Parameter s1: the string to copy Precondition: s1 is a string ...
4cb1e27e493a16c97fd6c26ebe9edbe984d06d20
575,898
import logging def token_required(token): """ Verifies token sent in request in `X-Auth-Token` header. If token is correct decorated method is executed. Otherwise request raises 401 HTTP error. :param (str) token: Secret token used to authorization. """ def wrap(func): def func_wrap...
523b5d2b2de9fbe0d438083176f34014acd08ce0
575,899
import re def note_to_pitch_class(note): """ Remove octave information. Input D#3 will return D# :param note: Original note, such as 'D#3' :return: Note without the octave, such as 'D#' """ return re.sub("\d", "", note)
b247f0d3af7e0a52d08e563a5ef9f25b2ec259e4
575,901
def combine_comments(comments): """ Given a list of comments, or a comment submitted as a string, return a single line of text containing all of the comments. """ if isinstance(comments, list): comments = [c if isinstance(c, str) else str(c) for c in comments] else: if not isinst...
423233abbfc2e302b839a834c7c37bcdddeae4aa
575,904
def _dicts_to_list(list_of_dicts, keys): """Transforms a list of dicts to a list of values. This is useful to create a list of Tensors to pass as an argument of `host_call_fn` and `metrics_fn`, because they take either a list as positional arguments or a dict as keyword arguments. Args: list_of_dicts: (...
de0e4437a694c7fbf889c3f5bab600206da244f4
575,906
def d4(dx, fc, i): """ fourth-order centered derivative at index i """ D = -fc[i+2] + 8.0*fc[i+1] - 8.0*fc[i-1] + fc[i-2] D = D/(12.0*dx) return D
e36538171d1d032ea0098a5997886885b6152d6b
575,907
def timestamps2frame_durations(timestamps: list, last_frame_duration=None) -> list: """ Produces frame durations list to make gifs produced with write_pc2gif() more accurate temporally, Parameters ---------- timestamps : list List of timestamps of corresponding array frames. last_f...
c2ad1ca487fd9178cdf81be07a61ad4ba37c339d
575,909
def _get_list_of_branches(chain): """ Returns a list with the names of all the branches of the given TChain """ return [b.GetName() for b in chain.GetListOfBranches()]
29bdba2365e50838ec4d9bc2c68e247ef13ddb2e
575,912
def truncate(original: str, length: int) -> str: """ Provide an elided version of the string for which the last three characters are dots if the original string does not fit within the specified length. Args: original: string to elide length: constrain the elided string to this ...
44403f3606c1832bb1ad2ef1d01b9620ece3c7fa
575,913
def isSuffixOf(xs, ys): """``isSuffixOf :: Eq a => [a] -> [a] -> Bool`` Returns True if the first list is a suffix of the second. The second list must be finite. """ return xs == ys[-len(xs):]
c57da0216d8064f4a5902f2397025d29fa04784d
575,917
def accept_kwargs(func): """Wrap a function that may not accept kwargs so they are accepted The output function will always have call signature of :code:`func(val, **kwargs)`, whereas the original function may have call signatures of :code:`func(val)` or :code:`func(val, **kwargs)`. In the case of ...
acd243f37a8a6fe5021e2a0d3bab1985a5142d9e
575,919
def symmetrify_paths(shortest_paths): """Make paths symmetric Given a dictionary of all-pair shortest paths, it edits shortest paths to ensure that all path are symmetric, e.g., path(u,v) = path(v,u) Parameters ---------- shortest_paths : dict of dict All pairs shortest paths Retu...
a3be93d20ac6332911635ef8c00c9f21049b162a
575,920
def is_power2(num): """ Check if a number is a power of 2 """ return num != 0 and ((num & (num - 1)) == 0)
b1436dce638fd4620de62dbc2e51235d49d0ebbe
575,927
def pipe(*fns): """ Given a list of queryset functions as *args, return a new queryset function that calls each function in turn, passing the return value of each as the argument to the next. """ def piped(queryset): for fn in fns: queryset = fn(queryset) return quer...
a19645ead8eb0cace9b86cb20673844b53f2ee3b
575,931
def get_default_guc_value(cursor, guc): """Get parameter value assumed at server startup""" cursor.execute(""" SELECT boot_val FROM pg_settings WHERE name = %s; """, (guc,) ) return cursor.fetchone()[0]
4ef3ec9bc926a1574471f1642477617fa1fff676
575,932
import functools def max_subarray_cache(nums: list[int]) -> int: """Returns the largest non-empty contiguous subarray sum Args: nums: An array of integers drawn from the range [-10^5, 10^5] Examples: >>> max_subarray_cache([-2,1,-3,4,-1,2,1,-5,4]) 6 >>> max_subarray_cache...
25985d7c9d8512de50207cfb6b999743be111ac3
575,933
def games_to_list(games): """ Convert a list of Game objects to a list of objects for list API :param Game[] games: :return dict[]: """ return [ game.to_list_item() for game in games ]
901095850109ad1421ab43e7a63d7f69932c5496
575,936