content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
from typing import Set
def find_circle_num(M: List[List[int]]) -> int:
"""
:param M:
:return:
>>> find_circle_num([[1,1,0], [1,1,0], [0,0,1]])
2
>>> find_circle_num([[1,0,0,1],[0,1,1,0],[0,1,1,1],[1,0,1,1]])
1
"""
def dfs(row: int) -> None:
marked.a... | 8fe2becb033d2f3215419eb714c7daf5ae48a6bb | 625,791 |
import glob
def get_num_files(start_year, end_year, perf_dir):
"""
Get number of files to read given start_year
end_year and path to performance files
"""
count = 0
for year in range(start_year, end_year + 1):
count += len(glob.glob(perf_dir + f"/*{year}*"))
return count | c5948bf84ce3ce0a5061af8dbe2cfcd0c7f85f79 | 625,792 |
def _CountChar(line, opening_char, closing_char):
"""Count (number of opening_char) - (number of closing_char) in |line|.
Used to check for the end of JSON parameters. Ignores characters inside of
non-escaped quotes.
Args:
line: line to count characters in
opening_char: "+1" character, { or [
clos... | 43ca7a0d91e4fbed2af769840e228c910a659780 | 625,793 |
def write_user_config():
"""Creates a callable that writes a mock .nbreport.yaml file into the
current working directory. Used as a pytest fixture.
"""
def _write_user_config(path='.nbreport.yaml'):
data = (
'github:\n'
' username: testuser\n'
' token: mytok... | 08fe7ba60a4ad8deb343222b4ac8ad625a8a5922 | 625,794 |
def extractSpikesInWindow(window, samples, spikes, sampleRate=20000):
"""
Inputs:
window = sequence, len 2; start and stop of window in s
samples = sequence; list of samples at which spikes are detected for each sweep
spikes = sequence; list of spike IDs corresponding to samples in goodsamples_sweep... | a516a9b83eeafe0db092f52aa5f9be5551cfafb1 | 625,795 |
import os
def get_api_url():
"""Get current API URL from environment"""
return os.getenv("DYM_API_URL", "https://api.dymaxionlabs.com") | 3b9e69be22afceccd1f612e58a8b9a6ec0577c6d | 625,796 |
from typing import List
import re
def find_indexes(haystack: List[str], regex: str) -> List[int]:
"""
Find indexes in a list where a regular expression matches.
Parameters
----------
haystack
List of strings.
regex
Regular expression to match.
Returns
-------
... | b80924cb6955abb54968e793d2604b84c581f18c | 625,797 |
def optimize(gan, ddgan):
"""
Create optimizer
Args:
gan (GAN): The GAN to optimize
ddgan (Module): The ddgan module
Returns:
Optimizer: The optimizer
"""
kwargs_opt = {
"start_from": 0,
"nPOD": 10,
"nLatent": 100,
"npredictions": 2,
... | b19508e0115a05efdf883cbdfa083d9291f2aede | 625,798 |
import os
def override_environment(**kwargs):
"""Returns a copy of the current environment, with variables overridden
as specified in the arguments. Each key represents a variable name
and each value must be a string (to set the specified key to that
value) or None (to unset the specified key).
""... | bcffe7e2668675044109b502ac6907421722da78 | 625,799 |
def _batch_updates(updates):
"""Takes a list of updates of form [(token, row)] and sets the token to
None for all rows where the next row has the same token. This is used to
implement batching.
For example:
[(1, _), (1, _), (2, _), (3, _), (3, _)]
becomes:
[(None, _), (1, _), (2,... | b25af9f6748fb0dfc96c9d28989db27d5f23b176 | 625,800 |
def fixed2Float(value):
"""The fixed2Float method translates a fixed 1/64 pixel-unit value to
float."""
return float(value) / 64 | 4f9cda083aa4dc3ce1c1a67178d4aaaab44be93e | 625,801 |
def vectorize_edge(edge, lemma_index, pos_index, dep_index, dir_index):
"""
Return a vector representation of the edge: concatenate lemma/pos/dep and add direction symbols
:param edge: the string representation of an edge
:param lemma_index: index to lemma dictionary
:param pos_index: index to POS d... | b32abd589c66844969cc9dde5323b488b1742ff2 | 625,802 |
def update(ntuple, **kwargs):
"""Update named tuple."""
return dict(ntuple._asdict(), **kwargs) | 2d5dd7995ec668a9b2f425b20c6113584caa0cee | 625,803 |
import torch
def get_best_non_unk_predictions(logits: torch.Tensor, unk_id):
"""
For every sample, returns the prediction with the highest score. If this is the <unk> token, then the prediction
with the second highest score will be returned instead
:param logits: batch_size x num_predict x num_subtoke... | f5736c0b5f8f792f0fa2be0e49dbcb0bd1c36c09 | 625,804 |
def phi2 (n, p=2):
""" Euler phi function. Second version.
We use the fact that phi has a formula in terms of the prime
decomposition of n. We assume n is a positive integer. The
default initial value for prime p is 2. Thus calls such as
phi2 (52961) will succeed, though given n is odd we could... | 8f26d5d8831cc889261303e38f8512a2acdd2a54 | 625,805 |
from pathlib import Path
from typing import Optional
def normalize_path(path: Path, root: Path) -> Optional[str]:
"""Normalize `path`. May return `None` if `path` was ignored."""
try:
abspath = path if path.is_absolute() else Path.cwd() / path
normalized_path = abspath.resolve().relative_to(ro... | 49c34ba52312cdd399c2f3cc34b48c95f360ffb1 | 625,806 |
def tf(words) -> float:
"""Boolean term frequency, weighted over the document's word count."""
return 1/len(words) | 24a64f4af3e8af1a88075c3e0ce7c97761cb4510 | 625,807 |
from typing import List
def knapsack_no_value(target: int, objects: List[int], cur: int) -> bool:
"""
we should assume objects are in heavy to light order
:param target: the target weight, or the capacity of the knapsack
:param objects: all available weights for items
:param cur: current index in... | a619ed6d3f7b6637a5a1f2e1feb918bc7eb0c2b9 | 625,808 |
def nested_getattr(obj, attr):
"""getattr implementation supporting nested attributes."""
attributes = attr.split('.')
for i in attributes:
if obj is None:
break
try:
obj = getattr(obj, i)
except AttributeError:
raise
return obj | 76c7afe5e17f9808856554d5b44b90428aa5831d | 625,809 |
def _bind_awaitable(function):
"""
Composes a container a regular ``async`` function.
This function should return plain, non-container value.
In other words, it modifies the function's
signature from: ``a -> Awaitable[b]``
to: ``Container[a] -> Container[b]``
.. code:: python
>>>... | c1c5c522a68244bbd9134fcf2a2bb7f675e3b21e | 625,810 |
import logging
import subprocess
def check_call(commandline, *aargs, **dargs):
"""Wrapper around subprocess.check_call that logs the command."""
logging.info(" ".join(commandline))
return subprocess.check_call(commandline, *aargs, **dargs) | 70c98a128848ab20ea3663456ab8b481f1da0d2c | 625,811 |
def f(x, y=lambda x: x + 1, z=lambda y: y ** 2):
"""test function"""
return x, y, z | f05b0f52ceffa38b1b823d2bad201bc58930fcd5 | 625,812 |
def ndependents(dependencies, dependents):
""" Number of total data elements that depend on key
For each key we return the number of data that can only be run after this
key is run. The root nodes have value 1 while deep child nodes will have
larger values.
Examples
--------
>>> dsk = {'... | 5d45d83b26cfe079f5f8181d56333e66ed179f9a | 625,813 |
def fix_space_issue(encodings, tokenizer):
"""
Fix space issue by XLM-R tokenizer which will tokenize some punc/word
to two tokens with the same offset_mapping: (0, 1)
"""
input_ids = encodings.input_ids
offset_mappings = encodings.offset_mapping
num_sents = len(input_ids)
for i in ran... | e03c52f6a22edc91ebd9e8cece934b5d3e2cc914 | 625,814 |
import os
def get_root_dir(rootdir=None, verbose=True):
"""get a rootdir (a default one, or validate the one given etc.)"""
if rootdir is not None:
return rootdir
else:
rootdir = os.path.join(os.path.expanduser('~'), 'tmp', 'qchack')
if not rootdir.startswith(os.path.sep):
... | 5914153751a8159ef05fc4b37f774e8c382fd41a | 625,816 |
def unique_values_from_query(query_result):
"""Simplify Athena query results into a set of values.
Useful for listing tables, partitions, databases, enable_metrics
Args:
query_result (dict): The result of run_athena_query
Returns:
set: Unique values from the query result
"""
r... | 31dd32fdf548976694d50c8466c11c3a42f7b9cc | 625,817 |
import argparse
def get_args():
"""Parses command line arguments"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-c', '--config',
help='Python path to DAG config. config dict expected to be named DAG_CONFIG.',
default='sentiment_classifier.config.default_config'
)
... | ad6715727e21c902368b78e7824bd2b273536c65 | 625,818 |
def get_host_uptime(): # pragma: no cover
"""Returns host uptime in minutes."""
with open('/proc/uptime') as f:
uptime = float(f.readline().split()[0])
return uptime / 60 | 90c508b9bbb2346af52e7b264627059dbba4a7b5 | 625,819 |
def create_dockerfile(ctx):
"""
Creates a Dockerfile for this project.
"""
return ctx.obj['docker'].create_dockerfile(
project=ctx.obj['project_name']
) | 4530978e708bf727fd9c8e904972cf55da4aef18 | 625,820 |
def level(resp):
"""
Args:
resp:
level:
string
Returns:
[level 1: 배송준비중, 2: 집화완료, 3: 배송중, 4: 지점 도착, 5: 배송출발, 6:배송 완료]
"""
if resp['level'] == 1:
return {
"code": 1,
"level": "배송 준비중"
}
elif resp['level'] == 2:
return {
"code": 2,
"level": "집화 완료"
}
elif resp['level'] == 3:
retur... | 4f7fa846419e6e6976bea7b22b59c7fa9ede2b69 | 625,821 |
def find_name_from_len(lmin, lens):
"""
reverse lookup, get name from dict
>>> lens = {'chr1': 4, 'chr2': 5, 'chr3': 4}
>>> find_name_from_len(5, lens)
'chr2'
"""
for fname, l in lens.iteritems():
if l == lmin:
return fname
raise Exception('name not found') | 6e4dc740442243fea1ebd3c09645a7972b200db9 | 625,822 |
def bits_to_byte(bits):
""" Return int represented by bits, padded on right.
@param str bits: a string representation of some bits
@rtype: int
>>> bits_to_byte("00000101")
5
>>> bits_to_byte("101") == 0b10100000
True
"""
return sum([int(bits[pos]) << (7 - pos)
for p... | 1453e4fff3fc19b7a024424feb5486af83a0282b | 625,823 |
def play_media(lc):
""" From play media block """
if lc.gplay is None:
return False
if lc.gplay.player is not None:
lc.gplay.player.play() | ddb8db106d6386c05234d26b97579b7d15562a1d | 625,824 |
from typing import Dict
import collections
def count_char_ngrams(s: str, n: int, pad_char: str = "$") -> Dict[str, int]:
"""Count all character n-grams in s.
Args:
s: String to analyze
n: The desired length of the n-grams. E.g. `3` to get 3-grams like `"abc"`, `"def"`
pad_char: Paddin... | f3d0fb83f874f922ac09ea1b91acac020cfecd42 | 625,825 |
def is_fallback(x, y):
"""Fallback to x is y."""
return x is y | 3968358aaa1720e405d5b762dd4f34ab0e626ad4 | 625,827 |
def remove_background(df):
"""
Helper function removing background flows from a given dataframe
:param df: the dataframe
:return: the no-background dataframe
"""
df = df[df['label'] != 'Background']
return df | 7c5bc8ed5a4e68daf0fe4f402890ae0add9b3b20 | 625,828 |
def optimal_tilt(lat):
"""
Returns an optimal tilt angle for the given ``lat``, assuming that
the panel is facing towards the equator, using a simple method from [1].
This method only works for latitudes between 0 and 50. For higher
latitudes, a static 40 degree angle is returned.
These result... | 4c06ad391a4f71d56a952f28fcf28f94f657d9b3 | 625,829 |
def for_language(cell, languages=set()):
"""Check if a given paragraph is in an expected language"""
return cell.get("_lang") in languages | c79c61f85cef9b127994fc950cfc4c8e817f937f | 625,830 |
import torch
def setDevice(cuda = True):
"""
:param cuda: True if gpu usage is
:return torch device (cpu or cuda)
"""
device = torch.device("cuda" if (torch.cuda.is_available() and cuda) else "cpu")
torch.set_default_tensor_type("torch.FloatTensor")
if device.type == "cuda":
torch... | e081e9e5a14be47056c1304d4cbb33b3a11d9925 | 625,831 |
def boltHeadFinder(head):
"""
"""
_head = str(head).lower()
_head = _head.replace('bolt','')
_head = _head.replace('screw','')
_head = _head.replace('head','')
_head = _head.replace(' ','')
_head = _head.replace('_','')
_head = _head.replace('-','')
_head = _head.strip()
... | 4ede17143142adc090bcbc13b1ffdbfd6350d7e0 | 625,832 |
def to_binary(x):
"""Convert a binary field to 1's and 0's"""
if x == None:
return 0
else:
return 1 | 6f4c2db1da768c704f9ad8d150ce264dbfe48127 | 625,833 |
def gamma_poisson():
"""
Return Stan model code for a Gamma-Poisson Bayesian model. The model takes
as inputs two sequences of count variables, with each entry representing the
total number of target events that occur over a standardized time interval.
Must provide hyperparameters `alpha_` and `beta... | 590af2721385487b2eef00c6d6e98409c7f57625 | 625,835 |
from typing import Sequence
def bernstein3_d1(t: float) -> Sequence[float]:
""" First derivative of Bernstein polynom of 3rd degree. """
t2 = t * t
a = -3.0 * (1.0 - t) ** 2
b = 3.0 * (1.0 - 4.0 * t + 3.0 * t2)
c = 3.0 * t * (2.0 - 3.0 * t)
d = 3.0 * t2
return a, b, c, d | ce6c707d5d8c46c1d3f3c2833a042ef1f39834df | 625,836 |
def combinePeople(nestedlist1, nestedlist2):
"""Combines all people (dictionaries) from two lists, merging data along the way
For example, if a person is found once in both given lists, the cards they own and need will be combined into one person object and included in the result
:param List[List[Dict[str,... | 95a6c4637fc67eeef47f653bba8bb0e48ae1ee2a | 625,837 |
def flatten_tree(root):
""" get a flattened tree of the "paths" of all children of a tree of objects.
used in sidenav
"""
ret = []
if root["path"]: ret.append(root["path"])
for child in root["children"]:
ret = ret + flatten_tree(child)
return ret | bbf4d38343c2c62fbcbe26650094ef9cc54d9bc8 | 625,838 |
from typing import List
import re
def parse_tag_list(message: str, tag: str, allowed_chars: str) -> List[str]:
"""Parses a comma separated list following a tag.
Example:
The function call
parse_tag_list('abc IMPORTS=foo,bar abc', 'IMPORTS', 'a-z')
returns ['foo', 'bar'].
Args... | c8e846e751b783b09bb93b7984906cdaceb0e207 | 625,839 |
def upload_dup_file(rest_obj, module):
"""Upload DUP file to OME and get a file token."""
upload_uri = "UpdateService/Actions/UpdateService.UploadFile"
headers = {"Content-Type": "application/octet-stream",
"Accept": "application/octet-stream"}
upload_success, token = False, None
dup_... | d0c8c8c51fd99e689c1069591078a0f79ead0db8 | 625,840 |
def rename_uuid_columns(data):
"""Renames any columns called or containing `uuid`, to the convention of `id`.
Args:
data (:obj:`pandas.Dataframe`): dataframe with column names to amend
Returns:
(:obj:`pandas.Dataframe`): the original dataframe with amended column names
"""
renames ... | 71f2b17990ea3801e5406fb47fcc47dad42df5b8 | 625,841 |
import re
def getCpuInfo(field):
"""Read a given field from /proc/cpuinfo
Returns the first line which has the relevant fieldname
Opens and reads the file once for each enquiry, but this is mostly for
headers and so on, so it's probably not worth worrying about!
"""
# Unfortunately /proc/cpuin... | 03877a6217a2c72359ad8b9a7d6d3b4f87d3c1aa | 625,842 |
def _remove_none(**kwargs):
"""Drop optional (None) arguments."""
return {k: v for k, v in kwargs.items() if v is not None} | 586bdb799632f2ca860a1a908ae6cb2148d56c42 | 625,843 |
import random
def get_random_yes_no_question():
"""Return exit question for YES/NO answering."""
# type: () -> str
questions = [
"Would you like to get another Song Match with a different artist?",
"Can I help you get a Song Match for a different artist?",
"Do you want to try it fo... | 8ee6427604674e5cd81249fd94b20f741cc26bc9 | 625,844 |
def get_straights(edge):
""" Get vectors representing straight edges """
return [v for v in edge if v[0] == 0 or v[1] == 0] | a5e22561eb1cad7b6f5e7cc5bc72bb6cf68c228a | 625,846 |
import hashlib
def get_hash(params_dict):
"""
Get a unique has for the given dictionary
params_dict
a python dictionary
TO DO:
Add sort for hash
"""
txt = str(params_dict).encode()
return hashlib.sha1(txt).hexdigest() | df06d6c57623c548a91f593a4e991922de2acbe4 | 625,847 |
import os
def get_project_dir(dir_arg):
"""Define project directory."""
if dir_arg is None:
return os.path.abspath(os.getcwd())
os.mkdir(dir_arg) if not os.path.isdir(dir_arg) else None
return os.path.abspath(dir_arg) | b3ad7ccd320f907c0546e3b99d2f73eec945c577 | 625,848 |
import re
def get_list_of_object(seq, is_sort=True):
""" return a sorted list of all data object in the seq (but why sort?) """
# regexp to match all type of objects exist in sequence
regex = re.compile(r'obj\b(?:(?!endobj).)*\bendobj', flags=re.DOTALL)
# match is now a list contains all object in a s... | 5dd60350856e7e3d43faa492c70115927353ee48 | 625,849 |
def clean_img_attributes(page):
"""
Remove image alt and data-mathml attributes because they confuse html2text.
"""
imgs = page.find_all('img')
for img in imgs:
img['alt'] = ''
img['data-mathml'] = ''
return page | 07db938a3a525ee73c66ff2ed1925a5edb72c24d | 625,850 |
import time
def compute_timeout_value( timeout, timeout_date ):
"""
Computes and returns a timeout in seconds. The timeout is adjusted to be
a minimum of 0.01 seconds.
"""
assert timeout != None or timeout_date != None
if timeout != None:
rtn = float(timeout)
if timeout_date ... | 7d4bc44cbbf40d5c0fb6ab78e391c64501843e16 | 625,851 |
def filter(trajectory_list, filter_str):
"""
Evaluate filter_str on all elements (traj) of the trajectory_list and returned the filtered list.
Return a deepcopy of the elements. Change to a reference instead of copy for performance optimisation.
It is better to use list comprehension directly ex. : filt... | d3f6351a59c19914488ad411c43fd2e01d456137 | 625,852 |
import math
def cal_line_length(point1, point2):
"""Calculate the length of line.
Args:
point1 (List): [x,y]
point2 (List): [x,y]
Returns:
length (float)
"""
return math.sqrt(
math.pow(point1[0] - point2[0], 2) +
math.pow(point1[1] - point2[1], 2)) | c1f86763523da7eb7e713319cba6429268021471 | 625,853 |
import textwrap
def reindent(text, indentation):
"""Return reindented text that matches indentation."""
if '\t' not in indentation:
text = text.expandtabs()
text = textwrap.dedent(text)
return '\n'.join(
[(indentation + line).rstrip()
for line in text.splitlines()]).rstrip()... | 429ae2b9b5081d2cd6b9c61637ebb912e44cf4bb | 625,854 |
from datetime import datetime
def as_date(value):
"""Converte uma sequência string para um objeto :class:`datetime.date`. Os
espaços em branco das bordas da sequência serão removidos antes da
conversão.
:param str value: String contendo uma data ANSI (``yyyymmdd``)
:rtype: datetime.date
"""
... | 0357c69a1a8cfcf33bab57755f4d7a31bf99b3f7 | 625,855 |
import yaml
def load_yaml_config(yaml_path):
"""Helper function to load a yaml config file"""
with open(yaml_path, "r") as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
raise ValueError("Yaml error - check yaml file") | b0d92536613b2ae31a9f23e64070f0baabb2205a | 625,856 |
def extended_euclidean_algorithm(a: int, b: int) -> tuple[int, int]:
"""
Extended Euclidean Algorithm.
Finds 2 numbers a and b such that it satisfies
the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity)
>>> extended_euclidean_algorithm(1, 24)
(1, 0)
>>> extended_euclidean_algorithm(... | 616c2ef7277f03c0ca8b6213e7870958731e9fb3 | 625,857 |
import json
def load_from_json(file_path):
"""
Loading data from a json file.
Input:
file_path: (the source file)
Output:
data: the loaded data
"""
# catching possible pathlib.Path object
if isinstance(file_path, str) is False:
file_path = str(file_path)
# c... | 1265b060633b3422df31deb477835eb8bcf3b3fd | 625,858 |
from datetime import datetime
def ip_str_2(sci):
"""String interpolation using format_map() & vars() | Also see format()."""
data = '%s is %d years old' % (sci.name, (datetime.now().year - sci.born))
return data | 2d8f91c9bedc09d8949b78262a4009e0d44ac295 | 625,859 |
def get_mean_value(predicted_values):
"""
Method for calculate mean prediction value by all predicted value
:param predicted_values: all predicted values
:type predicted_values: list
:return: mean prediction value
:rtype: float
"""
if len(predicted_values) == 0:
return None
... | 76471d0f8212cda6676fd06eaad03bc529dc7f75 | 625,860 |
import random
import math
def check_gcd():
"""
Generates two random integers and finds the greatest
common divisor of generated integers.
:return: gcd and integers
"""
number_1 = random.randint(1, 100)
number_2 = random.randint(1, 100)
expression = f"{number_1} {number_2}"
answer =... | 0024d31b242ee86609520e24000b1f2d27b09be4 | 625,861 |
def crop_center(img, crop_x, crop_y):
"""
Crops image from center to new size
Args:
img: input image
width: width of cropped image
height: height of cropped image
Returns:
Cropped image
"""
height, width = img.shape
startx = width // 2 - (crop_y // 2)
st... | f1da95e8f8f64a4510b7e124f8574d00bf6d0e6a | 625,862 |
import json
def load_learner_id(json_path):
"""Saves dict of floats in json file
Args:
d: (dict) of float-castable values (np.float, int, float, etc.)
json_path: (string) path to json file
"""
with open(json_path, 'r') as f:
# We need to convert the values to float for json (i... | efad1052c088f817c0c48fad6023471f6251479e | 625,863 |
from typing import Any
def _dump_ast_or_value(value: Any, python=True, indent: int = 0) -> str:
""" Helper function to dump the AST node type or a reconstructible
node value.
:param python: Use Python syntax for output.
"""
if python and hasattr(value, 'dump_ast'):
return value.dum... | d45bbeb4c9ec55a794e71bfae28293c1e0ed90a6 | 625,864 |
import uuid
def generate_id() -> str:
""" Create a unique ID.
This is passed in each message, and used to match requests
to responses.
"""
return uuid.uuid4().hex | eae268d641f0ee6e310ea85d75316bfa327b31b9 | 625,865 |
def _calc_time_table_from_events(event_list):
"""Calculate the time table from list of events."""
time_table = []
start_time = event_list[0].start_time
if start_time is None:
print('The first ACL event is not finished!')
start_time = 0.0
for event in event_list:
name = event.name
if event.fini... | 9e1a6eb3cda4a85b654161ea568c5f32d27b0120 | 625,869 |
def xstr(s):
"""return empty string if input is none/false"""
return '' if not s else s | 2a9e2075d7d21f0d7af237d97f472eec72e14088 | 625,870 |
def get_column(wks, row, col, number):
"""Get column with starting row and column, and then going down `number`
rows."""
return list(map(lambda x: x.value,
wks.range(row, col, number+row-1, col))) | 3a0f82cd824325de0e5fd4e91ee4a54fcdc4ad78 | 625,871 |
def is_valid_name(s):
"""
Validate name strings
"""
INVALID_CHARS = '~`!$%^&*{}+=?/\\.,:;><|\'\"'
for char in INVALID_CHARS:
if char in s:
return False
return True | 849774c59761991536e898753fb30e439a2b2577 | 625,872 |
import tempfile
import os
def create_temp_logfile(name):
"""
This function uses tempfile.mkstemp to create a temporary
log filename in the /tmp directory
"""
try:
tmp_file = tempfile.mkstemp(prefix="%s-" % (name), suffix=".log", dir="/tmp")
except Exception:
return None
# ... | 6f93b4373f9839318efca4fad2528d3aa986f42a | 625,873 |
def not_empty(x):
"""Check if a collection is not empty or object is not None"""
if hasattr(x, '__len__'):
return len(x) > 0
return x is not None | 377d188bf0922ee1d5e5a511b2393227f77a61cd | 625,875 |
import time
def get_object_paths(s3, bucket, prefix):
"""List objects in S3 bucket with given prefix.
Uses paginator to ensure a complete list of object paths is returned.
"""
# r1 = s3.list_objects(Bucket=DEND_BUCKET, Prefix=prefix)
# r2 = list(map(lambda obj: obj['Key'], r1['Contents']))
# r... | e284cd6ac420cd293675d18cb7c16700fe52e019 | 625,876 |
import sys
def remove_empty_genotypes(line, start1, end1, start2, end2, start3, end3):
"""For variants found by only one caller, remove empty (.:.:.) fields.
If only DeepVariant has call, set dv_priority_GT to the DV GT
Set all consensus GT to ./.
"""
line[8] = line[8] + ":concensus_GT:dv_pr... | 47a0eb246f36a3509e8bcaf0248abf10e212868d | 625,877 |
def evaluate_cv_total_accuracy(val_beauty_acc, val_fashion_acc, val_mobile_acc, kaggle_public_acc=None):
"""Utility function to evaluate results, pass kaggle_public_acc=False to evaluate local CV score"""
if kaggle_public_acc:
total_examples = 57317 + 43941 + 32065 + 172402*0.3
num_correct = 573... | 1f3f3391cc53322ef151ca11a7594a8ffd58911f | 625,878 |
import json
def read_json(json_path):
"""Read json file."""
with open(json_path, "r") as f:
meta = json.load(f)
return meta | bb4b2398694c268fd7d5b4a009a90ee0db6e99fd | 625,879 |
def plot_deviations():
"""Plot deviations in results for a group of samples."""
return NotImplementedError | e944fffd321f78149ae031ee1141486dbd065705 | 625,880 |
def keymap(fn, d):
""" Apply function to keys of dictionary
>>> bills = {"Alice": [20, 15, 30], "Bob": [10, 35]}
>>> keymap(str.lower, bills) # doctest: +SKIP
{'alice': [20, 15, 30], 'bob': [10, 35]}
See Also:
valmap
"""
return dict(zip(map(fn, d.keys()), d.values())) | 27b3a9cab7b24bff893e3f668d9fc55853eaad41 | 625,881 |
from typing import Callable
from typing import Optional
from typing import Tuple
import multiprocessing
def start_process(
target: Callable, args: Optional[Tuple] = None
) -> multiprocessing.Process:
"""Start a process from with the multiprocessing framework.
Parameters
----------
target: callabl... | 7570672290436527e200e0bb59746ac2203315eb | 625,882 |
import hashlib
def sha256(_input: str):
""" Creates a sha256 hash from the input
Args:
_input (str): A string
Returns:
A sha256 hash string
"""
m = hashlib.sha256()
m.update(_input.encode("UTF-8"))
return m.hexdigest() | a09835aca6726bb8d974fe1be443806588b7288e | 625,883 |
def find_cfg(config, name):
"""
(Ze'ev) reaaaaallly cryptic function which returns the config object for
specified group.
"""
cfg = None
for k, v in config.items():
try:
if k.lower() == name.lower():
cfg = v
return cfg
else:
... | cf3c8d6df063d6b479db2cf93857478813970708 | 625,884 |
import json
def build_search_body(event):
"""Extract owners and filters from event."""
owners = json.loads(event["Owners"])
filters = json.loads(event["Filters"])
return {"Owners": owners, "Filters": filters} | 07818f59cd992cb10e5dd28d112873c136bf5dc1 | 625,885 |
def mergeSegments(lSegment, iMin):
"""Take as input a list of interval on some axis,
together with the object that contributed to this interval.
In this module it's a textbox or an image
Merge overlapping segments
Return a sorted list of disjoints segments together
with the associated objects (t... | e6a794739abbb318f16fde1bfe0a0418c485f1cb | 625,886 |
import traceback
def read_txt(*, file_path: str) -> str:
"""
Read specified file's text.
Parameters
----------
file_path : str
File path to read.
Returns
-------
txt : str
Target file's text.
"""
with open(file_path, 'r', encoding='utf-8') as f:
try:
... | 77271f8f34f5eaf6aef7bfeb8dcd84c985afe3ae | 625,887 |
import requests
import logging
import json
import gzip
def get_geojson(commune, source="parcelles"):
"""
charge une donnée du PCI au format GeoJSON
les sources disponibles sont:
['batiments', 'communes', 'feuilles', 'lieux_dits', 'parcelles',
'prefixes_sections', 'sections', 'subdivisions... | cbe028eef6f83fe51748e63afda7350e9337a5a9 | 625,888 |
def _get_interior_years(from_year, to_year, start_year, end_year):
"""Return the Rule years that overlap with the Match[start_year, end_year].
"""
years = []
for year in range(start_year, end_year + 1):
if from_year <= year and year <= to_year:
years.append(year)
return years | 6d0c73edef146b113f357e8eb75ef6806597b052 | 625,889 |
def get_show(name, cursor):
"""returns None if TV series name does not exists in
database
Args:
name: name of TV series
cursor: cursor object
"""
sql = "select id from tvshow where name = %s"
cursor.execute(sql, (name,))
result = cursor.fetchone()
if result == None:
return None
else:
return result[0] | f364cf695ba773c42fd9cb7aaa7d6378f42002ca | 625,890 |
def dict_sweep(d, vals=[".", "-", "", "NA", "none", " ", "Not Available", "unknown"]):
"""
@param d: a dictionary
@param vals: a string or list of strings to sweep
"""
for key, val in d.items():
if val in vals:
del d[key]
elif isinstance(val, list):
for item i... | 5708ca319819c223ac58acfb2c9d659ab05e018c | 625,891 |
import os
import logging
def find_sources_root(tree_root='csse332'):
"""
Find the root directory containing the sources for the website.
:return: Returns the real path of the sources root.
:rtype: str
"""
curr_dir = os.path.realpath(os.curdir).split('/')
curr_dir[0] = '/' # adjust to hav... | b6b5a85d0d361beaa538aa65652876a421fe2132 | 625,892 |
def distribute_indices_base(indices, nprocs, rank, allow_split_comm=True):
"""
Partition an array of "indices" evenly among a given number of "processors"
This function is similar to :func:`distribute_indices`, but allows for more
a more generalized notion of what a "processor" is, since the number of
... | 17cefd2d45944e6eb9c788f7ec8bcf1d813e91d9 | 625,893 |
def blend_union(da, db, r):
""" Blend union of the distances da, db with blend radius r. """
e = max(r - abs(da - db), 0)
return min(da, db) - e * e * 0.25 / r | 7128b3a78295da0a744046a0b76e466afbcf322d | 625,894 |
def get_ring_param(sigma, v, sigma_g, v_g, dt, thick=True):
"""
This function finds the velocities and surface densities of the dust species and the gas only for the dust trapped ring.
Parameters:
sigma: 3-D list of 2 dimensional surface densities for dust species
v: 3-D list of 2 dimensional velocities for... | bee67aeb5931079f857dae0748694a42b10d8b59 | 625,895 |
def get_subplot_rows_columns_figsize(number_subplots):
"""Get the size of a sub plot in (rows, columns), based on the number of subplots that are going to be plotted.
Parameters
-----------
number_subplots : int
The number of subplots that are to be plotted in the figure.
"""
if number_... | cb82db8dc7b22414c10d3c8957f6ab2ad44a1974 | 625,896 |
def linkcmp(link1, link2):
"""
comparison function for Link objects used to sort list of Link objects
by 'from' node ascending and within that by 'to' node ascending
"""
if link1.init_node < link2.init_node:
return -1
elif link1.init_node > link2.init_node:
return 1
else:
... | 42e7ce8a6bc7aee132a9568d971f66c819e62c09 | 625,897 |
def combsort(array, scaling_factor):
"""
combsort(array, scaling_factor) -> list
array -> [list]: A list of elements to be sorted using combsort
scaling_factor -> [float]: A scalar that reduces the size of the
gap every sweep (>1)
"""
steps = 0
gap = len(array)
while ... | c576d7b2b776c82aa7246173714e22a951c05d20 | 625,901 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.