content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
from typing import Dict
from typing import Union
from typing import Any
def extract_outputs(path: List[str], results: Dict) -> Union[Any, List[Any]]:
"""Pull data out of results according to ref.
:param path: The data location.
:param results: The data to pull content from.
:r... | f60e7f7c9db3a3db72acde26837c9236d7d93a72 | 656,234 |
def trainTest(classifier_temp,train_bags,test_bags):
"""
Trains the classifier over train_bags and returns the decision scores of test_bags
Takes a classifier object, list of training bags and list of test bags as input
Returns the list of decision scores
"""
classifier=classifier_temp.__cla... | 0b73f94958b8006540d6e6af6b249943b36efccc | 656,235 |
def construct_bap_id(subscription_id, group_name, lb_name, address_pool_name):
"""Build the future BackEndId based on components name.
"""
return ('/subscriptions/{}'
'/resourceGroups/{}'
'/providers/Microsoft.Network'
'/loadBalancers/{}'
'/backendAddressPools... | 8d23cf5487a8b8f77f126af6d14961636d6855d1 | 656,236 |
import resource
import sys
def get_ru_maxrss():
""" Return max RSS usage (in bytes) """
size = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
if sys.platform != 'darwin':
# on Mac OS X ru_maxrss is in bytes, on Linux it is in KB
size *= 1024
return size | 1a48157d4f6c69b4d547196eecc4968434950215 | 656,237 |
def pt2():
"""Second test point."""
return 120, 45 | 63f69c97b47715a0698a5e2a8c8b13639f8674bd | 656,238 |
def get_channel_block(peer_ex, ord_name, ord_namespace, channel, cmd_suffix):
"""Get channel block from Peer.
Args:
peer_ex (Executor): A Pod Executor representing a Peer.
ord_name (str): Name of the orderer we wish to communicate with.
ord_namespace (str): Namespace where the orderer r... | 22787dada06502413ce3134d4cf78188133780ae | 656,239 |
import sys
import os
import subprocess
def install_package(package, upgrade=False, target=None):
"""
Install a PyPi package with pip in the background.
Returns boolean.
"""
pip_args = [sys.executable, '-m', 'pip', 'install', '--quiet', package]
if upgrade:
pip_args.append('--upgrade'... | c06134820335be6e20ece1017e642dece8a4585f | 656,240 |
import warnings
def future_warning():
"""Using element / syntax that will soon change."""
warnings.simplefilter('error', FutureWarning)
try:
warnings.warn("won't implement", FutureWarning)
except FutureWarning:
return "forget this feature"
finally:
warnings.simplefilter('i... | 60784e75a58432db5a03c97d0ff9e1f2fbde27f9 | 656,241 |
def _check_if_list_of_featuregroups_contains_featuregroup(featuregroups, featuregroup_name, version):
"""
Check if a list of featuregroup contains a featuregroup with a particular name and version
Args:
:featuregroups: the list of featuregroups to search through
:featuregroup_name: the name... | e25d603d7620f814b08bd1300678cade515396cf | 656,242 |
import six
def _skip_dunder(settings):
"""
Skip double underscore keys
"""
return {k: v for k, v in six.iteritems(settings) if not k.startswith('__')} | 1923da15dbbf864f2e0337fb1c74287a8c044247 | 656,243 |
from typing import Iterable
from typing import Tuple
def replace(s: str, src_dst: Iterable[Tuple[str, str]]) -> str:
"""
:param s: string
:param src_dst: [(src1, dst1), (src2, dst2), ...]
:return: string with srcX replaced with dstX
"""
for src, dst in src_dst:
s = s.replace(src, dst)... | 43ba3e4bf2cca55d9d1ac6b0117aea3456b0c3c0 | 656,245 |
import torch
def rm_conditioning(p_yCx):
"""Remove the conditioning of a distributions p(Y|X) -> p(Y) by taking a Monte Carlo Expectation
of all besides current index.
Parameters
----------
q_yCx : torch.Tensor or torch.Distributions
Distribution to uncondition. Each batch should be f... | b30ce006faf0dfb150de49efdaf127149e23b05b | 656,246 |
def _normalize_activity_share_format(share):
"""
Convert the input share format to the internally format expected by FTS3
{"A": 1, "B": 2} => [{"A": 1}, {"B": 2}]
[{"A": 1}, {"B": 2}] => [{"A": 1}, {"B": 2}]
"""
if isinstance(share, list):
return share
new_share = list()
for key,... | b1289054a10554d858e74a311f8ff327beaa9062 | 656,247 |
import random
def shuffle_deck(deck):
"""
Shuffle desk
"""
return random.shuffle(deck) | f4d4357bc7091a52eec219d042dcf0990b58e282 | 656,248 |
import os
def _is_unix_link(link_path):
""" basically a wrapper around path.islink """
return os.path.islink(link_path) | 845a9edddac2ceb0beda114629cb30a36c69cce0 | 656,249 |
import os
def get_working_dir():
"""get working directory"""
#wd= os.environ['PWD']
wd=os.getcwd()
#print(wd)#
return wd | 63bab169312d80808495d6bdf1181ef5ccee7563 | 656,250 |
import random
def simpleSampleBalanced(gl, mcl, cr, fix, sd=0):
"""Builds a map by randomly choosing glomeruli to sample to mitral cells.
If fix != true, cr serves as mean for # of glom sample to each mitral cell.
Weights are randomly chosen uniformly. Limits number of mitral cells that
glom can proj... | 798adc864338da0bd8d78f58eef62f66361f7b28 | 656,251 |
def _num_columns(data):
"""Find the number of columns in a raw data source.
Args:
data: 2D numpy array, 1D record array, or list of lists representing the
contents of the source dataframe.
Returns:
num_columns: number of columns in the data.
"""
if hasattr(data, 'shape'): # True for numpy arr... | 5be48bbc4b7970818c2eac37ad8489b8394af4f9 | 656,252 |
def imshow_args(x):
"""Matplotlib imshow arguments for plotting."""
if len(x.shape) == 2:
return x
if x.shape[2] == 1:
return x[:, :, 0]
elif x.shape[2] == 3:
return x | 22eee06afe8bd725fd78a1c5462bdb23e5f71a23 | 656,253 |
def parse_vars(string):
"""Parse a list of var/values separated by \\n"""
d = {}
for line in string.split('\n'):
if '=' not in line:
continue
name, value = line.strip().split('=')
value = value.strip('"')
d[name] = value
return d | d32d9d15001a2d669bea7014b52a2fd2d5e08c51 | 656,254 |
from typing import List
def parse(data: str, separators: str) -> List[str]:
"""
This function parses string into list of strings based on 'separators'.
It follows hJOPserver`s PanelServer messages format.
"""
output: List[str] = []
item = ''
escaped_level = 0
for c in data:
if... | 9e5afc840933778d0a0ec7a3190692b30fcabb4b | 656,255 |
def keep_specific_neurons(X, neuron_list):
"""
Filter activations so that they only contain specific neurons.
.. warning::
This function is deprecated and will be removed in future versions. Use
``interpretation.ablation.filter_activations_keep_neurons`` instead.
Parameters
-------... | 101e72b988836716385a781425fa450e29dc247c | 656,256 |
def equal(a, b, eps=0.001):
""" Check if a and b are approximately equal with a margin of eps
"""
return a == b or (abs(a - b) <= eps) | f53903dc52ec50957877473b4193f602fe552b9a | 656,257 |
import sys
import json
def target2json(target,out=sys.stdout):
"""Output JSON representing a given target
Parameters:
target - instance of Target
out - where to write the representation (default: stdout)
"""
return json.dump(target.info,out) | d1290475964e427b909a343e5eb2575fe4794a62 | 656,259 |
def center_x(display_width: int, line: str) -> int:
"""
Find the horizontal center position of the given text line
Parameters:
display_width (int) : The character width of the screen/space/display
line (int) : Line of text
Returns:
(int): Horizontal character number
... | 00559aa1f63515856314a5750a159738fd6f59ff | 656,260 |
def Parents(it):
""" Return a generator to the parents of all the nodes in the passed
iterable. Note that we first use a set to remove duplicates among the
parents."""
return iter(set((n.GetParent() for n in it if n.GetParent() != None))) | a0c2d7588e92384913071ea4fb4d09d134f6aa55 | 656,262 |
def df_rename_col(data, col, rename_to, destructive=False):
"""Rename a single column
data : pandas DataFrame
Pandas dataframe with the column to be renamed.
col : str
Column to be renamed
rename_to : str
New name for the column to be renamed
destructive : bool
If ... | da424f4c7202aa397153a3293f8f24a672c783d9 | 656,263 |
def _create_policies_key(config_key):
"""Create policies key from config key
Assumes config_key is well-formed"""
return "{:}:policies/".format(config_key) | c0e799c31af95abea5f7732696c3e334c9687d04 | 656,264 |
def identity(n):
"""
Return the identity matrix of size n
:param n: size of the identity matrix to return
:return: identity matrix represented by a 2 dimensional array of size n*n
"""
return [[1 if i == j else 0 for i in range(n)] for j in range(n)] | 82be8893c42c396c50e94f5d7baeee2454f4b449 | 656,265 |
def create_coco_dict(images, categories, ignore_negative_samples=False):
"""
Creates COCO dict with fields "images", "annotations", "categories".
Arguments
---------
images : List of CocoImage containing a list of CocoAnnotation
categories : List of Dict
COCO categories
... | 21ec7655d7c85a332c04e6f1370be8c9a160a2f5 | 656,266 |
def invert_map(mapping: dict, one_to_one: bool = True) -> dict:
"""Invert a dictionary. If not one_to_one then the inverted
map will contain lists of former keys as values.
"""
if one_to_one:
inv_map = {value: key for key, value in mapping.items()}
else:
inv_map = {}
for key,... | dee2d431882230d79b161d5eb86af56b4ad628a4 | 656,267 |
def reduce_breed_list(test):
"""
Input: cleaned dataset
returns: a data set with the variable "breeds" reduced for cats and dogs.
Removes the "Mix" part of the breed name and stripped white space.
Made choice that Domestic Shorthair is equivalent to Domestic Shorthair Mix when it comes to cats... | 01ad52a046d8333052514ac0bde98f629f29f1a4 | 656,268 |
import os
def is_mach_o_binary(path):
"""Determine if the file at the given path is a Mach-O binary.
:param path: The path to check
:returns: True if the file at the given location is a Mach-O binary.
"""
# A binary is any file that is executable, or has a suffix from a known list
if os.acces... | 58d03e62d070c49db3e84e6f101ceab0c54c4d6e | 656,269 |
import itertools
def broadcast_lists(list_a, list_b):
"""Broadcast two lists.
Similar behavior as ``gs.broadcast_arrays``, but for lists.
"""
n_a = len(list_a)
n_b = len(list_b)
if n_a == n_b:
return list_a, list_b
if n_a == 1:
return itertools.zip_longest(list_a, list_b... | 7938cf533bceb388f72940ccdb52053acc3204f2 | 656,270 |
import os
def get_test_replay_folder():
"""
:return: The folder where downloaded replays are stored for testing.
"""
return os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'test_replays') | 696739d12728d244e3ba01b616b9a33acae757de | 656,271 |
def any_endswith(items, suffix):
"""Return True if any item in list ends with the given suffix """
return any([item.endswith(suffix) for item in items]) | d3ca627bcd2fd0f10dd58a3d06129b5a65b75680 | 656,273 |
def print_plastic_material(self):
"""
"""
output = ("{:1.4E} {:1.4E} {:1.4E} {:1.4E} {:1.4E} {:1.4E}\n"
.format(self.Fy.convert('megapascal').value,
self.Fu.convert('megapascal').value,
self.E.convert('megapascal').value,
sel... | 7bb0b941cbf6c030d87edf0527573c012837fc5f | 656,274 |
def resolve_value(val):
""" if given a callable, call it; otherwise, return it """
if callable(val):
return val()
return val | fa489c128cbbe5aa4e59cb94bb3ab0ef9246962f | 656,276 |
import json
def read_data_from_file(filepath):
"""
This function reads data from the testbed saved into a file
"""
data = []
with open(filepath, "r") as file:
for json_obj in file:
data.append(json.loads(json_obj))
return data | 540a0b28a7316a4d9d9dbdb674cfc9b7aedd1416 | 656,277 |
import random
import string
def generate_random_code(length=8):
"""
generate random characters of length matching input length
:param length:
:return:
"""
return ''.join(random.choice(string.ascii_uppercase + string.digits + string.punctuation) for _ in range(length)) | abc07cde25b5a3b93e1eb28ac878eb655b8c861a | 656,278 |
import subprocess
def validate_octave_file(filename):
""" Determine if an Octave file is valid
Args:
filename (:obj:`str`): path to Octave file
Returns:
:obj:`tuple`:
* nested :obj:`list` of :obj:`str`: nested list of errors
* nested :obj:`list` of :obj:`str`: ne... | 98b285ca858bcabdd132dea96e99b89d48b2ee7d | 656,279 |
def _generate_root_manifest_content(label, input_files):
"""Generates the contents for a root manifest for a manifest bundle.
Args:
label: the BUILD rule that generated the bundle, e.g. //a/b:c
input_files: File objects for all the input files in the bundle.
"""
content = ["// Root manifes... | d08f73aa85fa6a569f26445942cbd700775db2dd | 656,280 |
def to_iso_date(timestamp):
"""Convert a UTC timestamp to an ISO8601 string.
datetime instances can be constructed in alternate timezones. This
function assumes that the given timestamp is in the UTC timezone.
Args:
timestamp(datetime): A datetime object in the UTC timezone.
Returns:
... | b6453dbbddb498debb33137ea953d2b999031e35 | 656,281 |
def part2(input_string):
"""We realize that the last digit in the FFT is always the same, since the
filter will be [0,0,...,1]. For the second last element, the filter looks
like [0,0,...,1,1], all the way until the middle digit in the number.
Hence, we can compute the number backwards if the offset is ... | 0624454011b9353dd67a10f093fe4e3d573d5d78 | 656,282 |
from pathlib import Path
import string
def kernelspec_dir(kernelspec_store: Path, kernel_id: str) -> Path:
"""Return path to the kernelspec directory for a kernel with a given ID
Parameters
----------
kernelspec_store
Path to the place kernelspec store where kernelspec dir should be
p... | 0fb4f40dd6f54d144f314e64873e1f5dca27731b | 656,283 |
def test_iterable(value):
"""Check if it's possible to iterate over an object."""
try:
iter(value)
except TypeError:
return False
return True | fcd42730d0adb9febc8d01f29a65f463b5932407 | 656,284 |
def _write_to(string, path):
"""
Writes a string to a file on the server
"""
return "echo '" + string + "' > " + path | 5f440ca07b4b9a52f65aec6eff7cf97d8fa54829 | 656,286 |
import string
def linguistic_feature_gen(df, col = "text"):
"""
Fucntion to generate linguistic features to be used in classification tasks.
Parameters
----------
df : Pandas DataFrame
Dataframe with the text field to be cleaned
col : str
The name of the text field... | 7053492d116eab1fbee9b0f932c90f831d6b5970 | 656,287 |
def calculate_hate_speech_ratio(df_usa, y_pred):
"""
Calculates avg hate speech per US state.
Parameters
----------
df_usa: Pandas dataframe
US test dataframe
y_pred: Numpy array
Predicted va... | 886799db70156f862e264f27cd37ad5e54f971c5 | 656,291 |
def get_plot_properties_for_trajectory(plot_nums:int,
base_color:str='r') -> tuple:
"""
Get plot properties for trajectory.
Args:
plot_nums (int): The number of plots.
base_color (str): Base color.
Returns:
tuple: (cs, alphas, linewidths, ... | cdec1d5e7b78cd9954976f8728f0d054c8762f77 | 656,292 |
def one_assignement(composite,movies,household_size=2):
""" Assign everything to the same user."""
assignments=[]
for account in composite:
classification=[]
for show in account[1]:
classification.append((show[0],0))
assignments.append((account[0],classification))
ret... | 25450e9ff794a1f2aefb8fa044ddea24bbefb6f8 | 656,293 |
def ho_well(x, k):
"""V (x) = k(exp(a|x|) − 1)"""
return k * x ** 2 / 2.0 | d5bc7455403b49474c695ced62858f9275ab2f0f | 656,294 |
def get_qstar_with_error(inv, extrapolation=None):
"""
Get invariant value with uncertainty
"""
return inv.get_qstar_with_error(extrapolation) | dafddbe2f653661288e5102a9f71bd4f98783023 | 656,296 |
def minCostClimbingStairsB(cost):
"""
:type cost: List[int]
:rtype: int
"""
cost.append(0)
for i in range(2,len(cost)):
cost[i] += min(cost[i-1], cost[i-2])
return cost[-1] | b120996ce940fefbb3c1cddf6d11771f796dd92b | 656,297 |
import argparse
def get_args():
"""Construct an argparser and return parsed arguments."""
parser = argparse.ArgumentParser(description="tool to convert calibration formats")
parser.add_argument(
"-o", "--output", help="output path (default cwd)", default=None
)
parser.add_argument(
... | c07b6649a336111e409e2700e7354a934521abfa | 656,298 |
import os
def _case_ok(directory, check):
"""Check if the directory contains something matching 'check'.
No check is done if the file/directory exists or not.
"""
if 'PYTHONCASEOK' in os.environ:
return True
elif check in os.listdir(directory):
return True
return False | 9e141c3158b6cbc0ef47c0aef504f41b15581021 | 656,299 |
def change_image_mode(img, label, args):
"""
Change image mode (RGB, grayscale, etc.)
"""
img = img.convert(args.get("image_mode"))
label["image_mode"] = args.get("image_mode")
return img, label, args | 5be45e3821954fbd297a0bb298e40028bb4a835c | 656,300 |
def get_all_attached_volumes(self):
"""
Get all the the volumes that are attached to an instance.
:param boto.ec2.instance.Instance self:
Current instance.
:return: List of attached boto.ec2.volume.Volume
:rtype: list
"""
return [v for v in self.connection.get_all_volumes() if v.at... | a7285ec9cb385c75fa93633fef4d66a8fedd8b32 | 656,301 |
def get_common_prefix(z):
"""Get common directory in a zip file if any."""
name_list = z.namelist()
if name_list and all(n.startswith(name_list[0]) for n in name_list[1:]):
return name_list[0]
return None | 0019813499c48802b75f104946dc1170b0cc91be | 656,302 |
def solution(A): # O(N)
"""
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n,
find the one that is missing from the array.
Your algorithm should run in linear runtime complexity.
Could you implement it using only constant ext... | 93b38ce36224803e3d911f55a152df1258d1c7c1 | 656,303 |
from typing import Union
def _c_delay(list_len: int, delay: Union[int, float]):
""" Sets single delay value to whole list.
"""
delays = [delay] * list_len
# sets incrementing offsets to the first 8 elements
inc = .2 # Increment set to .2
offset = len(delays[0:8]) / 5 # offset
# checks i... | 0163300a0e84f4f9ead9016cdfaf77e84af22357 | 656,304 |
def get_prob_from_odds( odds, outcome ):
""" Get the probability of `outcome` given the `odds` """
oddFor = odds[ outcome ]
oddAgn = odds[ 1-outcome ]
return oddFor / (oddFor + oddAgn) | b4507dde8285c357cb17c1b749657a2c634efa63 | 656,305 |
from typing import Any
from typing import List
def check_list_str(data: Any) -> List[str]:
"""Check if data is `List[str]` and return it."""
if not isinstance(data, list):
raise TypeError(data)
for value in data:
if not isinstance(value, str):
raise TypeError(value)
return ... | 955768d0d99ca89b45745d60223d3e59f72b5d46 | 656,306 |
def p2(max):
"""Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find... | 5e3bf97381dba3789b810b86d5226a7364b7a743 | 656,307 |
def broadcast_trt_tensors(network, trt_tensors, broadcast_ndim):
"""Broadcast TensorRT tensors to the specified dimension by pre-padding shape 1 dims"""
broadcasted_trt_tensors = [None] * len(trt_tensors)
for i, t in enumerate(trt_tensors):
if len(t.shape) < broadcast_ndim:
# append 1 ... | 88d5545175908c1e1e0e5cbd05a10f5f19a6bb64 | 656,308 |
def make_loop_index(ss):
"""Returns a list of loop indices to see where new base-pairs can be formed.
"""
loop, stack = [], []
nl, L = 0, 0
for i, char in enumerate(ss):
if char == '(':
nl += 1
L = nl
stack.append(i)
loop.append(L)
if char ... | 6eaf5f108143f1f620370b0bee4e32558f106856 | 656,309 |
from typing import Set
import re
def _replace_stopwords(text: str, words: Set[str], symbol: str = " ") -> str:
"""
Remove words in a set from a string, replacing them with a symbol.
Parameters
----------
text: str
stopwords : Set[str]
Set of stopwords string to remove.
symbol: str... | 76a4526e6f93dc08d05dff17898eb1db7f4a610b | 656,311 |
def frags_overlap_same_chrom(frags, start, end):
"""
get the fragments overlapping the interval [start, end], assuming
all fragments in the input table are already on the correct chromosome
"""
f = frags.loc[((frags["start_pos"] < start) & (frags["end_pos"] > start)) |
((frags["sta... | 978e52070e0f28a2ede6497bc7415ec3a9c01646 | 656,312 |
from typing import Dict
import sys
def split_hashes_by_type(all_hashes: Dict[str, str]) -> Dict[str, Dict[str, str]]:
"""Split hashes by type."""
result = {
"agents": {},
"protocols": {},
"contracts": {},
"connections": {},
"skills": {},
} # type: Dict[str, Dict[st... | 6c12ec6e01379e48eff28015ab8f9a19c1fc4fb6 | 656,313 |
def cp_model(k_min: float, mu_min: float, phi: float, cp=0.4) -> tuple:
"""
Build rock physics models using critical porosity concept.
:param k_min: Bulk modulus of mineral (Gpa)
:param mu_min: Shear modulus of mineral (Gpa)
:param phi: Porosity (fraction)
:param cp: critical porosity, default ... | 1be141d91969a9acf4e55651d5f676e0807665fc | 656,314 |
def get_user_by_email(self):
"""
Construiremos essa fução
"""
return '' | b2b61565cbff31a5ec59e90e225af39e7d8a2548 | 656,315 |
def djfrontend_h5bp_html(lang):
""" Returns HTML tag according to chosen language.
Included in HTML5 Boilerplate.
"""
output=[
'<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="%s"> <![endif]-->' % lang,
'<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="%s"> <![e... | 6d105b10404d92ebbde0272bf363f888ee0e9272 | 656,316 |
import torch
from typing import Tuple
def compute_perceptual_loss(norm_de: torch.Tensor, norm_sr: torch.Tensor, model) -> Tuple[torch.Tensor, torch.Tensor]:
""" Compute perceptual losses """
feat_loss, style_loss = [], []
layer_names = {x.split('.')[0] for x in model.state_dict().keys() if 'conv' in ... | e5788c9cb072f41468878756146d7283da24b454 | 656,317 |
def sum_even_fibonacci_numbers(limit):
"""
Finds the sum of the even-valued terms in the Fibonacci sequence
:param limit:
:return:
"""
a, b = 1, 2
total = 0
while a < limit:
if a % 2 == 0:
total += a
tmp = a
a = b
b = a + tmp
return total | 996de8ff14a2f349047fd7bc763260f6c65da129 | 656,318 |
import re
def validate(seq, alphabet='dna'):
"""
Check that a sequence only contains values from DNA alphabet """
alphabets = {'dna': re.compile('^[acgtn]*$', re.I),
'protein': re.compile('^[acdefghiklmnpqrstvwy]*$', re.I)}
if alphabets[alphabet].search(seq) is not None:
return T... | e3e54c8cbb85b162f62051e8814735ed38ae143a | 656,319 |
def get_items(request, client):
""" Get items using the request with the given parameters
"""
# query results
result = client.quick_search(request)
# get result pages
items_pages = [page.get() for page in result.iter(None)]
# get each single item
return [item ... | f8b15e7d3f63cb4f1e42bfb15850f07d35fc6fe0 | 656,320 |
def split_list(values, split_string=","):
"""
Convert a delimited string to a list.
Arguments
values -- a string to split
split_string -- the token to use for splitting values
"""
return [value.strip() for value in values.split(split_string)] | 8f0aa4676473d35f84a4ef1b6c7428b482f938d0 | 656,322 |
import hashlib
def md5(filename: str) -> str:
"""
Given a filename produce an md5 hash of the contents.
>>> import tempfile, os
>>> f = tempfile.NamedTemporaryFile(delete=False)
>>> f.write(b'Hello Wirld!')
12
>>> f.close()
>>> md5(f.name)
'997c62b6afe9712cad3baffb49cb8c8a'
>>>... | 6a71e03bc64d22281c9daf00100d04ad51993ca7 | 656,323 |
import math
def scale_value(
value: float,
input_lower: float,
input_upper: float,
output_lower: float,
output_upper: float,
exponent: float = 1,
) -> float:
"""Scales a value based on the input range and output range.
For example, to scale a joystick throttle (1 to -1) to 0-1, we woul... | 3592c0072c25a246e80fc9d5807482eb3ee456b3 | 656,324 |
def list_videos(plugin, item_id, category_url, **kwargs):
"""Build videos listing"""
return False
# videos_json = urlquick.get(URL_PLAYLIST % category_playlist).text
# videos_jsonparser = json.loads(videos_json)
# for video_data in videos_jsonparser["videos"]:
# item = Listitem()
# ... | 728a24757ad050fdab235abeaeadfa20a01d4166 | 656,325 |
def user_select_csys(client, file_=None, max_=None):
"""Prompt the user to select one or more coordinate systems.
and return their selections.
Args:
client (obj):
creopyson Client.
`file_` (str, optional):
File name.
Defaults is the currently active mode... | 2cacfb6c51d74b78d7da6b4d04b450375bc2457a | 656,326 |
def copy_image_info(reference, target):
"""
Copy origin, direction, and spacing from one antsImage to another
ANTsR function: `antsCopyImageInfo`
Arguments
---------
reference : ANTsImage
Image to get values from.
target : ANTsImAGE
Image to copy values to
Returns
... | 113b49fe9a1b88baf7b571a275278d802a45cf20 | 656,327 |
def get_task_segments(workflow):
"""
Returns a dict that has the corresponding segment for each task.
Segments are zero-based numbered
:param workflow:
:return:
"""
visited = dict()
segment = dict()
def get_segment(task):
"""
Calculates recursively the depth of the w... | 4c39d8d53931139693799133e7ca59b0decf03ec | 656,328 |
def get_join_parameters(join_kwargs):
"""
Convenience function to determine the columns to join the right and
left DataFrames on, as well as any suffixes for the columns.
"""
by = join_kwargs.get("by", None)
suffixes = join_kwargs.get("suffixes", ("_x", "_y"))
if isinstance(by, tuple):
... | 5410593f84ff3b43dcc169e9c7bd81839164c728 | 656,329 |
def function_sync(from_fun, to_fun):
"""
Copy name and documentation from one function to another.
This function accepts two functional arguments, ``from_fun`` and ``to_fun``,
and copies the function name and documentation string from the first to the
second, returning the second. This is useful wh... | b70a5b264d6028a8389ca5f952e31213cc6917f8 | 656,330 |
def process_titl_list(titl_list, atoms_list):
"""Process the titl_list"""
out_list = []
for titl, atom in zip(titl_list, atoms_list):
out_list.append('\t'.join([
titl.label,
str(titl.natoms),
atom.get_chemical_formula(mode='hill', empirical=True),
titl... | c97c23b0a8a9444fcd0feee04bc2b640b7257bbe | 656,331 |
def some_function():
"""
A function doing nothing.
"""
return "nothing" | 76b2a6c27c657793bf5a90581df9c672093b7fc7 | 656,332 |
def daily_profit(daily_mined: float, xmr_price: float, kwh: float, kwh_cost: float, pool_fee: float, precision: int) -> float:
"""
Computes how much money you gain after paying the daily mining expense. Formula:
(daily_income - daily_electricity_cost) * (100% - pool_fee)
:param daily_mined: Float. Amou... | 6f4cbc1ff857948e3a53ea3899d424f5cc45dee1 | 656,333 |
def correct_coordinates(ds, verbose=False):
"""converts wrongly assigned data_vars to coordinates"""
ds = ds.copy()
for co in ['x', 'y', 'lon', 'lat', 'lev',
"bnds", "lev_bounds", "lon_bounds", "lat_bounds", "time_bounds",
'vertices_latitude', 'vertices_longitude',
... | 9bb67192eeacf0772d38489f37b9549ede3f397b | 656,335 |
import collections
import functools
def iterdict(dicts):
""" Converts a tuple/list of dicts to a dict of lists """
return collections.OrderedDict(
{key: [_dict[key] for _dict in dicts if key in _dict]
for key in functools.reduce(set.union, [set(_dict.keys())
... | d08c8836e8004d8e94d8e1d115833143072860b3 | 656,336 |
def topK(predict, k):
"""
为用户推荐前K个商品
"""
top_recommend = []
len_predict = len(predict)
if k >= len_predict:
top_recommend = predict
else:
top_recommend = predict[ : k]
return top_recommend | 52294e83ccb6d4f06afc5d164135d19b6b8f02b1 | 656,337 |
def postorder_traversal(root):
"""
in order traversal
input: root node of a binary tree
output: array of values
"""
results = []
stack = [root]
while stack:
node = stack.pop()
results.append(node.value)
if node.left:
stack.append(node.left)
if... | 44884427a44f12d4e1dbf700ec632ae30186eab2 | 656,338 |
def Re(F_mass, z_way, d_inner, n_pipe, mu_mix):
"""
Calculates the Reynold criterion.
Parameters
----------
F_mass : float
The mass flow rate of feed [kg/s]
z_way : float
The number of ways in heat exchanger [dimensionless]
d_inner : float
The diametr of inner pipe, [... | 82e0128877c45dce27c7124f0fd4ac51cf3da99c | 656,339 |
import re
def snake(string):
"""Convert string to snake case
Implementation must be consistent with tf.Module's camel_to_snake in
github.com/tensorflow/tensorflow/blob/master/tensorflow/python/module/module.py
"""
return re.sub(r"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))", r"_\1", string).lower() | 1d434ddd1bdaff54b8a418e830d9110028e1985b | 656,340 |
def log_metrics(metrics, time, task_id, acc_db, loss_db):
"""
Log accuracy and loss at different times of training
"""
print('epoch {}, task:{}, metrics: {}'.format(time, task_id, metrics))
# log to db
acc = metrics['accuracy']
loss = metrics['loss']
loss_db[task_id][time-1] = loss
acc_db[task_id][time-1] = ac... | 968444fa87b435391c0aba6d47e45486fa963f50 | 656,341 |
def search_item(tag): # catching the item of the searched word
"""
assure that the web scraping returns the item
"""
try:
if ' '.join(tag['class'])=='hom': # or tag.div == None
try:
if ' '.join(tag.div['class'])=='sense':
return True
... | 5eefb7c3fd8fbe36d6942395bebd9c6b580eb99b | 656,342 |
import binascii
def fingerprint(key):
"""Returns fingerprint of a given key
:param key
"""
# noinspection PyBroadException
try:
converted = binascii.hexlify(key.get_fingerprint())
except Exception:
return 'Failed to return fingerprint'
else:
return converted | b98b52a4861404ef530b50a5a64ccb4c130f0292 | 656,343 |
import base64
def str64uToBytes(str64u):
"""
Convert and return unicode base64 url-file safe string to bytes version
"""
return base64.urlsafe_b64decode(str64u.encode("utf-8")) | f94e366ae6a27ec9ea57b4bcb7c836632fac2807 | 656,344 |
import functools
def list_generalizer(f):
"""
A decorator that makes a function work for either a single object or a list of objects by calling the function on
each element
Parameters
----------
:param f: the function to decorate, of the form f(data, *args, **kwargs).
Returns
-------... | 8b4e5cf8371a3ee1b8d02a1066e269941874c632 | 656,345 |
import json
def get_target_names(json_label_decode):
"""Get encode of label
Args:
json_label_decode (string): path to json file
Returns:
[dict] encode of label
"""
if json_label_decode:
with open(json_label_decode) as f:
label_decode = json.load(f)
t... | 556dc3837fea9271b886ebcf02d6c6323061405c | 656,346 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.