content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import time
def retry(func_name, max_retry, *args):
"""Retry a function if the output of the function is false
:param func_name: name of the function to retry
:type func_name: Object
:param max_retry: Maximum number of times to be retried
:type max_retry: Integer
:param args: Arguments passed... | 29051605dbad65823c1ca99afb3237679a37a08c | 21,018 |
def encode_randomness(randomness: hints.Buffer) -> str:
"""
Encode the given buffer to a :class:`~str` using Base32 encoding.
The given :class:`~bytes` are expected to represent the last 10 bytes of a ULID, which
are cryptographically secure random values.
.. note:: This uses an optimized strategy... | 5d1ba06d4d16f724a86c2c47c180c12fe0b16602 | 21,019 |
from typing import OrderedDict
import six
import json
def obtain_parameter_values(flow):
"""
Extracts all parameter settings from the model inside a flow in OpenML
format.
Parameters
----------
flow : OpenMLFlow
openml flow object (containing flow ids, i.e., it has to be downloaded
... | 25374b844eb3172927e74fe20b26483e547a1583 | 21,020 |
def logging_sync_ocns(cookie, in_from_or_zero, in_to_or_zero):
""" Auto-generated UCSC XML API Method. """
method = ExternalMethod("LoggingSyncOcns")
method.cookie = cookie
method.in_from_or_zero = str(in_from_or_zero)
method.in_to_or_zero = str(in_to_or_zero)
xml_request = method.to_xml(optio... | 178e8207305f419a8f7d182b10b23ab8548ad624 | 21,021 |
def story_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Link to a JIRA issue.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages.
Both are allowed to be empty.
:param name: The role name used in the document.
:pa... | 0f347d7c5a7a802b9f3b23ee70996e86155d2ca9 | 21,022 |
def benedict_bornder_constants(g, critical=False):
""" Computes the g,h constants for a Benedict-Bordner filter, which
minimizes transient errors for a g-h filter.
Returns the values g,h for a specified g. Strictly speaking, only h
is computed, g is returned unchanged.
The default formula for the ... | ca40941b4843b3d71030549da2810c9241ebdf72 | 21,023 |
import ispyb.model.datacollection
import ispyb.model.processingprogram
import ispyb.model.screening
import ispyb.model.image_quality_indicators
import ispyb.model.detector
import ispyb.model.sample
import ispyb.model.samplegroup
import logging
import configparser
def enable(configuration_file, section="ispyb"):
"... | a48ce8d2157f151a4f3e7146e7d8c8881a4dfc23 | 21,024 |
def median(f, x, y, a, b):
"""
Return the median value of the `size`-neighbors of the given point.
"""
# Create the sub 2d array
sub_f = f[x - a:x + a + 1, y - b:y + b + 1]
# Return the median
arr = np.sort(np.asarray(sub_f).reshape(-1))
return np.median(arr) | 7cdb625ad4906efac92cd94b1dfce91df7854daf | 21,025 |
from typing import Set
from pathlib import Path
def build_relevant_api_reference_files(
docstring: str, api_doc_id: str, api_doc_path: str
) -> Set[str]:
"""Builds importable link snippets according to the contents of a docstring's `# Documentation` block.
This method will create files if they do not exi... | e83aaed8cfc0ec7ee8fffb3f95eb2c5aa948d212 | 21,026 |
def find_zip_entry(zFile, override_file):
"""
Implement ZipFile.getinfo() as case insensitive for systems with a case
insensitive file system so that looking up overrides will work the same
as it does in the Sublime core.
"""
try:
return zFile.getinfo(override_file)
except KeyError:... | 33b1b868378a789ebc014615b1bc93b34b3f1e67 | 21,027 |
def get_mode(elements):
"""The element(s) that occur most frequently in a data set."""
dictionary = {}
elements.sort()
for element in elements:
if element in dictionary:
dictionary[element] += 1
else:
dictionary[element] = 1
# Get the max value
max_value ... | bc792ffe58ffb3b9368559fe45ec623fe8accff6 | 21,028 |
def holtWintersAberration(requestContext, seriesList, delta=3):
"""
Performs a Holt-Winters forecast using the series as input data and plots the
positive or negative deviation of the series data from the forecast.
"""
results = []
for series in seriesList:
confidenceBands = holtWintersConfidenceBands(r... | 05040695e7d6f6e5d8e117d32f66ebbfb0cb7392 | 21,029 |
def get_in_addition_from_start_to_end_item(li, start, end):
"""
获取除开始到结束之外的元素
:param li: 列表元素
:param start: 开始位置
:param end: 结束位置
:return: 返回开始位置到结束位置之间的元素
"""
return li[start:end + 1] | 7106a9d409d9d77ab20e7e85d85c2ddb7a2a431c | 21,030 |
import re
def remove_special_message(section_content):
"""
Remove special message - "medicinal product no longer authorised"
e.g.
'me di cin al p ro du ct n o lo ng er a ut ho ris ed'
'me dic ina l p rod uc t n o l on ge r a uth ori se d'
:param section_content: content of a section
:ret... | 37d9cbd697a98891b3f19848c90cb17dafcd6345 | 21,031 |
def simulate_cash_flow_values(cash_flow_data, number_of_simulations=1):
"""Simulate cash flow values from their mean and standard deviation.
The function returns a list of numpy arrays with cash flow values.
Example:
Input:
cash_flow_data: [[100, 20], [-500, 10]]
number_of_simulations: 3
O... | 691122945f811e20b40032cb49920d3b2c7f5c13 | 21,032 |
import time
def sim_v1(sim_params, prep_result, progress=None, pipeline=None):
"""
Map the simulation over the peptides in prep_result.
This is actually performed twice in order to get a train and (different!) test set
The "train" set includes decoys, the test set does not; furthermore
the the er... | 243fca643749a5d346013f0547cefea1c1df7767 | 21,033 |
def apply_function_elementwise_series(ser, func):
"""Apply a function on a row/column basis of a DataFrame.
Args:
ser (pd.Series): Series.
func (function): The function to apply.
Returns:
pd.Series: Series with the applied function.
Examples:
>>> df = pd.Da... | d2af0a9c7817c602b4621603a8f06283f34ae81a | 21,034 |
from bs4 import BeautifulSoup
def is_the_bbc_html(raw_html, is_lists_enabled):
"""
Creates a concatenate string of the article, with or without li elements included from bbc.co.uk.
:param raw_html: resp.content from response.get().
:param is_lists_enabled: Boolean to include <Li> elements.
:return... | fb6bca09e1ebb78d7afd6d2afaa52feab9843d21 | 21,035 |
def create_empty_module(module_name, origin=None):
"""Creates a blank module.
Args:
module_name: The name to be given to the module.
origin: The origin of the module. Defaults to None.
Returns:
A blank module.
"""
spec = spec_from_loader(module_name, loader=None, origin=ori... | f65e1fbbbba13fc25e84ea89c57329ba48d22ac7 | 21,036 |
def BitWidth(n: int):
""" compute the minimum bitwidth needed to represent and integer """
if n == 0:
return 0
if n > 0:
return n.bit_length()
if n < 0:
# two's-complement WITHOUT sign
return (n + 1).bit_length() | 46dcdfb0987268133d606e609d39c641b9e6faab | 21,038 |
import copy
import numpy
def read_many_nam_cube(netcdf_file_names, PREDICTOR_NAMES):
"""Reads storm-centered images from many NetCDF files.
:param netcdf_file_names: 1-D list of paths to input files.
:return: image_dict: See doc for `read_image_file`.
"""
image_dict = None
keys_to_concat = [PR... | 100e6dfcd998ae6d2d2f673251c6110ccec90b00 | 21,039 |
def rouge_l_summary_level(evaluated_sentences, reference_sentences):
"""
Computes ROUGE-L (summary level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = SUM(1, u)[LCS<union>(... | 9022cc4cc90d9b57f48716839b5e97315a7b78c6 | 21,040 |
def construct_classifier(cfg,
module_names,
in_features,
slot_machine=False,
k=8,
greedy_selection=True
):
"""
Constructs a sequential model of fully-connected l... | 84091ce1a74a5baae8cde8b32c2ab28e0ccc7175 | 21,041 |
def size_adjustment(imgs, shape):
"""
Args:
imgs: Numpy array with shape (data, width, height, channel)
= (*, 240, 320, 3).
shape: 256 or None.
256: imgs_adj.shape = (*, 256, 256, 3)
None: No modification of imgs.
Returns:
imgs_adj: Numpy array wit... | 5143a34b3ad2085596a682811b6f35dca040c3e0 | 21,042 |
def to_full_model_name(root_key: str) -> str:
"""
Find model name from the root_key in the file.
Args:
root_key: root key such as 'system-security-plan' from a top level OSCAL model.
"""
if root_key not in const.MODEL_TYPE_LIST:
raise TrestleError(f'{root_key} is not a top level mod... | 8c73a54cb03c8cc52d24ec4bc284326289ff04f1 | 21,043 |
from typing import Dict
def is_unique(s: str) -> bool:
"""
Time: O(n)
Space: O(n)
"""
chars: Dict[str, int] = {}
for char in s:
if char in chars:
return False
else:
chars[char] = 1
return True | 4f77691be1192202b57b20bdc5676a31bc8b175e | 21,044 |
def is_available() -> bool:
"""Return ``True`` if the handler has its dependencies met."""
return HAVE_RLE | b4e035dc62ef79211cb038a8b567985679c500aa | 21,046 |
def model_with_buckets(encoder_inputs,
decoder_inputs,
targets,
weights,
buckets,
seq2seq,
softmax_loss_function=None,
per_example_loss=False,
... | 795c7445bdf608db85148656179ccc0467af6dee | 21,047 |
def sqlite_cast(vtype, v):
"""
Returns the casted version of v, for use in
database.
SQLite does not perform any type check or conversion
so this function should be used anytime a data comes
from outstide to be put in database.
This function also handles CoiotDatetime objects and
accept... | 2ecf79b5aec2d5516cc624b9aa279be9f1b9d1b2 | 21,048 |
def read_table(name):
"""
Mock of IkatsApi.table.read method
"""
return TABLES[name] | 261ab82a5389155997924c1468087a139b50f9e8 | 21,050 |
def cosh(x, out=None):
"""
Raises a ValueError if input cannot be rescaled to a dimensionless
quantity.
"""
if not isinstance(x, Quantity):
return np.cosh(x, out)
return Quantity(
np.cosh(x.rescale(dimensionless).magnitude, out),
dimensionless,
copy=False
) | d50891be37de3c9729c3a15e1315f74ff55baedc | 21,051 |
from datetime import datetime
def dates_from_360cal(time):
"""Convert numpy.datetime64 values in 360 calendar format.
This is because 360 calendar cftime objects are problematic, so we
will use datetime module to re-create all dates using the
available data.
Parameters
----------
tim... | d13e2146414a4dbd25cab0015348281503134331 | 21,052 |
def db_queue(**data):
"""Add a record to queue table.
Arguments:
**data: The queue record data.
Returns:
(dict): The inserted queue record.
"""
fields = data.keys()
assert 'request' in fields
queue = Queue(**data)
db.session.add(queue)
db.session.commit()
return... | ca5dda54fecf37be9eae682c2b04325b55caf931 | 21,053 |
def loadMnistData(trainOrTestData='test'):
"""Loads MNIST data from sklearn or web.
:param str trainOrTestData: Must be 'train' or 'test' and specifies which \
part of the MNIST dataset to load.
:return: images, targets
"""
mnist = loadMNIST()
if trainOrTestData == 'train':
X = mni... | 3fb06616a784ac863f4df093e981982be077f5a7 | 21,054 |
def times_once() -> _Timing:
"""
Expect the request a single time
:return: Timing object
"""
return _Timing(1) | dd4d97344613676668cf7e07fad6e5f696861924 | 21,055 |
def linear_growth(mesh, pos, coefficient):
"""Applies a homotety to a dictionary of coordinates.
Parameters
----------
mesh : Topomesh
Not used in this algorithm
pos : dict(int -> iterable)
Dictionary (pid -> ndarray) of the tissue vertices
coefficient : ... | bed27bc4a75d1628bf3331062817d1bf1b21e9c8 | 21,056 |
def einstein_t(tini, tfin, npoint, HT_lim=3000,dul=False,model=1):
"""
Computes the *Einstein temperature*
Args:
tini: minimum temperature (K) of the fitting interval
tfin: maximum temperature
npoint: number of points in the T range
HT_lim: high temperature limit where C... | bc914dcd600f9f5b3327a0e954356f4dd5d87493 | 21,057 |
import pathlib
def normalize_uri(path_uri: str) -> str:
"""Convert any path to URI. If not a path, return the URI."""
if not isinstance(path_uri, pathlib.Path) and is_url(path_uri):
return path_uri
return pathlib.Path(path_uri).resolve().as_uri() | b0682d1b2b1dea07195865db4be534a18e6b965e | 21,058 |
import logging
def RETune(ont: Ontology, training: [Annotation]):
""" Tune the relation extraction class over a range of various values and return the correct
parameters
Params:
ont (RelationExtractor/Ontology) - The ontology of information needed to form the base
training ([Datapoint]) -... | d53831f08fd1855537b3bb7cb5a5f27625fa8b31 | 21,059 |
def create_instance(test_id, config, args):
"""
Invoked by TestExecutor class to create a test instance
@test_id - test index number
@config - test parameters from, config
@args - command line args
"""
return TestNodeConnectivity(test_id, config, args) | a3defb1f0f72fc0788fa2120829334f9a9670042 | 21,060 |
def to_me() -> Rule:
"""
:说明:
通过 ``event.is_tome()`` 判断事件是否与机器人有关
:参数:
* 无
"""
return Rule(ToMeRule()) | 92b6a04bbeac6e0b3eb3f53641efd2552b19f620 | 21,061 |
def unsaturated_atom_keys(xgr):
""" keys of unsaturated (radical or pi-bonded) atoms
"""
atm_unsat_vlc_dct = atom_unsaturated_valences(xgr, bond_order=False)
unsat_atm_keys = frozenset(dict_.keys_by_value(atm_unsat_vlc_dct, bool))
return unsat_atm_keys | 0af0469b3370a0c015238cad5b2717fbb977e6c5 | 21,062 |
def clip_data(input_file, latlim, lonlim):
"""
Clip the data to the defined extend of the user (latlim, lonlim)
Keyword Arguments:
input_file -- output data, output of the clipped dataset
latlim -- [ymin, ymax]
lonlim -- [xmin, xmax]
"""
try:
if input_file.split('.')[-1] == 'tif... | bf691d4021cf0bbeade47b6d389e5daa3261f22a | 21,063 |
def fetch_last_posts(conn) -> list:
"""Fetch tooted posts from db"""
cur = conn.cursor()
cur.execute("select postid from posts")
last_posts = cur.fetchall()
return [e[0] for e in last_posts] | dd5addd1ba19ec2663a84617904f6754fe7fc1fc | 21,064 |
def update_click_map(selectedData, date, hoverData, inputData):
"""
click to select a airport to find the detail information
:param selectedData:
:param date:
:param hoverData:
:return:
"""
timestamp = pd.to_datetime(date) if date else 0
fig = px.scatter_geo(
airports_info,
... | 1baaba25254eede65c2dff9b95c9ac40a0777dac | 21,065 |
def EncoderText(model_name, vocab_size, word_dim, embed_size, num_layers, use_bi_gru=False, text_norm=True, dropout=0.0):
"""A wrapper to text encoders. Chooses between an different encoders
that uses precomputed image features.
"""
model_name = model_name.lower()
EncoderMap = {
'scan': Enco... | bf3657e2c5def238e9ec84cd674c21c079169b9e | 21,066 |
def feat_extract(pretrained=False, **kwargs):
"""Constructs a ResNet-Mini-Imagenet model"""
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet52': 'https://do... | 9e628b4905e696aa55c9e4313888f406bf1fb413 | 21,067 |
from typing import Union
from pathlib import Path
from typing import Optional
import fnmatch
import tempfile
def compose_all(
mirror: Union[str, Path],
branch_pattern: str = "android-*",
work_dir: Optional[Path] = None,
force: bool = False,
) -> Path:
"""Iterates through all the branches in AOSP a... | 4293df4708633574ccab70fe597ca390b04aa12c | 21,068 |
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
n = len(input_list)
heap_sort(input_list)
decimal_value = 1
n1 = 0
... | 3d0d4964ce5faca8aeb27bef56de1840e5cb5f51 | 21,069 |
def _partial_ema_scov_update(s:dict, x:[float], r:float=None, target=None):
""" Update recency weighted estimate of scov-like matrix by treating quadrants individually """
assert len(x)==s['n_dim']
# If target is not supplied we maintain a mean that switches from emp to ema
if target is None:
... | b54f2897abe45eec85cb843a23e8d6f0f4f2642d | 21,070 |
def _get_chrome_options():
"""
Returns the chrome options for the following arguments
"""
chrome_options = Options()
# Standard options
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument('--ignore-certificate-errors')
# chrome_options.add_argument('--no-sandbo... | 0db0799c53487e35b4d2de977fa07fb260d7e930 | 21,072 |
def legendre(n, monic=0):
"""Returns the nth order Legendre polynomial, P_n(x), orthogonal over
[-1,1] with weight function 1.
"""
if n < 0:
raise ValueError("n must be nonnegative.")
if n==0: n1 = n+1
else: n1 = n
x,w,mu0 = p_roots(n1,mu=1)
if n==0: x,w = [],[]
hn = 2.0/(2*... | bfd2bb0603e320e9ea330c8e51b17ab53a03382f | 21,074 |
def cal_sort_key(cal):
"""
Sort key for the list of calendars: primary calendar first,
then other selected calendars, then unselected calendars.
(" " sorts before "X", and tuples are compared piecewise)
"""
if cal["selected"]:
selected_key = " "
else:
selected_key = "X"
... | 4235700b003689fed304b88085ba9fa9880f3839 | 21,075 |
def preview_game_num():
"""retorna el numero de la ultima partida jugada"""
df = pd.read_csv('./data/stats.csv', encoding="utf8")
x = sorted(df["Partida"],reverse=True)[0]
return x | 7af698416fd60be4e7be74e7a104cd6fa956f649 | 21,077 |
def XCO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "4.46", **kwargs
) -> Graph:
"""Return XC... | 34c77f3074031b41fba8da0523a263a511734bff | 21,078 |
def wraplatex(text, width=WIDTH):
""" Wrap the text, for LaTeX, using ``textwrap`` module, and ``width``."""
return "$\n$".join(wrap(text, width=width)) | b558f2524917ec73160f4bea48029dedb9b6a12e | 21,080 |
def register(request):
"""
Render and process a basic registration form.
"""
ctx = {}
if request.user.is_authenticated():
if "next" in request.GET:
return redirect(request.GET.get("next", 'control:index'))
return redirect('control:index')
if request.method == 'POST':
... | f8d81d16903d0d5fe2e3224a535fd8f1795f9ad0 | 21,081 |
from typing import List
def green_agg(robots: List[gs.Robot]) -> np.ndarray:
"""
This is a dummy aggregator function (for demonstration) that just saves
the value of each robot's green color channel
"""
out_arr = np.zeros([len(robots)])
for i, r in enumerate(robots):
out_arr[i] = r._co... | 8e86200bf7ed51cea3bdce06be2fb3300ac20a5a | 21,082 |
import socket
def tcp_port_open_locally(port):
"""
Returns True if the given TCP port is open on the local machine
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(("127.0.0.1", port))
return result == 0 | f5c801a5016085eedbed953089742e184f514db5 | 21,083 |
def wrap(text, width=80):
"""
Wraps a string at a fixed width.
Arguments
---------
text : str
Text to be wrapped
width : int
Line width
Returns
-------
str
Wrapped string
"""
return "\n".join(
[text[i:i + width] for i in range(0, len(text), w... | 793840a1cae51397de15dd16051c5dfffc211768 | 21,084 |
def parallel_vector(R, alt, max_alt=1e5):
"""
Generates a viewing and tangent vectors
parallel to the surface of a sphere
"""
if not hasattr(alt, '__len__'):
alt = np.array([alt])
viewer = np.zeros(shape=(3, len(alt)))
tangent = np.zeros_like(viewer)
viewer[0] = -(R+max_alt*2)
... | 49f4a1c4fe7267078cfac05af78c2fc850c1edfb | 21,085 |
from pathlib import Path
def load_datasets(parser, args):
"""Loads the specified dataset from commandline arguments
Returns:
train_dataset, validation_dataset
"""
args = parser.parse_args()
dataset_kwargs = {
"root": Path(args.train_dir),
}
source_augmentations = Compos... | 17f25443b34b9b6bc87c259c65d4af13b76b5303 | 21,086 |
def stock_total_deal_money():
"""
总成交量
:return:
"""
df = stock_zh_index_spot()
# 深证成指:sz399001,上证指数:sh00001
ds = df[(df['代码'] == 'sz399001') | (df['代码'] == 'sh000001')]
return ds['成交额'].sum() / 100000000 | 241c0080ed64acc21c1d8072befd168415184130 | 21,087 |
def _ls(dir=None, project=None, all=False, appendType=False, dereference=False, directoryOnly=False):
"""
Lists file(s) in specified MDSS directory.
:type dir: :obj:`str`
:param dir: MDSS directory path for which files are listed.
:type project: :obj:`str`
:param project: NCI project identi... | 7a26c9459381364ad145bab2b6230fd2037e5433 | 21,088 |
def uploadMetadata(doi, current, delta, forceUpload=False, datacenter=None):
"""
Uploads citation metadata for the resource identified by an existing
scheme-less DOI identifier (e.g., "10.5060/FOO") to DataCite. This
same function can be used to overwrite previously-uploaded metadata.
'current' and 'delta'... | 22902f2649f20d638ba61b8db7ff6a32821bf965 | 21,089 |
def one_away(string_1: str, string_2: str)-> bool:
"""DP, classic edit distance
funny move, we calculate the LCS and then substract from the len() of the biggest string in O(n*m)
"""
if string_1 == string_2: return False
@lru_cache(maxsize=1024)
def dp(s_1, s_2, distance=0):
"""standard ... | 754cd1b383d21935992ba95bde65bde5340a8ef8 | 21,090 |
def test(net, loss_normalizer):
"""
Tests the Neural Network using IdProbNet on the test set.
Args:
net -- (IdProbNet instance)
loss_normalizer -- (Torch.Tensor) value to be divided from the loss
Returns:
3-tuple -- (Execution Time, End loss value,
Model's predictio... | 4abdd1426545af6d093be2f549f6e2b8e86b3659 | 21,091 |
def scale_from_matrix(matrix):
"""Return scaling factor, origin and direction from scaling matrix.
"""
M = jnp.array(matrix, dtype=jnp.float64, copy=False)
M33 = M[:3, :3]
factor = jnp.trace(M33) - 2.0
try:
# direction: unit eigenvector corresponding to eigenvalue factor
w, V = jnp.linalg.eig(M33)
... | 1e6ef044b35ec4eff86764d9a222764c74977fb1 | 21,092 |
def get_fort44_info(NDX, NDY, NATM, NMOL, NION, NSTRA, NCL, NPLS, NSTS, NLIM):
"""Collection of labels and dimensions for all fort.44 variables, as collected in the
SOLPS-ITER 2020 manual.
"""
fort44_info = {
"dab2": [r"Atom density ($m^{-3}$)", (NDX, NDY, NATM)],
"tab2": [r"Atom tempe... | 0eca35ae512d3fd690124c45d5cde303d860ae0b | 21,093 |
def lens2memnamegen_first50(nmems):
"""Generate the member names for LENS2 simulations
Input:
nmems = number of members
Output:
memstr(nmems) = an array containing nmems strings corresponding to the member names
"""
memstr=[]
for imem in range(0,nmems,1):
if (imem < 10)... | 81ebbf1b17c56d604d8c6c9bc7bacd4a3093ec82 | 21,094 |
def initialize_settings(tool_name, source_path, dest_file_name=None):
""" Creates settings directory and copies or merges the source to there.
In case source already exists, merge is done.
Destination file name is the source_path's file name unless dest_file_name
is given.
"""
settings_dir = os... | c32e35f6323e2ae87c5d53a8b2e2c0d69a30c6e4 | 21,095 |
def get_stopword_list(filename=stopword_filepath):
""" Get a list of stopword from a file """
with open(filename, 'r', encoding=encoding) as f:
stoplist = [line for line in f.read().splitlines()]
return stoplist | 8578428ec387309907f428f3eec91a526f11167a | 21,096 |
def to_text(value):
"""Convert an opcode to text.
*value*, an ``int`` the opcode value,
Raises ``dns.opcode.UnknownOpcode`` if the opcode is unknown.
Returns a ``str``.
"""
return Opcode.to_text(value) | 85395ecdaa2fae4fc121072747401c114d7b4ed3 | 21,098 |
import torch
def _demo_mm_inputs(input_shape, num_classes):
"""Create a superset of inputs needed to run test or train batches.
Args:
input_shape (tuple):
input batch dimensions
num_classes (int):
number of semantic classes
"""
(N, C, H, W) = input_shape
rn... | 9d8de5d5bd337720f386a45ad40f9e901a999b52 | 21,100 |
import socket
def get_ephemeral_port(sock_family=socket.AF_INET, sock_type=socket.SOCK_STREAM):
"""Return an ostensibly available ephemeral port number."""
# We expect that the operating system is polite enough to not hand out the
# same ephemeral port before we can explicitly bind it a second time.
s... | 37287b70e35b8aa7fbdb01ced1882fb3bbf38543 | 21,101 |
from typing import Optional
def IR_guess_model(spectrum: ConvSpectrum, peak_args: Optional[dict] = None) -> tuple[Model, dict]:
"""
Guess a fit for the IR spectrum based on its peaks.
:param spectrum: the ConvSpectrum to be fit
:param peak_args: arguments for finding peaks
:return: Model, paramet... | fa56e3c183ef08b35f177df1d727ff134c964eaf | 21,102 |
def virus_monte_carlo(initial_infected, population, k):
""" Generates a list of points to which some is infected
at a given value k starting with initial_infected infected.
There is no mechanism to stop the infection from reaching
the entire population.
:param initial_infected: The amount of people... | 856af13a8a7fdbb931ba32b97ff7bd5207e9ca49 | 21,103 |
def threadsafe_generator(f):
"""
A decorator that takes a generator function and makes it thread-safe.
"""
def g(*a, **kw):
return threadsafe_iter(f(*a, **kw))
return g | 013e0df91f70da8c8f4f501bc31d8bddcf378787 | 21,104 |
def lastmsg(self):
"""
Return last logged message if **_lastmsg** attribute is available.
Returns:
last massage or empty str
"""
return getattr(self, '_last_message', '') | ad080c05caadbb644914344145460db0164f017c | 21,105 |
def _callback_on_all_dict_keys(dt, callback_fn):
"""
Callback callback_fn on all dictionary keys recursively
"""
result = {}
for (key, val) in dt.items():
if type(val) == dict:
val = _callback_on_all_dict_keys(val, callback_fn)
result[callback_fn(key)] = val
return re... | 3cab018413a7ba8a0e5bbae8574025253a2ea885 | 21,106 |
def top_ngrams(df, n=2, ngrams=10):
"""
* Not generalizable in this form *
* This works well, but is very inefficient and should be optimized or rewritten *
Takes a preposcessed, tokenized column and create a large list.
Returns most frequent ngrams
Arguments:
df = name of DataFrame wit... | a6c540a30a288a8d26bf6f966b44b9f080db0026 | 21,108 |
def install_openvpn(instance, arg, verbose=True):
""" """
install(instance, {"module":"openvpn"}, verbose=True)
generate_dh_key(instance, {"dh_name":"openvpn", "key_size":"2048"})
server_conf = open("simulation/workstations/"+instance.name+"/server_openvpn.conf", "w")
server_conf.write("port 1... | d95d99e7847dd08c43f54fc3dde769f69888da77 | 21,109 |
def rossoporn_parse(driver: webdriver.Firefox) -> tuple[list[str], int, str]:
"""Read the html for rossoporn.com"""
#Parses the html of the site
soup = soupify(driver)
dir_name = soup.find("div", class_="content_right").find("h1").text
dir_name = clean_dir_name(dir_name)
images = soup.find_all("... | 21aad0798bc3e13badb1076ec40c36c56f47ebf7 | 21,110 |
def pid_from_context(_, context, **kwargs):
"""Get PID from marshmallow context."""
pid = (context or {}).get('pid')
return pid.pid_value if pid else missing | 350fd4c915e186dd41575c5842e47beb7d055fb5 | 21,111 |
def score_text(text, tokenizer, preset_model, finetuned_model):
""" Uses rule-based rankings. Higher is better, but different features have different scales.
Args:
text (str/ List[str]): one story to rank.
tokenizer (Pytroch tokenizer): GPT2 Byte Tokenizer.
preset_model (Pytorch model)... | e304975b55c44e78f6ce92f4df9d1ba563389b8b | 21,112 |
def parse_cards(account_page_content):
"""
Parse card metadata and product balances from /ClipperCard/dashboard.jsf
"""
begin = account_page_content.index(b'<!--YOUR CLIPPER CARDS-->')
end = account_page_content.index(b'<!--END YOUR CLIPPER CARDS-->')
card_soup = bs4.BeautifulSoup(account_page_c... | 6ec10941aebe88af27a75c407e6805698d5cf31c | 21,116 |
def interaction_time_data_string(logs, title):
"""
times = utils.valid_values_for_enum((models.LogEntry.TIME_CHOICES))
contexts_map = dict(models.LogEntry.TIME_CHOICES)
counts = {contexts_map[k]: v
for k, v in _counts_by_getter(logs, lambda l: l.time_of_day).items()
}
pl... | fc6f6a32d39f3bd87c3b7b816e333aef462fb0f3 | 21,117 |
import math
def _label_boost(boost_form, label):
"""Returns the label boost.
Args:
boost_form: Either NDCG or PRECISION.
label: The example label.
Returns:
A list of per list weight.
"""
boost = {
'NDCG': math.pow(2.0, label) - 1.0,
'PRECISION': 1.0 if label >= 1.0 else 0.0,
}
... | 811e87949b0bbe7dc98f63814b343ffd90fe129a | 21,118 |
def has_matching_ts_templates(reactant, bond_rearr):
"""
See if there are any templates suitable to get a TS guess from a template
Arguments:
reactant (autode.complex.ReactantComplex):
bond_rearr (autode.bond_rearrangement.BondRearrangement):
Returns:
bool:
"""
mol_gra... | 10061734d2831668099f3e85d99366dda9f51157 | 21,119 |
def get_commands(xml: objectify.ObjectifiedElement):
"""
Returns an action and the room from the xml string.
:param xml:
:return:
"""
return xml.body.attrib["action"] | 3724e00c626814e792911ae094a5b200d8593f4c | 21,120 |
def compression_point(w_db, slope = 1, compression = 1,
extrapolation_point = None, axis = -1):
"""Return input referred compression point"""
interpol_line = calc_extrapolation_line(w_db, slope, extrapolation_point,
axis)
return cross(interp... | 4c8793c5796d1359aa1fc00f226ecafda98c3f61 | 21,121 |
from typing import List
import logging
def pattern_remove_incomplete_region_or_spatial_path(
perception_graph: PerceptionGraphPattern
) -> PerceptionGraphPattern:
"""
Helper function to return a `PerceptionGraphPattern` verifying
that region and spatial path perceptions contain a reference object.
... | cbcc79602bf87e1ea88f8a0027d6cd19b74fb81c | 21,122 |
def other_shifted_bottleneck_distance(A, B, fudge=default_fudge, analysis=False):
"""Compute the shifted bottleneck distance between two diagrams, A and B (multisets)"""
A = pu.SaneCounter(A)
B = pu.SaneCounter(B)
if not A and not B:
return 0
radius = fudge(upper_bound_on_radius(A, B))
e... | 51455945743bfc5f262711e826d1097122309f83 | 21,123 |
def getCountdown(c):
"""
Parse into a Friendly Readable format for Humans
"""
days = c.days
c = c.total_seconds()
hours = round(c//3600)
minutes = round(c // 60 - hours * 60)
seconds = round(c - hours * 3600 - minutes * 60)
return days, hours, minutes, seconds | f49225ae2680192340720c8958aa19b9e9369f5f | 21,124 |
def fromPSK(valstr):
"""A special version of fromStr that assumes the user is trying to set a PSK.
In that case we also allow "none", "default" or "random" (to have python generate one), or simpleN
"""
if valstr == "random":
return genPSK256()
elif valstr == "none":
return bytes([0])... | 73fa661458601ec33d2b839aeea060f7a26b530f | 21,125 |
def list_hierarchy(class_name, bases):
"""
Creates a list of the class hierarchy
Args:
-----
class_name: name of the current class
bases: list/tuple of bases for the current class
"""
class_list = [Uri(class_name)]
for base in bases:
if base.__name__ not in IGNORE_C... | 1b82dfe6576a472c04bb7cb53f8eed94a83a1ac1 | 21,127 |
def rss():
"""Return ps -o rss (resident) memory in kB."""
return float(mem("rss")) / 1024 | 92580a4873f2afca3f419a7f661e5cd39ec28b96 | 21,129 |
def compare_words(
word1_features,
word2_features,
count=10,
exclude=set(),
similarity_degree=0.5,
separate=False,
min_feature_value=0.3
):
"""
Сравнение двух слов на основе списка похожих (или вообще каких-либо фич слова).
Возвращает 3 списка: характерные для первог... | 4a04292e48911e6a4152cb03c19cda8de51802fb | 21,130 |
def dispatch_for_binary_elementwise_apis(x_type, y_type):
"""Decorator to override default implementation for binary elementwise APIs.
The decorated function (known as the "elementwise api handler") overrides
the default implementation for any binary elementwise API whenever the value
for the first two argumen... | 743d6f85b843f6200cf8b6c6361fc81154c37936 | 21,131 |
def grid(mat, i, j, k):
"""Returns true if the specified grid contains k"""
return lookup(k, [ mat[i + p][j + q] for p in range(3) for q in range(3) ]) | b2df3a905ada922011fc344f555a908aa03d5f64 | 21,132 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.