content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def seed_flavors():
"""Seed the database with default static flavor.
:rtype: list of dicts containing flavor data
"""
return [{
'id': 'static',
'provider': 'static',
'params': {},
}] | 9a5569f5573d65292f9aaae8c34b29ea97f5c0cb | 673,861 |
import torch
def numerically_stable_exp(tensor, dim=-1):
""" Removes largest value and exponentiates, returning both.
:param tensor: the input tensor
:param dim: which is the dim to find max over
:returns: exp(tensor - max), max
:rtype: (torch.Tensor, torch.Tensor)
"""
max_value, _ = tor... | 8cd7fae4c0a498a1b06b95f97c341f6147f21dbf | 673,862 |
def get_dictionary_of_tagged_reactions(filename='globchem.eqn',
Mechanism='Halogens', wd=None):
"""
Construct a dictionary of reaction strings for tagged reactions in
globchem.eqn
Notes
-------
- From v11-2d the KPP mechanism is in a single *.eqn file (gl... | 46a5d5191946ffea115fcd24490328a4ad7a2bd7 | 673,863 |
import json
def samples_from_json(samples_file):
"""Sample generator from JSON."""
with open(samples_file, "rt", encoding="UTF-8") as f_samples:
samples = [sample["original"] for sample in json.load(f_samples)]
return samples | e20c5da7128b42167657121f565fc967d594b52c | 673,865 |
def get_sweep(hyper):
"""Sweeps over datasets."""
# Apply a learning rate sweep following Table 4 of Vision Transformer paper.
return hyper.product(
[hyper.sweep('config.lr.base', [0.03])]) | 853fb466a238f6c74cb31312d6f952ae45049f76 | 673,866 |
def median_manual(l):
"""
l: List of integers
return median of list l
"""
n = len(l)
l = sorted(l)
if n%2 == 1: return l[int((n-1)/2)]
return (l[int(n/2)-1] + l[int(n/2)]) / 2 | 63104190a38759563e8c003ac1c91ab8bbc78f89 | 673,867 |
def format_list_of_string_2_postgres_array(list_of_string):
"""
{{"GO:0005783",0.214286},{"GO:0005794",0.642857},{"GO...
removes internal spaces
:param list_of_string: List of String
:return: String
"""
return "{" + str(list_of_string)[1:-1].replace(" ", "").replace("'", '"') + "}" | b357925fafb8a61a347c1d9b49063d1c996d1c0c | 673,868 |
import os
def return_and_delete(target):
"""
Read text file, then delete it. Return contents.
:param target: Text file to read.
:type target: str
"""
with open(target, "r") as thefile:
content = thefile.read()
os.remove(target)
return content | 15205cb720563d5c98f8709bc6308497ed29cc08 | 673,869 |
def selectdeclevel(freq):
"""
Calculate an appropriate SHD order for the given frequency
:param freq: Frequency (in Hz)
:return: Decomposition order
Note: This is not used since we are looking at frequencies above 2607 Hz only. Hence Nmax=4 is used
"""
if freq < 652.0:
Ndec = 1
... | bc20ba08f9d02536a9a591069c689ef4a9d4f8cc | 673,870 |
def getAdjNodes(curr_node, validPoints, clearance):
"""
Definition
---
Method to generate all adjacent nodes for a given node
Parameters
---
curr_node : node of intrest
validPoints : list of all valid points
clearance : minimum distance required from obstacles
Returns
---
... | b45e85f045c51d0c9e1cdaa85550f6fc6ada1226 | 673,871 |
def unoccupied_adjacent(data, pos):
""" Get a list of unoccupied positions adjacent to position pos.
Does not give information about the walls. """
adjacent = []
snakes = data['board']['snakes']
# print("POS: {}".format(pos))
# [[x,y],[x,y],...]
# [{'x' : x, 'y' : y}, {...]
# s['body'] ... | 70969ab877509d9f79185f45059ff1199f35ff87 | 673,872 |
def get_account_trades(self, **kwargs):
"""
|
| **Account Trade List (USER_DATA)**
| *Get trades for a specific account and symbol.*
:API endpoint: ``GET /dapi/v1/userTrades``
:API doc: https://binance-docs.github.io/apidocs/delivery/en/#account-trade-list-user_data
:parameter symbol: opti... | 8b09e5896c9132c96a33ba33a690ee7991a09f6f | 673,873 |
import tempfile
def _tmpnam_s():
"""Implementation of POSIX tmpnam() in scalar context"""
ntf = tempfile.NamedTemporaryFile(delete=False)
result = ntf.name
ntf.close()
return result | 0df2458db2f41514cb19f5cc4e65d94449aff343 | 673,874 |
def sink_for_card(card, pulse):
"""Return first sink that uses the given card otherwise return None"""
sinks = pulse.sink_list()
for sink in sinks:
if sink.card == card.index:
return sink
return None | e877a745fd8376220f73cd0344c0a24292bc5ea9 | 673,875 |
import math
def _compute_rdp_discrete_gaussian_simplified(l2_scale, tau, dimension, order):
"""See Proposition 14 / Eq. 17 (Page 16) of the main paper."""
assert order >= 1, "alpha must be greater than or equal to 1."
term_1 = order * (l2_scale**2) / 2.0 + tau * dimension
term_2 = (order / 2.0) * (l2_scale + ... | 8554a61c25a827c3a93faf13abb129876149638e | 673,876 |
def packItem(call_name, method, tags, summary, description, params, query_metadata, extraMetadata):
"""Generate a swagger specification item using all the given parameters."""
item = {
'call_name': call_name,
'method': method,
'tags': tags,
'summary': summary,
'descriptio... | db8e63722a51db98d390cf9a2d441eecb799dcc9 | 673,877 |
import sys
def trace(msg):
"""
Print a trace message
:param msg:
:return:
"""
print("EDMCOverlay: {}".format(msg), file=sys.stderr)
return msg | 332fb129ed7260425f775ec2ad31778c7a9089c9 | 673,879 |
def _NormalizeSourcePath(path):
"""Returns (is_generated, normalized_path)"""
if path.startswith('gen/'):
# Convert gen/third_party/... -> third_party/...
return True, path[4:]
if path.startswith('../../'):
# Convert ../../third_party/... -> third_party/...
return False, path[6:]
return True, pa... | f4076422eebb0035828510bbbe29672903f1fbc8 | 673,880 |
def prepend(value, text):
"""
Prepends text if value is not None.
"""
if value is not None:
value = str(value).strip()
if value:
return "{}{}".format(text, value)
return "" | 80f8067f467540a64cdaf4310407e675d4121696 | 673,881 |
import os
def get_config():
"""Find the config file."""
home = os.path.expanduser("~")
user_config = os.path.join(home, ".config", "selena", "config.ini")
if os.path.isfile(user_config):
return user_config
return "config.ini" | 39337ef8d8bd92f178ebcaa6edac038d09a9c3c2 | 673,882 |
import random
def random_from_alphabet(size, alphabet):
"""
Takes *size* random elements from provided alphabet
:param size:
:param alphabet:
"""
return list(random.choice(alphabet) for _ in range(size)) | aeb8e4f1609ab799dd2dd6d66b8bf266fcb34f20 | 673,883 |
def has_trailing_slash(url):
""" :return: true if the part of the url before parameters ends with a slash, false otherwise """
return False if not url else url.split('?', 1)[0].split('#', 1)[0].endswith('/') | 857c85ce86fba9927275fd4abfb6e2a06cb931b9 | 673,884 |
import os
def env_default(key):
"""Return environment variable or placeholder string.
Set environment variable to placeholder if it doesn't exist.
"""
test_environ = 'prawtest_{}'.format(key)
test_value = os.environ.get(test_environ, 'placeholder_{}'.format(key))
return os.environ.setdefault(... | 0222138231db28ba1c2cab324d19d2a986349668 | 673,885 |
def vis147(n):
"""
OOOO
OOO OOOO
OO OOO OOOO
OO OOO OOOO
O OO OOO
5 11 19
"""
result = ''
for i in range(n):
result += 'O' * (n + 1) + '\n'
result += 'O' * n
return result | 9c7b06604ff6324cea0a7ff69260507923ef415a | 673,886 |
import inspect
def _get_vispy_caller():
"""Helper to get vispy calling function from the stack"""
records = inspect.stack()
# first few records are vispy-based logging calls
for record in records[5:]:
module = record[0].f_globals['__name__']
if module.startswith('vispy'):
l... | 40831652094e59b91483db1082440688861e9f27 | 673,887 |
def check_help_flag(addons: list) -> bool:
"""Checks to see if a help message needs to be printed for an addon.
Not all addons check for help flags themselves. Until they do, intercept
calls to print help text and print out a generic message to that effect.
"""
addon = addons[0]
if any(arg in a... | 1650f1b18e3da831eebc0ea41528727a4f3adbb9 | 673,888 |
def _str_to_list(val):
"""If val is str, return list with single entry, else return as-is."""
l = []
if val.__class__ == str:
l.append(val)
return l
else:
return val | 6268db0a3f70215035783deeeec9859150c122e9 | 673,890 |
def integer_squareroot(n: int) -> int:
"""
Return the largest integer ``x`` such that ``x**2 <= n``.
"""
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x | 894ac9ff8538dddf8b6c9d124f555182ca764a15 | 673,891 |
import os
import glob
def expand_files(input_files, file_pattern='*', completed_files=None):
"""
expand the list of files and directories
:param input_files:
:param file_pattern: glob pattern for recursive example '*.jsonl*' for jsonl and jsonl.gz
:param completed_files: these will not be returned... | a75996fe1cc725805529e11901346eb9c2f6706b | 673,892 |
def is_threshold_sequence(degree_sequence):
"""
Returns True if the sequence is a threshold degree seqeunce.
Uses the property that a threshold graph must be constructed by
adding either dominating or isolated nodes. Thus, it can be
deconstructed iteratively by removing a node of degree zero or... | ba00d6cf1eb943d28940e18faff6ca72b31eaae1 | 673,893 |
def get_description(transaction):
"""
:return: the description of the transaction
"""
return transaction['description'] | 04833b64c477f589a8326b57e7c6b25f7ef6217c | 673,894 |
def crop_to_image_boundary(image, boxes, image_boundary):
"""Crop transformed image to original image boundaries (e.g., remove
padding).
Parameters
----------
image : np.ndarray
Numpy integer array of shape (H, W, C).
boxes : np.ndarray
Numpy array of shape (N, 4), where N is th... | b1614f58dae4e64c001a401d3006e533a0651d8b | 673,895 |
def cv19errorbuild(input):
"""
Function builder
# crear un iterador que recorra el input y cree la función a partir de un comando exec:
# Acepta diccionarios o strings con forma de diccionario
"""
if callable(input):
return input
elif type(input)==str:
pr... | 8ee90ab6fcaa658d5a15308f7b17added7162aeb | 673,896 |
def following_mention_ids(api, ids):
"""
This function has the mention_ids and make sure if the account follow them
if not ... don't make sense to unfollow them
returns the ids list only with the ones that the account follow
"""
ids = list(set(ids))
following_mention_ids = []
... | 508032d92b563e8776c736404d6465d76c20a4a8 | 673,897 |
import importlib
def _load_ngram(name):
"""Dynamically import the python module with the ngram defined as a dictionary.
Since bigger ngrams are large files its wasteful to always statically import them if they're not used.
"""
module = importlib.import_module('lantern.analysis.english_ngrams.{}'.forma... | 846d4d203eec2d1c9818678a295bcda46b3123a5 | 673,898 |
def get_golden_feature_list(df,threshold=.5):
"""
:param df: Main Data csv
:param threshold: Your Lower Bound of Correlation
:return: Golden Feature List
"""
df_numeric = df.select_dtypes(include=["float64","int64"])
df_corr = df_numeric.corr()
df_corr = df_corr.iloc[2,:-1]
golden_f... | 3eab01a3f52ce73eab2e70fc7c17ebd1a0d6db36 | 673,899 |
def deleting_matches_below_threshold(threshold, my_dict):
"""
Deletes the fuzzy matches below a certain set threshold
Inputs: threshold -- threshold value for matching strings set in config.py
my_dict -- dictionary containing fuzzywuzzy matches
Output: my_dict -- dictionary containing fuzz... | 850b98b929bbb688e558b46b0980ee17865bc8cf | 673,900 |
import os
import tempfile
def _ensure_win_line_endings(path, dest=None):
"""Replace unix line endings with win. Return path to modified file."""
if not dest:
dest = os.path.join(tempfile.mkdtemp(), os.path.basename(path) + "_lf")
with open(path, "rb") as inputfile:
with open(dest, "wb") a... | a79ddcaa536a192ccb72347a2b07e89df4b947be | 673,901 |
from typing import Counter
def is_valid_part2(line):
"""
>>> is_valid_part2('abcde fghij')
True
>>> is_valid_part2('abcde xyz ecdab')
False
>>> is_valid_part2('a ab abc abd abf abj')
True
>>> is_valid_part2('iiii oiii ooii oooi oooo')
True
>>> is_valid_part2('oiii ioii iioi iii... | 83509255def578218edbcd1c0334d1ea0563cdc9 | 673,902 |
import requests
from bs4 import BeautifulSoup
def getHtml(url):
"""Get url html and return only img elements"""
html = requests.get(url).content
bsObj = BeautifulSoup(html, 'html.parser')
imgs = bsObj.find_all('img')
return str(imgs) | ce981df37a3a5ccaab0c36cad11d66e309280b95 | 673,903 |
from typing import Callable
def UserAction(fun: Callable) -> Callable:
"""Helper decorator to handle user input."""
def res(*args, **kwargs):
try:
return fun(*args, **kwargs)
except (AssertionError, ValueError) as error:
print(error)
except TypeError:
... | 2df04856537f9f382e49ce9644cf50de12b6e726 | 673,904 |
def files_diff(list1, list2, optional=None):
"""returns a list of files that are missing or added."""
if not optional:
optional = []
if list1 and list2:
for i in ["mlperf_log_trace.json", "results.json"] + optional:
try:
list1.remove(i)
except:
pass
if len(list1) > len(list... | c8c96e9ff282590354f6809e1d08c9ea28c98c1b | 673,905 |
def function():
"""普通函数"""
return 1 | ad070eb2a5c1435ecef94cf7337dd61e5ab41006 | 673,907 |
def Trim(t, p=0.01):
"""Trims the largest and smallest elements of t.
Args:
t: sequence of numbers
p: fraction of values to trim off each end
Returns:
sequence of values
"""
n = int(p * len(t))
t = sorted(t)[n:-n]
return t | 53f10d3d25bc1ad351595fca7010d6c07cb3dacd | 673,908 |
def _maybe(variant):
"""Gets a maybe value from a GVariant - not handled in PyGI"""
v = variant.get_maybe()
if v is None:
return None
return v.unpack() | bfe95d5b4d1f8ef3eda46eee8b33486670dbd762 | 673,909 |
def files_get(): # noqa: E501
"""Returns a list of names of the files uploaded
# noqa: E501
:rtype: List[str]
"""
return 'do some magic!' | 7c0c190b06a4b7597b0315453ffe26a70fee7ec6 | 673,910 |
import functools
def comparable_to_none(cls):
"""
Examples
--------
>>> @comparable_to_none
... @dataclass(order=True)
... class A:
... a: int = 0
>>> @comparable_to_none
... @dataclass(order=True)
... class B:
... b: Optional[A] = None
>>> b0 = B()
>>> re... | b6fd2df809ddfa2763787882ab81d3987baebdf5 | 673,911 |
def show_volume(client, resource_group_name, name):
"""Show details of a volume. """
return client.get(resource_group_name, name) | 10a529da1408037c2363183e48d3f69ffb473b4f | 673,913 |
import torch
def get_matrix_kernel(A, eps=1e-10):
"""
Compute an orthonormal basis of the kernel (x_1, x_2, ...)
A x_i = 0
scalar_product(x_i, x_j) = delta_ij
:param A: matrix
:return: matrix where each row is a basis vector of the kernel of A
"""
_u, s, v = torch.svd(A)
# A = u ... | 0cfb55fd3431b19d6e3287708b31b4a2c04ece0c | 673,915 |
def get_common_tables(old_conn, new_conn):
""" a comparison function which checks for tables with the same name
:param
old_conn: the connection to the old db
new_conn: the connection to the new db
:return: A list of table names
"""
list_table_query = "select name from sqlite_ma... | 00c19620c711c40e3081de3fcc64dd78235a6673 | 673,916 |
def get_iteration_prefix(i, total):
""" Return a String prefix for itarative task phases.
:param i int current step.
:param total int total steps.
"""
return " [{0}/{1}]".format(i, total) | a1131b8ad931aaa07ccd8fb714ec91ddd985f0f3 | 673,917 |
from pathlib import Path
def cp_path_to_dir(cp_path, tag):
"""Convert a checkpoint path to a directory with `tag` inserted.
If `cp_path` is already a directory, return it unchanged.
"""
if not isinstance(cp_path, Path):
cp_path = Path(cp_path)
if cp_path.is_dir():
return cp_path
... | 011ee9ee6ec72d34a1883eb98661c6d9024092f6 | 673,918 |
def join_extract(arr, attr_str, join_str):
"""Join the ``attr_str`` of the element of the ``arr`` with ``join_str``."""
return join_str.join([str(getattr(item, attr_str)) for item in arr]) | f5d3f56e015402864176f1723288c148ca272cc6 | 673,919 |
def _key_case(arg: str):
"""Convert string to key_case.
Only the non-prefix part of curies is retained
all spaces and _ removed
then all lowercased
"""
tmp = arg.split(':')[-1]
tmp = ''.join(tmp.split(' '))
tmp = ''.join(tmp.split('_'))
tmp = ''.join(tmp.split(','))
tmp = tmp.lo... | 5e48429c3b53ff1ceafaef7c32577bb45a4851a8 | 673,920 |
import os
def _normalize(base, vendor, name, version):
""" Combine a base path bith the app name/vendor/version information. """
parts = []
if vendor is not None:
parts.append(vendor)
if name is not None:
parts.append(name)
if version is not None:
parts.append(version)
... | c7c8688e325494f93f2699e9d879150327785729 | 673,921 |
def _CreateImage(media_service, opener, url):
"""Creates an image and uploads it to the server.
Args:
media_service: a ZeepServiceProxy instance for AdWords's MediaService.
opener: an OpenerDirector instance.
url: a str URL used to load image data.
Returns:
The image that was successfully upload... | d53b36320870d6dbc6c20d8e3cc5ac647cc91e21 | 673,922 |
def get_ann_energy_demands(city, print_out=False):
"""
Returns annual energy demands of city in kWh (space heating, electrical,
hot water)
Parameters
----------
city : object
City object of pycity_calc
print_out : bool, optional
Print out results (default: False)
Return... | cdb0603468be1e61e56c37c51ea630c9c2fdcbf1 | 673,923 |
def PGetList (inImage):
"""
Return the member InfoList
returns InfoList
* inImage = Python Image object
"""
################################################################
if ('myClass' in inImage.__dict__) and (inImage.myClass=='AIPSImage'):
raise TypeError("Function unavai... | 8760a340af4d1a181634806306b83461494d83a0 | 673,924 |
def complex_abs_sq(data):
"""
Compute the squared absolute value of a complex tensor
"""
assert data.size(-1) == 2
return (data ** 2).sum(dim=-1) | e2a64d99b6a5dbad6b1239a0a876854db72d1a15 | 673,925 |
def format_cpf(value):
"""
This function returns the Brazilian CPF with the normal format.
:param value is a string with the number of Brazilian CPF like 12345678911
:return: Return a sting with teh number in the normal format like 123.456.789-11
"""
return f'{value[:3]}.{value[3:6]}.{value[6:9]... | d0b6c40244b0d75e690b214a998cd934c48194dc | 673,926 |
def oddify(num):
"""
Return the next odd number if ``num`` is even.
Examples
--------
>>> oddify(1)
1
>>> oddify(4)
5
"""
return num + (num % 2 == 0) | 6ce1e8ba20dd447a8967da63fd746981aaff0361 | 673,927 |
def n_5(x):
"""Max aft wing root location: x_offset + chord_0"""
x_aft = x[0] + x[2]
return x_aft | 6f4a8b49b0106b4612b620ad27a296dfc1a831f6 | 673,928 |
async def mock_async_call():
""" mocks a generic async function """
return True | 09d35540c0a9c69a2b90cced80085fe58384858e | 673,929 |
from typing import List
def remove_repeated_and_leq(tokens: List[int], blank_id: int = 0):
"""Generate valid token sequence.
Result may be used as input of transformer decoder and neural language model.
Fristly, remove repeated token from a "token alignment" seqs;
Then remove blank symbols.
This... | 2c9bd78e9bec41ddd85f95d5ce76b75b0ffe099d | 673,930 |
import os
def append_to_filename(path, suffix):
"""
Appends a suffix to a filename, e.g. append_to_filename("test.csv", "_2")
will return "test_2.csv".
"""
name, ext = os.path.splitext(path)
return name + suffix + ext | 09509a2c7edbb5d7a350bf37aeeac5fd04c253b5 | 673,931 |
import importlib
def _get_profile_pkg(aaz_module_name, cloud):
""" load the profile package of aaz module according to the cloud profile.
"""
profile_module_name = cloud.profile.lower().replace('-', '_')
try:
return importlib.import_module(f'{aaz_module_name}.{profile_module_name}')
except... | b16b81875144ce55b335c2d1240291266af9ca7f | 673,932 |
def normalizeArea(value):
"""
Normalizes area.
* **value** must be a positive :ref:`type-int-float`.
"""
if not isinstance(value, (int, float)):
raise TypeError("Area must be an instance of :ref:`type-int-float`, "
"not %s." % type(value).__name__)
if value < 0:
... | c064297191cc4bf6a991708b7aa2510ef9af455d | 673,933 |
def dec_indent(indent, count=1):
"""
decrease indent, e.g.
if indent = " ", and count = 1, return " ",
if indent = " ", and count = 2, return "",
"""
if indent.endswith('\t'):
indent = indent[:len(indent) - 1 * count]
elif indent.endswith(' '):
indent = in... | 0f8bf02b67ea7fbb539cdf04ac8d70dd51f3e57a | 673,934 |
import yaml
from textwrap import dedent
def create_cron_resource(name="cron", minute=5, image="cron-image"):
"""Create a CronTab resource from parameters.
Args:
name (str): name of the resource
minute (int): time set for the minutes in the CRON specifications.
image (str): image used ... | 03d9ae543b49d067792d80463b80cccb295be747 | 673,935 |
def check_args(args):
""" check args to avoid sql injections"""
for arg in args:
if isinstance(arg, str) is True:
if arg.find('\'') != -1 or arg.find('\"') != -1:
return False
return True | 1f69f6def879f28c7db67c3917e5209a1e306734 | 673,936 |
def read_reshape2d(sx, dataname):
"""read seissol dataset
and if there is only one time stamp
create a second dimension of size 1"""
myData = sx.ReadData(dataname)
if len(myData.shape) == 1:
myData = myData.reshape((1, myData.shape[0]))
return myData | e36693badbdba953d9d7a977f58affa9c765a670 | 673,937 |
import os
def get_toplevel_dirs():
"""
Returns a list of the top level directories directly under root (/),
"""
toplevel_dirs = sorted(filter(lambda x: not os.path.islink(x), map(lambda x: "/" + x, os.listdir('/'))))
return toplevel_dirs | afb65a72c5582df1b3788ed6cf15d1515899482f | 673,938 |
def freeze_one_half(basis):
"""
Split the structure into two parts along the z-axis and then freeze the position of the atoms
of the upper part (z>0.5) by setting selective dynamics to False.
Args:
basis (pyiron_atomistics.structure.atoms.Atoms): Atomistic structure object
Returns:
... | f48f1c3e1b9b73b203ea9dec0091e6500c5a338c | 673,939 |
import re
def snakelize(camel_cased_str):
"""
Convers a PascalCase str to snake_case
:returns: str
"""
return "_".join(
word.lower()
for word in re.findall('[A-Z][^A-Z]*', camel_cased_str)
) | 81160a41a0bb7bab40407a19f8e55f79bdeca0f1 | 673,940 |
def format_args(args):
"""Formats the args with escaped " """
comma = "," if args else ""
return comma + ",".join(['\\\"' + a + '\\\"' for a in args]) | d62baeb4f4bb45fdd13386fdf023bc1fb66444ba | 673,941 |
def rescale(ndarray, min, max):
"""Rescale values of ndarray linearly so min of ndarray is min, max is max
Parameters
----------
ndarray: numpy nd array
min: int
max: int
Returns
-------
numpy ndarray
"""
old_max = ndarray.max()
old_min = ndarray.min()
old_range =... | f1266a6d91fe207a454293de30ff7c7603f91bf3 | 673,942 |
def parse_so_terms(so_file):
"""Retrieve all available Sequence Ontology terms from the file.
"""
so_terms = []
with open(so_file) as in_handle:
for line in in_handle:
if line.find('name:') == 0:
name = line[5:].strip()
so_terms.append(name)
return... | c61acbd574701244a4ad9cdca5095e4b12514bda | 673,943 |
def avgTeq(L, a, e=0., albedo=0., emissivity=1., beta=1.):
"""compute the time-averaged equilibrium temperature as in Mendez+2017.
This uses eqn 16 in Méndez A, Rivera-Valentín EG (2017) Astrophys J 837:L1.
https://doi.org/10.3847/2041-8213/aa5f13"
Parameters
----------
L : float
stell... | 994821be5f397cd504bfcb4040e17d066bcaf3ae | 673,944 |
def is_member(user, groups):
""" Test if a user belongs to any of the groups provided.
This function is meant to be used by the user_passes_test decorator to control access
to views.
Parameters
----------
user : django.contrib.auth.models.User
The user which we are trying to identify t... | f1b2acc378900d9f4d53b2a9069531c45e3743b8 | 673,945 |
def move_up(mesh):
"""Navigate one mesh up"""
if len(mesh) == 4:
return str(int(mesh[:2])+1) + mesh[2:]
elif len(mesh) == 6:
mesh2 = mesh[4:6]
if int(mesh2[0]) < 7:
return mesh[:4] + str(int(mesh2[0])+1) + mesh2[1]
else:
return move_up(mesh[:4]) + '0'... | c1638ab504058018e5dc08bee58e851ba39d2631 | 673,947 |
def _UpdateFertileSlotsShape(unused_op):
"""Shape function for UpdateFertileSlots Op."""
return [[None, 2], [None], [None]] | 6332cb6856bf124a1c051c20f7fe227b17cca160 | 673,948 |
def delta_origin(bloat=False):
"""origin is at bottom left (0, 0) of floor plan
(encounter of cafe vertical and gym horizontal)"""
x_cafe = 10
x_hall = 60
x_gym = 17
y_cafe = 1.8
dx = x_cafe + x_hall - x_gym
dy = 0
return dx, dy | 0694c21cc443040393bb0df49159ed02a10e5578 | 673,949 |
def reverse_bit(num):
"""Turn an LSB byte to an MSB byte, and vice versa. Used for SPI as
it is LSB for the PN532, but 99% of SPI implementations are MSB only!"""
result = 0
for _ in range(8):
result <<= 1
result += (num & 1)
num >>= 1
return result | d5bcaaa8af21f8178203b5f8836caebab99b9a9e | 673,950 |
def str2bytes(data):
"""
Converts string to bytes.
>>> str2bytes("Pwning")
b'Pwning'
"""
return bytes(data, encoding="utf-8") | 0e9ef347c245cdf4965e0b594b450ebeebc52a41 | 673,951 |
def _is_mode_enabled(ctx, mode):
"""Check whether a compilation mode is enabled.
Args:
ctx: Rule context.
mode: Mode to check.
Returns:
bool: True if the mode is enabled, False otherwise.
"""
return ctx.var["COMPILATION_MODE"] == mode; | accb0b35d8251c35d0b39ec0319b315ee85331e0 | 673,952 |
def get_max_degree(linked_nodes):
"""get the max degree of the network
Args:
linked_nodes: dict, <node_id, neighbor_nodes>
Returns:
None
"""
max_degree = 0
for key, val in linked_nodes.items():
if len(val) > max_degree:
max_degree = len(val)
return ma... | cad7332e7a42de56625f96b1a0d29bc4dc0b824d | 673,953 |
def command_all_raise_mock(command_mock, dummyapi_instance, request):
"""Mock of _repobee.command where all functions raise expected exceptions
(i.e. those caught in _sys_exit_on_expected_error)
"""
def raise_(*args, **kwargs):
raise request.param
command_mock.setup_student_repos.side_effe... | ce831594f7985d06136b9c0ea03a218007fe18fc | 673,954 |
def parse_cigar(cigar):
"""
parse cigar string into list of operations
e.g.: 28M1I29M2I6M1I46M ->
[['28', 'M'], ['1', 'I'], ['29', 'M'], ['2', 'I'], ['6', 'M'], ['1', 'I'], ['46', 'M']]
"""
cigar = cigar.replace('M', 'M ').replace('I', 'I ').replace('D', 'D ').split()
cigar = [c.replac... | a36d3697d0e44974506bbbd2567c417e861fe6ca | 673,955 |
def getUserData(data):
"""Fetch data from request"""
return (data.get('user_id'), data.get('user_name'), data.get('channel_id')) | 8b3628fdd64a39ca155778c12a87d3a79a32969b | 673,956 |
def rs256_jwks_uri(rs256_domain):
"""
Return a jwks uri for use in fixtures from the armasec pytest extension.
"""
return f"https://{rs256_domain}/.well-known/jwks.json" | f5fca6c4db19ec04c5cae48e700219fb62ad9f79 | 673,957 |
def cal_feed_back_angle(k, x):
"""[summary]
Args:
k ([type]): [lqr k gain]
x ([type]): [state]
Returns:
[type]: [feedback angle]
"""
return (-k @ x)[0, 0] | 3871a3c077e6130a396609be16d4036c4c905124 | 673,959 |
import math
def normalize(val, min_val, max_val):
"""
Normalize the popularity value with log transformation.
"""
new_val = val - min_val + 1
return math.log(new_val) | 011bb397fadf80bc05be80fc02773816e8aff2e1 | 673,960 |
import time
def timing(function):
"""Timing decorator
Decorators allow us to wrap some
`function` with added functionality;
in this case, measuring how much time
the function took to run.
"""
def wrap(*args, **kwargs):
start = time.perf_counter()
ret = function(*args, **kw... | 58612f71685dd657cbe51559f08c936a672d774b | 673,961 |
def black_is_not_installed(*args, **kwargs):
"""Check black is not installed."""
return not args[0] == "black" | 1f6942e529aefbb905fcee67bd315af7f7e8e6a9 | 673,963 |
import os
def checkDsVsDir(ds, ds_dir):
"""
Check loaded dataset with respect to source datset directory
Parameters:
- ds -- dictionary defining dataset to be checked
- ds_dir -- directory with source dataset
Returns:
- number of errors found
"""
_n_errors = 0
for _p, _so... | 57e1ad74e7819f0d835c26c21c3dc53b7502e7fc | 673,964 |
def get_trend(row, window_size, center=True):
"""
Returns trend component of a time series
:param row: pandas series containing the time series to extract seasonality from
:param window_size: length of moving window
:param center:
:return:
"""
trend = row.rolling(window_size, center=cent... | 6c241f595c1ce904bc56dc639358abcdf9ae62e7 | 673,968 |
import torch
def flow_warp_feats(x, flow):
"""Use flow to warp feature map.
Args:
x (Tensor): of shape (N, C, H_x, W_x).
flow (Tensor): of shape (N, C, H_f, W_f).
Returns:
Tensor: The warpped feature map with shape (N, C, H_x, W_x).
"""
assert len(x.shape) == 4
assert... | da9fb03c6a9f80bdeb5e00be59f42a545757866f | 673,969 |
def lengthOfLastWord(s):
"""
:type s: str
:rtype: int
"""
index_list=[i for i in range(len(s)) if s[i] != " "]
if not index_list:
return 0
for i in range(len(index_list)-1,-1,-1):
if index_list[i]-1 != index_list[i-1]:
return index_list[-1]-index_list[i]+1 | 5cfe25f2b8c70975befad773c60e9f7867693b92 | 673,970 |
def _get_prefixes(response):
"""
return lists of strings that are prefixes from a client.list_objects() response
"""
prefixes = []
if 'CommonPrefixes' in response:
prefix_list = response['CommonPrefixes']
prefixes = [prefix['Prefix'] for prefix in prefix_list]
return prefixes | 4f4734d4f8282aea7699bb54fe17991cb339020c | 673,971 |
def interface_to_ip(interface):
"""
Gets the IPv4 address from a `net_if_addrs` interface record.
The record is passed as a `snic` `namedtuple`.
This function locates the IPv4 one and returns it.
"""
for record in interface:
if record.family == 2: # AF_INET
return record.add... | 1ee2ae312c892e11e7abcabcf7846651030215e2 | 673,972 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.