content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get(client, name: str, namespace: str = "default"):
"""Get a CronJob if it does exist, if it doesn't, return None.
:batch_v1_api: The Batch V1 API object.
:name: The name of the CronJob.
:namespace: The namespace of the CronJob.
:returns: CronJob if it does exist, None if it doesn't exist.
... | 18529aee0afecd27466a0bbfa71799e6534ffdfd | 662,855 |
from typing import List
def octet_list_to_int(octet_list: List[int]) -> int:
"""
Convert octet list to integer.
:param octet_list: Octet list to convert.
:returns: Converted integer.
"""
result = 0
for octet in octet_list:
result <<= 8
result += octet
return result | f6c42461843b66c9cbc0026c1e242a72e1d95ae8 | 662,856 |
def get_host_replica(volume, host_id):
"""
Get the replica of the volume that is running on the test host. Trigger a
failed assertion if it can't be found.
:param volume: The volume to get the replica from.
:param host_id: The ID of the test host.
:return: The replica hosted on the test host.
... | efa06107afd39d81a7cb1e1f41724ba9e5310227 | 662,857 |
def delete_border_detections(chip_detections, chip_w, border_delete_amount):
"""Deletes detections near borders. This is to make merging of several slided inference patches easier.
The function is implemented vectorized and is therefore lightning fast.
Args:
chip_detections (list): List of np.array... | 0d1a7c56c27d4d0c0c57878dbc1ba3645c56d3ec | 662,858 |
import io
import contextlib
import re
def clean_mgs(func, sep='\n\n'):
"""
first captures what's printed by a function and then cleans up special command-line
stuff (ie.
colors)
"""
f = io.StringIO()
with contextlib.redirect_stdout(f):
func()
out = f.getvalue()
ansi_escape... | 71987b2ef850163f914080c7bf0b17d30327f83a | 662,859 |
def mosaic_name(pairs_param):
"""
Generates a filename for the mosaic. Concatenating the pair names would be very long so instead we combine the last
four numbers of the product_id's.
"""
return ''.join(
[
f'{pair["left"][-5:-1]}-{pair["right"][-5:-1]}_'
for pair in p... | c8ec322e0f7069261068e2dbd220822ed227e903 | 662,860 |
import re
def deserialize(stream):
"""
Convert stdout from running binderThroughputTest into a list
of [avg_latency, iters] pair.
"""
result = {}
lines = stream.split("\n")
for l in lines:
if "average" in l:
latencies = re.findall("\d+\.\d+|\d+", l)
result["... | 4abe84254ab7fe1019ddddb8c6753271f4ea5611 | 662,861 |
def add(x, y):
"""
Returns x+y
Parameter x: The first number to add
Precondition: x is an int or float
Parameter y: The second number to add
Precondition: y is an int or float
"""
return x+y | 4d9cdc4ad3e41e74ffecece68b9cccd32440c664 | 662,862 |
def strip_uri_host_and_path(concept_uri):
"""remotes the host and path from a URI, returning only the final resource name
"""
if concept_uri is None:
return None
rightmost_slash_position = concept_uri.rfind('/')
rightmost_colon_position = concept_uri.rfind(':')
simplified_start = max(0, ... | bbbdda1cfeebf462f69dc9e75bcc63b8f5e51899 | 662,863 |
def get_intervals(label, length):
"""
turns label into intervals
with min and max starts aswell as their durations
"""
temp = []
for i, val in enumerate(label):
min_start = sum(label[:i]) + len(label[:i])
duration = label[i]
if len(label) == 1:
max_start = len... | db6070d366161e43690aa2be3da5c88873d0460b | 662,864 |
def extra(request):
""" Add information to the json response """
return {'one': 123} | 599be1cf18bed6b622c9a55aca73b62a7a1cb04e | 662,865 |
def parseDockerAppliance(appliance):
"""
Takes string describing a docker image and returns the parsed
registry, image reference, and tag for that image.
Example: "quay.io/ucsc_cgl/toil:latest"
Should return: "quay.io", "ucsc_cgl/toil", "latest"
If a registry is not defined, the default is: "d... | 73d75fcbe504c2404e24958db1d67b0880abdf4c | 662,866 |
def get_dadvs(words_li,pos_li,j):
"""
获取方位状语
"""
d=''
while pos_li[j]!='p' and words_li[j]!=','and j>0:
d=words_li[j]+d
j-=1
if words_li[j]!=',':
d=words_li[j]+d
return d | 12280e38bd4e6bd938f61dfc95ed5dda47319dfa | 662,867 |
def update_kwargs(kwargs, **params):
"""params override kwargs"""
return dict(kwargs, **params) | cf9d636acf1010cbf17c1c965531d7e11e8f13bf | 662,868 |
from typing import Counter
def getExternalAndInnerIOToDirAndWidth(slot_name_2_io_name_2_dir_and_width):
"""
when we wrap up multiple slots, some slot io become internal connection
other IOs remain to be the IO of the wrapper
"""
# io name -> dir + width (in string)
list_of_io_name_2_dir_width_pair = slot... | 8ebbcdec6cedcaeea465f374375bba6f6d774578 | 662,869 |
def scramble(base, hexa):
"""
Scramble given base and hex
"""
result = bytearray()
for c in hexa:
result.append(base.index(c))
return bytes(result) | 70c720729a742589461716fce634b50938b2fa1d | 662,871 |
def getValidOption():
"""
Prompts a user for an option until a valid open is entered
and then returns
"""
while(1):
try:
option = int(input("Enter an option: "))
except:
print("Please enter an integer")
else:
if option >= 0:
return option
else:
print("Option must be an interger of zero... | 2c3b77c4691b7ce82ee566dd16092ecb6831f437 | 662,873 |
def getFilename(f):
"""Get the filename from an open file handle or filename string."""
if isinstance(f, str):
return f
return f.name | 62a0e4301ee5284bac569134f3cf89edec7762a4 | 662,874 |
import re
def version2tuple(ver: str) -> tuple:
"""Convert version to numeric tuple"""
if re.match(r"\d+\.\d+\.\d+$", ver) is None:
raise ValueError(r"Version must be well formed: \d+\.\d+\.\d+")
return tuple([int(val) for val in ver.split(".")]) | 25af541689728666ba166773b2925890d516d5c1 | 662,875 |
from typing import Tuple
def move_ferry_with(instructions: list) -> Tuple[int, int]:
"""Navigate ferry according to navigation instructions."""
direction = 0
moves = {"N": 0, "S": 0, "E": 0, "W": 0}
for action, value in instructions:
if action == "F":
moves[["E", "N", "W", "S"][dir... | b6c7199594ad40e126238327aa3297bcfb5ae5f2 | 662,876 |
import uuid
from datetime import datetime
import os
def upload_directory_path(instance, filename):
"""
Determine directory path for uploaded files at runtime.
"""
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
today = datetime.now().strftime('%Y-%m-%d')
return os.pa... | 7b095de32bc1a35473565345f128d03089f2cc60 | 662,877 |
import json
def compact_json(r, sort_keys=False):
"""
JSON as small as we can make it, with UTF-8
"""
return json.dumps(r, ensure_ascii=False, separators=(',', ':'),
sort_keys=sort_keys).encode('utf-8') | 7d992d650836bbb07e8e06efd0f05e6d93e74ad3 | 662,878 |
def coordinates(location):
"""Return a (lat, lng) tuple from an OpenCage location result
location: a dict (from opencage.geocoder.OpenCageGeocode.geocode)
"""
geometry = location['geometry']
return geometry['lat'], geometry['lng'] | 201216a53194842aba102fe8e5c1d8609f5b197c | 662,879 |
def m_seq_inx0_sort_in_list(seq, args=False):
"""
对列表中单个列表按第一个元素排序,返回新的列表
:param seq: 列表形成的列表
:param args: 是否倒序 True or False
:return: 排序后的列表
example:
:seq [['20160708', 'gyf'], ['20180505', 'zme'], ['20170101', 'zkp']]
:args True
... | 27521ee6fff748c96f4e1ba00016662d8d6d4808 | 662,880 |
def cubes(l=[1, 2, 3]):
"""
task 0.5.29
implement one line procedure taking list of integers 'l'
output should be a list of numbers whose 'i'th element is the cube of the 'i'th element of 'l'
e.g. input[1, 2, 3] output[1, 8, 27]
def cubes(l=[1, 2, 3]): return [i ** 3 for i in l]
"""
... | a7143f5efd86a4b21e75a7a7fc7f93309840d156 | 662,882 |
import re
def validate_date(date: str) -> dict:
"""
Validate provided date data.
Desired format: YYYY or YYYY-MM (2021 or 2021-12).
"""
# regex patters
rp_year_month = re.compile('^(20[0-9]{2})-((0[1-9])|(1[0-2]))$')
rp_year = re.compile('^(20[0-9]{2})$')
# Match year-month object
... | 86ed53dc1a7a1b7e060fc1acf8762e3f447ff279 | 662,883 |
import requests
def has_reads(biosample):
"""
Query INSDC reads for a <biosample>.
Return True or False.
"""
warehouse = 'https://www.ebi.ac.uk/ena/data/warehouse'
url = ("%s/filereport?accession=%s&result=read_run"
% (warehouse, biosample))
try:
response = requests.get... | d2c891f2227fb6c019b8963b3a6afa1aca8f1f2c | 662,884 |
def has_material(obj, name):
"""check if obj has a material with name"""
return name in obj.data.materials.keys() | 3c8ce0daaacf59b49e486d09266d6bc94f805590 | 662,885 |
def compute_ious(tracks, candidates, backward):
"""
Returns:
ious (dict): Map track.id to list of ious for each candidate detection
in new_candidates.
"""
ious = {}
for track in tracks:
if not candidates[track.id]:
continue
ious[track.id] = [
... | 94795477f86078978ff1295b6b1e44a39d7223fd | 662,886 |
import sys
def get_dependency(dep):
"""
safe function to import a module programmatically
:return: module or None (if not importable)
"""
try:
__import__(dep)
return sys.modules[dep]
except ImportError: # pragma: no cover
return None | 2d3fa1eb99305561471dc99326fd7adb6d971f7b | 662,887 |
from functools import reduce
def fuseDotAl(dotAl):
"""Given input [ (2, "3"), (4, "5"), (2,"6") ],
d will be a dict { 2: {"3","6"}, 4: {"5"} }
and return value { 2: {"3 \n 6"}, 4: {"5"} }
"""
d = dict([(x, {y for (z,y) in dotAl if z==x}) for (x,w) in dotAl]) # sets of y for the same x
... | b93ec0a30dcc69ef5b0561191ba543459e6f7801 | 662,888 |
def outline_az_sub(sub_index, sub, tenant):
"""Return a summary of an Azure subscription for logging purpose.
Arguments:
sub_index (int): Subscription index.
sub (Subscription): Azure subscription model object.
tenant (str): Azure Tenant ID.
Returns:
str: Return a string th... | e947598b16e44d1bd3e86e65c31f5b933d256a11 | 662,889 |
def lowercase_set(sequence):
""" Create a set from sequence, with all entries converted to lower case.
"""
return set((x.lower() for x in sequence)) | 23f55bd4ad1c9ec19b9d360f87a3b310ad619114 | 662,890 |
import requests
def _get_token(ZC, username, password):
"""Gets the client's token using a username and password."""
url = '{}/oauth/token/'.format(ZC.HOME)
data = {'username': username, 'password': password, 'noexpire': True}
r = requests.post(url, json=data)
if r.status_code != 200:
r... | 192c113d6e904f6d7756e28e7a80147b9d20cb54 | 662,891 |
import os
def format_uniform_path(path):
"""format the path to a new path which seperated by os.sep.
"""
path = path.replace("//", os.sep)
path = path.replace("/", os.sep)
path = path.replace("\\", os.sep)
return path | 8a40fa37f27daed09fca47dd7a4b89001c67f6f9 | 662,892 |
def error_general_details(traceback_str: str) -> str:
"""
Error message DM'ed to the user after a general error with the traceback associated
with it.
:param traceback_str: The formatted traceback.
:returns: the formatted message.
"""
return f"Here is some more info on the error I encounte... | 232f61f377c0a9883279a84c52867b63f5777744 | 662,895 |
import csv
def get_genes(path):
"""Returns a list of genes from common results tables. Assumes the genes are in the first column."""
with open(path) as full_gene_list:
full_gene_list = csv.reader(full_gene_list)
gene_list = [row[0] for row in full_gene_list]
del gene_list[0] # Remove ... | 9262fee113decbbf249c0f87febed74fc99077a3 | 662,896 |
import os
def mass_delete(directory,regex,topdown=True):
"""deletes all files matching regex in directory and all its subdirectories"""
deleteList = []
for root, _, files in os.walk(directory, topdown=topdown):
for name in files:
if regex in name:
deleteList.append(name)
os.remove(os.path.join(root, n... | a33918223d43b6363847725842518f9c9ff1c986 | 662,897 |
def _validator(validator):
"""
Validator that is tightly coupled to the implementation
of the classes here.
This expects that the object has a ._tls property which
is of type _DictStack.
"""
name = validator.__name__
doc = validator.__doc__
def fget(self):
return self._tl... | 5b313222217173ab8e95c1bd7b397398f19e7b53 | 662,898 |
def pretty_bytes(b):
"""
Format a value of bytes to something sensible.
"""
if b >= 10 * (1024**3): # 10 GiB
return '%0.0f GiB' % (float(b) / (1024**3))
elif b >= (1024**3): # 1 GiB
return '%0.1f GiB' % (float(b) / (1024**3))
elif b >= 10 * (1024**2): # 10 MiB
return '%0.0f MiB' % (float(b) / (1024**2))
e... | 49dd88e055aa80a7b91e17c53233320ab2011372 | 662,899 |
def path_name_to_name(path_name):
"""
:param path_name:
:return:
"""
return path_name.replace("\\\\", "\\") \
.replace(r"\.", ".", ) \
.replace(r"\$", "$") \
.replace(r"\|", "|") \
.replace(r"\[", "[") \
... | eb04a980c865731bd97f3809869a199cae75ba88 | 662,900 |
from typing import List
def min_last_period(prev_vals: List[float], period: int) -> float:
"""
The minimum mobility estimate observed over the preceding days.
"""
last_n_values = min(len(prev_vals), period)
return min(prev_vals[-last_n_values:]) | c84a479e037dee53dda302fe501c3676c321c19a | 662,901 |
import logging
def mask_sanity_fail(mask, shape, description):
"""
Sanity check on training masks; shape needs to match.
description affects the logging, on failure.
"""
if mask is None:
logging.warn("{} : mask is None".format(description))
return True
if mask.shape != shape:
... | b656a44dfaa87e00b3df0e0b1277f9f4ec59cf94 | 662,902 |
def get_error_score(y_true, y_predicted):
""" Error score calculation for classification.
Checks if the labels correspond and gives a score.
An error score of 1 means that everything is falsly predicted.
An error score of 0 means that everything is correctly predicted.
Inputs:
y... | e8b9c9b8bc7f76c974ac45c636aa7254967e3e26 | 662,903 |
def every(y):
""" Returns all values (sequences) of y """
return y | ff1a0b19890a78ce628bb21f8bf8a65a1f0379ac | 662,904 |
import hashlib
def get_consts(method):
"""
Create hash object and its integer upper bound.
"""
hasher = getattr(hashlib, method)
max_plus_one = 2 ** (hasher().digest_size * 8)
return hasher, max_plus_one | 4b6d3fa9eb73a9efbbd9d32ae82ad73b03b9c98f | 662,905 |
def get_cell_ids(widget, filter_function):
"""
:param qmxgraph.widget.QmxGraph widget: The widget used to display the
graph.
:param str filter_function: A javascript function used to filter the
cells.
:rtype: list[str]
"""
cells_ids = widget.inner_web_view().eval_js('''(function(... | ba8a373dab31aad72d679fb29ba5df4690cb01f0 | 662,906 |
import os
def _GetName(item):
"""Returns name of the C++ variable to use for the binary file data."""
return os.path.basename(item['path']).replace('.', '_').replace('$', '_') | 3a1ab039d3ecaf67532450efd87ab0be66ac78db | 662,907 |
def remove_by_index(l, index):
"""removes element at index position from indexed sequence l and returns the result as new object"""
return l[:index] + l[index + 1:] | 1c55d35d6f37c1180de4eaf1244985734a73a033 | 662,908 |
import warnings
def reduce_function(op_func, input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
"""
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.r... | c5f56fd1c070203c45f5a7f3f463d011b0f357d0 | 662,909 |
import re
def installed_package_name(ctx, pkg_conf):
"""
:param: ctx
:param: pkg_conf such as bootflash:/Image/packages.conf
:return: the installed package name
"""
output = ctx.send('dir ' + pkg_conf)
if not output:
ctx.error("dir {} failed".format(pkg_conf))
return None
... | c6e0bb1ffca05fd477409f0a81ff779b2909f733 | 662,910 |
def resdiv_r2(Vin, Vout, R1):
"""
Calculate the exact value of R1 with R2 given.
"""
return R1 / (Vin/Vout - 1) | 7c83447a58c15b4a096164e45ff1571d8bdf34d6 | 662,911 |
def get_file_changes(commit, prev_commit):
"""
Perform a diff between two commit objects and extract the changed
files from it.
Args:
commit(:class:`~git.objects.commit.Commit`): Commit object for commit
with file changes
prev_commit(:class:`~git.objects.commit.Commit`): Com... | 8094032a2ff7a9759b120fe0d5e4a5d9cbc7e462 | 662,912 |
import csv
def loadPathwayInfoFromFile(filename, csv_separator):
""" loadPathwayInfoFromFile(): Loads pathway information from given filename (with given CSV separator character)
Parameters:
- filename: name of file to load pathway information from (string)
- csv_separator: CSV sep... | 539dd297a80603304f365bdb9a1f0246a93ba5be | 662,913 |
def _is_higher_better(metric: str) -> bool:
"""
Args:
metric:
Returns:
>>> _is_higher_better("AUC")
True
>>> _is_higher_better("auc")
False
"""
higher_better_metrics = {
"Recall",
"Precision",
"F1",
"TotalF1",
"Accuracy",
"AU... | a2f9127aedd4ee5318fe95fc77d486c1573f0a84 | 662,914 |
def is_3des(fnc):
"""
Is function 3-des?
Specific key constrains
:param fnc:
:return:
"""
return fnc.lower() == 'triple-des' | d5d8095a115617f2e1c5e7e396c9b744f26cbf75 | 662,915 |
import os
import json
def find_workflow_dir():
"""Finds the installation path for Alfred workflows"""
alfred_prefs_path = os.path.join(os.path.expanduser('~'), "Library", "Application Support", "Alfred", "prefs.json")
with open(alfred_prefs_path, 'r') as f:
alfred_prefs = json.load(f)
return o... | 6a1eaf305e8d391fd191a205823a5f60b05a6adc | 662,916 |
def prod_client(application, production_gateway):
"""
Prepares application and service for production use and creates new production client
:return Api client for application
"""
version = application.service.proxy.list().configs.latest()['version']
application.service.proxy.list().promote(versi... | 936b6a67d035eea93d85d67a9b8787923f2e8165 | 662,917 |
def quicksort(x):
"""
Describe how you are sorting `x`
input x takes in a list, output is a sorted list, numnber of assignments,
and number of conditionals
choose a pivot point to compare all other values in the list
using the pivot point as the last element in the list
Use this pivot point ... | d7cd2a7b3f628f2ea8a24f6a11b44613bbfcf888 | 662,918 |
import random
import string
def random_string(length=25):
"""Generate a random string."""
return ''.join(random.choice(string.ascii_letters) for i in range(length)) | 912cb70351317c4bb6988123b442885379005aa7 | 662,919 |
def get_package_data():
"""
Returns a list of all files needed for the installation relative to the
'pyexodus' subfolder.
"""
return ["RELEASE-VERSION"] | e3b294c4ea13fd4527993a24cabc5b0bf759da50 | 662,920 |
def find_response_end_token(data):
"""Find token that indicates the response is over."""
for line in data.splitlines(True):
if line.startswith(('OK', 'ACK')) and line.endswith('\n'):
return True
return False | 07b9022803c1da0f9ebef06dc674dd1c05aff79e | 662,921 |
def to_bytes(value):
"""Returns value as bytes"""
if isinstance(value, str):
return bytes(value, "utf-8")
if isinstance(value, bool) or isinstance(value, int):
number = int(value)
return number.to_bytes((number.bit_length() + 7) // 8, "big", signed=False)
return value | 11949cc28593bb3ef05e3f1c9324f8b4dadc20c7 | 662,922 |
def _deploy_func(func, dataframe, *args):
"""Deploys a function for the _map_partitions call.
Args:
dataframe (pandas.DataFrame): The pandas DataFrame for this partition.
Returns:
A futures object representing the return value of the function
provided.
"""
if len(args) == 0... | 58f84edd0aab006ae6ee18e13a3ae9afe06c194d | 662,923 |
def perc95(chromosomes):
"""
Returns the 95th percentile value of the given chromosomes.
"""
values = []
for peaks in chromosomes.values():
for peak in peaks:
values.append(peak[3])
values.sort()
# Get 95% value
return values[int(len(values) * 0.95)] | 670763d1c8823286fea97716a4a8a5a552bfdb5c | 662,924 |
def unscale_features_by_num_nodes(datasets_list, scaled_index_list, nodes_num_list):
"""datasets_list: list of datasets to scale back, e.g., [true_values, predicted_values];
true_values and predicted_values[num_heads][num_samples][num_atoms]
"""
for dataset in datasets_list:
for scaled_index in ... | ac1e7f43d38567b66e7747bbd63cded740c7c67d | 662,925 |
def is_square(arr):
"""
Determines whether an array is square or not.
:param ndarray arr: numpy array
:return: condition
:rtype: bool
"""
shape = arr.shape
if len(shape) == 2 and (shape[0] == shape[1]):
return True
return False | 8a65d3c576bc159e1a0e83a9a1fb1560a6689ce4 | 662,926 |
import hashlib
def string_hash(data: str) -> str:
"""Given a string, return a hash."""
md5 = hashlib.md5()
md5.update(data.encode())
# Note: returning plain integers instead of hex so linters
# don't see words and give spelling errors.
return str(int.from_bytes(md5.digest(), byteorder='big')) | c2c2a432e72d9effe45dee2f41cabdaaf47e6468 | 662,927 |
import os
def get_first_env_var(ev):
"""
Get the name and value of the first set environment variable
:param ev: a list of the environment variable names
:type: list[str] | str
:return: name and the value of the environment variable
:rtype: list
"""
if not isinstance(ev, list):
... | 20d2fd8e31c1f6b7b637a018fffe38079d1aa188 | 662,928 |
import os
def get_sql_scripts():
"""Get all SQL scripts for database creation."""
return (
os.path.join(os.path.dirname(__file__), 'user.sql'),
os.path.join(os.path.dirname(__file__), 'files.sql'),
os.path.join(os.path.dirname(__file__), 'hashtags.sql'),
os.path.join(os.path.di... | 50216ebf4a003da44d312d683bebcfb596b0bd5d | 662,929 |
import asyncio
def event_loop():
"""Create a session scoped event loop.
pytest.asyncio plugin provides a default function scoped event loop
which cannot be used as a dependency to session scoped fixtures.
"""
return asyncio.get_event_loop() | 82048922f6565c66b0df639f6ce443f59e94fb6e | 662,930 |
import os
import re
def find_in(token, deploy, is_file=True):
"""
Find token in deploy directory by walking the directory looking for reg-ex
:param token: token to search for
:param deploy: directory to start with
:param is_file: true if looking for file, otherwise false
:return: full path to ... | bbb8041b98c8349df0b0a63136c345e973999b3b | 662,931 |
import argparse
def _parse_args():
"""Create and parse command line args."""
argparser = argparse.ArgumentParser(
description='Import BitBucket issues into Github.')
argparser.add_argument(
'file', help='JSON file with BitBucket exported data')
argparser.add_argument(
'-t', '-... | fde4ce56de01eb692a4faca41258e5a7b63011b9 | 662,932 |
def _escape_filename(filename):
"""Escapes spaces in the given filename, Unix-style."""
return filename.replace(" ", "\\ ") | 9bb22a7ab928cbe88bfa3c9b48b2b33faa657fc9 | 662,933 |
def _parse_languages(value):
"""
Utility function to parse languages.
>>> _parse_languages(None) is None
True
>>> _parse_languages("en") == frozenset(('en',))
True
>>> _parse_languages('')
''
>>> _parse_languages("en,es") == frozenset(('en', 'es'))
... | a430d37af90c2dd9262ce88db6f0b7b61dd868e3 | 662,934 |
import csv
def read_csv(filename):
"""
Read values from csv filename and returns a list of OrderedDict for each row.
"""
csv_data = []
with open(filename, 'r') as f:
csv_file = csv.DictReader(f)
for row in csv_file:
csv_data.append(row)
return csv_data | ad031209f7d5a6e88dab4636fbf67c2795941b4d | 662,935 |
import os
def get_config_path(config_dir):
"""
Args:
config_dir(str): Path to dir containing model config file
Returns:
Path to config file
"""
config_path = [i for i in os.listdir(config_dir) if i[-4:] == '.ini'][0]
return config_path | 915173993b8f7e0a861f2615fdf951d171ea44a7 | 662,936 |
def ns2mm(time, velocity):
"""Return the distance (mm) from signal travel time (ns) and velocity (m/ns).
Attributes:
time <float>: travel time (ns) of radio signal;
velocity <float>: travel velocity (m/ns) of radio signal.
"""
meters = velocity * time
distance = meters * ... | f5b21cab539bc2489601fe5864615f0c3a1fed7a | 662,937 |
import torch
def mask_to_tight_box_pytorch(mask):
""" Return bbox given mask
@param mask: a [H x W] torch tensor
"""
a = torch.nonzero(mask)
bbox = torch.min(a[:, 1]), torch.min(a[:, 0]), torch.max(a[:, 1]), torch.max(a[:, 0])
return bbox | c1acbce2af16cc0321e6fc5334d780e56c49e704 | 662,938 |
import os
def is_docker():
"""Returns whether or not Journal is being executed in Docker"""
return os.environ.get('JOURNAL_DOCKER', False) | e1368dad0b27d89c49fbfdac6122a5ca11df917b | 662,939 |
def str_to_dpid (s):
"""
Convert a DPID in the canonical string form into a long int.
"""
if s.lower().startswith("0x"):
s = s[2:]
s = s.replace("-", "").split("|", 2)
a = int(s[0], 16)
if a > 0xffFFffFFffFF:
b = a >> 48
a &= 0xffFFffFFffFF
else:
b = 0
if len(s) == 2:
b = int(s[1])... | 8aac064435d55412191344046daa109d5c0a2c53 | 662,940 |
import json
def jsonEncode(input):
"""
JSON encode.
@param (mixed) input
@return (str|None)
"""
try:
return json.dumps(input)
except: pass | 832687b09116d83b38a8a5bb877165f4929c445a | 662,941 |
import requests
import click
def _update_resource(url, token, data):
"""
Update a resource using a PATCH request.
This function is generic and was designed to unify all the PATCH requests to the Backend.
:param url: url to update the resource
:param token: user token
:param data: dict with t... | 95a4f576f2489b01e99aeb8d1f72caa1837db241 | 662,942 |
def extended_euclidean(a, b, test=False):
"""
Extended Euclidean algorithm
Given a, b, solve:
ax + by = gcd(a, b)
Returns x, y, gcd(a, b)
Other form, for a prime b:
ax mod b = gcd(a, b) = 1
>>> extended_euclidean(3, 5, test=True)
3 * 2 + 5 * -1 = 1 True
>>> extended_euclidean(2... | 330284588739d84372307df57040253ce8c1365b | 662,944 |
import subprocess
def check_output(cmd):
"""Convenience implementation of subprocess.check_output."""
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if proc.wait() != 0:
raise Exception('Command failed: %s' % ' '.join(cmd))
return proc.communicate()[0] | 53677ecd08a7241f17b7517999c6c1ed25644872 | 662,945 |
def get_sample_name(sample, delimiter='_', index=0):
"""
Return the sample name
"""
return sample.split(delimiter)[index] | ba29852b1a85a20c882628be557c309b09eb005a | 662,946 |
def parse_fields(pr):
"""
given: https://github.com/<org>/<repo>/pull/<num>
"""
fields = pr.split("/")
org = fields[3]
repo = fields[4]
num = fields[-1]
return (org, repo, num) | 6bacb8cba1b07bf23688c1ddeab3f7b1ea9873c3 | 662,947 |
def right_pad (strg, length, ch=' '):
"""As seen on http://www.halfcooked.com/mt/archives/000640.html"""
return (strg + ch * (length - len(strg))) | fd694f63b768b58850c4be48b0230d7640276d85 | 662,948 |
def negate_condition(condition):
"""Negates condition.
"""
return "not ({0})".format(condition) | 72198a8a6ab86ba4196e4069c8d97a6b23002f57 | 662,950 |
def long_description():
"""
Attempt to read README.rst (which is generated during deploy-time),
otherwise, use README.md.
"""
try:
return open('README.rst').read()
except IOError:
return open('README.md').read() | a95f8915501898508a2105874247c13017e5c107 | 662,951 |
import os
def load_spk2utt(spk2utt_file):
"""load_spk2utt."""
# returns dictionary { spkid: list of uttids }
if not os.path.exists(spk2utt_file):
return None
lines = [line.strip().split() for line in open(spk2utt_file)]
return {x[0]: x[1:] for x in lines} | f056fa58df2c87bbf2e12318561291d7eeb3256e | 662,952 |
def busca_sentinela(list_to_search, value):
"""
Implementacao de um algoritmo de busca sentinela.
Argumentos:
value: Any. Valor a ser buscado na lista
list_to_search: list. lista na qual o valor sera buscado
Retorna o indice do valor em "list_to_search" ou -1 caso nao exista nela.
"""
... | 28dd60b8ec83293927c1bc95c0b426b8983b4961 | 662,953 |
from typing import Callable
from typing import Dict
def add_features(transform: Callable[[Dict], Dict], x: Dict) -> Dict:
"""
Takes the input, passes it to a transformation and merge the original
input with the result of the transformation, can be used to
augment data in the batch.
.. note::
... | ea62fb3fbd1987755d2abebfca6334beef93a560 | 662,954 |
def get_spacy_token_class_config():
"""
Configuration of spacy's Token class attribute
:return: config dictionary of attributes/properties
"""
token_config = {
"PROPERTIES": [
"lefts",
"rights",
"n_lefts",
"subtree",
"children",
... | 07e16a34ef9d39860d6c821a6cc91e8c073c648b | 662,955 |
def create_grid_mapping(ds, wrf_out):
"""Add grid_mapping information from wrf_out to ds.
Also adds coordinate variables and metadata
does not set them
Parameters
----------
ds: netcdf4.Dataset
The dataset that needs the grid_mapping
wrf_out: dict
A dictionary with the grid... | 88d2bf1f9f43d05611bc9e58ee979bf4739dd00c | 662,957 |
def insertGame(gtitle: str, release_date: str="0000-00-00") -> str:
"""Return a query to insert a game into the database."""
return (f"INSERT IGNORE INTO game (title, release_date) "
f"VALUES ('{gtitle}', '{release_date}');"
) | 9ab73633db7f2cda9ec69ab011e6d63d6a086ea0 | 662,958 |
import pathlib
from typing import Tuple
import ast
def find_import_region(file: pathlib.Path) -> Tuple[int, int]:
"""Return the index of the first last import line that precedes any other code.
Note: will not handle try/except imports
file: pathlib.Path path to file to evaluate
Return: Tuple[int, in... | 5b2690d78b6172915c064ff7f0c133dc1c46c56b | 662,959 |
def lat_aggregate(cube, coord_names, lat_bounds, agg_method):
"""Dummy."""
return lat_bounds | db49c784a869da280b2d76a29e872111c1d6b41c | 662,961 |
def all_subclasses(obj):
"""Used to introspect all descendents of a class. Used because metaclasses
are a PITA when doing multiple inheritance"""
sc_recr = []
for sc_obj in obj.__subclasses__():
sc_recr.append(sc_obj)
sc_recr.extend(all_subclasses(sc_obj))
return sc_recr | b8d350e50ff4d68ae0372ece35726266737ef672 | 662,962 |
def greatest_product(array: list):
"""return greatest product of three numbers given positive numbers"""
greatest_product = None
array.sort()
if len(array) >= 3:
greatest_product = array[-1] * array[-2] * array[-3]
print(f'Greatest product of three numbers: {greatest_product}')
else:
print('Not enough eleme... | 7de5bd14fcafe149bc9226d7af3d6ecef842f88c | 662,963 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.