content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def validar_correo(usuario: str, dominio: str = '@calufa.com') -> bool:
"""Función que valida si un correo electrónico pertenece al dominio
calufa.com
:param usuario: correo electrónico a validar
:type usuario: str
:param dominio: dominio a validar
:type dominio: str
:return: True si perten... | 46af169b1045347a05927afd9b4d3db70e53b8f3 | 649,838 |
import torch
def compute_dihedrals(xyz, particle_index):
""" Compute dihedral angles between sets of four particles.
Parameters:
-----------
xyz: torch.Tensor
input tensor of shape :math:`(\text{frames} , \text{particles} , 3)`
particle_index: torch.LongTensor
particle index tens... | 67294f93b3237b3e1e37b8b4484cb1bf78bfe1c9 | 649,841 |
def degdiff(angle1, angle2):
"""
The difference of two angles given in degrees. The answer is an angle from
-180 to 180. Positive angles imply angle2 is clockwise from angle1 and -ve
angles imply counter-clockwise.
>>> int(degdiff(40, 30))
-10
>>> int(degdiff(30, 40))
10
>>> int(deg... | cb5ff913ccfff49dd0ccb4b6ce1e748ab3f9e4ba | 649,848 |
def mul(a, b):
"""
>>> mul(2,3)
6
>>> mul('a',2)
'aa'
"""
return a*b | d74be2cf2cf4ca4673cb8a24a2c1d8813ed4e4d6 | 649,849 |
def quote(string):
""" Surround a string with double quotes """
return f'"{string}"' | fb025db6c19e78a0e980f1a2eecb2a8edc51c671 | 649,850 |
def filter_top_exchange_addresses(exhanges_df, min_balance = 2000, min_txn_count = 400000):
"""
Filter exchanges with balance > min_balance and transaction count > min_txn_count
Args:
exchanges_df: (pd.Dataframe) Exchanges with atleast columns 'balance'(float), 'txn_count'(float) and 'address' (str... | 088265f4e0021095a8b03977bc5209ed2a103a09 | 649,854 |
from typing import Optional
from typing import List
def drop_duplicates(df, columns: Optional[List[str]]):
"""
Remove duplicate rows
---
### Parameters
*mandatory :*
- `columns` (*list*): columns to consider to identify duplicates (set to null to use all the columns)
### Example
*... | 6f328a760b50454f7b5f578eead8decc8d561819 | 649,857 |
def _entities_from_messages(messages):
"""Return all entities that occur in at least one of the messages."""
return list({e["entity"] for m in messages for e in m.data.get("entities", [])}) | d0858c09bea65a396ed33079385590167a8280f7 | 649,860 |
def remove_indent(s):
"""Remove indention of paragraph."""
s = "\n".join(i.lstrip() for i in s.splitlines())
return s | 4874aabeae73033813308b24e06f88575c0d53fd | 649,861 |
import socket
def find_free_port() -> int:
"""
Find a free port
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('', 0))
_host, port = s.getsockname()
return port | 6a63058c8db249489acb6652b9e46bad23f9f9ae | 649,863 |
def ngrams(sequence, n):
"""Create ngrams from sequence, e.g. ([1,2,3], 2) -> [(1,2), (2,3)]
Note that fewer sequence items than n results in an empty list being returned"""
# credit: http://stackoverflow.com/questions/2380394/simple-implementation-of-n-gram-tf-idf-and-cosine-similarity-in-python
seq... | 8c630e38da0cc511f2005df651e45dee3abae818 | 649,864 |
import six
def combine_logged_values(*logged_values_dicts):
"""Combine logged values dicts. Throws if there are any repeated keys."""
combined_dict = dict()
for logged_values in logged_values_dicts:
for k, v in six.iteritems(logged_values):
if k in combined_dict:
raise ValueError('Key "%s" is ... | 023d384886d9dcb22360badc900e74bbe33a0877 | 649,865 |
def _section_has_changes(section_data) -> bool:
"""
Looks for a section containing something other than "No changes."
:param section_data: list of lines
:return: boolean
"""
non_empty_lines = [line.strip() for line in section_data[1:] if line.strip()]
if len(non_empty_lines) == 0:
r... | 9e460ca8ceea5048c627fcdc77a9e6af4655cfca | 649,869 |
import re
def parse_phone(phone):
"""Parses the given phone, or returns `None` if it's invalid."""
if isinstance(phone, int):
return str(phone)
else:
phone = re.sub(r'[+()\s-]', '', str(phone))
if phone.isdigit():
return phone | fbf0f2324a49bf16354c59efedcfa6b3f3f70998 | 649,870 |
def list_sequence(lst, seq):
"""Return sequences of seq in lst"""
sequences = []
count = 0
len_seq = len(seq)
upper_bound = len(lst)-len_seq+1
for i in range(upper_bound):
if lst[i:i+len_seq] == seq:
count += 1
sequences.append([i,i+len_seq])
return sequences | ef03e1a848497eff09db3327571cf6a63ea8ac36 | 649,871 |
def moffat(x, amplitude=1, center=0., sigma=1, beta=1.):
""" 1 dimensional moffat function:
moffat(amplitude, center, sigma, beta) = amplitude / (((x - center)/sigma)**2 + 1)**beta
"""
return amplitude / (((x - center)/sigma)**2 + 1)**beta | cc5db5f6fd675be4ab26ae7297cd6468fcdcc8b5 | 649,872 |
def round_filters(filters, mconfig, skip=False):
"""Round number of filters based on depth multiplier."""
multiplier = mconfig.width_coefficient
divisor = mconfig.depth_divisor
min_depth = mconfig.min_depth
if skip or not multiplier:
return filters
filters *= multiplier
min_depth = min_depth or divis... | 32105b3c1d9649940d1100cfd6ade3838f463981 | 649,873 |
def get_spectral_w(w_pars,energy):
"""
Return spectral weight of an event
Parameters
----------
w_pars: parameters obtained with get_spectral_w_pars() function
energy: energy of the event in GeV
Returns
-------
float w
"""
E0 = w_pars[0]
index = w_pars[1]
index_w =... | 9a9d9479a8f62ac007dddee1f1bf742ddce44bec | 649,878 |
import hashlib
def sha1_hash_lst(byte_lst):
"""
Compute the SHA-1 hash of a list with byte streams.
"""
sha = hashlib.sha1()
for l in byte_lst:
sha.update(l)
return sha.digest() | 3a77d6d58c805146804d1d5513f8619765775f4a | 649,884 |
def bs3_cols(num_entries):
"""Return the appropriate bootstrap framework column width.
Args:
num_entries (int): The number of entries to determine column width for.
Returns:
int: The integer value for column width.
"""
if not isinstance(num_entries, int):
return 12
mapp... | dfc882f7177551d38b309a58bc8a26755e4ea034 | 649,886 |
def one_of_k_encoding_unk(x, allowable_set):
"""
Maps inputs not in the allowable set to the last element.
Unlike `one_of_k_encoding`, if `x` is not in `allowable_set`, this method
pretends that `x` is the last element of `allowable_set`.
Parameters
----------
x: object
Must be present i... | fbcad4bece352976d87952966eee5d16c0684160 | 649,891 |
def all_children(model):
"""Return a list of all child modules of the model, and their children, and their children's children, ..."""
children = list(model.children())
for child in model.children():
children.extend(all_children(child))
return children | d6bbb247e27013349ab6428dc6b6fe215bbfb991 | 649,893 |
def problem_48_self_powers(series_limit, digits):
""" Problem 48: Find the last digits of series n^n (n = 1 to series limit).
Args:
series_limit (int): The maximum base and power in the series.
digits (int): The number of last digits to take from sum.
"""
result = 0
for number in ra... | a1b5cbb89724b264cef2867588391f7756eba128 | 649,898 |
def mapd(f, d):
"""Map function over dictionary values"""
return {k: f(v) for k, v in d.items()} | b7ff21ca57f83fbf8d331cbe3b50d9b2b6ef19be | 649,899 |
def lt(y, x):
"""Returns true if the first argument is less than the second; false
otherwise"""
return x < y | c6cb678617c634d4af03a010e157edb1e6023cf9 | 649,901 |
def find_key(dic, val):
"""Return the keys of dictionary dic with the value val."""
return [k for k, v in dic.iteritems() if v == val] | 158060d8be64d8f547bc5c3762452861a5ba0bec | 649,902 |
def relu(x):
""" ReLU Activation Function
"""
return x.clamp_min(0.) | 5223f81fe0d5c4266f01a70640ab9d474b2dd207 | 649,903 |
import re
def translate_dict(cmd_list, label_map, dict_key='label'):
"""Create a translate dictionary of labels
Parameters
----------
cmd_list : list of dict
The Benchpress commands to translate
label_map : dict
Dictionary mapping old to new labels: {'old_label': 'new_label'}.... | 2bdb013fc476e6b77c0e61dd396c099a1c98e3bf | 649,905 |
def choose_max_efficiency(efficiencies):
"""
Given a single or list of DOM efficiencies choose the highest
"""
if type(efficiencies) == list or type(efficiencies) == tuple:
return max(map(float,efficiencies))
else:
return float(efficiencies) | 736327b6d33d84125aa8df1f1b31a018d0ec8691 | 649,907 |
import re
import fnmatch
def FilterTestNames(all_tests, gtest_filter):
"""Filter a list of test names based on the given gtest filter.
See https://github.com/google/googletest/blob/main/docs/advanced.md
for gtest_filter specification.
Args:
all_tests: List of test names.
gtest_filter: Filter to appl... | 4d6af4f6abf3f2d04d457f27c3ef2701dfe47a01 | 649,908 |
def chartx(x, clen=70, c='#'):
"""generate a string of max length clen which is a bargraph of
floating point value 0. <= x <= 1 consisting of character c """
if x > 1.:
x = 1.
slen = int(x*clen)
cstr = [c for s in range(slen)]
return "".join(cstr) | 597ce3cf4b9486c66c92be99b728f4cc1786cbfc | 649,912 |
def get_pixel_dist(pixel, red, green, blue):
"""
Returns a value that refers to the "color distance" between a pixel and a mean RGB value.
Input:
pixel (Pixel): the pixel with RGB values to be compared
red (int): the average red value of the pixels to be compared
green (int): the av... | ab55a4f60134f848eabc658e5deef9b69c6c2183 | 649,914 |
def process_datafile(filename):
""" process_datafile -> (universities,enrollments,total_number_of_students)
universities: list of University
namesenrollments: corresponding list with enrollments
total_number_of_students: over all universities"""
universities=[]
enrollments=[]
with open(file... | ac80107cba1f60709cd221f2667219de92a50bfb | 649,916 |
def _to_j2kt_native_name(name):
"""Convert a label name used in j2cl to be used in j2kt native"""
if name.endswith("-j2cl"):
name = name[:-5]
return "%s-j2kt-native" % name | 2b3f95353486aea658ff8e001dff61d73913e32f | 649,917 |
def validating_property(func, allow_del=False):
"""Factory that makes properties that perform some user-specified
validation when setting values. The returned function must be used as a
descriptor to create a class variable before setting the instance
attribute.
Parameters
----------
func: ... | 5f1a6e3343a41176f78a8c9126ed9c3da3abbe63 | 649,918 |
def _lockedSql(db, func, *args):
"""
Ensure write lock on database, otherwise concurrent access can result in
"schema has changed" errors.
"""
if not db.inTransaction():
db.cursor().execute('BEGIN IMMEDIATE')
return func(*args) | 530043b26007ead588ff3a1255e908d1436757fa | 649,919 |
def eval_agent(env, agent, num_episodes):
"""Evaluates `agent` for `num_episodes`."""
rewards = 0.0
for _ in range(num_episodes):
time_step = env.reset()
episode_reward = 0
while not time_step.last():
agent_output = agent.step(time_step, is_evaluation=True)
time_step = env.step([agent_outp... | 97eddda4c5a675ef991b3610411183ef5516ea4a | 649,921 |
def _handle(request, handler, *rest): # pragma: no cover
"""invoke the next handler"""
return handler(request, *rest) | 4bb0506f7b42cd3441d4e3694ebd41ba8973a39d | 649,924 |
def full_record(marc21_record, marc21_metadata):
"""Full record as is expected by the UI serializer."""
marc21_record
marc21_record["id"] = "9jkx5-hx115"
marc21_record["pid"] = {
"pk": 58,
"status": "R",
"obj_type": "rec",
"pid_type": "marcid",
}
marc21_record["f... | 0ae2d50e8d2bee97d34f353ca1914d291ca6a585 | 649,933 |
def iter_in(value, seq, cmp):
"""
A function behaving like the "in" Python operator, but which works with a
a comparator function. This function checks whether the given value is
contained in the given iterable.
Args:
value: A value
seq: An iterable
cmp: A 2-arg comparator ... | 68b4231b009c7b07e0f7d56e4068e5e3d4a7a3f1 | 649,937 |
from typing import OrderedDict
def network_to_phenotype(net):
"""Converts a network instance to a phenotype representation,
i.e. a structure dictionary.
Arguments
----------
net: EvoNet instance
The network to convert.
Returns
----------
An ordered dictionary. Phenot... | 0fca2f85c670e8296818b3f9fec3641dc599f27d | 649,943 |
def join_neighs_OR_notrelpos(idxs0_ki, idxs1_ki):
"""Join neighs with OR.
Parameters
----------
idxs0_ki: list or np.ndarray
the indices of the neighs of neighbourhood0
idxs1_ki: list or np.ndarray
the indices of the neighs of neighbourhood1
Returns
-------
neighs: list... | 4b45f897fd1fd5955459a8a90fea769b7f84351e | 649,945 |
def power_digit_sum(base, power):
"""Return the sum of the digtis in base**power"""
return sum([int(x) for x in list(str(base**power))]) | b7edd0037387b0894276cdab9a21357a4d49f5d1 | 649,946 |
def upsert(manager, defaults=None, updates=None, **kwargs):
"""
Performs an update on an object or an insert if the object does not exist.
:type defaults: dict
:param defaults: These values are set when the object is inserted, but are irrelevant
when the object already exists. This field sh... | 8b103b051600ab1bf222b1c88353835732c7ceff | 649,947 |
def eval_callbacks(callbacks, record, logbook, estimator):
"""Evaluate list of callbacks on result.
Parameters
----------
callbacks : list of callables
Callbacks to evaluate.
record : logbook record
logbook:
Current stream logbook with the stats required
estimator: :class... | 49a1c46a4fa4475a97cf58d62d76ce7a097d03c2 | 649,948 |
def sizeStr(size):
"""Returns formatted string of a byte size
Args:
size (int): size in bytes
Returns:
string: Size with appropriate byte suffix
"""
prefixes = ["B", "KB", "MB", "GB", "TB"]
exponent = 0
while size > 1024:
size /= 1024
exponent += 1
pr... | d0698c5c8ef040d26621e656327b3f9e82f7bb1c | 649,949 |
import re
def get_grammatical_function(attributes):
""" Compute the grammatical function of a mention in its sentence.
Args:
attributes (dict(str, object)): Attributes of the mention, must contain
a value for "parse_tree".
Returns:
str: The grammatical function of the mention... | f3105bd17d9f03a99d36af40f0d128816fe2156c | 649,953 |
def blanks(i):
"""
Return i number of blank spaces
Used in places where reading number of blanks is tough
"""
return ''.join(' ' * i) | 7b9ccc5bd88f79c77c83d483c169f149e07495ed | 649,957 |
def simplify_replacements(replacements):
"""
Simplify a list of replacement patterns to make sure there are no needless ones.
For instance in the sequence "Bert->BertNew, BertConfig->BertNewConfig, bert->bert_new", the replacement
"BertConfig->BertNewConfig" is implied by "Bert->BertNew" so not needed.... | ff702f72f0503de2451f5b95883f2952c69b9d78 | 649,958 |
import re
def _transform_file_name_to_migration_name(name):
"""extracts from filename migration name
:param name: filename
:type name: string
:returns: Transformed filename
:rtype: string
"""
return re.sub(r'\.(up|down)\.sql$', '', name) | aa15ffbe9effb8b6fc51df388dd994a47b4846fe | 649,962 |
import uuid
import random
def make_ds_id() -> str:
"""Generate a dataset ID like DataLad would.
This is intended for lightweight tests that don't create
full-fledged datasets.
"""
return str(uuid.UUID(int=random.getrandbits(128))) | c85f4662f93df6dd7c3035170f806d50e3480c30 | 649,968 |
def is_object_translated(verbose, object_id, strings_by_object):
""" Checks if there are any translations for the given file id """
if object_id in strings_by_object:
return True
if verbose:
print(f"No translations for {object_id} in dump file -- skipping")
return False | f7abc448c1346087f9f423ba68f664729236e93f | 649,970 |
def median_val(vals):
"""
:param vals: an iterable such as list
:return: the median of the values from the iterable
"""
n = len(vals)
sorted_vals = sorted(vals)
if n % 2 == 0:
return (sorted_vals[n // 2] + sorted_vals[n // 2 - 1]) / 2
else:
return sorted_vals[n // 2] | b0255bce064d72c7031f81ed6b7f0b5f7c2c4ca0 | 649,971 |
def extension(path_):
"""Returns extension from given path. Skips end slash if any."""
if path_.endswith('/'):
path_ = path_[:-1]
filename = path_.split('/')[-1]
if not '.' in filename:
return None
return '.'+filename.split('.')[1] | f588f609a26c944c483b94907c03ff40b9b84bd4 | 649,973 |
def has_workflow_stage(artifact, workflow_step_name):
"""
Checks that the artifact's sample's root artifact has been through the given workflow.
:return True if it has False otherwise
"""
for w, status, name in artifact.samples[0].artifact.workflow_stages_and_statuses:
if name == workflow_st... | 13d9d4c2e79331bc5f8bec8ebadfca705439442e | 649,975 |
import collections
def build_vocab(data):
"""Build vocabulary.
Given the context in list format.
Return the vocabulary, which is a dictionary for word to id.
e.g. {'campbell': 2587, 'atlantic': 2247, 'aoun': 6746 .... }
Parameters
----------
data : a list of string
the context in ... | 04cb83cb50f8a611b55dea27bffe2e85adc5be93 | 649,978 |
def instrumented_stage(args, stage):
"""
Returns true if we are using PGO and on stage 2
:param args: The args variable generated by parse_parameters
:param stage: What stage we are at
:return: True if using PGO and on stage 2, false if not
"""
return args.pgo and stage == 2 | e4058f2f2c4a671d27057257bdafd34b2536493c | 649,981 |
def get_data_science_bookmarks(bookmarks):
"""Function to select the top level data science folder of bookmarks.
Returns the first element of bookmarks where 'Data Science' is one of the keys.
"""
for item in bookmarks:
if type(item) is dict:
if 'Data Science' in item.keys():... | ae8eb873e4775c030e67c49dd693fc9ee1fb902e | 649,983 |
from pathlib import Path
def project_path() -> Path:
"""Find project directory."""
current_dir = Path.cwd()
if (current_dir / 'pyproject.toml').exists():
return current_dir
raise ValueError('This is not a project dir!') | 130dbb516873309984355bf3dc14b5d21eabcf3d | 649,984 |
def multivariate_regression_predict(X, w_opt):
"""Predict with multivariate regression.
Arguments:
X {DataFrame} -- Independent variables.
w_opt {ndarray} -- Parameter values.
Returns:
ndarray -- Predicted values.
"""
X = X.values
y_pred = X.dot(w_opt)
return y_pre... | 34a9d70dfc2a4a647184255413a792f5270004d0 | 649,986 |
import tempfile, os, shutil
def createSampleAssembly(workdir, template_dir, sa_xml):
"""Create a sampleassembly folder in the workdir
using files in template directory and the given sampleassembly.xml file
return the path to the new directory
"""
d = tempfile.mkdtemp(dir=workdir)
for fn in os.... | 3ee793ba7f2b2173959d23719047ff7ebe5e74fa | 649,990 |
from typing import Tuple
from typing import Optional
def _parse_url(url : str) -> Tuple[str,int,Optional[str]]:
"""
Parses the url in the following format if authentication enabled:
tcp://<hostname/url>:<port>?token=<token>
If authentication is not enabled, the url is expected to be in the format:
... | 2a86725edaf017bd06de28452a5c2825de5285b0 | 649,991 |
import requests
def get_data(url: str):
"""Get the data from the url.
:param url: The link used to get the data.
:return: The raw response from requests.
"""
response = requests.get(url, stream=True)
return response.raw | 84bddf623e5340c6914347b532ca058a3f4cfd17 | 649,997 |
def get_links(soup):
"""Gets the story links from the given hacker soup."""
links = soup.select(".storylink")
return links | def4637af3b223b03d5fb528ec47dde03f6c6589 | 650,000 |
def _cache(f):
"""Decorator to cache return value of a function."""
cached = {}
def cached_function():
"""Cache return value in closure before calling function."""
if 'value' not in cached:
cached['value'] = f()
return cached['value']
return cached_function | cf25a68f4ac7a5cb94e1db7c3ef36e36002fa422 | 650,007 |
def make_list(var):
"""
Convert a variable to a list with one item (the original variable) if it isn't a list already.
:param var: the variable to check. if it's already a list, do nothing. else, put it in a list.
:return: the variable in a one-item list if it wasnt already a list.
"""
if... | 5ffcd3ef5d436162dae62cb823dc43a9438fc0f3 | 650,008 |
def win_safe_name(trackname):
"""Edit the track name so as the resulting file name would be
allowed in Windows.
"""
# In order: strip the whitespace at both ends, replace a trailing
# full stop by an underscore. Replace any forbidden characters by
# underscores.
trackname = trackname.strip(... | 7ede4e9af12e6fd4249f47e2b2519819e8b439dd | 650,012 |
import re
def clean_path(dirty):
"""Convert a string of python subscript notation or mongo dot-notation to a
list of strings.
"""
# handle python dictionary subscription style, e.g. `"['key1']['key2']"`:
if re.match(r'^\[', dirty):
return re.split(r'\'\]\[\'', re.sub(r'^\[\'|\'\]$'... | 0c5cce0e5e6e6b89167622e627ef5e8ca2dd154e | 650,013 |
def is_primitive(pyobj):
"""Determine if pyobj is one of (what other languages would deem) a primitive"""
if type(pyobj) in (int, float, bool, str, bytes):
return True
else:
return False | 72f26ba3361bac67142e0022f22faea3cab0de94 | 650,014 |
def _next_significant(tokens):
"""Return the next significant (neither whitespace or comment) token.
:type tokens: :term:`iterator`
:param tokens: An iterator yielding :term:`component values`.
:returns: A :term:`component value`, or :obj:`None`.
"""
for token in tokens:
if token.type ... | 992d0d6a42e8815ebae9f0ae6d5bd696bb4818f3 | 650,015 |
import itertools
def compact_batches(batches):
"""Pack down batches to lists of continuous batches."""
return [
[x[1] for x in g]
for k, g in itertools.groupby(enumerate(batches), lambda i_x: i_x[0] - i_x[1])
] | 292b7c5ca09f20cd0066ce81e5ad7db107a50005 | 650,018 |
def korean_year(cycle, year):
"""Return equivalent Korean year to Chinese cycle, cycle, and year, year."""
return (60 * cycle) + year - 364 | 50c5fac933820474c9c6cbd4c6abd8fe26c89edb | 650,021 |
def fmt_bytes(bytes: int) -> str:
"""
Prints out a human readable bytes amount for a given number of bytes
"""
if bytes > 1000000000:
return '{:.2f} GB'.format(bytes / 1000000000)
if bytes > 1000000:
return '{:.2f} MB'.format(bytes / 1000000)
if bytes > 1000:
return '{:.2... | 0652ee1d48133a3d59832ae8cd0cd3fbbf6dcc08 | 650,022 |
def __k_chk(k):
"""
Ensures a kelvin value is not below absolute zero. If it is
not, we raise a ValueError instead. If it is valid, we return it.
"""
if k < 0:
if k % 1 == 0:
k = int(k)
raise ValueError(f'{k}K is below absolute zero, and is invalid.')
return k | af40cec948ff1df639737139dbcb00d9a553712d | 650,024 |
def rounded(n, base):
"""Round a number to the nearest number designated by base parameter."""
return int(round(n/base) * base) | 231cd9c9972ab422bcf478defeb98c1abc06c333 | 650,025 |
def bits_to_array(num, output_size):
""" Converts a number from an integer to an array of bits
"""
##list(map(int,bin(mushroom)[2:].zfill(output_size)))
bit_array = []
for i in range(output_size - 1, -1, -1):
bit_array.append((num & (1 << i)) >> i)
return bit_array | 7df0bd8bf3e95770e4eee332df4514581704eef6 | 650,029 |
import pickle
def read_chains(in_dir):
"""Read chains file."""
pickle_in = open(in_dir, 'rb')
chains = pickle.load(pickle_in)
pickle_in.close()
return chains | 073d0c6743efd2cc09557371f9de59b156c65691 | 650,034 |
def _convert_pandas_csv_options(pandas_options, columns):
""" Translate `pd.read_csv()` options into `pd.DataFrame()` especially for header.
Args:
pandas_options (dict):
pandas options like {'header': None}.
columns (list):
list of column name.
"""
_columns = pa... | 2e64ee3c503bc91b167030e8c967204d489d3657 | 650,036 |
def ask_player_for_location(player):
"""Ask the player where they would like to use their turn"""
move = None
while not move:
try:
move = int(input(f"{player} where would you like to go? "))
if move not in range(1, 10):
move = None
raise ValueE... | 3a35ce8ef135d8a849e7403c763b9bf6b98b1b0e | 650,037 |
def age_restricted(content_limit, age_limit):
""" Returns True iff the content should be blocked """
if age_limit is None: # No limit set
return False
if content_limit is None:
return False # Content available for everyone
return age_limit < content_limit | fe61fe3ac8dedd77d3d77d7166125f12625ca906 | 650,043 |
def T(parameters, theta_v, pi, r_v=None):
"""
Returns an expression for temperature T in K.
:arg parameters: a CompressibleParameters object.
:arg theta_v: the virtual potential temperature in K.
:arg pi: the Exner pressure.
:arg r_v: the mixing ratio of water vapour.
"""
R_d = paramet... | 152648b6a338b7ac92769b0228fb26223aa1d7f9 | 650,045 |
def rshift(x, n):
"""For an integer x, calculate x >> n with the fastest (floor)
rounding. Unlike the plain Python expression (x >> n), n is
allowed to be negative, in which case a left shift is performed."""
if n >= 0: return x >> n
else: return x << (-n) | dbf38eacccb59e64099054d32253d791ed9eb672 | 650,046 |
def phrase2seq(phrase, word2idx, vocab):
"""
This function turns a sequence of words into a sequence of indexed tokens according to a vocabulary and its word2idx mapping dictionary.
:param phrase: List of strings
:param word2idx: Dictionary
:param vocab: Set or list containing entire v... | dac991872df01b0c44959d559395fa64f30e6979 | 650,047 |
def is_json_validation_enabled(schema_keyword, configuration=None):
"""Returns true if JSON schema validation is enabled for the specified
validation keyword. This can be used to skip JSON schema structural validation
as requested in the configuration.
Args:
schema_keyword (string): the name of... | d028a5c27a947872f4ca850ea1bbafde58751279 | 650,048 |
def combine_runs(runsets):
"""
Combine the output results of many runs into a single dictionary.
Parameters
----------
runsets : list
Outputs of multiple calls to 'chnbase.MOSOSolver.solve'
Returns
-------
rundatdict : dict
"""
rundatdict = dict()
for i, st in enume... | 4d257cbc2640b2fe3def30e723792f18db204ddb | 650,050 |
import json
def load_cexfreqtable(fname):
""" Loads a Context Feature frequency table """
with open(fname) as fp:
cexfreqtable = json.load(fp)
return cexfreqtable | f8e48b67e1db501332e54294c3087b4f2b1fb938 | 650,052 |
def extend(key, term):
""" extend a key with a another element in a tuple
Works if they key is a string or a tuple
>>> extend('x', '.dtype')
('x', '.dtype')
>>> extend(('a', 'b', 'c'), '.dtype')
('a', 'b', 'c', '.dtype')
"""
if isinstance(term, tuple):
pass
elif isinstance(... | fdc14d4918618627d2c8dae5f54a0ad02a2b0feb | 650,053 |
def str_or_list(value):
"""
String to list of string.
"""
if isinstance(value, list):
return value
return [value] | 48e710af66d4f76980f7df92dd80f5848ea42c2a | 650,055 |
def contains_test_passer(t, test):
"""
Return whether t contains a value that test(value) returns True for.
@param Tree t: tree to search for values that pass test
@param function[Any, bool] test: predicate to check values with
@rtype: bool
>>> t = descendants_from_list(Tree(0), [1, 2, 3, 4.5,... | 56cbd48f9c416c64c1822b637fd4e8780ce72bc5 | 650,058 |
import json
def ReadMeasurements(test_result):
"""Read ad hoc measurements recorded on a test result."""
try:
artifact = test_result['outputArtifacts']['measurements.json']
except KeyError:
return {}
with open(artifact['filePath']) as f:
return json.load(f)['measurements'] | ebb51702d9b45ee9103478161e72d567de719f03 | 650,061 |
def calculate_fibonacci(num: int) -> int:
"""
>>> calculate_fibonacci(-1)
Traceback (most recent call last):
...
ValueError: num must not be negative.
>>> calculate_fibonacci(0)
0
>>> calculate_fibonacci(1)
1
>>> calculate_fibonacci(2)
1
>>> calculate_fibonacci(3)
... | b1532997b0ac20f8ac17bf7ab0a652ca0ec49b8b | 650,066 |
def make_tweet_content(preamble: str, message: str, link: str) -> str:
"""
Make formatted tweet message from preamble, message and link.
Arguments:
preamble (str): Preamble to be used in the beginning of the tweet.
message (str): Main message of the tweet.
link (str): Link to be add... | da349534af48e0614785a838f868130cb7ee0a57 | 650,070 |
import torch
def linear_quantize(input, scale, zero_point, inplace=False):
"""
Quantize single-precision input tensor to integers with the given scaling factor and zeropoint.
Args:
input (`torch.Tensor`):
Single-precision input tensor to be quantized.
scale (`torch.Tensor`):
... | 690fcc8250b989f1005cfac845b602dbb9d897bc | 650,071 |
def parser(response):
"""Parses the json response from CourtListener /opinions endpoint."""
results = response.get("results")
if not results:
return []
ids = []
for result in results:
_id = result.get("id", None)
if _id is not None:
ids.append(_id)
return ... | 9632ba800b5de4978aa1c85615dfdeb389bfe5ca | 650,076 |
def equal_test_conditions(testapi_input, nfvbench_input):
"""Check test conditions in behave scenario results record.
Check whether a behave scenario results record from testapi matches a given
nfvbench input, ie whether the record comes from a test done under the same
conditions (frame size, flow coun... | 737f3ed9e4ff5e6bd73b9519c60bb555f3d3acc8 | 650,078 |
def merge_n_reduce(f, arity, data):
""" Apply f cumulatively to the items of data,
from left to right in n-tree structure, so as to
reduce the data.
:param f: function to apply to reduce data
:param arity: Number of elements in group
:param data: List of items to be reduced
:return: List of... | 7cb1c2c3dd7da95abcd1ab5b737d6f03c686a4b5 | 650,080 |
def is_substring_in_list(needle, haystack):
"""
Determine if any string in haystack:list contains the specified
needle:string as a substring.
"""
for e in haystack:
if needle in e:
return True
return False | f85ac189ec622aa91d543b5a2d82bc4edcbf0802 | 650,081 |
def deep_access(x, keylist):
"""Access an arbitrary nested part of dictionary x using keylist."""
val = x
for key in keylist:
val = val.get(key, 0)
return val | 1f100949a8603c7924ce1ab40e66a3a220cffa6d | 650,082 |
def getcommontype(action):
"""Get common type from action."""
return action if action == 'stock' else 'product' | 70de4e1fe270804fea883b96d7111db141cc3c22 | 650,083 |
from typing import Union
def olt_value_str_to_str(value:str, field_id:int) -> Union[str, int]:
""" convert value str in show oltqinq-domain to str value
Args:
value (str): 要处理的值
field_id (int): 字段类型ID
Returns:
str or int: 处理后的值
"""
# 1(Dst Mac) 00 00 00 00 00 00 ... | 2b42fd982ae868c1d34fa1deb4ea7ce6628c27f6 | 650,084 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.