content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def getStereoPair(pipeline, monoLeft, monoRight):
"""
Generates a stereo node. Takes left and right camera streams as inputs and generates outputs
"""
stereo = pipeline.createStereoDepth()
stereo.setLeftRightCheck(True)
monoLeft.out.link(stereo.left)
monoRight.out.link(stereo.right)
return stereo | 5ef27fdb4f2a635adcf026d1e148a484a66f7718 | 679,721 |
from fractions import Fraction
def compile_continued_fraction_representation(seq):
"""
Compile an integer sequence (continued fraction representation) into its corresponding fraction.
"""
# sanity check
assert seq
# initialize the value to be returned by working backwards from the last number... | 6140f5e74c88734b8f9be1f0df191ed82c8540e3 | 679,723 |
def get_skin_num(id, skin_id):
"""
Returns Skin Number from the Skin ID
"""
skin = str(id)
length = len(skin)
new_id = str(skin_id)[length:]
return int(new_id) | 0ade64b93280efc5662c1d7fcfa7627d7aae3cb6 | 679,724 |
def check_int(value: int) -> bool:
"""Check whether value can be written as 2^p * 5^q where p and q are
natural numbers."""
if value == 1:
return True
else:
if value % 2 == 0:
return check_int(value//2)
if value % 5 == 0:
return check_int(value//5)
ret... | 754d89997e73acd81dd8d08f50a88f29f50b6783 | 679,725 |
def make_ngrams(tokens: list, n: int) -> list:
"""Creates n-grams for the given token sequence.
Args:
tokens (list): a list of tokens as strings
n (int): the length of n-grams to create
Returns:
list: list of tuples of strings, each tuple being one of the individual n-grams
"""
n_grams ... | 17699d058d2d8707e68642bc22f91996757882c3 | 679,726 |
import inspect
def get_channelmethods(obj):
"""
Returns a sorted list of the names of all channelmethods defined for an object.
"""
channelmethods = list()
# getmembers() returns a list of tuples already sorted by name
for name, method in inspect.getmembers(obj, inspect.ismethod):
# To... | 2443434f3b4141272cbf6266cfec2da5c57d1e90 | 679,727 |
def map_range(value, from_lower, from_upper, to_lower, to_upper):
"""Map a value in one range to another."""
mapped = (value - from_lower) * (to_upper - to_lower) / (
from_upper - from_lower
) + to_lower
return round(min(max(mapped, to_lower), to_upper)) | dd4bd400e4b117af4ff73a551771b7921b6148f6 | 679,731 |
def default_logfile_names(script, suffix):
"""Method to return the names for output and error log files."""
suffix = script.split('.')[0] if suffix is None else suffix
output_logfile = '{}_out.txt'.format(suffix)
error_logfile = '{}_err.txt'.format(suffix)
return output_logfile, error_logfile | b28b03f1b3f49efdb2d286bb431b9ad99145b32f | 679,732 |
import re
def str_split(string, split_length=1):
"""Method splits string to substrings
Args:
string (str): original string
split_length (int): substrin length
Returns:
list: list of strings
"""
return list(filter(None, re.split('(.{1,%d})' % split_length... | 65dd325fb7fda7ac1af2b18840e42f567d1b971d | 679,733 |
def flatten(l):
"""Flattens a list of lists to the first level.
Given a list containing a mix of scalars and lists,
flattens down to a list of the scalars within the original
list.
Args:
l (list): Input list
Returns:
list: Flattened list.
"""
if not isinstance(l, list... | 87cf038798ce562b0bdce5efbd573f4a800d1ebf | 679,743 |
def is_annotation_size_unusual(annotation, minimum_size, minimum_aspect_ratio, maximum_aspect_ratio):
"""
Checks if object described by annotation has unusual size - is too small or has unusual aspect ratio
:param annotation: net.utilities.Annotation instance
:param minimum_size: int, minimum size objec... | d9f62e3600faeee0662d29aaba4d0d26a6b9252f | 679,746 |
def to_json_list(objs):
"""
Wrap strings in lists. Other iterables are converted to lists directly.
"""
if isinstance(objs, str):
return [objs]
if not isinstance(objs, list):
return list(objs)
return objs | b2541ca880856aa07e8178ac6924caab0a2ffa00 | 679,749 |
def make_list(item_or_items):
"""
Makes a list out of the given items.
Examples:
>>> make_list(1)
[1]
>>> make_list('str')
['str']
>>> make_list(('i', 'am', 'a', 'tuple'))
['i', 'am', 'a', 'tuple']
>>> print(make_list(None))
None
>>> # ... | 5769e6331fce84d9ae236ddb1c38d081379c08ab | 679,750 |
def check(these_bytes):
"""Tests a file for presence of a valid header"""
test = str(these_bytes[8:12])
if test[2:6] != 'logo':
return 1
return 0 | 36e4df36be229fc280ba4db2b568c02717102e19 | 679,752 |
def safe_get(lst, index, default=None):
"""
An implementation of the similar :meth:`get` of the dictionary class.
:param lst: the list to perform the operation on
:param index: the index to query
:param default: the default value if not found
:return: the result if exists or the def... | d1f1410663ed4ff090e38594ff5dac1d304fecc3 | 679,755 |
def calculate(x: int, y: int = 1, *, subtract: bool = False) -> int:
"""Calculates the sum (or difference) of two numbers.
Parameters:
`x` : int
The first number
`y` : int, optional
The second number (default is 1)
`subtraction`: bool, optional
Whether to perform subtraction... | 8f46dadf73536167c23e17d3b5da0f57fd084d7e | 679,757 |
def elevation_line(client, format_in, geometry,
format_out='geojson',
dataset='srtm',
validate=True,
dry_run=None):
"""
POSTs 2D point to be enriched with elevation.
:param format_in: Format of input geometry. One of ['geojson'... | cc53bc954ec9b110ef0858cfd34236b8c1d77070 | 679,759 |
import sqlite3
def commit_data(conn):
"""Commit data to db"""
try:
conn.commit()
conn.close()
except sqlite3.Error as e:
print(e)
return None | 5107563c659c0acdd9d2d59c526284ffe38a4740 | 679,763 |
import re
def _strip_terminal_commas(data: str) -> str:
"""Remove all terminal commas.
Samples sheets have a large number of commas append to the end of the
various sections. I think this is an artifact of exporting to a CSV
forcing each row to have the same number of columns as the main Data
sec... | 656e0114fe4ce94937bfbc1a4b99f61510cf6762 | 679,767 |
def _get_runfile_path(ctx, f):
"""Return the runfiles relative path of f."""
if ctx.workspace_name:
return ctx.workspace_name + "/" + f.short_path
else:
return f.short_path | 50b64d1e90ebfb4599b081d1789b0f7b789b2e28 | 679,769 |
def calculate_cn_values(m, sigma_veff):
"""
CN parameter from CPT, Eq 2.15a
"""
CN = (100 / sigma_veff) ** m
if CN > 1.7:
CN = 1.7
return CN | d1dfb14414bfe0f59a5a432e6c5dfd4994ee29ff | 679,772 |
import torch
def shuffle_data(inputs, outputs):
"""Shuffle the first dimension of a set of input/output data"""
n_examples = outputs.shape[0]
shuffled_indices = torch.randperm(n_examples)
inputs = inputs[shuffled_indices]
outputs = outputs[shuffled_indices]
return inputs, outputs | 6c264ae3840c4c0c338c9423e3a74a1598e6946b | 679,776 |
import re
def is_valid_entity(line: str) -> bool:
"""Check if the line is a valid entity annotation."""
regex = r'^T\d+\t\w+ \d+ \d+(;\d+ \d+)*\t.+$'
return re.search(regex, line) is not None | 7340603532b6ec9891e1d73047261c3ef1a23a49 | 679,778 |
def _blob_and_weights(net, layer_name):
"""Get the activation blob and the weights blob for the named layer
in the Caffe network.
"""
# Get the activation blob for this layer and its parameters
# (weights).
blob = net.blobs[net.top_names[layer_name][0]]
weights = net.params[layer_name][0]
... | 07fb1a2c363f710d6f53691facb3a07ef33a3475 | 679,780 |
def null_val(val):
"""Return True if the value is a mmCIF NULL charactor: ? or .
"""
if val == "?" or val == ".":
return True
return False | 7a9c778e4bdf917cc94d453e458d4212a925677a | 679,785 |
import torch
def radius_gaussian(sq_r, sig, eps=1e-9):
"""
Compute a radius gaussian (gaussian of distance)
:param sq_r: input radiuses [dn, ..., d1, d0]
:param sig: extents of gaussians [d1, d0] or [d0] or float
:return: gaussian of sq_r [dn, ..., d1, d0]
"""
return torch.exp(-sq_r / (2 *... | 22dbe61ef2930313ec7f1e5fc1726c3e643350f8 | 679,787 |
def human_to_mb(s):
"""Translates human-readable strings like '10G' to numeric
megabytes"""
if len(s) == 0:
raise Exception("unexpected empty string")
md = dict(M=1, G=1024, T=1024 * 1024, P=1024 * 1024 * 1024)
suffix = s[-1]
if suffix.isalpha():
return float(s[:-1]) * md[suffi... | 1cf5a6afbb4e51d415de4307a07947a741af71bc | 679,791 |
import collections
def longest_substring_deque_rotations(s: str) -> int:
"""
find the longest substring without repeating characters
512 ms 14.5 MB
>>> longest_substring_deque_rotations("abac")
3
>>> longest_substring_deque_rotations("abcabcbb")
3
>>> longest_substring_deque_rotations... | f19ed9735007ead22405c6cd2f361973625f333e | 679,793 |
def CodepointsToUTF16CodeUnits( line_value, codepoint_offset ):
"""Return the 1-based UTF-16 code unit offset equivalent to the 1-based
unicode codepoint offset |codepoint_offset| in the Unicode string
|line_value|"""
# Language server protocol requires offsets to be in utf16 code _units_.
# Each code unit is... | 976daeb55916dbfeeff7f92e5352ee3ab135a608 | 679,794 |
import importlib
def _import_name(generator):
"""Import a class from its module name."""
# A generator 'path'
try:
mod_name, func_name = generator.rsplit(".", 1)
except ValueError:
raise ValueError("Invalid generator class name %s" % generator)
try:
mod = importlib.import_... | e79ef1c5d66e799a35eb7b6db9b93557fe1fa91b | 679,795 |
def sciNot(x):
"""Returns scientific notation of x value"""
return '%.2E' % x | cf30d76318ed1c0a86c3b59d767e3ee2292ca16b | 679,800 |
import ctypes
def struct_to_dict(struct: ctypes.Structure) -> dict:
"""Create a dict from a struct's fields and their values."""
return {name: getattr(struct, name) for name, _ in getattr(struct, "_fields_")} | ddb1789e90f60ae8916e93affa0fa6a7d346181d | 679,801 |
def parse_hkey(idx):
"""parse index and convert to str
Args:
idx (pd.DatetimeIndex): datetime index
Returns:
str: zero padded 24-clock hour(%H)
"""
return str(idx.hour).zfill(2) | e3c1e41bf28ad1d340b54e155c02105486435c37 | 679,802 |
def apparent_latitude(t='now'): # pylint: disable=W0613
"""Returns the true latitude. Set to 0 here."""
return 0 | c7b4a0c9e262a8c7ba219626ae3b1e3e6886185d | 679,805 |
def normalise_activity_by_sector_month(
topic_activity, sector_month_labels, sector_variable="sector"
):
"""Normalise s.t. each [sector, month] sums to 1."""
norm_factor = (
sector_month_labels.dropna()
.groupby(
[
"month",
sector_variable,
... | 0c9fb4d8cd3b877cc08568bedb7019cbbc40cd90 | 679,806 |
def is_permutation(a: int, b: int) -> bool:
"""Returns boolean if a and b are permutations of each other."""
s_a, s_b = str(a), str(b)
if set(s_a) != set(s_b):
return False
if len(s_a) != len(s_b):
return False
return sorted(list(s_a)) == sorted(list(s_b)) | e3fa9e013f5794ec44d739282d98f72b8b601ed2 | 679,808 |
from collections import Counter
def related_by_digit_permutation(num_a, num_b):
"""
Check if two numbers are related by digit permutation.
"""
return Counter(str(num_a)) == Counter(str(num_b)) | 9c211d7e93f6fb6e39a07532e412b9ffda1ba96b | 679,813 |
from typing import Dict
from typing import Any
from typing import Optional
def get_name(hook: Dict[Any, Any]) -> Optional[str]:
"""
Creates a name based on the webhook call it recieved
Format: Timestamp_Devicename.mp4
Removes any characters that are not regular characters, numbers, '_' '.' or '-'
... | 2b9a034ee551894adc4a03cebce3711cdbad58d3 | 679,814 |
def iterator(it):
"""
Convenience function to toggle whether to consume dataset and forecasts as iterators or iterables.
:param it:
:return: it (as iterator)
"""
return iter(it) | f0efa7c377aac88eb2d9f849bf00359327e702e9 | 679,816 |
def normalize_date(date):
"""Round datetime down to midnight."""
return date.replace(hour=0, minute=0, second=0, microsecond=0) | d4021f6e984045d9bd0172fd1c7d060acc8054e0 | 679,817 |
import math
def hits_to_kill(damage, health):
"""
Returns the number of hits it takes to kill the target.
"""
if damage > 0:
hits = health / damage
else:
hits = math.inf
if hits < 1:
hits = 1
elif hits < math.inf:
hits = math.ceil(hits)
return hits | 4cb87b0216145a42778781be844c4b44c87d355b | 679,820 |
from textwrap import dedent
def create_script(molecule_name, temperature=273.15, pressure=101325,
helium_void_fraction=1.0, unit_cells=(1, 1, 1),
simulation_type="MonteCarlo", cycles=2000,
init_cycles="auto", forcefield="CrystalGenerator",
input_... | eaef3ef51d2ff019b83b57ed36c2f4bb5a138450 | 679,823 |
import uuid
def generate_unique_id(text):
"""
Generate a unique UUID based on a string
Args:
text(str): The string to base the uuid on
Returns:
str: The UUID in hex string format
"""
return uuid.uuid3(uuid.NAMESPACE_URL, text).hex | 02e44b594e043314450c85bf86e14349f9a4d87f | 679,825 |
import random
import string
def generate_random_key() -> str:
"""
Creates and returns a randomly generated 10 character alphanumeric string.
:return:
"""
return "".join(
random.SystemRandom().choice(string.ascii_uppercase + string.digits)
for _ in range(10)
) | 324a74e50b00ad287838ea7ad10b127f094ca380 | 679,826 |
def _df_meta_to_arr(df):
"""Check what kind of data exists in pandas columns or index. If string return as numpy array 'S' type, otherwise regular numpy array.
"""
if len(df.columns):
if isinstance(df.columns[0], str):
columns = df.columns.values.astype("S")
else:
co... | 17a3b457d97726bf9c540fc9c8cc8fdf650c5d00 | 679,827 |
from pathlib import Path
import yaml
def load_yaml(yamlpath: str):
"""
Loads a yaml file from a path.
:param yamlpath: Path to yaml settings file
:returns: dict settings object """
yamlpath_full = Path(yamlpath).absolute()
with open(yamlpath_full, 'r', encoding="utf-8") as stream:
try... | 7c1e1f7a9a861532e5eafe277299bb4a6d0df41b | 679,828 |
def has_field(analysis, field):
"""Return true or false if given field exists in analysis"""
for f in field:
try:
analysis = analysis[f]
except:
return False
return True | 29a2a6f1c4a89d282220bd5cbd4c9e6e18ae4440 | 679,837 |
import multiprocessing
def queue_loader(q_list):
"""
Copy values from a List into a SimpleQueue.
"""
q = multiprocessing.SimpleQueue()
for item in q_list:
q.put(item)
return q | 31a41cfc555baeaa0c5c462afdc3596e8f7f714b | 679,839 |
def generate_method(method_name):
"""Generate a method for a given Thrift service.
Uses the provided TChannelSyncClient's threadloop in order
to convert RPC calls to concurrent.futures
:param method_name: Method being called.
:return: A method that invokes the RPC using TChannelSyncClient
"""
... | 08ea4a3d62f034add07c45219da6d96ea3795e8d | 679,842 |
def color_to_int(rgb):
"""Converts a color from floating point range 0-1 to integer range 0-255."""
return tuple(int(round(c * 255)) for c in rgb) | 4ee66330665300c27dda598c070c5519b63eda54 | 679,843 |
import re
def _get_before_pronounce_sentence(words, index):
"""Return before pronounce sentence
Args:
words (List[Words]): stanfordnlp word object list.
index (int): Pronounce index.
Return:
sentence (str): target word contains sentence to pronounce.
"""
roots = [(i, w) fo... | 018f8197b7b1fbe2992131dffe941949eb0157a8 | 679,846 |
def _get_kaggle_type(competition_or_dataset: str) -> str:
"""Returns the kaggle type (competitions/datasets).
Args:
competition_or_dataset: Name of the kaggle competition/dataset.
Returns:
Kaggle type (competitions/datasets).
"""
# Dataset are `user/dataset_name`
return 'datasets' if '/' in compet... | 6341c5ecda800b6f5cee260f4ac50d1748b78528 | 679,848 |
def token_response_json(token_response):
"""
Return the JSON from a successful token response.
"""
return token_response.json | a879b95407251c8cc018e132fdd3e0d0ad109867 | 679,849 |
def get_subgraph(G, attribute, attribute_value):
"""
This function returns the subgraph of G with the attribute
attribute_value.
Input:
------
G: networkx graph
attribute: attribute of the nodes
attribute_value: value of the attribute
Output:
-------
subgra... | f84895c73f5b0b8508587b5491cf5d765471429a | 679,850 |
import re
def verifyFormat(ATS_LIST):
"""
Matches a list of input ATS coordinates against the AltaLIS format in a regex.
Returns True if any of the coordinates match the regex,
False if none return.
"""
# Defines a list of expressions to check against the coordinates.
# Anything in s... | aaa20e4ebd3118bb9e761e7d7e8c74dab7d8ea55 | 679,852 |
def SanityCheck(s):
"""
Class performs a simple text-based SanityCheck
to validate generated SMILES. Note, this method
does not check if the SMILES defines a valid molecule,
but just if the generated SMILES contains the
correct number of ring indices as well as opening/closing
brackets.
... | d0cfece50836a3025ae2f45286bee942bd44b27c | 679,853 |
def priormonthToDay(freq, j_mth, k_mth):
"""
Consistent w/ Fama and French (2008, 2016), map the prior `(j-k)` monthly return strategy into a daily strategy
(see `Ken French's online documentation <https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html>`_).
Parameters
__________... | 124332f879f059a97eb165f26cc3780d97f7c595 | 679,856 |
import re
def _filter_zones(wanted_zones_prefix, zone_list):
"""Filter unwanted zones from a zone list using a prefix."""
target_zones = []
for zone in zone_list:
for prefix in wanted_zones_prefix:
pattern = re.compile(f'^{prefix}')
if pattern.match(zone):
... | 9ec1f068f819ce0d15879ccd81cf3254aabae654 | 679,859 |
def _cut_if_too_long(text: str, max_length: int) -> str:
"""Cut a string down to the maximum length.
Args:
text: Text to check.
max_length: The maximum length of the resulting string.
Returns:
Cut string with ... added at the end if it was too long.
"""
if len(text) <= max_... | 72745efb8a4fd7d6b2af7356d00e1e5bc554ff62 | 679,860 |
import ipaddress
def is_address(entry):
""" Check if entry is a valid IP address """
try:
_ = ipaddress.ip_address(entry)
except ValueError:
return False
return True | 08e9cc24e7319d03a7a5fc9b9768db4497f76039 | 679,862 |
def tuple_or_list(target):
"""Check is a string object contains a tuple or list
If a string likes '[a, b, c]' or '(a, b, c)', then return true,
otherwise false.
Arguments:
target {str} -- target string
Returns:
bool -- result
"""
# if the target is a tuple or ... | f29d4685b8e8bbb0c7e5c800a34a226782cdc7ae | 679,866 |
def get_ext(file):
"""Return the extension of the given filename."""
return file.split('.')[-1] | 5ee0d644557a4f7d5fc30727ed9beca6ab4a67f9 | 679,867 |
import inspect
def get_wrapped_sourcelines(f):
"""
Gets a list of source lines and starting line number for the given function
:param f: Input function
:return: Source lines
"""
if hasattr(f, "__wrapped__"):
# has __wrapped__, going deep
return get_wrapped_sourcelines(f.__wrapp... | 4ad7c9813e304a77f9f1b5c1096c8a3af379250c | 679,870 |
import inspect
import ast
import textwrap
def ast_object(obj):
"""Convert a Python object to its AST representation."""
src = inspect.getsource(obj)
# ast wraps always into a module
node = ast.parse(textwrap.dedent(src)).body[0]
return node | ce25f484f289410ccc08a5e42384b707cb418f76 | 679,873 |
def txt2str(filename):
"""Reads the plain text of a .txt file and returns a string"""
with open(filename, 'r') as myfile:
data=myfile.read().replace('\n', '')
myfile.close()
return data | 7b9ba73b6d33654e3be21d6d286fc3109dee0790 | 679,874 |
def _monitor_pvs(*pv_names, context, queue, data_type='time'):
"""
Monitor pv_names in the given threading context, putting events to `queue`.
Parameters
----------
*pv_names : str
PV names to monitor.
context : caproto.threading.client.Context
The threading context to use.
... | cf8e9a09851e5a9edf958b1fce13294fecdf37ae | 679,875 |
from typing import List
def column_widths(table: List[List[str]]) -> List[int]:
"""Get the maximum size for each column in table"""
return [max(map(len, col)) for col in zip(*table)] | 7f5f601c7d40bc96f257c120adbf6a32ba327789 | 679,877 |
def commands(command):
""" Check if command is to get available Commands (c | commands). """
return (command.strip().lower() == 'c' or command.strip().lower() == 'commands') | ae580a454446af391b17e7c33643160fbce13113 | 679,879 |
def build_concentartion(species_id, number):
"""
Builds the concentration component for each species
Parameters
----------
species_id : int
species id from the species_indices dictionary
number : float
stoichiometric co-eff of the species
... | 4a9a0cbc22e6d9ecf13c86b10d5d5d56baae06dc | 679,880 |
from typing import List
def _merge(nums: List[int], left: int, mid: int, right: int,
aux: List[int]) -> int:
"""
Helper function to merge the given sub-list.
:param nums: list[int]
:param left: int
:param mid: int
:param right: int
:param aux: list[int]
:return: int
"""
... | f1549f9beaa068275a82869363ca9db19b3cbb2b | 679,883 |
def int_to_byte(n):
""" convert int into byte """
return n.to_bytes(1, byteorder='big') | 2be4943d138f27e893cbc8a5eb9b11f480a8fce3 | 679,886 |
def get_coords_from_line(line):
""" Given a line, split it, and parse out the coordinates.
Return:
A tuple containing coords (position, color, normal)
"""
values = line.split()
pt = None
pt_n = None
pt_col = None
# The first three are always the point coords
if l... | 3058feec12847b11b7ffcddb2856bd734e72f109 | 679,887 |
def get_dataset_names(datasets):
"""
Returns the names of the datasets.
Parameters
----------
datasets : tuple
tuple of datasets
Returns
----------
dataset_names : list
list of dataset names
"""
dataset_names = []
for index_dataset, (dataset_name, df_data) in enumerate... | 88d92b1d982e8279a98f1cfd7d10af6fe626d36d | 679,889 |
def angle_offset(base, angle):
"""
Given a base bearing and a second bearing, return the offset in degrees.
Positive offsets are clockwise/to the right, negative offsets are
counter-clockwise/to the left.
"""
# rotate the angle towards 0 by base
offset = angle - base
if offset <= -180:... | 8d71b88c1f96983fc04c22530f4d141bca7a6f3f | 679,890 |
def is_leaf(node):
"""Checks whether the :code:`node` is a leaf node."""
return not isinstance(node, list) | bfcf8d20448d7ec15b2a51c7c47da39a4ec13f7d | 679,891 |
def raiz(x, y):
"""
La raíz enésima de un número.
.. math::
\sqrt[y]{x}
Args:
x (float): Radicando.
y (float): Índice.
Returns:
float: La raíz.
"""
return x**(1/y) | ab3fab67dff08de02ecf1e51692099e519e902d0 | 679,892 |
def is_tar(name):
"""Check if name is a Tarball."""
return (
name.endswith(".tar") or name.endswith(".gz") or name.endswith(".bz2")
) | 4aa5f88ed2412f625d57ba2395d1e2cc932a37a6 | 679,893 |
def format_date(datestring):
"""Convert a long iso date to the day date.
input: 2014-05-01T02:26:28Z
output: 2014-05-01
"""
return datestring[0:10] | 920c37e0d808af3ca79d34b15dc50885933f6bfe | 679,894 |
import torch
def _train_step_ddc(x_batch, y_batch, model):
"""
Single training step for DDC.
Args:
x_batch: Batch of inputs
y_batch: Batch of labels
model: ddc.DynamicDropConnect object
Returns:
Model output, batch loss
"""
# Compute forward pass o... | bd2a6b7ae65f684582b32ce7bb5a4a8944ca58e9 | 679,901 |
def compare_file(file1, file2):
"""
Compare two file, line by line
"""
line1 = True
line2 = True
with open(file1, 'r') as f_1, open(file2, 'r') as f_2:
while line1 and line2:
line1 = f_1.readline()
line2 = f_2.readline()
if line1 != line2:
... | 5bdf12a2a73dba61f52d9d7b01aa674fb50ca47a | 679,903 |
def get_bar_order(plot_params):
"""
Gets which cumulative bars to show at the top of the graph given what level
of detail is being specified
Parameters
----------
plot_params: dict
Dictionary of plotting parameters. Here, `all_pos_contributions`,
`detailed`, `show_score_diffs`, ... | f727568ebf3449219c5651a4680e89cda0c9d7b0 | 679,904 |
def _pad_name(name, pad_num=10, quotes=False):
"""
Pad a string so that they all line up when stacked.
Parameters
----------
name : str
The string to pad.
pad_num : int
The number of total spaces the string should take up.
quotes : bool
If name should be quoted.
... | 19469843abea1c0999dbf2e539ccf0aa60dd232e | 679,914 |
def respond(text):
"""Creates a response in-channel."""
return {
"response_type" : "in_channel",
"text" : text
} | 48ab977d0492245ab4dea05f6b1a4ed801563aeb | 679,920 |
def split(s, sep=None, maxsplit=None):
"""对一个长字符串按特定子字符串进行分割
:param s: 原长字符串
:type s: str
:example s: "a b c d e f"
:param sep: 子字符串,为None时值为 " "
:type sep: str
:example sep: " "
:param maxsplit: 分割次数,为None时代表全部分割
:type maxsplit: int
:example maxsplit: 3
:rtype list
:... | 7184746e0ebb15ea1d235a4fe1067f28466e636d | 679,922 |
def normalize_qa(qa, max_qa=None):
""" Normalize quantitative anisotropy.
Used mostly with GQI rather than GQI2.
Parameters
----------
qa : array, shape (X, Y, Z, N)
where N is the maximum number of peaks stored
max_qa : float,
maximum qa value. Usually found in the CSF (corti... | 1330434a0a630634c5284920fa35c7518bc34937 | 679,923 |
def stop_filter(record):
""" A filter function to stop iteration.
"""
if record["int"] == 789:
raise StopIteration
return record | c0da5e80e77d37ca465f2a1afe4c575a4c223e0c | 679,926 |
def distributeN(comm,N):
"""
Distribute N consecutive things (rows of a matrix , blocks of a 1D array)
as evenly as possible over a given communicator.
Uneven workload (differs by 1 at most) is on the initial ranks.
Parameters
----------
comm: MPI communicator
N: int
Total number ... | 8d62837abc4dfb5122216bcb46b8f04c020129d4 | 679,928 |
import requests
def _get_etag(uri):
"""
Gets the LDP Etag for a resource if it exists
"""
# could put in cache here - but for now just issue a HEAD
result = requests.head(uri)
return result.headers.get('ETag') | 5296a8be8434edd605337a776963473d8c5c0a98 | 679,930 |
def jmp(cur_position, value_change):
"""Jump relatively from cur_position by value_change."""
return cur_position + value_change | a64a19c90dc28f0d28418304f264dce8ad1b40ed | 679,934 |
def correction_factor(rt, lt, icr=None, ocr=None):
"""
Calculate the deadtime correction factor.
Parameters:
-----------
* rt = real time, time the detector was requested to count for
* lt = live time, actual time the detector was active and
processing counts
* icr = true inpu... | 1edc03c9c8bea0ddc23a34a5b5918a6d440df110 | 679,936 |
def normalize_key(key):
"""
Return tuple of (group, key) from key.
"""
if isinstance(key, str):
group, _, key = key.partition(".")
elif isinstance(key, tuple):
group, key = key
else:
raise TypeError(f"invalid key type: {type(key).__class__}")
return group, key or Non... | 9ff1c16bbd79937b32425d2b07188469653b911f | 679,937 |
import random
def random_sign(number):
"""Multiply number on 1 or -1"""
return number*random.choice([-1, 1]) | cc1dc61be0bf7a336ce18784e89b7a2b2f26ca1d | 679,938 |
def compute_all_relationships(scene_struct, eps=0.2):
"""
Computes relationships between all pairs of objects in the scene.
Returns a dictionary mapping string relationship names to lists of lists of
integers, where output[rel][i] gives a list of object indices that have the
relationship rel with object i.... | a51269fe271c6dbdc949f73ba992c9a3bea692d1 | 679,945 |
import colorsys
def hsl_to_rgb(h, s, l):
"""
Converts HSL to RGB.
Parameters
----------
h: :class:`int`
The hue value in the range ``[0, 360]``.
s: :class:`float`
The saturation value in the range ``[0, 1]``.
l: :class:`float`
The lightness value in the range ``[0,... | 16d1d135744bf1b2c158f19a1981f1ee7fabfd97 | 679,948 |
from typing import Dict
def recount_map_sample_to_study(metadata_file: str) -> Dict[str, str]:
"""
Parse the recount3 metadata file and extract the sample to study mappings
Arguments
---------
metadata_file: The path to where the metadata is stored
Returns
-------
sample_to_study: A ... | 500f101c658867328f59587d509819593b9fc32c | 679,951 |
def data_sort(gdf,str):
"""
sort the geodataframe by special string
Parameters
----------
gdf : geodataframe
geodataframe of gnss data
str: sort based on this string
Returns
-------
geodataframe:
geodataframe of gnss data after sorting
"""
gdf = gdf.sort_valu... | 8010c66872ec9c2954659bdcd34bfa313963ffc7 | 679,960 |
def pages(record):
"""
Convert double hyphen page range to single hyphen,
eg. '4703--4705' --> '4703-4705'
:param record: a record
:type record: dict
:return: dict -- the modified record
"""
try:
record['pages'] = record['pages'].replace('--', '-')
except KeyError:
re... | 4eafce92f501c473522e251b57c2a118908348d6 | 679,962 |
def is_response(body):
"""judge if is http response by http status line"""
return body.startswith(b'HTTP/') | c57da1a212642ad28dbba99871fc0d3ead025886 | 679,964 |
import csv
def get_valid_rows(report_data):
"""Fetch all the rows in the report until it hits a blank in first column.
This is needed because sometimes DV360 inserts a weird additional metric at
the end of all the rows. This prevents us from just counting backwards to get
all the rows.
Args:
report_da... | 39647d816c4fc9f8319aca988970d8294d8faa44 | 679,967 |
def format_isk_compact(value):
"""Nicely format an ISK value compactly."""
# Based on humanize.intword().
powers = [10 ** x for x in [3, 6, 9, 12, 15]]
letters = ["k", "m", "b", "t", "q"]
if value < powers[0]:
return "{:,.2f}".format(value)
for ordinal, power in enumerate(powers[1:], 1)... | 55ffb181e1e91b795343f298246efb13061e0827 | 679,968 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.