content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _parse_string(s):
"""Parse a string representation of a tree structure (implementation)
Nodes are separated by whitespace, while child lists are enclosed in
balanced parentheses.
Return value is a tuple of (tree_structure, length_in_characters)"""
if '(' not in s:
s, _, _ = s.p... | d347f090c60c0c663ff3d6d778c7977cc2cd84e8 | 635,714 |
def reformatExampleBlock(lines, name):
"""Turn an example block into a verbatim text.
"""
out = [u'::', u'']
out += lines
# safety line
out.append(u'')
return out | 908ed6bbbafa622f7ca62700a016c5fe3d246014 | 635,717 |
def chr_less(chr_left, chr_right, sorted_lex):
"""
Returns true if the left chromosome comes before the right or is the same.
Args:
chr_left = (string) the left chromsome being compared
chr_right = (string) the right chromosome being compared
sorted_lex = true if file sorted lexicog... | 8db132ffcdbfdc585dc8efadd3e2ddc0b8f83dd7 | 635,718 |
from typing import Optional
import re
def get_package_version(
package_xml_path: str,
) -> Optional[str]:
"""
Get a package's version from its package.xml file.
:param package_xml_path: the path to the package's package.xml file
:return: the version, or None if it failed
"""
version = Non... | 2b8bc740232f077601258ff0acca8d91112a28f7 | 635,719 |
def find_subnet_nat_instance(subnet_id, ec2_conn, vpc_conn):
"""
Find the NAT instance for the given subnet
:param subnet_id: The desired subnet
:param ec2_conn: A boto.ec2.connect_to_region() object
:param vpc_conn: A boto.vpc.connect_to_region() object
:return: The NAT instance public IP
"... | 2f071a2962832d1793d45589100835025e69a6e7 | 635,721 |
import json
def eval_functions_dumps(obj):
"""
This is a replacement for json.dumps that
does not quote strings that start with 'function', so that
these functions are evaluated in the HTML code.
"""
if isinstance(obj, str):
if obj.lstrip().startswith("function"):
return ob... | b0ecdb178e401c04753df6a04ec490682e046f68 | 635,726 |
def edge(geom):
"""
return a polygon representing the edge of `geom`
"""
h = 1e-8
try:
geomext = geom.exterior
except:
try:
geomext = geom.buffer(h).exterior
except:
geomext = geom
return geomext | d65d80910e7fe4b2b4b81fe566c705900cdb48d9 | 635,728 |
def prime_sieve(num: int) -> list[int]:
"""
Returns a list with all prime numbers up to n.
>>> prime_sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> prime_sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> prime_sieve(10)
[2, 3, 5, 7]
>>> prime_sieve(9)
[2, 3,... | aec8a9f257f069668f1dda2eaa447dbedb0f85d8 | 635,731 |
from typing import Tuple
from pathlib import Path
def get_relative_and_absolute_paths(path: str) -> Tuple[str, str]:
"""Get relative (if possible) and absolute versions of path."""
absolute_path = Path(path).resolve()
try:
relative_path = absolute_path.relative_to(Path.cwd())
except ValueError... | e4cb546594a425997427cf607a561f78184b0152 | 635,733 |
def getRequestRedirectForRole(entity, role_name):
"""Returns the redirect to create a request for a specific role.
"""
result ='/%s/request/%s' % (
role_name, entity.key().id_or_name())
return result | 62012503b90ed14658c931d83943d896673eb44f | 635,734 |
def run_log_retention_in_days() -> int:
"""How many days to keep node run times, output logs and system statistics"""
return 30 | 33f2e782f50413e56db8e9d977b9fecdd639a118 | 635,736 |
import hashlib
def get_hashed_string(s):
"""Given a string s return a sha1 hashed version"""
return hashlib.sha1(s.encode('utf-8')).hexdigest() | 29be25216bb9c4e74000abdcb94d8dbd3e3b9761 | 635,744 |
def hosts_contain_id(hosts_data, host_id):
"""
True if host_id is id of a host.
:param hosts_data: list of hosts
:param host_id: id of a host
:return: True or False
"""
for host in hosts_data:
if host_id == host['id']:
return True
return False | 23d6cd7da2a0c508564d19135d024700b40ce8c6 | 635,746 |
import re
def validate_gene_sets(genesets, var_names, context=None):
"""
Check validity of gene sets, return if correct, else raise error.
May also modify the gene set for conditions that should be resolved,
but which do not warrant a hard error.
Argument gene sets may be either the REST OTA form... | 0c47b6c5f8674c6d29bfd191af4af4adcbfb7366 | 635,752 |
from typing import Set
def all_subclasses(cls) -> Set:
"""Return all (transitive) subclasses of cls."""
res = set(cls.__subclasses__())
for sub in res.copy():
res |= all_subclasses(sub)
return res | c5bcc25fe4ae6be39f1a458f97f086f88d6b3415 | 635,754 |
import hashlib
def string_to_md5(content):
"""Calculate the md5 hash of a string.
This 'string' can be the binary content of a file too."""
content = content.encode("utf8")
return hashlib.md5(content).hexdigest() | 5a0fe4a35a9c067708439574c6ece1c42746e80a | 635,757 |
def with_request(method):
"""
Decorator to enable the request to be passed as the first argument.
"""
method.with_request = True
return method | 05433aaa34018603a7392094132ef6c8b3c62ddf | 635,758 |
def _GetHoles(i, n, cont, assigned):
"""Find holes for path i: i.e., unassigned paths directly inside it.
Directly inside means there is not some other unassigned path k
such that path such that path i contains k and path k contains j.
(If such a k is already assigned, then its islands have been assign... | b058c077527fb184ef700a7b1104679083074ef8 | 635,759 |
def get_unique_office_name(element=None):
"""Provide an autogenerated unique <office:name> for the document.
"""
if element is not None:
body = element.document_body
else:
body = None
if body:
used = body.get_office_names()
else:
used = []
# unplugged current ... | 0e7cf51241cc3b3be77b15c11fcb8c96f3a20e57 | 635,762 |
def key(row, key_attributes):
"""Return a key for identifying equivalent rows.
Return a key consisting of a tuple of the key attributes for the
row, which should be a dict-like object.
Parameters
----------
row : dict-like
The row for which to create a key.
key_attributes : List[st... | 1a4ce8d1818f48c7e21442e21b07eac0edf43920 | 635,763 |
def get_cluster_status(els):
"""Function: get_cluster_status
Description: Return status of the Elasticsearch cluster.
Arguments:
(input) els -> ElasticSearch instance.
(output) Status of the Elasticsearch cluster.
"""
return els.cluster.health()["status"] | b8f129f3f6f8687b363835492b1420881f96a9b1 | 635,765 |
def convert_words_to_id(corpus, word2id):
"""Convert list of words to list of corresponding id.
Args:
corpus: a list of str words.
word2id: a dictionary that maps word to id.
Returns:
converted corpus, i.e., list of word ids.
"""
new_corpus = [-1] * len(corpus)
for i, wo... | df0e3211a53936a641b3d41dcac01f2e613465fe | 635,772 |
def endfInterpolationLine( interpolation ) :
"""Makes one ENDF interpolation line."""
s = ''
for d in interpolation : s += "%11d" % d
for i1 in range( len( interpolation ), 6 ) : s += "%11d" % 0
return( s ) | d627b4001885ec06dce913aca1b47ee112a9bc17 | 635,773 |
def glob_to_regex(pattern):
"""Given a glob pattern, return an equivalent regex expression.
:param string glob: The glob pattern. "**" matches 0 or more dirs recursively.
"*" only matches patterns in a single dir.
:returns: A regex string that matches same paths as the input glob does.
"""... | 9118549123e298bcf47664e53c13291824083e2c | 635,774 |
def endf_float_str(value):
"""
Return the ENDF format string of a floating point number
Parameters
----------
value : float
A single floating point value
Returns
-------
valstring : str
An ENDF format string of input par `value`
"""
if(abs(value) < 1e-9 or abs(v... | 502c7e777cc15da0ec0a9c033a536cea03306d40 | 635,784 |
def next_permutation(seq):
"""Emulation of C++ std::next_permutation:
Treats all permutations of seq as a set of "dictionary" sorted
sequences. Permutes the current sequence into the next one of this set.
Returns true if there are more sequences to generate. If the sequence
is the largest of the set, the smal... | 3f68b53bb1076d02683e7b0a06aab8cb6a15b2bf | 635,788 |
def condense_into_single_line(text):
"""
Remove all the newlines from a block of text, compressing multiple
lines of HTML onto a single line. Used as a Jinja2 filter.
"""
lines = [line.lstrip() for line in text.split('\n')]
return ''.join(lines) | 17fce92fc19985b4bdb470810d8dcd5df3e2240f | 635,790 |
def get_table_count(connection, table):
"""
Return the number of table entries.
:param connection: A database connection instance
:param str table: Name of the database table
:return: The number of table entries
:rtype: int
"""
sql = 'SELECT COUNT(*) FROM {table};'.format(table=table)
... | 718fb234d8d4869112b3faac2826a6520887d92f | 635,795 |
def _clear_entity_type_registry(entity, **kwargs):
"""Clear the given database/collection object's type registry."""
codecopts = entity.codec_options.with_options(type_registry=None)
return entity.with_options(codec_options=codecopts, **kwargs) | e8901dba01bdebae3415673568cf85c7134a6161 | 635,796 |
def fibonacci2(number: int) -> int:
"""
Generate the fibonacci number for n
Utilizes caching to mimic literal memoization, has lower recursive limit...
0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc
:param number: iteration of the Fibonacci sequence
:return: Fibonacci number
"""
... | ba32daf9b9b56faecda305f50d9e8f5cb7e4c1cb | 635,802 |
def get_tasks_args(parser):
"""Provide extra arguments required for tasks."""
group = parser.add_argument_group(title='tasks')
# parameters for the knowledgeable dialogue generation
group.add_argument('--task', type=str, required=True,
help='Task name.')
group.add_argument("-... | 17f5623c82341e75bf974b295692f6c5c4fbdb9e | 635,806 |
def clean_process_parameters(params):
"""
Removes any null valued parameters before passing them to the extension scripts
:param dict params:
:return: cleaned parameters
:rtype: dict
"""
for key, value in params.items():
if value is None:
del params[key]
return param... | 7c22be0723b46ec5df30ace716459413e3f4b8ee | 635,809 |
def extract_fragment_features_librosa(time_series, start_time, end_time, description, PID, EXP):
"""
Extracts / aggregates features in a certain time period within the time series data
Parameters
----------
time_series: pandas.core.frame.DataFrame
A pandas data.frame for which there is a co... | 5c3b1685dac38ec404f38041eaeb7810a8915675 | 635,813 |
def b64d(n):
"""Return decoded values from a base64 string."""
b64 = n.decode("base64")
return b64 | 3adef2be0e9eeb81b6e6d97625fe2a5e6e142b3c | 635,819 |
def get_writetoinput_filenames(writetofile):
"""
Extract the writeToFile file name(s).
writeToFile='tmpin_mc16_13TeV.blah:AOD.15760866._000002.pool.root.1'
-> return 'tmpin_mc16_13TeV.blah'
:param writetofile: string containing file name information.
:return: list of file names
"""
fil... | 62a7fd2bdb25011204561b63232c48ae550a98f1 | 635,820 |
def pdb(coords, types, a, b, c, alpha, beta, gamma, model=1):
"""
Return string in the protein databank atomic structure format.
Arguments:
coords[i, j] (float): j-th Cartesian coordinate of the i-th atom
types[i] (str): chemical symbol of atom i
a, b, c (float): lenghts of the three latt... | 7bb69e717c14e1a272321f0247d833f4ca9f8405 | 635,825 |
def divisors(num):
"""
Takes a number and returns all divisors of the number, ordered least to greatest
:param num: int
:return: list (int)
"""
divlist = []
counter = 0
for item in range(1, num + 1):
if num % item == 0:
divlist.append(item)
counter = count... | d904273e6e988f8643f39a1fcf45ad9f2699a87a | 635,828 |
def firstNotNone(*args):
"""
Returns first not-None value from a given list of arguments
>>> firstNotNone(None, None, 1, 2, 3)
1
"""
retVal = None
for _ in args:
if _ is not None:
retVal = _
break
return retVal | 450f927a62a460bd26206a44c9bd64d82c9e5666 | 635,832 |
from typing import Optional
from typing import Union
from typing import Sequence
from typing import Tuple
def _get_target_principal_and_delegates(
impersonation_chain: Optional[Union[str, Sequence[str]]] = None
) -> Tuple[Optional[str], Optional[Sequence[str]]]:
"""
Analyze contents of impersonation_chain... | 87fb76f10568b22115a1f671da28d4d35ae947da | 635,834 |
def mean(array):
"""
Returns the mean (average) of a numpy array
:param array: A one dimensional numpy array
"""
return float(sum(array) / max(len(array), 1)) | 43517e91ae838357c5df3a3dc5798825c4c02bde | 635,835 |
def should_quit(string_given) -> bool:
"""
This function determines if the string_given should exit
:param string_given:
:return: Returns if the string is 'q' or 'quit'
"""
return string_given in ['q', 'quit'] | 53ef5055ea4271934962afcb7b27e5eb47c1616b | 635,836 |
def linked_embeddings_name(channel_id):
"""Returns the name of the linked embedding matrix for some channel ID."""
return 'linked_embedding_matrix_%d' % channel_id | da3a095d86add49741fcb15f28059c124e6e7916 | 635,838 |
def hamming_weight(number):
"""Returns the number of bits set in number"""
return bin(number).count("1") | e0be33c5ad03b4a6d8329a680cf6cf56e19ce857 | 635,841 |
def search_for_vertex_at_pos(chromosome, position, location_dict):
""" Given a chromosome and a position (1-based), this function queries the
location dict to determine whether a vertex
fitting those criteria exists. Returns the row if yes, and __ if no.
"""
try:
return location_di... | 38f77b0cbfeb2548908fab6142ebc1b348e1b06b | 635,842 |
import hashlib
def sha256sum(file: str) -> str:
"""
Returns the sha256 sum of a file
:param file: (str) path to file
:return: (str) checksum
"""
sha256 = hashlib.sha256()
try:
with open(file, "rb") as file_handle:
while True:
data = file_handle.read(65... | f2fc1f36faea123fc59e1f7289816dcb9bc731c4 | 635,843 |
def scatter_geo(ds, prop="pressure", stat="count"):
"""
Takes in xarray Dataset and creates a tidy and clean pandas DataFrame for plotting with plotly
Parameters
----------
ds : xarray Dataset
A dataset of aggregated data with a specified format
prop : str, default 'pressure'
... | 8ad34b181df030d370a2014846f53a29b4b1496b | 635,848 |
def compare_rows(row_check, dataframe_check, drop_column="idx"):
"""Find all the matched rows in dataframe_check given a row to check (row_check)"""
# all(1) means that all items of row_check should match with
# rows in dataframe_check except for drop_column
dataframe_matched = dataframe_check[(datafram... | 54c7aca6985d83685b7c205fbeb8ccd5e2861cf0 | 635,852 |
def search_cord_start(xy_cord):
"""
Find at the index of the coordinate corresponding
to the coordinate -11.810 cm in order to exclude
the doses at positions at which there are no detectors
"""
for idx in range(len(xy_cord)):
if abs(xy_cord[idx] + 11.810) < 0.01:
return idx | 0d787c66693a46b68bb400ed32c5fa7d966d8b98 | 635,853 |
def get_trid_isrc_full_con(tr_id, tr_exc, exid2next_dic, nexts_cisrc_dic):
"""
Get intron-spanning read count for transcript with ID tr_id. Also return
if transcript exons are fully connected by intron-spanning reads
(True, False).
tr_id:
Transcript ID
tr_exc:
Transcript exon c... | 3efc5d16e95b4cd98924e25a166b8793df4ae42e | 635,857 |
def aic_scorer(estimator, X, y_true = None) -> float:
"""AIC score for Gaussian Mixture Model Metric
can be used in GridSearch for hyperparameter tuning
:param estimator: must have ``aic`` method which returns aic score
:param X:
:param y_true:
:return: the protocol requires greater the better,... | 1a7a96cd57176992cc032d75a12fc662fa67f66b | 635,860 |
async def read_body(receive):
"""
Read and return the entire body from an incoming ASGI message.
"""
body = b''
more_body = True
while more_body:
message = await receive()
body += message.get('body', b'')
more_body = message.get('more_body', False)
return body | 7a45893cc2ff66a4266af158b9c556b55093d1ff | 635,861 |
def inInfo(item,info,alt='None'):
"""
Checks if item is in given list.
return item if true, else return alt
Args:
item: the item to be compared
info: the list to be checked
alt: alternative output
"""
if item in info:
return info[item]
... | 135b91e25f060e137f6340ff95c0435b8d881d0b | 635,862 |
import re
def extract_features_for_clustering(text):
"""
Extracts the presence of specific word phrase features that are used to
determine the overall structure of the document.
:param text: original report in str form
:return: feature vector
"""
key_phrases = [
'Electronically sig... | 9c5805e7f788b5cefc92364d45b62edfb2b80e4d | 635,863 |
import json
def map_category_names(cat_to_name:str, classes:list) -> list:
"""Map category labels to category names
Args:
cat_to_name: Path to JSON file with category to name mapping
classes: list of predicted classes
Returns:
List of category names
"""
with open(cat_to_n... | bbe9ddfebc4a138ab4d3378275a7559bf6eac70d | 635,867 |
def multiply(string, times):
"""
Repeats a string a given number of times.
:param str string: given string
:param number times: number of repeats
:return str: repeated string
"""
return string * times | dc1df8534d5be18eda66c18e6f005538e42b2078 | 635,869 |
import re
def extract_dependencies(content):
"""Extract dependencies by parsing import statements"""
deps = set()
for line in content.split('\n'):
line = line.strip() # we don't care about indentation
if not (line.startswith("from") or
line.startswith("import")):
... | 39799fa79a30768f4751a0cbc39dadd812d7f893 | 635,871 |
def dict_from_str(s):
"""Convert 'key:value, ...' string to dict."""
d = {}
for item in s.split(','):
key, value = item.split(':')
d[key.strip()] = value.strip()
return d | cce94e0b934ae6ac3ebef3b7ea402b8eddd28477 | 635,874 |
from typing import List
def word_block(text: str, blocked_words: List[str], replace: str = '****') -> str:
"""Replace blocked words in text."""
tmp_string: str = text
for word in blocked_words:
if word in tmp_string:
tmp_string = tmp_string.replace(word, replace)
return tmp_string | edf68c58ee462a23d4a518f71a1a61fbb3f5e5a4 | 635,882 |
from typing import Tuple
from typing import Counter
def generate_checksum_components(box: str) -> Tuple[int, int]:
"""
Generates the checksum components from the string and returns a tuple
indicating whether a character appeared twice or thrice in string. For
example a (1, 1) would indicate that at le... | bcd50361ad37a4973925ea7edb15a4903f619912 | 635,884 |
def identity(label):
"""Identity function that returns the input label.
Args:
label: A `Tensor` or anything that can be converted to a tensor using
`tf.convert_to_tensor`.
Returns:
The input label.
"""
return label | 4a2f09b14510353d419ea2986043bc95cbff76da | 635,885 |
import torch
def smooth_l1_loss(input, target, beta=1. / 9, size_average=False):
"""Smmoth L1 loss, as defined in the Fast R-CNN paper.
Girshick, R. (2015). Fast R-CNN.
"""
diff = torch.abs(input - target)
mask = (diff < beta)
loss = torch.where(mask, 0.5 * diff ** 2 / beta, diff - 0.5 * b... | a5a23f07235a650ddadb16e94644708fcc7c2548 | 635,887 |
import torch
def predict_rating(review, classifier, vectorizer,
decision_threshold=0.5):
"""
Predict the rating of a given review
:param review (str): the text to review
:param classifier (ReviewClassifier): the trained model
:param vectorizer (ReviewVectorizer): The correspo... | 3b7efa77ed64b44b31b87d9587d413726ed05308 | 635,892 |
from typing import OrderedDict
def secondary_settings(structure,form,primary_settings):
"""Return secondary settings, along with sensible default values.
Secondary settings depend on the structure, form,
and possibly primary setting values.
Primary settings are defined by xrsdkit.definitions.structur... | b1d42a6eaf68eee38e1448c6c2bd913df22cbef0 | 635,893 |
import json
def jsonify(obj):
"""Return Python objects as JSON (in bytes)."""
jsonified = "{}".format(json.dumps(obj)).encode()
return jsonified | 2bf3d52554665011863d60f04437ca9d3b52eb6d | 635,894 |
def expected_utility(a, s, U, mdp):
"""The expected utility of doing a in state s, according to the MDP and U."""
return sum(p * U[s1] for (p, s1) in mdp.T(s, a)) | 429e1c8e162206e558b5c61b676bf034dffe5440 | 635,898 |
import uuid
def load_table(service, source_schema, source_csv,
projectId, datasetId, tableId, num_retries=5):
"""
Starts a job to load a bigquery table from CSV
Args:
service: an initialized and authorized bigquery
google-api-client object
source_schema: a valid big... | 11f3a7cbbfbd30e48fe167c9b0bb4f0aae8a80f2 | 635,899 |
def nodes_iter(topology):
"""Get an iterator for all nodes in the topology"""
return topology.nodes_iter() | 66613676ae76d1705c9a45eeb336862d99df2ebe | 635,902 |
def indent(text, prefix=" "):
"""
Return `text` indented using `prefix`.
"""
return "\n".join(prefix + repr(line) for line in text.splitlines()) | 7417aa0fcdfd1e8bb056b4b8d6ccd32a462551c4 | 635,904 |
def format_number(num):
"""Format a number in a string.
>>> format_number(1234567) -> '1 234 567'
>>> format_number(1234.56789) -> '1 234.56' # round with 2 decimals
>>> format_number(None) -> '???'
>>> format_number('not a number') -> 'not a number'"""
if isinstance(num, int):
return f"... | cc7972959f9c0f26a907e91d7342a24465bee3e9 | 635,910 |
from typing import OrderedDict
def remove_repeated_elements(tokens):
""" removes repeated tokens
args:
tokens: a list of tokens
returns:
filtered_tokens: a list of tokens without repeated tokens
"""
filtered_tokens = list(OrderedDict((token, None) for token in tokens))
return f... | b7dd36ea222c29fcbb2bfcc6fe0b0d1150755db5 | 635,912 |
import torch
def gradient_retriever(model):
"""fn to retrieve gradients from model
:param model: torch model
:returns: gradient norm, gradient tensor
:rtype: (float, tensor)
"""
grads = []
grad_norm = 0
for p in model.parameters():
grads.append(p.grad.clone())
grad_no... | 4e60b7746538fdb2e1b52fdaf2ea246cf07f421e | 635,913 |
def alpha (v, dt, dx):
"""
Calculate Courant number, alpha = v*dt/dx.
For 2D, this function can be used if dx=xz
"""
return (v*dt/dx) | 6cde4bb1a7d96a297648f881b44d7c07d2d204f9 | 635,914 |
def funct_worker(input_list,pre_text):
"""
Worker Function: define function that each process should do
e.g. create string from content in input_list while begin with pre_text => "[pre_text] [input_list]
"""
output_string = f"{pre_text}"
output_string = output_string + " ".join(input_list)
... | e28c0bb9d07d6df7c0d88b11869fa58f098825cd | 635,918 |
def _models_count_all_function_name(model):
"""Returns the name of the function get the number of models in the database"""
return '{}_count_all'.format(model.get_table_name()) | 22ea542e640e1b53fefe22d467c2dd852203b8a9 | 635,919 |
def cut_file(source_file, aim_path, chunk_size):
"""
this function will take a source file, cut it into pieces with chunk size
store them to the aim path
return a list of cut names
"""
ori_bin = open(source_file, 'rb')
chunk_list = []
while True:
cur_bin = ori_bin.read(chunk_size... | a3128fccc389da9bae9ccd6cc2b3454fa6505db7 | 635,926 |
def is_datetime(input):
"""
Template tag to check if input is Datetime
:param input: Input field
:return: True if is datetime, False if not
"""
return input.field.widget.__class__.__name__ == "DateTimeInput" | 1b9016a90c363fb9c4a5ce9c180635db3223f5ed | 635,927 |
import math
def get_biorhythms(days_elapsed: int):
"""바이오리듬을 반환합니다.
Args:
days_elapsed: 출생일로부터의 경과일
Returns:
바이오리듬(신체, 감성, 지성)의 튜플
"""
def biovalue(circle, elaspeddays):
"""바이오리듬 값(%)"""
return math.sin(2 * math.pi * elaspeddays / circle) * 100
physical = bi... | 5f284903d38d2e83595a488cda92194b4b6c8005 | 635,932 |
def convert_tokens_to_ids_and_pad(word_pieces, max_length, token_converter):
"""Converts the input tokens to padded ids and mask.
Args:
word_pieces: list of word-piece tokens.
max_length: length sequences should be padded/truncated to.
token_converter: the tokenizer used.
Returns:
word_piece_id... | 86e220c621bec1d2adbe1b865c61a54cb9e6f06c | 635,935 |
def fsextract(string,method):
"""
Extracts the indices or filenames from a comma-separated string
Input Parameters
----------------
string : str
a comma separated string of either file names or file index numbers.
method : {'index','filename'}
'index' if the values passed are ... | 5236976a196c727eb6c9e5e888bafd4973fa0b9f | 635,939 |
def GC_skew(seq, window=100):
"""Calculates GC skew (G-C)/(G+C) for multiple windows along the sequence.
Returns a list of ratios (floats), controlled by the length of the sequence
and the size of the window.
Does NOT look at any ambiguous nucleotides.
"""
# 8/19/03: Iddo: added lowercase
... | 1d6ce6e244de8991834f35b7b039af0594a6227a | 635,940 |
def oxy_umolkg_to_ml(oxy_umol_kg, sigma0):
"""Convert dissolved oxygen from units of micromol/kg to mL/L.
Parameters
----------
oxy_umol_kg : array-like
Dissolved oxygen in units of [umol/kg]
sigma0 : array-like
Potential density anomaly (i.e. sigma - 1000) referenced to 0 dbar [kg/... | 4398ce32cddffdbac2db2de417ed8d4f6c041630 | 635,941 |
def get_exit_event(state, events):
"""Check if a given state has been exited at some point during an execution"""
return next(
(
e
for e in events
if e["type"].endswith("StateExited")
and e["stateExitedEventDetails"]["name"] == state
),
Non... | cf413dfff15b7060cc0d7f6b847231789071413d | 635,943 |
def validate_comparison_operator(comparison_operator):
"""
Validate Comparison Operator for WebACL SizeConstraintStatement
Property: SizeConstraintStatement.ComparisonOperator
"""
VALID_COMPARISON_OPERATORS = (
"EQ",
"GE",
"GT",
"LE",
"LT",
"NE",
... | 825a2f09cc2859613ef05c4da6c2e0b319291ac7 | 635,944 |
def get_device_name_prefix(device_name):
"""Return device name without device number.
/dev/sda1 -> /dev/sd
/dev/vda -> /dev/vd
"""
dev_num_pos = 0
while '0' <= device_name[dev_num_pos - 1] <= '9':
dev_num_pos -= 1
return device_name[:dev_num_pos - 1] | 486397ab516d13eccc3a88a0b8cad3df0e25329f | 635,945 |
import struct
def calc_padding(fmt, align):
"""Calculate how many padding bytes needed for ``fmt`` to be aligned to
``align``.
Args:
fmt (str): :mod:`struct` format.
align (int): alignment (2, 4, 8, etc.)
Returns:
str: padding format (e.g., various number of 'x').
>>> ca... | 8144d8d61334d8126f7fdb2c8bc92f5c438a72ef | 635,948 |
import re
def dep_base(dep):
"""
Strip a dependency of version requirements, for example:
dep_base('foo >= 1.2.3') == 'foo'
:param dep: dependency to strip version from
:return: dep stripped of version requirement (str)
"""
dep = str(dep)
m = re.match(r'([^<>!=\s]+)\s*[<>!=]', de... | dcca1acb1fe8fc219266bac24314cbe723f56804 | 635,954 |
def is_simple_requires(requires):
"""
Return True if ``requires`` is a sequence of strings.
"""
return (
requires
and isinstance(requires, list)
and all(isinstance(i, str) for i in requires)
) | d13c9fe631c32677fbf2be55fd7c048ed566f950 | 635,956 |
import math
def simplify_U(theta, phi, lam):
"""Return the gate u1, u2, or u3 implementing U with the fewest pulses.
U(theta, phi, lam) is the input gate.
The returned gate implements U exactly, not up to a global phase.
Return (gate_string, params, "OpenQASM string") where gate_string is one of
... | c9de34af0e81eac0f43091c177226098c0bdd385 | 635,957 |
import urllib3
def get_wikidata_item(wikidata_id: str) -> bytes:
"""Get Wikidata item structure."""
return urllib3.PoolManager().request(
"GET",
f"https://www.wikidata.org/wiki/Special:EntityData/Q{wikidata_id}.json",
).data | 5461a3a2006b62677c378f90bf6e8a26fdda6735 | 635,958 |
import torch
def get_targeted_classes(model, images, clip, a, b, k=5, case='avg'):
"""
Input:
- model (pytorch model): bagnet model without avgerage pooling
- images (pytorch tensor): a batch of preprocessed images, same context as model's images
- k (int): get targeted classes based on top-K pr... | 1c10c18df3fb79283cdf177f75641a65febdab70 | 635,959 |
import re
def safe_name(string: str) -> str:
"""Returns 'string' with all non-alpha-numeric characters replaced by '_'."""
return re.sub("[^A-Za-z0-9]", "_", string) | 77bd143a63cf63f6259c0dc27d848f628d65fd36 | 635,966 |
from pathlib import Path
import csv
def get_fieldnames_from_csv_file(f_name, encoding='utf-8',
newline='', delimiter=','):
"""
Возвращает список заголовков колонок CSV-файла.
:param f_name: CSV-файл
:param encoding: кодировка CSV-файла
:param newline: newline: new... | 5439593242c70fd05d8e4240d15b5b57dedf4f95 | 635,976 |
def to_int(toks):
""" Parser action for converting strings of digits to int. """
return int(toks[0]) | 82f9374de3b8fb2d4d4da200fe51e0bad0624e77 | 635,978 |
def _get_expression_from_node_if_one_exists(
parsed_node, components_to_check):
"""This function first checks whether the parsed node represents
the required angular component that needs to be derived by checking if
its in the 'components_to_check' list. If yes, then it will return the
expressi... | 7ebe6111eda1f9619462be8d402e33a7aa36230e | 635,979 |
def get_default_token(word2vec_model):
"""
Returns the token from a Word2Vec model to use as a default
for end-of-sequence marking.
"""
return "." if "." in word2vec_model.vocab.keys() else word2vec_model.index2word[0] | 3974935a21a841ae4a2855b8d05ca5870e1493a7 | 635,985 |
def plain_text(node):
"""
Return the plain text of a node with all tags ignored.
This is needed where Doxygen may include refs but Sphinx needs plain text
because it parses things itself to generate links.
"""
if node.tag == "sp":
markup = " "
elif node.text is not None:
ma... | 4f0f846e12e3ea870789b7c6490d281475612377 | 635,994 |
from typing import Callable
def position_features(sentence: str, tokenizer: Callable, vocab: set) -> list:
"""Encodes the relative position of the tokens in :param sentence: as follows:
- 0 for tokens at the beginning of the sentence;
- 1 for tokens in the middle of the sentence;
- 2 for tokens at t... | c809a8591278a6357370a2a42e698a5d055e5553 | 635,995 |
from typing import Callable
def runge_kutta_method_o4(f: Callable[[float, float], float], y0: float, x: list[float], h: float, precission: int = 5) -> float:
"""Finds the value of y(x) for some ODE using Runge Kutta method (order 4).
Params
------
f: Callable[[float, float], float]
function r... | 5f8f19bdf6e565b63d350888bd7b08f36f7d4ee7 | 635,996 |
import re
def clean_for_filename(string):
""" Cleans up string for use in filename """
string = re.sub(r"\[.*?]", "", string) # noqa: W605
string = re.sub('\s+', ' ', string) # noqa: W605
string = string.replace(' : ', ' - ')
string = string.replace(':', '-')
string = string.replace('&', 'an... | 8bb33044b4e29afb780bbcb6e814df6267a3f543 | 635,998 |
def prod(seq):
"""
return the product of all numbers in seq
"""
p = 1
for a in seq:
p *= a
return p | 1a1d8c3cb020a0a2d738cafda25fc797a2b3c8a7 | 636,000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.