content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def cap_case_str(s):
"""
Translate a string like "foo_Bar-baz whee" and return "FooBarBazWhee".
"""
return re.sub(r'(?:[^a-z0-9]+|^)(.)', lambda m: m.group(1).upper(), s, flags=re.IGNORECASE) | a6941c994280eb1564a1d2029d05c43e05925ca7 | 676,112 |
import numpy
def get_utm_code(lng, lat):
"""Return the UTM zone code that contains the given coordinate.
Args:
lng (float): longitude coordinate.
lat (float): latitude coordinate.
Return:
An EPSG code representing the UTM zone containing the given
coordinate. This value i... | 96e6492fc495a00f7e89d55d0d4631465e0d0f61 | 676,113 |
def color_code(rgb):
"""
Provide the ANSI color code for terminal printing.
"""
r05 = int(rgb[0] / 256 * 5)
g05 = int(rgb[1] / 256 * 5)
b05 = int(rgb[2] / 256 * 5)
c_idx = 16 + 36 * r05 + 6 * g05 + b05
return f"\x1b[48;5;255m" + f"\x1b[38;5;{c_idx}m" | ca476594962042b43c85fa1eecf0263cf2d31c22 | 676,114 |
def ndarray_match(x1, x2, as_int=True, verbose=1):
"""
input:
ndarray_match(x1, x2, True, 1)
print: return:
x1[4]==x2[4] { 4: 4,
x1[11]==x2[99] 11: 99}
"""
if as_int:
x1=x1.astype(int)
x2=x2.astype(int)
lis... | 4217d5fcb2156889a73e87888f44a581c7b9879d | 676,116 |
def transfer_mac(mac):
"""Transfer MAC address format from xxxx.xxxx.xxxx to xx:xx:xx:xx:xx:xx"""
mac = ''.join(mac.split('.'))
rslt = ':'.join([mac[e:e + 2] for e in range(0, 11, 2)])
return rslt | 09cf5e33f24c6052cb3c45c8a8c26431f17abb5c | 676,117 |
def safe(board: list[list[int]], row: int, col: int) -> bool:
"""
Fungsi ini mengembalikan nilai boolean True jika aman untuk menempatkan
ratu di sana Mempertimbangkan keadaan saat ini.
Parameter: board(matriks 2D) : papan baris ,
kolom : koordinat sel pada papan Kembali: Nilai Boolean
"""
f... | 4aff85ac74df719403ba0760b5e36722477b9988 | 676,118 |
def make_name(key):
"""Return a string suitable for use as a python identifer from an environment key."""
return key.replace('PLATFORM_', '').lower() | 9b7167025a60958b20939c17cc7ad18084e4d4ee | 676,119 |
def get_crowd_selection_counts(input_id, task_runs_json_object):
"""
Figure out how many times the crowd selected each option
:param input_id: the id for a given task
:type input_id: int
:param task_runs_json_object: all of the input task_runs from json.load(open('task_run.json'))
:type task_r... | 83fc32c0426aaa20055924337048bbac35f9f00d | 676,120 |
def _GetSupportedApiVersions(versions, runtime):
"""Returns the runtime-specific or general list of supported runtimes.
The provided 'versions' dict contains a field called 'api_versions'
which is the list of default versions supported. This dict may also
contain a 'supported_api_versions' dict which lists ap... | a6136ae1cc2ecf6e7068b80c9f6d968dfbcddf2d | 676,121 |
def redundant_list():
"""
"""
return [[1.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | 8d7b87ceff46c18604bcf7da48400519f313d71a | 676,122 |
import os
def load_text(name_file):
""" load mail-template text
:param str name_file: name of the file, assuming to be in the same folder
:return str: text
"""
with open(os.path.join(os.path.dirname(__file__), name_file)) as fp:
text = fp.read()
return text | 630863611ee6337eb79fd0a80947cf4cfda41e7c | 676,123 |
def unpack_list(reader, deserializer):
"""
The deserializer function should take an OFReader and return the new object.
"""
entries = []
while not reader.is_empty():
entries.append(deserializer(reader))
return entries | 9c05105ac778279b382a915ad685ad24d8ad5373 | 676,124 |
def build_hugo_links(links: list) -> list:
"""
Extens the passed wiki links list by adding a dict key for the hugo link.
"""
for link in links:
link['hugo_link'] = f'[{link["text"]}]({{{{< ref "{link["link"]}" >}}}})'
return links | 98bad831be77545505a2dba92ba84548d91378a2 | 676,125 |
import os
def project_id_batches():
"""Returns the project id that contains batches."""
return os.getenv("GENCOVE_PROJECT_ID_BATCHES_TEST") | b55f7414d0006b72ec8bd9b62bda28007e68221c | 676,126 |
def genes_by_alias(hgnc_genes):
"""Return a dictionary with hgnc symbols as keys
Value of the dictionaries are information about the hgnc ids for a symbol.
If the symbol is primary for a gene then 'true_id' will exist.
A list of hgnc ids that the symbol points to is in ids.
Args:
hgnc_gene... | df7192ec24fb97a4ca8996683cf5644c75887a29 | 676,127 |
def _is_digit_power_sum(number: int, power: int) -> bool:
""" Returns whether a number is equal to the sum of its digits to the given power """
return number == sum(d ** power for d in map(int, str(number))) | 82b7347c4886a8133a9f50809214f61d8f56f40e | 676,128 |
def get_achievement(dist):
"""Получить поздравления за пройденную дистанцию."""
# В уроке «Строки» вы описали логику
# вывода сообщений о достижении в зависимости
# от пройденной дистанции.
# Перенесите этот код сюда и замените print() на return.
if dist >= 6.5:
return 'Отличный результа... | c71a804806322e24dd0c4ac4ab6524ac15dd9552 | 676,129 |
def solucion(source: str, target: str, steps: int = 6, take: int = 2) -> str:
"""Toma una cantidad determinada de valores de una cadena fuente
y las inserta en un número determinado de posiciones de la cadena
destino.
:param source: Cadena de texto fuente de la cual tomar valores
:type source: str... | b09abeca49686d3e84c7af137538e7212935a6cd | 676,130 |
def support(node):
"""Get support value of a node.
Parameters
----------
node : skbio.TreeNode
node to get support value of
Returns
-------
float or None
support value of the node, or None if not available
Notes
-----
A "support value" is defined as the numeric... | 788814d06d02cdbfdf5803e231dd0bb56e4ea06e | 676,131 |
def merge_sort(sorted_l1, sorted_l2):
""" Merge sorting two sorted array """
result = []
i = 0
j = 0
while i < len(sorted_l1) and j < len(sorted_l2):
if sorted_l1[i] < sorted_l2[j]:
result.append(sorted_l1[i])
i += 1
else:
result.append(sorted_l2[... | 4ffc22f57f70dc23f4e12cb359f4b3b3fc4fd65b | 676,133 |
def distanceBetweenStrings(needle, haystack):
"""Calculates the fuzzy match of needle in haystack,
using a modified version of the Levenshtein distance
algorithm.
The function is modified from the levenshtein function
in the bktree module by Adam Hupp"""
doesLevenshteinModuleExist = Fa... | 8f679bfb05bf653ec596dc6dadc5279b8f5ab5c9 | 676,134 |
import re
def xml_to_table(s, root, row):
# pylint: disable=line-too-long
"""
>>> xml_to_table('<?xml version="1.0" encoding="UTF-8" ?><response><action><row><a>1</a><b>2</b></row><row><a>3</a><b>4</b></row></action></response>','action','row') # noqa
[{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}]
"... | a8f3df86a35f55df2e2589bc77a203b78a00d39e | 676,136 |
def construct_html(search_term, results):
"""
Given a list of results, construct the HTML page.
"""
link_format = '<a href="{0.img_url}"><img src="{0.thumb_url}" alt="{0.name}" title="{0.name}"></a>'
html_links = '\n'.join([link_format.format(result) for result in results])
html_output = (
... | 8e77abdf3d18fc8eeb9795847d5565c951762e24 | 676,137 |
def readtxt(ftxt_to_read):
"""
This routine read a text file and put the information in a python dictionary
that is returned.
"""
dictfile={}
dictfile["fpath"] = ftxt_to_read
nlin=0
try:
ftxt=open(ftxt_to_read,"r")
llist = ftxt.readlines()
nlin=len(llist)
dictfile["nlin"]=nlin
dictfi... | 5d88c8e36f926eb8df1fa9df1cfeab322f67dfaa | 676,138 |
def split_by_comma(s):
""" Split a string by comma, trim each resultant string element, and remove falsy-values.
:param s: str to split by comma
:return: list of provided string split by comma
"""
return [i.strip() for i in s.split(",") if i] | eb8a5dd0353addeae55cd85e30e5b0e18c661a8d | 676,139 |
def Use(name): # real signature unknown; restored from __doc__
"""
Use(name: str) -> object
Use(name) -> module
Attempts to load the specified module searching
all languages in the loaded ScriptRuntime.
Use(path: str, language: str) -> obje... | e72f99dd98f45fc4cfa1d7b252d66360ca17b2ad | 676,140 |
from typing import Union
import os
def _get_ext(x: Union[str, os.DirEntry]):
"""Parse extensions from filepath
(Note) Return without starting '.'.
Examples:
>>> x = 'dir/filepath.jpg'
>>> _get_ext(x)
'jpg'
Args:
x (str, list): Filepath to parse.
Returns:
... | accead5283a748cf26157ac31dc3f4815ab6c39b | 676,141 |
def compute_resource_attributes(decos, compute_deco, resource_defaults):
"""
Compute resource values taking into account defaults, the values specified
in the compute decorator (like @batch or @kubernetes) directly, and
resources specified via @resources decorator.
Returns a dictionary of resource ... | bbc02bfb4dab6bc4825b326f166b2a4d63bfc69d | 676,142 |
from typing import Dict
from typing import Union
from typing import Any
def expand_dict(
d: Dict[str, Union[Any, Dict]],
ignore_underscore=False
) -> Dict[str, Any]:
"""
Распаковывает вложенный dict
Examples
-------
>>> expand_dict(
... {'key1': 'value1', 'key2':{'... | e116dc5b8ca6539e9323f03cdaaf6e163f937203 | 676,143 |
import glob
def get_file_list(file_type):
"""
Returns a list of all files to be processed
:param file_type: string - The type to be used: crash, charges, person, primaryperson, unit
:return: array
"""
return glob.glob("/data/extract_*_%s_*.csv" % file_type) | f8d4d63348b1abc61e566698fa70b04da63fab89 | 676,144 |
def _ns(obj, search):
"""Makes searching via namespace slightly easier."""
return obj.xpath(search, namespaces={'aws':'http://www.aws.com/aws'}) | 488f1bf232b9acc5aa3ee801721776ca824e0930 | 676,145 |
def clustering(cloud, tol, min_size, max_size):
"""
Input parameters:
cloud: Input cloud
tol: tolerance
min_size: minimal number of points to form a cluster
max_size: maximal number of points that a cluster allows
Output:
cluster_indices: a list of list. Each element ... | dc12cee3a359eb6dda07ab3f5888d74d21182150 | 676,146 |
def ExtractFeatureImp(featureImp, dataset, featuresCol):
"""
From an index based importance list, to a feature label based importance list.
"""
list_extract = []
for i in dataset.schema[featuresCol].metadata["ml_attr"]["attrs"]:
list_extract = list_extract + dataset.schema[featuresCol].metad... | abfac032d4bf6687febdaee9a4384276ca203d83 | 676,147 |
def findInEdges(nodeNum, edges, att=None):
"""
Find the specified node index in either node_i or node_j columns of input edges df.
Parameters
----------
nodeNum : int
This is the node index not protein index.
edges : pandas dataframe
Dataframe in which to search for node.
R... | 83ffce762bf660c33787f58c0d132f8a38cf8db9 | 676,148 |
from functools import reduce
def deepGetAttr(obj, path):
"""
Resolves a dot-delimited path on an object. If path is not found
an `AttributeError` will be raised.
"""
return reduce(getattr, path.split('.'), obj) | 9029369c204e78184066032bd2b264d2af758da5 | 676,149 |
def documents(pmid_16384925, pmid_27819322):
"""Create test fixture for documents."""
return [pmid_16384925, pmid_27819322] | 652d6d000a94049694516a0cd1dcb5a6a2574bc5 | 676,150 |
import os
def plugin_dir() -> str:
"""Return the location of the plugin dir for errbot."""
return os.path.dirname(__file__) | 0a2f6a0126e165417f8c659b6bc304c8d997e27f | 676,151 |
import os
def process_directory_paths():
""" Process directory paths core """
while True:
ddg_path = input("Enter full path of com.duckduckgo.mobile.android: ")
if os.path.exists(ddg_path):
if ddg_path[-1:] != '/':
ddg_path += '/'
break
else:
... | ca00cf70d4915ca25a6304347c94bedea1be776f | 676,152 |
def tokenize(sent, bert_tok):
"""Return tokenized sentence"""
return ' '.join(bert_tok.tokenize(sent)) | c955114fb98a62e42e0b6d3fbef0822514dd30e6 | 676,153 |
def get_mask_from_lengths(memory, memory_lengths):
"""Get mask tensor from list of length
Args:
memory: (batch, max_time, dim)
memory_lengths: array like
"""
mask = memory.data.new(memory.size(0), memory.size(1)).byte().zero_()
for idx, l in enumerate(memory_lengths):
mask[id... | 129feda0dabdc5d3b264e82b4fb417723baba31c | 676,154 |
import platform
import os
def getBinaryDir():
"""Get the directory where the RenderDoc binaries is located. This is platform specific"""
platform_dir = {
"Windows": {
"32bit": "win32",
"64bit": "win64",
},
"Linux": {
"32bit": "linux32",
"64bit": "linux64",
},
}[platform.system()][platform.archi... | 1e41083fdce79971858e06c11de1550425ee3636 | 676,155 |
def filter_bolts(table, header):
""" filter to keep bolts """
bolts_info = []
for row in table:
if row[0] == 'bolt':
bolts_info.append(row)
return bolts_info, header | 5f3c85a75064a61016bb2afc95a2fb7e1f6cbc2d | 676,157 |
import os
import logging
def sort_results_files(file_list):
"""This function classifies the benchmarks as being "key" or "full"
Args:
file_list (list) - List of full paths to individual benchmark
results files
Returns:
bm_files (list) - List of full paths to benchmark files that ... | 37fe92b88148d4925118aa4cb8bc281d695a0008 | 676,158 |
import numpy
def mw(moment, units='mks'):
"""
Moment magnitude
"""
if units == 'mks':
m = (numpy.log10(moment) - 9.05) / 1.5
else:
m = (numpy.log10(moment) - 16.05) / 1.5
return m | affad6b0a0cceaedd2716d088b2a94d7d78d3a61 | 676,159 |
def stemmer_filter(tokens):
"""
из-за грамматических правил в документах встречаются разные формы слов. стемминг сводит их к основной форме
:param tokens:
:return: возвращет список токенов приведенных к основной форме
"""
result_tokens = tokens
return result_tokens | a0e05dc0f9c13ed91e8df0e382437e9b2080fabb | 676,160 |
import math
def _get_burst_docids(dtd_matrix, burst_loc, burst_scale):
"""
Given a burst and width of an event burst, retrieve all documents published within that burst, regardless of
whether they actually concern any event.
:param dtd_matrix: document-to-day matrix
:param burst_loc: location of t... | f51c98678b6c6ffc38fa95f4fd721d19d634529e | 676,162 |
def split_by_commas(string):
"""Split a string by unenclosed commas.
Splits a string by commas that are not inside of:
- quotes
- brackets
Arguments:
string {String} -- String to be split. Usuall a function parameter
string
Examples:
>>> split_by_commas('foo, bar(ba... | 8f9c63a1bc4f491d2810b6c701d84bfe00941be8 | 676,163 |
def drop_null_values(df):
""" Drop records with NaN values. """
df = df.dropna()
return df | 2b695f39191267133d70be7c8f8b1b4c4f9307aa | 676,164 |
def run_checks(checks):
"""
Run a number of checks.
:param tuple checks: a tuple of tuples, with check name and parameters dict.
:returns: whether all checks succeeded, and the results of each check
:rtype: tuple of (bool, dict)
"""
results = {}
all_succeeded = True
for check, kwar... | 1a689676f291672112beee784a2440fbeb8db91c | 676,165 |
import torch
def super_concatenate(tensor1, tensor2):
"""
Args:
tensor1: [batch_size,seq_len,hidden1]
tensor2: [batch_size,seq_len,hidden2]
Returns: [batch_size,seq_len,seq_len,hidden1+hidden2]
"""
# batch_size,seq_len,hidden1 -> batch_size,seq_len,seq_len,hidden1
seq_len = ... | 2d8bf867c17bdc9e9e9af38fd4ed8109390ede61 | 676,166 |
import pickle
def read_raw_results(results_file):
"""
Read the raw results from the pickle file.
Parameters:
- results_file: the path to the pickle file.
Return:
- results: a dictionary of objects.
"""
results = None
with open(results_file, 'rb') as f:
results = p... | 66ac92d22a77667c63c0598e917205a590df9ce6 | 676,167 |
def cast_none(s :str):
"""
Cast a string into None if possible.
Args:
s: The input str.
Raises:
ValueError: if the cast cannot be achieved.
Returns:
None if successful.
"""
if s is None:
return None
elif isinstance(s, str) and s.lower() == "none":
... | 056ec0f5bce303f5e85420331a8601214f83c5a2 | 676,168 |
import calendar
def totimestamp(value):
"""
convert a datetime into a float since epoch
"""
return int(calendar.timegm(value.timetuple()) * 1000 + value.microsecond / 1000) | 6e41f9f23098f3e12d9d7d906e965ae3ba6f0daa | 676,170 |
import json, collections
def deserialize_json(filename): #pragma: no cover
"""Returns the JSON object from the file with the specified filename.
Args:
filename: The name of the file containing the JSON data to deserialize.
Returns:
dict: A dictionary containing the deserialized JSON data... | 483037731091e368afcb81830f881c3239090bcf | 676,171 |
import logging
import sys
def logger_has_stdeo(logger: logging.Logger) -> bool:
"""Check whether logger has stdout or stderr in its handlers."""
for handler in logger.handlers:
if hasattr(handler, "stream") and handler.stream in (sys.stdout, sys.stderr): # type: ignore
return True
ret... | 8638383b5010c6c55c9c03aebe153f62c08fb0b2 | 676,172 |
import os
import pathlib
def resource_root():
"""Get the path to the test resources directory."""
if not os.environ.get("ARROW_TEST_DATA"):
raise RuntimeError("Test resources not found; set "
"ARROW_TEST_DATA to <repo root>/testing/data")
return pathlib.Path(os.environ["... | a75df214b63c1a25de2a27364be7fdc98498e7b5 | 676,173 |
import os
def verify_bulk_loaders_filefilter(ldir):
"""
Prepare file names for :func:`verify_bulk_loaders`.
:param ldir: Directory to use.
:type ldir: str
"""
files = [os.path.join(ldir, file) for file in os.listdir(ldir) if not os.path.isdir(file)]
return files | 83b355d1c6c029a966a12ab6fd548fc0c16c2547 | 676,174 |
def error_format(search):
"""
:param search: inputted word
:return: bool.
Checking every element in the inputted word is in alphabet.
"""
for letter in search:
if letter.isalpha() is False:
return True | 3b6f6778cfe41e8a2e535f4fce71a7df602bced5 | 676,175 |
def default_config():
"""
- path: path to executable
- name: name of aerofoil
- profile/type: name of profile type, valid values '4', '4A', '6?', '6A'
- camber/type: camber type, valid values are '0', '2', '3', '3R', '6' and '6A'
- camber/max_fraction: maximum camber as fraction of chord
- c... | 06c202c5d7fd80d145519c01bc543ca0471e4ee5 | 676,176 |
def sqrt(x):
"""
Calulate the square root of argument x
"""
# Intitial guess for the square root
z = x / 2.0
#Continuously improve guess
while abs(x - (z*z)) > 0.0000001:
z = z - ((z*z -x) / (2*z))
return z | d26a4003e495a7aa096798b3f654be758b558c86 | 676,177 |
import glob
import os
def make_fiphot_list(searchdirs,
searchglob,
listfile):
"""
This makes a list of fiphot files in the list of directories specified in
searchdirs, using the searchglob to filter by filename. Returns a list of
absolute paths to the fiphot f... | a8489f8010bc667b0236e6a75cf19ebe62973264 | 676,178 |
def get_command_for_log(infasta,
minlen,
maxlen,
procs,
single_mode,
chunk_size,
strand,
starts,
stops,
table,
include_stop,
partial3,
partial5,
bw_stops,
longest,
byframe,
ign... | b2345eea73c6b275d43bde0c829294109aa0b846 | 676,179 |
import re
def from_dms(dms_string):
"""
Converts a string from sexagesimal format to a numeric value, in the same
units as the major unit of the sexagesimal number (typically hours or degrees).
The value can have one, two, or three fields representing hours/degrees, minutes,
and seconds respective... | 88e43206d774327f1637431f044f13a1402d30e3 | 676,180 |
def qualify_name(name_or_qname, to_kind):
"""
Formats a name or qualified name (kind/name) into a qualified
name of the specified target kind.
:param name_or_qname: The name to transform
:param to_kind: The kind to apply
:return: A qualified name like: kind/name
"""
if '/' in name_or_qn... | 2d12ac771fcee2ba75cfbdd056daef0900ba43d8 | 676,181 |
def evaluate_dirty_delta(df_delta, df_mask, attrs=None):
"""
:param df_delta:
:param df_mask:
:param attrs:
:return: attr_mean_dict, group by dirty/clean
"""
if attrs is None:
attrs = list(df_delta.columns)
df_delta[attrs] = abs(df_delta[attrs])
attr_mean_dict = {}
for... | 8aa6383d74ab7690d039672d371c3ae8c7effaf5 | 676,183 |
import typing
def linear_search(arr: typing.List[int], target: int) -> int:
"""
Performs a linear search through arr. This is O(N) as worst case the last element in arr
will need to be checked
:param arr: The sequence of integers
:param target: The target number to retrieve the index of.
:ret... | f5cd7d779e38e36a07559c6ac9a27ac59451c568 | 676,184 |
import signal
def timeout(duration):
"""
A decorator to force a time limit on the execution of an external function.
:param int duration: the timeout duration
:raises: TypeError, if duration is anything other than integer
:raises: ValueError, if duration is a negative integer
:raises Timeo... | 2a33ee56e97ecfdca1f424d5223c9767a3cab81b | 676,185 |
import math
def Hellinger_distance(P, Q):
"""
Hellinger_distance between two probability distribution.
"""
dist = 0.0
for p, q in zip(P, Q):
dist += (math.sqrt(p) - math.sqrt(q)) ** 2
dist = math.sqrt(dist)
dist /= math.sqrt(2)
return dist | 735330780508502e2681d13807d76a36d6cb03e8 | 676,186 |
import math
def distance(x0, y0, x1, y1):
"""Return the coordinate distance between 2 points"""
dist = math.hypot((x1-x0),(y1-y0))
return dist | ece17d5c5449df8c368e279cb0f7ff937c54343d | 676,187 |
def safe_cast(val, to_type, default=None):
"""Safely cast value to type, and if failed, returned default if exists.
If default is 'None' and and error occurs, it is raised.
Args:
val:
to_type:
default:
Returns:
"""
if val is None:
return default
try:
... | 2a654367a739394787408cfa26f317704295fb03 | 676,188 |
def r_squared(measured, predicted):
"""Assumes measured a one-dimensional array of measured values
predicted a one-dimensional array of predicted values
Returns coefficient of determination"""
estimated_error = ((predicted - measured)**2).sum()
mean_of_measured = measured.sum()/len(m... | ae61d447502af92adb289f0e3229657b749833a8 | 676,189 |
def compute_gcvf(sdam: float, scdm: float) -> float:
"""
Compute the goodness of class variance fit (GCVF).
:param sdam: Sum of squared deviations for array mean (SDAM)
:param scdm: Sum of squared class devations from mean (SCDM)
:return: GCVF
Sources:
https://arxiv.org/abs/2005.01653
... | 9a0fba7b949593c14e6cd0a441facc6001f626bd | 676,191 |
def bind(func, *args):
"""
Returns a nullary function that calls func with the given arguments.
"""
def noarg_func():
return func(*args)
return noarg_func | 3d83c66de52b9493919a7d64a63bf9fe01889f23 | 676,192 |
def get_slice(index):
"""Returns a slice converted from index."""
if index == -1:
return slice(0, None)
if isinstance(index, int):
# return slice(index, index+1)
return index
if isinstance(index, tuple):
return slice(index[0], index[1])
if isinstance(index, slice)... | 01930aa968a7010d433ce846e97ded9079861f10 | 676,193 |
import logging
def logging_fx(caplog) -> logging.Logger:
"""
Calls config.setup_logging with a test_log.log file for testing purposes.
:return:
"""
caplog.clear()
return logging.getLogger("mecha.logging_fx") | 986fcdd53166156cf8913434e67a381e12b74823 | 676,194 |
def read_fasta(fasta):
"""
Read the protein sequences in a fasta file
Parameters
-----------
fasta : str
Filename of fasta file containing protein sequences
Returns
----------
(list_of_headers, list_of_sequences) : tuple
A tuple of corresponding lists of protein desc... | a7e3d3a5dda7d76c66d9ceda57bd53956b84b978 | 676,195 |
def fill_dict_cols(collection):
"""
Convert the collection, which is a dictionary in which the keys are column names
and the values are the columns
"""
result = {}
max_length = 0
for col in collection:
result[col] = collection[col]
if len(collection[col]) > max_length:
max_length = len(collect... | 00c77eea8150bdff8c88e7e66d38c4912878ad84 | 676,196 |
def _jupyter_nbextension_paths():
"""
Jupyter nbextension location
"""
return [dict(
section="notebook",
src="ipython/nbextensions",
# directory in the `nbextension/` namespace
dest="nodebook",
# _also_ in the `nbextension/` namespace
require="nodebook/nod... | 1f5d5070d194f413415318bf568720e5c634d625 | 676,197 |
import csv
def get_taxonomy_results(filepath):
"""Extract the taxonomy results
filepath: path with csv with option description
"""
taxonomy_results = {}
with open(filepath, "r") as f:
reader = csv.DictReader(f, delimiter=';')
for row in reader:
result = row["Result"]
... | 69ee4f79669687ce05b76877477d15f9242983b6 | 676,198 |
def get_service_at_index(asset, index):
"""Gets asset's service at index."""
matching_services = [s for s in asset.services if s.index == int(index)]
if not matching_services:
return None
return matching_services[0] | 2a8e89b63cf8ce3f97226d7c281c8c8318409567 | 676,199 |
def cut_trailing_quotes(text: str) -> str:
"""Cut trailing quotes into one quote.
Args:
text: Input text.
Returns:
Text up to the dangling double quote.
"""
num_quotes = text.count('"')
if num_quotes == 1:
return text.replace('"', "")
elif num_quotes % 2 == 0:
... | 1a2e8c5d212559ff421c9bdbf2858145eb349ca6 | 676,200 |
def count(pets):
"""Return count from queryset."""
return pets.count() | c4e16693a7515765e09631a4f911a173906e21ac | 676,201 |
def gene_wise_compare(n_bed, u_bed, n_dict,u_dict):
"""
:param n_bed: bed coords in which genes are compared
:param u_bed: bed coords in which genes are compared
:param n_dict: dict with gene id as key value and [percent id,...] as return value.
:param u_dict: same as above.
:return: 2forma... | 54c58e9ea003066a4ebf8963a468a60c9b63dac8 | 676,202 |
import math
def length (v):
""" Length of a vector in 2-space.
Params: v (2-tuple) vector in 2-space
Returns: (float) length
"""
# INSERT CODE HERE, replacing 'pass'
x,y = v[0],v[1]
return math.sqrt ((x**2) + (y**2)) | 07f51cf0e10d2e3567cbe0bb77cc6f3ddedc3b0f | 676,203 |
def _convert_to_F(temp: float) -> float:
"""
Convert C temp to F
param temp: temp in C to convert
return: float
"""
return round((temp * 9/5) + 32, 1) | 5fb80640b0c216c206a15c2cf08c434bc7601c30 | 676,204 |
def descending_coin(coin):
"""Returns the next descending coin in order.
>>> descending_coin(25)
10
>>> descending_coin(10)
5
>>> descending_coin(5)
1
>>> descending_coin(2) # Other values return None
"""
if coin == 25:
return 10
elif coin == 10:
return 5
... | 72857bf5b41789f56862d4acb30a9cf7130761b6 | 676,205 |
import os
def join_warps(reference,affine_fs_2_anat,affine_anat_2_atlas,warp_anat_2_atlas):
"""
join warps to align freesurfer output to atlas
"""
# get the current working directory
cwd = os.getcwd()
# just set the output name for the freesurfer concatenated transform
fs_concat_tran... | dd35d80e034a8219201953339208c3f18d6007d5 | 676,206 |
def _ds_or_none(ds):
"""return none if ds is empty"""
if any(ds.coords) or any(ds.variables) or any(ds.attrs):
return ds
return None | d873815512527e5b58945ebec1e414864b5d2a19 | 676,207 |
def _set(data, name, value):
"""Safely set data attribute."""
if not value:
return False
if value == '-':
value = None
data[name] = value
return True | 433154ca76d845262edf458e335079a4e8df1bb4 | 676,209 |
import functools
def feature_decorator(function, ctx=None):
"""
A decorator that adds a context to a function call.
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
if ctx:
kwargs['ctx'] = ctx
return function(*args, **kwargs)
return wrapper | 01ef941d3cbc5836e846bbf012770a6ebb20bcd2 | 676,210 |
def get_section(soup, attrs={}, name='div', all=False):
"""
gets the bs4.element.Tag (or list thereof) of a section specified by the attrs (dict or list of dicts)
"""
if all==False:
if isinstance(attrs,dict):
return soup.find(name=name, attrs=attrs)
else:
tag = so... | 810dc2b433a31c04788073ee7caa05862751ba35 | 676,211 |
from typing import Callable
from typing import Any
def assert_and_pass(func: Callable, arg: Any):
"""Call ``func``` with ``arg`` and return ``arg``. Additionally allow arg
to be ``None``.
Args:
func: Test function.
arg: Function argument.
Returns:
Result of ``func(arg)``... | fae696f07b1d567b648fa32b3f2291e79b8550c7 | 676,212 |
def cut(list_, index=0):
"""Cut a list by index or arg"""
if isinstance(index, int):
cut_ = lambda x: x[index]
else:
cut_ = lambda x: getattr(x, index)
return list(map(cut_, list_)) | 91ca3c4c4108b4fece2732a74a9107ec9788edb9 | 676,213 |
def type_name(obj):
"""Fetch the type name of an object.
This is a cosmetic shortcut. I find the normal method very ugly.
:param any obj: The object you want the type name of
:returns str: The type name
"""
return type(obj).__name__ | 080f4826de4af3c5f14e08973003416e37ae8dd0 | 676,214 |
from typing import Generic
from re import T
def filter_by_organization(model: Generic[T], organization_id: str) -> QuerySet: # type: ignore
"""
Filters active resources that belong to an organization.
Args:
model (Generic[T]): Model that is going to be queried.
organization_id (str): ID ... | a8c7f2144f451f3f0950c112744a853f099f1337 | 676,215 |
import os
def get_safe_mode():
"""
Make Spyder use a temp clean configuration directory for testing
purposes SPYDER_SAFE_MODE can be set using the --safe-mode option.
"""
return bool(os.environ.get('SPYDER_SAFE_MODE')) | 7a59963f5f8b9e48b925f49f5d536da3e2f3150e | 676,216 |
import argparse
import os
def create_parser():
"""
Creates parser for setting bot's token via a cmd argument
"""
parser = argparse.ArgumentParser()
parser.add_argument('token', nargs='?', default=os.environ["token"])
return parser | 5dd4a4b99b80168ae7d68831e49b514f818a62b1 | 676,217 |
import torch
def pad_feature_map(feature_map: torch.Tensor, padding_size: int):
"""Zero-pad feature map by a constant padding margin.
Args:
feature_map: The map to extract features from.
padding_size: The padding size.
"""
return torch.nn.ConstantPad2d(padding_size, 0.0)(feature_map) | 0e5d08f31c958ac70ff219bf8fb6bf34ae3f9557 | 676,218 |
def MakeNormalisedSpectrum(inputdata, name):
"""
Normalise spectrum by the number of events and by the bin width
"""
inputdata.SetVertexRange(-10., 10.)
inputdata.SetPileupRejection(True)
inputdata.SelectTrackCuts(1)
return inputdata.MakeProjection(0, "ptSpectrum%s" %(name), "p_{t} (GeV/c)",... | 07c65ea6c6776701a8c4b9211f8502b94fa1e55e | 676,219 |
import os
import shutil
def initialize_repository(project, clear_first=True):
""" Initialize a repository for the project with the given id.
:param project_id: id of the project
:param clear_first: if true and the directory already exists, it will be removed first
:raise: Project.DoesNotExist
"""
... | 4eb390f180fdb8e38d25f519d9c7370b026c59fd | 676,221 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.