content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def mask_pipe_mw(text: str) -> str:
"""
Mask the pipe magic word ({{!}}).
:param text: Text to mask
:return: Masked text
"""
return text.replace("{{!}}", "|***bot***=***param***|")
|
546d7c4b71ce3403da7a33883dac2cd3171224e6
| 697,433 |
import base64
def decodebase64(inputStr, decodeFlag=True):
""" Decode base64 to real format """
if decodeFlag and inputStr:
return base64.b64decode(inputStr)
return inputStr
|
92047f7e1c798d3d0ca6a0a0f8f8d78fbecd1204
| 566,501 |
def relay_load_tuple(relay_loads):
"""
Create list of (relay, load) tuples
"""
relay_load_tuple = list()
for r, loads in relay_loads.items():
for l in loads:
relay_load_tuple.append((r,l))
return relay_load_tuple
|
420b5377f5b4f9c05cf140a1985457107daa019a
| 430,197 |
def CheckAttr(f):
"""Automatically set mock_attr based on class default.
This function decorator automatically sets the mock_attr keyword argument
based on the class default. The mock_attr specifies which mocked attribute
a given function is referring to.
Raises an AssertionError if mock_attr is left unspecified.
"""
def new_f(self, *args, **kwargs):
mock_attr = kwargs.pop('mock_attr', None)
if mock_attr is None:
mock_attr = self.DEFAULT_ATTR
if self.DEFAULT_ATTR is None:
raise AssertionError(
'mock_attr not specified, and no default configured.')
return f(self, *args, mock_attr=mock_attr, **kwargs)
return new_f
|
4d6fd797e854339e53f5f9d40c17f5420c6940c9
| 616,390 |
import torch
def sample_from_binary_logits(l, coord1, coord2):
"""
Args:
l: B x 2 x H x W output of NN (logits)
coord1
coord2
Returns:
pixels: B x 1 pixel samples at location (coord1, coord2) in range [-1, 1]
"""
assert l.size(1) == 2
l = l[:, :, coord1, coord2]
pixels = torch.distributions.categorical.Categorical(logits=l).sample()
pixels = pixels * 2. - 1.
return pixels.unsqueeze(1)
|
5ed8a75c94899cc5c4fc7a153f4c184d2be68f8e
| 518,916 |
def clean_split(text, delim):
"""
Split texts and removes unnecessary empty spaces or empty items.
:param text: Text to split
:param delim: Delimiter
:return: List of splited strings
"""
return [x1 for x1 in [x.strip() for x in text.split(delim)] if len(x1)>0]
|
bd454cd33989f6d198d32a0235a9f663df3fc4f8
| 308,845 |
def CompactArrayIndices(tree):
"""Makes a sparse tree dense.
Returns a tree that may have been sparse, with its indices now compacted.
Eg 'a.b.0.c', 'a.b.5.c' -> 'a.b.0.c', 'a.b.1.c'.
Args:
tree: or store. multi-level dict representing proto dbroot.
Returns:
The tree, compacted.
"""
new_tree = {}
index = 0
for key, rest in sorted(tree.iteritems()):
if key.isdigit():
key = "%06d" % index
index += 1
if isinstance(rest, dict):
new_tree[key] = CompactArrayIndices(rest)
else:
# primitive
new_tree[key] = rest
return new_tree
|
afcc6a5bceed9274d0494ea63cd4ec07e6dedc4e
| 354,123 |
from zipfile import ZipFile
def extract_shp(path):
"""Return a geopandas-compatible path to the shapefile stored in a zip archive.
If multiple shapefiles are included, return only the first one found.
Parameters
----------
path : Path
Path to zip archive holding shapefile.
Returns
-------
str
zip:///<path to zip file>!<relative path to shapefile>
"""
z = ZipFile(path)
fn = next(filter(lambda x: x.endswith(".shp"), z.namelist()))
z.close()
return f"zip://{path.absolute()}!{fn}"
|
273fb9917c5d5ecedee142e8e252a2376aac59b0
| 668,936 |
def length_of_overlap(first_start, first_end, second_start, second_end):
"""
Find the length of the overlapping part of two segments.
Args:
first_start (float): Start of the first segment.
first_end (float): End of the first segment.
second_start (float): Start of the second segment.
second_end (float): End of the second segment.
Return:
float: The amount of overlap or 0 if they don't overlap at all.
"""
if first_end <= second_start or first_start >= second_end:
return 0.0
if first_start < second_start:
if first_end < second_end:
return abs(first_end - second_start)
else:
return abs(second_end - second_start)
else:
if first_end > second_end:
return abs(second_end - first_start)
else:
return abs(first_end - first_start)
|
6d5779cf25bcd871f1db21f23adf0f5ed7d4447a
| 256,912 |
def upper(s: str) -> str:
"""Transforms string to upper-case letters."""
return s.upper()
|
a79e49a218869fdb71ba467cb09c99a784161784
| 277,343 |
def nice_pair(pair):
"""Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range.
"""
start, end = pair
if start == end:
return "%d" % start
else:
return "%d-%d" % (start, end)
|
07e8803a79150ac1fceb360717f0ad6e2af1324c
| 569,571 |
import socket
import struct
def int2ip(ip):
"""Convert an IP in an 32bit int to a string in dot-decimal notation.
:param ip: int
"""
if not isinstance(ip, int):
raise ValueError("ip must be int and is {0} instead".format(type(ip)))
return socket.inet_ntoa(struct.pack('!I', ip))
|
63f2a6cbc7c1562bc820dc824dbe65633b6471ef
| 231,320 |
def pass_intermediate_value(contents):
"""Grabs the content sent in by the user and acts as a intermediate callback, so that other callbacks can share the
data the user sent.
Args:
contents: content sent in from the user and the upload-image object.
Returns:
contents: content sent in from the user and the upload-image object.
"""
if contents is not None:
return contents
|
0a69c4af8c88fef7eb2538f4edaac45895e3426d
| 271,426 |
def focal_length_calculator(width_in_image, distance_in_image, real_width_of_object):
"""
This function is used to calculate the focal length for the distnace estimation
using triangle similarity
:param1 (width_in_image): The width of the object in the reference image
:param2 (distance_in_image): The distance of the object from the screen [measured] in the reference image
:param3 (real_width_of_object): The real width of the object [measured] in the reference image
:returns (focal_length): The focal_length is the product of all the parameters
"""
return ((width_in_image * distance_in_image)/real_width_of_object)
|
288a0dd064a960e3a6d1314476a4b4bccf7b7fd7
| 267,050 |
def lon2zone(lon):
""" Convert longitude to numeric UTM zone, 1-60.
"""
zone = int(round(lon / 6. + 30.5))
return ((zone - 1) % 60) + 1
|
b33fcaf81038c6fc429f0fb036b9f2ace2436d4b
| 227,331 |
def filter_file_paths_by_extension(file_paths, ext='csv'):
"""
Filters out file paths that do not have an appropriate extension.
:param file_paths: list of file path strings
:param ext: valid extension
"""
valid_file_paths = []
for file_path in file_paths:
ext = ".%s" % ext if ext[0] != '.' else ext
if not file_path.endswith(ext):
continue
valid_file_paths.append(file_path)
return valid_file_paths
|
6666434635b6054c736b1d54eb5adfdaeb422b7b
| 127,173 |
def function2path(func):
""" simple helper function to return the module path of a function """
return f'{func.__module__}.{func.__name__}'
|
a9781334089b4e1127576957ab79b16a59688a9b
| 253,174 |
def cell_source(cell):
"""Return the source of the current cell, as an array of lines"""
source = cell.source
if source == '':
return ['']
if source.endswith('\n'):
return source.splitlines() + ['']
return source.splitlines()
|
610eae2ae60106d7d5d8d91bfab41679782ac84e
| 352,974 |
import pathlib
def get_testdata_file_path(rel_path: str) -> pathlib.Path:
"""Gets the full path to a file in the testdata directory.
Arguments:
rel_path -- path relative to testdata/
Returns:
pathlib.Path -- the full path to the file.
"""
return pathlib.Path(__file__).parent / "testdata" / rel_path
|
48431abacceb289a8349bd10b911001525caf954
| 642,006 |
from typing import List
def int_version(name: str, version: str) -> List[int]:
"""splits the version into a tuple of integers"""
sversion = version.split('-')[0].split('+')[0].split('a')[0].split('b')[0].split('rc')[0]
#numpy
#scipy
#matplotlib
#qtpy
#vtk
#cpylog
#pyNastran
# '1.20.0rc1'
# '1.4.0+dev.8913610a0'
# matplotlib 3.1rc1
# matplotlib 3.5.5b1
try:
return [int(val) for val in sversion.split('.')]
except ValueError:
raise SyntaxError('cannot determine version for %s %s' % (name, sversion))
|
a9b0bd338526486b465379e131ebd0bfdacd306a
| 669,870 |
def parse_args(p):
""" parses command-line arguments and returns an arguments object """
p.add_argument('-l', '--location', metavar='LOCATION', action='store',
dest='location', choices=['dewick', 'Dewick', 'carm', 'Carm',
'carmichael', 'Carmichael'],
default='dewick', help='Dewick or Carm? (Default: Dewick)')
p.add_argument('-i', '--item', metavar='ITEM', action='store', dest='item',
default='chicken tenders',
help='What are you looking for? (Default: tendies)')
return p.parse_args()
|
7fcd550bccc1324403edc4c8d7351a96af0179a7
| 405,640 |
def translate(parsed):
"""
translate a tuple (mod, args) to a string
"""
if isinstance(parsed, tuple):
return '%s(%s)' % (parsed[0], ', '.join(map(translate, parsed[1])))
else:
return parsed
|
aa67dee8433103cd5273374c2a46db8000d9ea8c
| 591,343 |
import re
import keyword
import six
def _is_identifier(name):
"""Check if 'name' is a valid Python identifier.
Source: https://stackoverflow.com/a/2545164
"""
if name:
if six.PY2:
return re.match(r'^[a-z_][a-z0-9_]*$', name, re.I) and not keyword.iskeyword(name)
else:
return name.isidentifier()
else:
return False # empty string or None
|
af02c86156179cb506fcb5c1b5d861306d622ae8
| 357,418 |
import random
def get_random_start_end(len_genotype):
"""gets a random start and end type for genotype
used to get start and end times for fragments, used in mutations
Args:
len_genotype (int): length of genotype list
Returns:
(int, int): tuple of two integers representing randomly generated (start_index, end_index)
"""
end_index = random.randint(0, len_genotype-1)
start_index = random.randint(0, len_genotype-1)
if start_index > end_index:
temp = end_index
end_index = start_index
random_end_index = temp
return (start_index, end_index)
|
0fc216c917aaa2e96c44361022390aaa9401d0f3
| 435,814 |
def join_structures(src, dst, validate_proximity=False):
"""Joins two pymatgen structures"""
for site in src.sites:
dst.append(
species=site.species,
coords=site.coords,
coords_are_cartesian=True,
validate_proximity=validate_proximity,
)
return dst
|
ab0674af9cb8a37b5b2a97f6ad3262a9f3e5b06f
| 134,722 |
def find_collNames(output_list):
"""
Return list of collection names collected from refs in output_list.
"""
colls = []
for out in output_list:
if out.kind in {"STEP", "ITEM"}:
colls.append(out.collName)
elif out.kind == "IF":
colls.append(out.refs[0].collName)
return colls
|
cfcd9a8d8343009b09758a075b6b98a98a3ac0ea
| 677,724 |
def OneLett_to_ThrLett(resi, cap = 'standard', suppress_alert = True):
"""
Usage: OneLett_to_ThrLett(resi, cap = 'standard',
suppress_alert = True)
This function receives resi, a one-letter amino acid
code, and returns the three letter amino acid code.
If cap(italization) is standard, then only the first
letter will be capitalized. If cap is all, then all
letters will be capitalized (as in a PDB file). If
the one-letter amino acid is not recognized, it is
simply returned. If option suppress_error is False,
a message will also be printed to alert to user that
the code was not recognized.
"""
if resi == 'A':
res3 = 'Ala'
elif resi == 'C':
res3 = 'Cyx'
elif resi == 'D':
res3 = 'Asp'
elif resi == 'E':
res3 = 'Glu'
elif resi == 'F':
res3 = 'Phe'
elif resi == 'G':
res3 = 'Gly'
elif resi == 'H':
res3 = 'His'
elif resi == 'I':
res3 = 'Ile'
elif resi == 'K':
res3 = 'Lys'
elif resi == 'L':
res3 = 'Leu'
elif resi == 'M':
res3 = 'Met'
elif resi == 'N':
res3 = 'Asn'
elif resi == 'P':
res3 = 'Pro'
elif resi == 'Q':
res3 = 'Gln'
elif resi == 'R':
res3 = 'Arg'
elif resi == 'S':
res3 = 'Ser'
elif resi == 'T':
res3 = 'Thr'
elif resi == 'V':
res3 = 'Val'
elif resi == 'W':
res3 = 'Trp'
elif resi == 'Y':
res3 = 'Tyr'
else:
if not suppress_alert:
print(resi, "not recognized as residue. Returning", resi)
res3 = resi
if cap == 'all':
res3 = res3.upper()
elif cap != 'standard':
print('Ignoring invalid option for cap:', cap)
return res3
|
43fdbbf3f9a47846ee8ff07d162b975645b9e9bf
| 98,865 |
def get_sql_from_qbol_cmd(params):
"""
Get Qubole sql from Qubole command
"""
sql = ''
if 'query' in params:
sql = params['query']
elif 'sql' in params:
sql = params['sql']
return sql
|
c1d87676458352db3ed97860f94b94757e7a5900
| 478,933 |
def maximum(num_list):
"""Return the maximum number between number list"""
return_value = None
for num in num_list:
if return_value is None or num > return_value:
return_value = num
return return_value
|
c4c51b7ec13a8d651459617b71a374be713f53c6
| 291,596 |
def _create_chunks_from_list(lst, n):
"""Creates chunks of list.
Args:
lst: list of elements.
n: size of chunk.
"""
chunks = []
for i in range(0, len(lst), n):
chunks.append(lst[i:i + n])
return chunks
|
1da5ba267b8a3056a05c01087548a30d408661ab
| 382,981 |
def fix_line_problems(parts):
"""Fix problem alleles and reference/variant bases in VCF line.
"""
varinfo = parts[:9]
genotypes = []
# replace haploid calls
for x in parts[9:]:
if len(x) == 1:
x = "./."
genotypes.append(x)
if varinfo[3] == "0": varinfo[3] = "N"
if varinfo[4] == "0": varinfo[4] = "N"
return varinfo, genotypes
|
dd33a042175b925c76261fbd477eabdcaafc61ee
| 537,526 |
def parse_agent_args(str):
"""Parse agent args given in , separated list."""
if str is None:
return {}
pieces = str.split(',')
opts = {}
for p in pieces:
if '=' in p:
key, val = p.split('=')
else:
key, val = p, 1
opts[key] = val
return opts
|
1205e2e3f411a0055098939911e2308b8159a0ec
| 302,084 |
import hashlib
def get_thing(secret):
"""Get dweet thing name from secret.
"""
m = hashlib.sha1()
m.update(secret)
return m.hexdigest()
|
73a32e981e36d2217d09eb58f6558078e35e10d1
| 490,103 |
def load_char_mappings(mapping_path):
"""
load EMNIST character mappings. This maps a label to the correspondent byte value of the given character
return: the dictionary of label mappings
"""
mappings = {}
with open(mapping_path) as f:
for line in f:
(key, val) = line.split()
mappings[int(key)] = int(val)
return mappings
|
8653f22d8490add375747f2e4f1e3aa0bc006f47
| 101,973 |
from typing import Any
def simple_repr(record: Any) -> str:
"""
Simple renderer for a SQL table
:param record: A table record.
:return: A string description of the record.
"""
out = '{:28}: {}\n'.format('token', record.token)
columns = None
# get the columns of the table, we'd like to print out only these fields because
# jupyter notebook sometimes messes them with back_populate fields.
if hasattr(record, '__table__'):
columns = {c for c in record.__table__.columns.keys()}
for field, value in vars(record).items():
if columns and field not in columns:
continue
if not (field[0] == '_' or field == 'token'):
out += '{:28}: {}\n'.format(field, value)
return out + '\n'
|
94d4eca0ea03336f9d4c62344914b244f42dfceb
| 182,370 |
def _parsedrev(symbol):
"""str -> int or None, ex. 'D45' -> 45; '12' -> 12; 'x' -> None"""
if symbol.startswith(b'D') and symbol[1:].isdigit():
return int(symbol[1:])
if symbol.isdigit():
return int(symbol)
|
c3db8cee3b6a4fdb1c02efc2b931989ac6a1b19b
| 66,393 |
def analytical_domain(request):
"""
Adds the analytical_domain context variable to the context (used by
django-analytical).
"""
return {'analytical_domain': request.get_host()}
|
2d1f32ada6524cdc14075596a7b61de3d82d2ea1
| 668,749 |
def calculate_fibonacci_number(n : int) -> int:
"""
Calculate and return the `n` th fibonacci number.
Args:
n (int) : specify term.
Exceptions:
- TypeError: when the type of `n` is not int.
- ValueError: when `n` is negative.
Note:
This solution obtains the answer by tracing from the target term to the first term.
0 1 1 3 ... A(n - 2) A(n - 1) A(n)
↑ ↑ ↓
`--------⊥------
WARNING:
This implementation increases function calls exponentially.
And this recomputes Fibonacci numbers that have already computed.
"""
if type(n) != int:
raise TypeError("`n` MUST be int but {} was passed.".format(type(n)))
if n < 0:
raise ValueError("`n` MUST be a natural but a negative is passed.")
if n == 0:
return 0
elif n == 1:
return 1
else:
return (calculate_fibonacci_number(n - 2) + calculate_fibonacci_number(n - 1))
|
ae812418079d8b4c9756269da3a8dc62a8818969
| 123,632 |
import re
def find_uptime(show_ver):
"""
Example:
pynet-rtr1 uptime is 3 weeks, 1 day, 3 hours, 52 minutes
"""
match = re.search(r".* uptime is (.*)", show_ver)
if match:
return match.group(1)
return ''
|
b8be152a6010156c274bbbca57c18b8383e84d27
| 607,407 |
import torch
def nel_to_lne(tensor: torch.Tensor) -> torch.Tensor:
"""
Convert data layout. This conversion is required to use convolution layer.
Parameters
----------
tensor: torch.Tensor
(N, E, L) where N is the batch size, E is the embedding dimension,
L is the sequence length.
Returns
-------
tensor: torch.Tensor
(L, N, E) where L is the sequence length, N is the batch size, E is
the embedding dimension.
"""
return tensor.permute(2, 0, 1)
|
1c4aa1d7bf4b033e617683767452d59bfac0a9be
| 208,174 |
def read_from_device(path, start, count):
"""
Read data from a device
:param path: device path
:type data: string
:param start: starting offset for reading
:type start: int
:param count: lenght of data to read
:type count: int
:rtype: bytes
"""
with open(path, "rb") as f:
f.seek(start)
data = f.read(count)
return data
|
a8faa180762b66a35d32dc1d3cbad5784169e694
| 368,533 |
from typing import List
from typing import Dict
from typing import Any
def filter_maxlen(items: List[Dict[str, Any]], maxlen: int) -> List[Dict[str, Any]]:
"""Returns only payloads not longer than maxlen."""
if maxlen <= 0:
return items
filtered = []
for item in items:
if len(item["payload"]) <= maxlen:
filtered.append(item)
return filtered
|
825ff7bb40a2698be2c2f91abaf4f1825d0f4d54
| 183,155 |
import json
def readjson(fp):
"""Loads a JSON file"""
with open(fp) as jsonfile:
data = json.load(jsonfile)
return data
|
42aec1b54d0252c94c0e2d3846c3e1969dd81881
| 544,697 |
def parse_text_rules(text_lines):
""" A helper function to read text lines and construct and returns a list of
dependency rules which can be used for comparison.
The list is built with the text order. Each rule is described in the
following way:
{'target': <target name>, 'dependency': <set of dependent filenames>}
"""
rules = []
for line in text_lines:
if line.strip() == "":
continue
rule = {'target': line.split(': ')[0].strip(),
'dependency': set(line.split(': ')[-1].strip().split(' '))}
rules.append(rule)
return rules
|
5b65fe082e92b3b2891c77e1cea69c71b9a1bb74
| 227,043 |
def _expand(key, shortcuts, breadcrumbs=None):
"""Given shortcut key and mapping of shortcuts expand the shortcut key.
Return the key itself if it is not found in the mapping.
Avoids expansion cycles by keeping track of expansion history in the
`breadcrumbs` argument to recursive calls.
"""
breadcrumbs = [] if breadcrumbs is None else breadcrumbs
if key in breadcrumbs:
cyclic_path = " -> ".join(breadcrumbs)
raise ValueError(
f"Detected a cycle when expanding key '{key}': {cyclic_path}\n"
"Please check your shortcuts."
)
# There are two termination conditions for the recursion:
# - The key is in fact clearly a pattern (a dictionary for now).
# This would definitely exclude it as a candidate for further expansion.
# - The key is a string (a note, a simple pattern) but is not found in
# our shortcut mapping. This simply means it cannot be further expanded.
if isinstance(key, dict) or key not in shortcuts:
return [key]
expansion = shortcuts[key]
expansions = expansion if isinstance(expansion, list) else [expansion]
next_level = []
for sk in expansions:
next_level += _expand(sk, shortcuts, breadcrumbs=breadcrumbs + [key])
return next_level
|
f7d16176e17da549b138831f4cee18b400bece93
| 388,654 |
def source_key(resp):
"""
Provide the timestamp of the swift http response as a floating
point value. Used as a sort key.
:param resp: httplib response object
"""
return float(resp.getheader('x-put-timestamp') or
resp.getheader('x-timestamp') or 0)
|
80d56dfe1e4e0ddc9e1eeabb20a05e9b19357cb8
| 652,505 |
def split_data(data, val_size=0, test_size=0):
"""
splits data to training, validation and testing parts
"""
#split based on percentage
ntest = int(round(len(data) * (1 - test_size)))
nval = int(round(len(data.iloc[:ntest]) * (1 - val_size)))
df_train, df_val, df_test = data.iloc[:nval], data.iloc[nval:ntest], data.iloc[ntest:]
return df_train, df_val, df_test
|
d3da49c2307fffd8a6494af76769991100a59b64
| 281,670 |
def filter_request(req):
"""
Extract request attributes from the request metadata
"""
res = {'path': req['environ']['PATH_INFO'],
'method': req['environ']['REQUEST_METHOD'],
'user-agent': req['environ']['HTTP_USER_AGENT'],
'remote_addr': req['environ']['REMOTE_ADDR'],
'remote_port': req['environ']['REMOTE_PORT']
}
if req['environ'].get('CONTENT_TYPE'):
res['content_type'] = req['environ']['CONTENT_TYPE']
return res
|
4a8cb624f6367249efba652296ad93044335f962
| 67,043 |
def update_seq_ack(packet_params, previous):
"""Increase Sequence and Acknowledgement number"""
seq = packet_params.get("seq") + 1
ack = previous.seq +1
packet_params['seq'] = seq
packet_params['ack'] = ack
return packet_params
|
6e5b99e148608abc74ebcf44636e27025cd50553
| 239,447 |
def default_changelog_generator(item):
"""
Contruct the default changelog line for a given item (PR).
"""
title = item['title']
breaks_compat = 'compatibility' in item['labels']
pr_url = item['html_url']
if breaks_compat:
compat_msg = "**WARNING: Breaks compatibility with previous version.**"
else:
compat_msg = ""
return f" - {title}. {compat_msg} [View pull request]({pr_url})"
|
494c30cef1f36a7875d0456fcb4a414c0ec4bb41
| 390,190 |
import yaml
def load_yaml_config(filename):
"""Read the YAML configuration file into a dictionary.
Arguments:
filename {string} -- The location of the YAML configuration file.]
Returns:
Dictionary -- The contents of the configuration file. An empty
dictionary is returned on error.
"""
with open(filename) as the_stream:
try:
return yaml.safe_load(the_stream)
except yaml.YAMLError as exc:
print(exc)
return {}
|
e0d8c6c32919cf5c226bdf09eccea78bfa911b14
| 93,422 |
def has_experience(experience_string):
"""returns whether the current player has experience or not based on the string yes/no"""
if experience_string == 'YES':
return True
else:
return False
|
d6d870ce8713875f59399beadc3a4e61f5158914
| 341,128 |
def calc_saturated_fraction(unsatStore, unsatStore_max, alpha):
""" Calculate the saturated fraction of the unsaturated zone
Parameters
----------
unsatStore : int or float
Storage in the unsaturated zone [mm]
unsatStore_max : int or float
Maximum storage in the unsaturated zone [mm]
alpha : float
Parameter to account for the non-linearity in the variable source area for saturation-excess runoff
Returns
-------
satFrac: float
Saturated fraction of the unsaturated zone
"""
if unsatStore < unsatStore_max:
satFrac = 1 - (1 - (unsatStore / unsatStore_max)) ** alpha
else:
satFrac = 1
return satFrac
|
125dcf56764b7f8dca89f798194822593fd0e78d
| 251,008 |
def to_name_key_dict(data, name_key):
"""
Iterates a list of dictionaries where each dictionary has a `name_key`
value that is used to return a single dictionary indexed by those
values.
Returns:
dict: Dictionary keyed by `name_key` values having the information
contained in the original input list `data`.
"""
return dict((row[name_key], row) for row in data)
|
ce5c2938b29bf42d0835f0a375ee01ba052d8585
| 497,647 |
import fnmatch
def _is_excluded(name, exclude):
"""
Return true if given name matches the exclude list.
"""
if not exclude:
return False
return any((fnmatch.fnmatchcase(name, i) for i in exclude))
|
7cfe2422bd6ed6d7e6ab50569646be04c1858e29
| 140,421 |
def daisy_chain_from_acquisitions(acquisitions):
"""Given a list of acquisiton dates, form the names of the interferograms that would create a simple daisy chain of ifgs.
Inputs:
acquisitions | list | list of acquistiion dates in form YYYYMMDD
Returns:
daisy_chain | list | names of daisy chain ifgs, in form YYYYMMDD_YYYYMMDD
History:
2020/02/16 | MEG | Written
"""
daisy_chain = []
n_acqs = len(acquisitions)
for i in range(n_acqs-1):
daisy_chain.append(f"{acquisitions[i]}_{acquisitions[i+1]}")
return daisy_chain
|
47fe3f15427ded06a463860aaddcfb20a5223f8b
| 313,443 |
def isfloat(s:str) -> bool:
""" Functions to determine if the parameter s can be represented as a float
Parameters:
-----------
* s [str]: string which could be or not a float.
Return:
-------
* True: s can be represented as a float.
* False: s cannot be represented as a float.
"""
float_c = list(".0123456789")
if not all([c in float_c for c in s]):
return False
return True
|
5ba78309d10c1b0a42b2e6a14fa489b92fe3de01
| 542,645 |
def find_initial_start(pos,reference_sequence,min_length):
"""
Using an initial position, it finds the initial starting position which satisfies the minimum length
:param pos: int
:param reference_sequence: str
:param min_length: int
:return: int
"""
ref_len=len(reference_sequence)
nt_count = 0
start = pos - 1
for i in range(0,ref_len):
base = reference_sequence[start].upper()
if base in ['A', 'T', 'C', 'G']:
nt_count += 1
if start < 0:
start = 0
break
if nt_count >= min_length:
break
start -= 1
return start
|
14c805d03d3efb9c1a0f9b23d6d2f99d6c3251ce
| 296,890 |
from math import ceil, sqrt
def chooseGridThread(n):
"""
Modify this function to change how we choose number of
threads and blocks
Args:
n (int): number of datapoints
Returns:
(int, int): (nblocks, nthreads)
"""
nroot = sqrt(n)
curr = 32
while curr + 32 < nroot and curr < 2048:
curr += 32
nthreads = curr
nblocks = ceil(n / nthreads)
return nblocks, nthreads
|
2d54f516f61d5fe8aa4193260f78de82a244e53f
| 341,065 |
def add_lat_lon(df):
"""Add lat and lon columns to dataframe in WGS84 coordinates
Parameters
----------
df : GeoDataFrame
Returns
-------
GeoDataFrame with lat, lon columns added
"""
geo = df[["geometry"]].to_crs(epsg=4326)
geo["lat"] = geo.geometry.y.astype("float32")
geo["lon"] = geo.geometry.x.astype("float32")
return df.join(geo[["lat", "lon"]])
|
2264b865fbf8499c51728f858c863e675d00b021
| 381,241 |
def reddit_response_parser(results):
"""
:param results: JSON Object
:return: List of dictionaries
[
{
"title": "title of the news",
"link": "original link of the news source",
"source":"your-api-name"
},
...
]
"""
response = []
for child in results["data"]["children"]:
response.append({
"title": child["data"]["title"],
"link": child["data"]["url"],
"source": "reddit"
})
return response
|
b4cd22a1e1a549cb4e668eb543a61b12733d9a19
| 358,465 |
def _check_no_collapsed_axes(fig):
"""
Check that no axes have collapsed to zero size.
"""
for panel in fig.subfigs:
ok = _check_no_collapsed_axes(panel)
if not ok:
return False
for ax in fig.axes:
if hasattr(ax, 'get_subplotspec'):
gs = ax.get_subplotspec().get_gridspec()
lg = gs._layoutgrid
if lg is not None:
for i in range(gs.nrows):
for j in range(gs.ncols):
bb = lg.get_inner_bbox(i, j)
if bb.width <= 0 or bb.height <= 0:
return False
return True
|
2ecbc6a3e17f73ab4c09f606c4638ad7748ee59a
| 656,103 |
def mixed_radix_to_base_10(x, b):
"""Convert the `mixed radix`_ integer with digits `x` and bases `b` to base 10.
Args:
x (list): a list of digits ordered by increasing place values
b (list): a list of bases corresponding to the digits
Examples:
Generally, the base 10 representation of the mixed radix number :math:`x_n\ldots x_1` where :math:`x_i` is a digit in place value :math:`i` with base :math:`b_i` is
.. math::
\sum_{i=1}^nx_i\prod_{j=i+1}^nb_j = x_n + b_nx_{n-1} + b_nb_{n-1}x_{n-2} + \cdots + b_n\cdots b_2x_1
Convert 111 with bases :math:`(b_1,b_2,b_3)=(2,3,4)` to base 10:
>>> from fem.discrete.combinatorics import mixed_radix_to_base_10
>>> mixed_radix_to_base_10([1,1,1], [2,3,4])
17
.. _mixed radix:
https://en.wikipedia.org/wiki/Mixed_radix
"""
res = x[0]
for i in range(1, len(x)):
res *= b[i]
res += x[i]
return res
|
a821ca5ee4a720a9c445c98b2bcd2905bd6d87cb
| 12,107 |
from pathlib import Path
from typing import Tuple
import re
def parse_samtools_flagstat(p: Path) -> Tuple[int, int]:
"""Parse total and mapped number of reads from Samtools flagstat file"""
total = 0
mapped = 0
with open(p) as fh:
for line in fh:
m = re.match(r'(\d+)', line)
if m:
if 'in total' in line:
total = int(m.group(1))
if ' mapped (' in line:
mapped = int(m.group(1))
return total, mapped
|
60c6f9b227cefdea9877b05bb2fe66e4c82b4dd1
| 705,319 |
def clock_getres(clk_id): # real signature unknown; restored from __doc__
"""
clock_getres(clk_id) -> floating point number
Return the resolution (precision) of the specified clock clk_id.
"""
return 0.0
|
f51d80fda97e5a2c869818a0ef306be7936e6e82
| 265,407 |
from textwrap import dedent
def dedent_multiline(text):
"""Dedent multiline text, stripping preceding and succeeding newlines.
This is useful for specifying multiline strings in tests without having to compensate for the
indentation.
"""
return dedent(text).strip()
|
dff53acfc698072f2eeae9281cf33b3144fe12a4
| 278,592 |
def _guessFileFormat(file, filename):
"""
Guess whether a file is PDB or PDBx/mmCIF based on its filename and contents.
authored by pandegroup
"""
filename = filename.lower()
if '.pdbx' in filename or '.cif' in filename:
return 'pdbx'
if '.pdb' in filename:
return 'pdb'
for line in file:
if line.startswith('data_') or line.startswith('loop_'):
file.seek(0)
return 'pdbx'
if line.startswith('HEADER') or line.startswith('REMARK') or line.startswith('TITLE '):
file.seek(0)
return 'pdb'
file.seek(0)
return 'pdb'
|
ab04db18b05ee416315d8d2faa2381e469dda955
| 635,128 |
def index() -> str:
"""Root page of Flask API.
Returns:
A test message.
"""
return "What I think a REST API is supposed to be in flask (probably wrong)!"
|
bea6676bdbb95b359fd642073002d39ab9f60a9f
| 102,614 |
from typing import List
def txt_to_list(txtfilename: str) -> List[str]:
"""
Reads in file, splits at newline and returns that list
:param path: Path to dir the file is in
:param txtfilename: Filename
:return: List with lines of read text file as elements
"""
with open(txtfilename, "r", encoding="UTF-8") as f:
llist = f.read().split()
return llist
|
01e04352000113a6a5f5d4491773fd5378bae583
| 461,247 |
import random
def random_bytes(size=1024):
"""
Return size randomly selected bytes as a string.
"""
return ''.join([chr(random.randint(0, 255))
for i in range(size)])
|
bf09258ea7542b5f89c25100d1b19f95380bb8a0
| 180,680 |
def epoch_time(start_time, end_time):
"""
Computes the time for each epoch in minutes and seconds.
:param start_time: start of the epoch
:param end_time: end of the epoch
:return: time in minutes and seconds
"""
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
|
8265cb78c26a96a83a1035c09a7dccb0edf8c4d0
| 14,189 |
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 date_format(date, format='%d %m %Y'):
"""
convert date to string in a given format
"""
return date.strftime(format)
|
1402e0490780f9dec45638bac22a2b6dbb0897ce
| 443,930 |
def weekDay (obj):
"""
return the weekDay from a obj with a datetime 'date' field
weekDay 0 is monday
"""
return obj['date'].weekday()
|
f67d086076e99727e2b39f6a52608144ac24165d
| 26,342 |
def replace_at(string,old,new,indices):
"""Replace the substring "old" by "new" in a string at specific locations
only.
indices: starting indices of the occurences of "old" where to perform the
replacement
return value: string with replacements done"""
if len(indices) == 0: return string
indices = sorted(indices)
s = string[0:indices[0]]
for i in range(0,len(indices)-1):
s += string[indices[i]:indices[i+1]].replace(old,new,1)
s += string[indices[-1]:].replace(old,new,1)
return s
|
a136b498a627aba3ebdf6ed3c339a272c88dd3e3
| 65,277 |
def remove_background(image, threshold):
"""Threshold an image and use as a mask to remove the background. Used for improved compression
Parameters
----------
image : ndarray
input image
threshold : float
intensity to threshold the input image
Returns
-------
filtered : ndarray
output image with background set to 0
"""
mask = (image >= threshold)
return image * mask
|
b455f0e08bc13d54a046eeeaed5df8632d9bd41d
| 558,099 |
def V_tank_Reflux(Reflux_mass, tau, rho_Reflux_20, dzeta_reserve):
"""
Calculates the tank for waste.
Parameters
----------
Reflux_mass : float
The mass flowrate of Reflux, [kg/s]
tau : float
The time, [s]
rho_Reflux_20 : float
The destiny of waste for 20 degrees celcium, [kg/m**3]
dzeta_reserve : float
The coefificent of reserve, [dismensionless]
Returns
-------
V_tank_Reflux : float
The tank for Reflux, [m**3]
References
----------
&&&&&&&&&&&&
"""
return Reflux_mass * tau * dzeta_reserve / rho_Reflux_20
|
3e1adc446bbe2dd936663af895c59222cd000a48
| 7,419 |
def pretty_dict(dict):
""" Returns a pretty string version of a dictionary.
"""
result = ""
for key, value in dict.items():
key = str(key)
value = str(value)
if len(value) < 40:
result += f'{key}: {value} \n'
else:
result += f'{key}: \n' \
f'{value} \n'
return result
|
f21196e52ef7f0c5777c875d0b6a3669838a7eb5
| 450,226 |
def remove_duplicates(dict_of_lists):
"""Removes duplicates from a dictionary containing lists."""
return {key: list(set(value)) for (key, value) in dict_of_lists.items()}
|
a663df2f00700aac4a204dc8a25fa80ea0336294
| 322,818 |
def calc_DH_return(t_0, t_1):
"""
This function calculates the return temperature of the district heating network according to the minimum observed
in all buildings connected to the grid.
:param t_0: last minimum temperature
:param t_1: current minimum temperature
:return: ``tmax``, new minimum temperature
"""
tmin = min(t_0, t_1)
return tmin
|
6c058a70148ce08b9044f63df7622beb9df24907
| 512,439 |
def contour_coords(contour, source='scikit'):
"""Extract x, y tuple of contour positions from contour data.
Scikit has reversed x, y coordinates
OpenCV has an unusual numpy array shape (npts, 1, 2)
Parameters
----------
contour: contour data
source: 'scikit' or 'opencv'
Output
------
x, y (tuple of numpy arrays) that can be used directly on an imshow() graph
"""
if source == 'scikit':
return contour[:, 1], contour[:, 0]
elif source == 'opencv':
contour = contour.squeeze() # eliminate middle dimension in array
return contour[:, 0], contour[:, 1]
else:
raise ValueError(f'{source} not a valid source for contour data.')
|
971f269fab6c476aed1be0a047f843ff0372fe08
| 38,817 |
def extract_etymology(entry):
"""
extracts the etymology part of a given entry string
"""
state = 0
etymology = ""
for ch in entry:
if state == 0:
if ch == "[":
state = 1
elif ch == "]":
raise Exception(f"unexpected ] in: {entry}")
else:
pass
elif state == 1:
if ch == "[":
raise Exception(f"unexpected [ in: {entry}")
elif ch == "]":
state = 2
else:
etymology += ch
elif state == 2:
if ch == "[":
state = 1
etymology = "" # reset etymology so only last [...] is counted
elif ch == "]":
raise Exception(f"unexpected ] in: {entry}")
else:
pass
else:
raise Exception(f"unexpected state {state} in: {entry}")
if state not in [0, 2]:
raise Exception(f"unexpected end state {state} in: {entry}")
return etymology
|
def5c936f72bb937f7dd5ad168f8a595318d40ef
| 104,468 |
def search_name(needle, name, obj):
"""Match if needle is contained in name"""
return name and needle in name
|
4cc81df1ed35f6aceaa5d9f82b6414f9ebfa7b5d
| 472,420 |
def return_data_side_effect(*args, **kwargs):
"""Side effect to return data from a miller array."""
return kwargs["i_obs"].data()
|
ca740eb5f61160130b64d2bfb9594ce8471c3dee
| 186,537 |
from typing import Mapping
def merge(left, right):
"""
Merge two mappings objects together, combining overlapping Mappings,
and favoring right-values
left: The left Mapping object.
right: The right (favored) Mapping object.
NOTE: This is not commutative (merge(a,b) != merge(b,a)).
"""
merged = {}
left_keys = frozenset(left)
right_keys = frozenset(right)
# Items only in the left Mapping
for key in left_keys - right_keys:
merged[key] = left[key]
# Items only in the right Mapping
for key in right_keys - left_keys:
merged[key] = right[key]
# in both
for key in left_keys & right_keys:
left_value = left[key]
right_value = right[key]
if isinstance(left_value, Mapping) and isinstance(
right_value, Mapping
): # recursive merge
merged[key] = merge(left_value, right_value)
else: # overwrite with right value
merged[key] = right_value
return merged
|
5cfeaf647eaf1377c181180f10484602e30f562e
| 494,385 |
def _set_custom_clusters(bspecs, clusters):
"""Given a list of custom clusters, set them to the custom
clusters to add to bspecs
Parameters
----------
bspecs : dict
clusters : list of properly formatted clusters
Returns
-------
dict
"""
bspecs["orbit_specs"]=clusters
return bspecs
|
4182f0e251111d8ebf6835a5aaa779083285bcce
| 326,394 |
def config(config):
""" A config containing a smaller exposure sequence. """
config["exposure_sequence"]["n_days"] = 1
config["exposure_sequence"]["n_cameras"] = 1
config["exposure_sequence"]["n_dark"] = 1
config["exposure_sequence"]["n_bias"] = 1
config["exposure_sequence"]["filters"] = ["g_band"]
config["collections"]["ExposureCollection"]["name"] = "fake_data_lite"
config["collections"]["CalibCollection"]["name"] = "calib_test"
return config
|
f11381b7ad4e6bfce7521a843bd54856305ca246
| 444,536 |
import requests
import time
def call_crossref_api(doi):
"""
Calls the crossref works API for a given DOI.
"""
url = "http://api.crossref.org/works/{}".format(doi)
headers = {
"User-Agent": "JournalsDB/1.1 (https://journalsdb.org; mailto:team@ourresearch.org)"
}
r = requests.get(url, headers=headers)
time.sleep(0.2)
return r
|
ce4f60b5f25c64a2eb88dcefc7e7077118799b1f
| 578,578 |
def count_long_words(sentence, length):
"""Given a sentence, computes and returns the number of words equal to or longer
than the provided threshold length
Keyword arguments:
sentence -- sentence or series of sentences
length -- minimum length for a word to be counted
"""
long_words = 0
words = sentence.split()
for word in words:
if len(word) >= length:
long_words += 1
return long_words
|
7a827ebf0d36c3f6eb8f0beda4bae227efa34ada
| 206,858 |
from typing import List
def mutate_sentences(sentence: str) -> List[str]:
"""
Given a sentence (sequence of words), return a list of all "similar"
sentences.
We define a sentence to be similar to the original sentence if
- it as the same number of words, and
- each pair of adjacent words in the new sentence also occurs in the original sentence
(the words within each pair should appear in the same order in the output sentence
as they did in the original sentence.)
Notes:
- The order of the sentences you output doesn't matter.
- You must not output duplicates.
- Your generated sentence can use a word in the original sentence more than
once.
Example:
- Input: 'the cat and the mouse'
- Output: ['and the cat and the', 'the cat and the mouse', 'the cat and the cat', 'cat and the cat and']
(reordered versions of this list are allowed)
"""
# BEGIN_YOUR_CODE (our solution is 17 lines of code, but don't worry if you deviate from this)
words = sentence.split()
pairs = set([x for x in zip(words, words[1:])])
result = []
def recurse(current_sentence: list = []):
if len(current_sentence) == len(words):
result.append(' '.join(current_sentence))
return
for pair in pairs:
if current_sentence[-1] == pair[0]:
recurse(current_sentence + [pair[1]])
for pair in pairs:
recurse([pair[0], pair[1]])
return result
# END_YOUR_CODE
|
3d3915d6af6c30895199603f373ab492b45a81d8
| 564,482 |
def search(bs, arr):
"""
Binary search recursive function.
:param bs: int
What to search
:param arr: array
Array of ints where to search. Array must be sorted.
:return: string
Position of required element or "cannot found" string
"""
length = len(arr)
check_item = arr[int(length / 2)]
if check_item == bs:
return str(check_item) + ' is on position ' + str(arr[int(length / 2)])
if check_item < bs:
return search(bs, arr[int(length / 2):])
if check_item > bs:
return search(bs, arr[:int(length / 2)])
return "cannot found"
|
c157d25414a5aaa746b9b26cb51cdb2472376ece
| 98,039 |
def int_from_bytes(b) -> int:
"""
int_from_bytes - converts bytes to int
Args:
b: bytes
Returns:
int: result
"""
return int.from_bytes(b, 'big')
|
086eb0b0568dd7b12186eb32f84e6a82e0998b63
| 553,789 |
def helper(n, order, current_max):
"""
This function help find the biggest digit.
:param n: the input integer
:param order: the number of digits
:param current_max: the currently biggest digit
:return: the biggest digit
"""
# +-(0~9)
if order == 0:
return int(current_max)
# +-(10~99999)
else:
# Get digit
division = 10**(order-1)
num = (n - (n % division))/division
if num > current_max:
current_max = num
return helper(n % division, order-1, current_max)
|
88e363aa0933d9727d8be6aa2e4de7c3a9c0ff49
| 374,233 |
def issubclass_safe(x, klass):
"""return issubclass(x, klass) and return False on a TypeError"""
try:
return issubclass(x, klass)
except TypeError:
return False
|
0b5ade96aa4b5fd3c55969aa22a0501549600d6b
| 98,467 |
def pretty_org_name(org_name):
"""Convert e.g. "homo-sapiens" to "Homo sapiens"
"""
first_letter = org_name[0].upper()
return first_letter + org_name[1:].replace("-", " ")
|
86afe1f48d6dd7b62435ef133a7079fb7b61ce8d
| 102,125 |
def crc16(data):
"""
Generate the crc-16 value for a byte string.
>>> from binascii import unhexlify
>>> c = crc16(unhexlify(b'8792ebfe26cc130030c20011c89f'))
>>> hex(~c & 0xffff)
'0xc823'
>>> v = crc16(unhexlify(b'8792ebfe26cc130030c20011c89f23c8'))
>>> hex(v)
'0xf0b8'
"""
crc = 0xffff
for byte in iter(data):
crc ^= byte
for i in range(8):
lsb = crc & 1
crc >>= 1
if lsb == 1:
crc ^= 0x8408
return crc
|
119e067ba38604d699bf2fc222a7c871d2170a02
| 201,485 |
def accom_replace(df):
"""
replaces values of the variable "SettledAccommodationInd" from input dataset
to the format used for analysis and visualisation
Grouped in to 'in accommodation' or 'not in accommodation'
Parameters
----------
df : main datatset
Returns
-------
df : main dataset after replacement
"""
accom_replaced_values = {"Y": "1", "N": "0", "Z": "0", "9": "0"}
df.SettledAccommodationInd = [accom_replaced_values[item] for item in df.SettledAccommodationInd]
return df
|
5ff54051f8c7333ca0217d15bc61a70c27e25f35
| 354,767 |
def is_git_sha(xs: str) -> bool:
"""Returns whether the given string looks like a valid git commit SHA."""
return len(xs) > 6 and len(xs) <= 40 and all(
x.isdigit() or 'a' <= x.lower() <= 'f' for x in xs)
|
3da4f923d32ef94e234738e38a8f98e31756d2da
| 106,845 |
import math
def _TValue(mean1, mean2, v1, v2, n1, n2):
"""Calculates a t-statistic value using the formula for Welch's t-test.
The t value can be thought of as a signal-to-noise ratio; a higher t-value
tells you that the groups are more different.
Args:
mean1: Mean of sample 1.
mean2: Mean of sample 2.
v1: Variance of sample 1.
v2: Variance of sample 2.
n1: Sample size of sample 1.
n2: Sample size of sample 2.
Returns:
A t value, which may be negative or positive.
"""
# If variance of both segments is zero, return some large t-value.
if v1 == 0 and v2 == 0:
return 1000.0
return (mean1 - mean2) / (math.sqrt(v1 / n1 + v2 / n2))
|
6c3f7e9399b8d54f65a429c14a76c9b6795fe051
| 136,106 |
def calc_center_point(point_a, point_b):
"""
已知两点坐标,计算中间点坐标
:param point_a: A点坐标
:param point_b: B点坐标
:return: 中心点坐标
"""
return (point_a[0] + point_b[0]) // 2, \
(point_a[1] + point_b[1]) // 2
|
b7b7b4f1c3258b1159f0f1977ad0839c239f2d7f
| 120,421 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.