content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Any
from typing import Optional
from typing import IO
import yaml
def dump_yaml(data: Any, stream: Optional[IO[str]] = None) -> Optional[str]:
"""Dump YAML to stream or return as string."""
if stream is not None:
return yaml.safe_dump(data, stream, default_flow_style=False)
else... | 7ff998722e5d7754f83e960127bbed39d4a8d728 | 59,300 |
import logging
import requests
import json
def distribute_task(task):
"""
This function assign task to machines that is not running in MACHINES
:param task: task to run
:return: True for assign success false for fail
"""
for m in MACHINES:
m: Machine
if m.running:
c... | cb7ea172934464a2c81b29fc9ab0684a208eea0e | 59,301 |
def to_rq_symbol(symbol: str, exchange: Exchange) -> str:
"""将交易所代码转换为米筐代码"""
# 股票
if exchange in [Exchange.SSE, Exchange.SZSE]:
if exchange == Exchange.SSE:
rq_symbol: str = f"{symbol}.XSHG"
else:
rq_symbol: str = f"{symbol}.XSHE"
# 金交所现货
elif exchange in [Ex... | af42fc7b25435e5e267cbd77f4f08f0628c7d61b | 59,302 |
def random_pig():
"""Return a pig species tag with random serial for testing."""
return Tag().from_parameters(
"".join(
'0001',
str(randint(1, 999999)).zfill(SPECIES_DIGITS),
'00000620211216'
),
'1', '-88', '0', '1') | e401b9e792692c0443dcab48ae61a7d425405fd1 | 59,303 |
def get_link_to_referenced_comment(subreddit_name, user_note):
"""Extracts the id of the comment referenced by the usernote and formats it as a reddit-internal link"""
link_code_segments = user_note['l'].split(',')
if len(link_code_segments) == 3:
submission_id = link_code_segments[1]
commen... | cb41189bc05962e37fdf91aa3e5c53c64acb9400 | 59,304 |
import logging
def GetInterrupts():
"""Gets the list of interrupt names and its count.
Returns:
A dict of interrupt names to their interrupt counts. The interrupt names
are all strings even if some of the names are numbers, e.g. the name for
interrupt 88 is "88" instead of 88.
"""
interrupt_coun... | 88d6c52638641a1040febcc2d2d5eb3e56c16c6e | 59,305 |
def _detects_peaks(ecg_integrated, sample_rate):
"""
Detects peaks from local maximum
----------
Parameters
----------
ecg_integrated : ndarray
Array that contains the samples of the integrated signal.
sample_rate : int
Sampling rate at which the acquisition took place.
... | ab9dd461f65095f048942ab8b8c069c456ea4933 | 59,306 |
def FixedRate_ReadFileAdapter_Carousel(readmode = "bytes", **rateargs):
"""A file reading carousel, that reads at a fixed rate.
Takes filenames on its inbox
"""
return Graphline(RC = RateControl(**rateargs),
CAR = ReusableFileReader(readmode),
link... | b25735924841c61507e205e7249501dd849dfe70 | 59,307 |
def get(id, user=None):
"""# Retrieve a specific DictKey
Receive a single DictKey object by its id
## Parameters (required):
- id [string]: DictKey object unique id and PIX key itself. ex: "tony@starkbank.com", "722.461.430-04", "20.018.183/0001-80", "+5511988887777", "b6295ee1-f054-47d1-9e90-ee57b74f60... | f7cfc8bb94a1bdec437ce4387285de0f08c16c21 | 59,308 |
import re
def pascal2title(string: str) -> str:
"""Splits on whitespace between capital and lowercase letters."""
# https://stackoverflow.com/a/29922050
return " ".join(re.findall(r"[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))", string)) | c91019552d1d0a3e58b65b3d2d84ec78a48fec52 | 59,309 |
def _topological_sort(data, head, top_node, raise_exception=False, result=None, visited=None):
""" Internal function """
if not result:
result = []
if not visited:
visited = []
deps = data.get(head, list())
if head in visited:
if head == top_node and raise_exception:
... | e20d4a62278b978489d708a77324a443b6199c5c | 59,310 |
from typing import List
from typing import Tuple
async def _compile_filters_devs(for_sets: List[ForSetDevelopers],
request: AthenianWebRequest,
account: int,
meta_ids: Tuple[int, ...],
) -> ... | 2ce1491dd606c3c718977d41ca25ec97f8fc5f3e | 59,311 |
import copy
def flatten_samplesets(samplesets):
"""
Takes a list of SampleSets (with one or multiple samples in each SampleSet)
and returns a list of SampleSets (with one sample in each SampleSet)
Parameters
----------
samplesets: list of SampleSets
Input list of SampleSets (with one o... | d89c5b58db69caa7570088fbfae4d7e414c5b9af | 59,312 |
import torch
def center_conv_point(bboxes, kernel_size=3, c_min=0, c_max=1, v3_form=False):
"""In a parallel manner also keeps the gradient during BP"""
#bboxes.clamp_(min=c_min, max=c_max)
if v3_form:
base = torch.cat([bboxes[:, :2][:, (1, 0)]] * (kernel_size ** 2), dim=1)
else:
base ... | a5b14c544525672f8f47fbdbb31a1ccb96ff8e8b | 59,313 |
def lambda_curry2(func):
"""
Returns a Curried version of a two-argument function FUNC.
>>> from operator import add
>>> curried_add = lambda_curry2(add)
>>> add_three = curried_add(3)
>>> add_three(5)
8
"""
"*** YOUR CODE HERE ***"
return lambda x: lambda y: func(x,y) | bb524c02756c57dcb82ce9dbf722113b7314871d | 59,314 |
def unit_work_v3(entry, work, client_name, client_int_name, client_int_req,
client_expected_identity, decrypted_params, params,
in_downtime, condorQ):
"""
Perform a single work unit using the v2 protocol. When we stop supporting
v2 protocol, this function can be removed alo... | 200c46afbb6f4e93d0cd8c2772a08a0178a19e00 | 59,315 |
def get_trailer_offset(line_list):
"""Determine the line number where coordinates end."""
i = 0
for i, line in enumerate(line_list):
if match_trailer.match(line):
break
return i | b87c73baecafd829ebde353c6dd3bae35f8a13bb | 59,316 |
def cosine_similarity_sklearn(x, y):
"""
:param x:
:param y:
:return:
"""
result = cosine_similarity(np.array(x).reshape(1, -1), np.array(y).reshape(1, -1))
return result[0][0]*100 | d5c2d2b0998787a58cc202bb8dde96fda38aeb27 | 59,317 |
def calcPubChemFingerPart2(mol):# 116-263
""" *Internal Use Only*
Calculate PubChem Fingerprints (116-263)
"""
bits=[0]*148
bits=func_1(mol,bits)[1]
bits=func_2(mol,bits)[1]
bits=func_3(mol,bits)[1]
bits=func_4(mol,bits)[1]
bits=func_5(mol,bits)[1]
bits=func_6(mol,bits)[1]
... | cf0d47671544bd9ff1db8339e28a1214e15b5493 | 59,318 |
def auto_type_convert(value):
"""Try to convert 'value' to a int, float, or bool. Otherwise leave
as a string. This is done recursively with complex values."""
if value is None:
return None
if isinstance(value, list):
return [auto_type_convert(item) for item in value]
elif isinstan... | 1fe873dca7017d25128c30cc5144c3cf890319a1 | 59,319 |
def get_spike_nearest_neighbors(
all_spikes,
n_neighbors,
low_memory,
knn_verbose,
all_chan_idx,
n_samples=50,
n_channel_neighbors=8,
n_jobs=1,
max_candidates=60,
):
""" Builds a graph of nearest neighbors from sparse spike array.
TODO: There are potentially faster ANN approa... | da37a766e450cd9e57bb3b5b73a136761a0d90a5 | 59,320 |
def norm_get_dly():
"""Get all daily climate normals data"""
prcp = norm_get_dly_prcp()
snow = norm_get_dly_snow()
tavg = norm_get_dly_tavg()
tmax = norm_get_dly_tmax()
tmin = norm_get_dly_tmin()
by = ["id", "month", "day"]
df = pd.merge(prcp, snow, how="outer", on=by)
df = pd.merge(... | 1894ca46bbc1853fc2d0952a85e36a62c64a3a85 | 59,321 |
def allowed_with_lowinverse(solution: Solution, other: Solution) -> bool:
"""Returns True if other can be combined with solution; Otherwise, False.
Args:
solution (Solution): a Solution with rule=Rule.Lowinverse.
other (Solution): a Solution.
Requires:
1. solution must have rule=Ru... | af6a8ee81079a4e57ecb7e57d9ff992b20aaadb0 | 59,322 |
import os
def test_image():
"""
Returns a test image (first image of the small dataset).
:return: image
:rtype: numpy.ndarray
"""
global _test_image
if _test_image is None:
t = TiffFile(os.path.join(os.path.dirname(__file__), 'example-frame.tif'))
_test_image = t.pages[0].... | 2e4d99cceead395c03c66883d539a48043702deb | 59,323 |
import requests
def _create_upload_url(auth_control, name, size, ht_space='user',
ht_space_id=None, ht_id_path=ID_ROOT_PATH,
metadata=None):
"""
Create an upload URL to use to upload a file.
Parameters
----------
auth_control
HTAuthorizationCo... | 7f5d67f663dbca71f995fd3a0b7ac6c006000e97 | 59,324 |
def string(commands, data, node):
""" Компиляция выражения "строка" """
commands.add(Push, 0)
for character in node.characters:
commands.add(Push, ord(character))
commands.add(Push, len(node.characters))
StringCompiler.store(commands, data)
return commands.set_and_return_type(Types.STR... | eb9ca1a6774553918e285ffc39bea6fc8515c922 | 59,325 |
import json
def master_serializer(resource):
"""Function to return a resource json"""
data = resource.serialize()
user_json = json.dumps(
data, default=datetimeconverter, sort_keys=True
)
return user_json | 1d1ea730a0bb54963960016d945d09d871122dbd | 59,326 |
import itertools
def normalise_text(text):
"""
Removes leading and trailing whitespace from each line of text.
Removes leading and trailing blank lines from text.
"""
stripped = text.strip()
stripped_lines = [line.strip() for line in text.split("\n")]
# remove leading and trailing empty li... | 52ab40cfa4c39ed194fa71aa28d70f5fa737d70c | 59,327 |
def global_precision(actual, predicted, k = 5):
""" Computes global precision for recommendation systems using actual items and predicated items at k
If the argument `k` isn't passed in, the default k 5 is used.
Parameters
----------
actual : list
A list of lists of... | b3f0f78e04aa5595cea9ee2789278c0372c86e28 | 59,328 |
def export_module_part(request, pk):
""" Creates an excel sheet that contains all tests that are in a course. Used mainly to download sign off excel sheets.
:param request: Django request
:param pk: Module part ID
:return: A file response containing an .xlsx file.
"""
module_part = get_object_... | 70b443314c7c041231ab0f3dddb145990ccaa8d3 | 59,329 |
import re
import string
def stdtextpreprocessing(text):
""" Desc: Text preprocessing of social media text using
typical text cleaning methods such as lowercasing, removal of mentions, etc.
Input: text (string) - text to be cleaned
Output: text (string) - cleaned text """
# Instantiate wordnet le... | b7319ddca4c629aa77e34cd4220cc00b8c9bf0d0 | 59,330 |
def dedispersion_plan(nchan, dmmin, dmmax, start_freq, bandwidth, sample_time):
"""
Examples
--------
>>> tDM = dedispersion_plan(10, 0, 10, 1400, 128, 0.0005)
>>> np.isclose(tDM[0], 0)
True
>>> np.isclose(tDM[-1], 10., atol=1)
True
"""
# dfreq = bandwidth / nchan
stop_freq =... | 2cb09d31cd581e10593710c48096aac0e9bc1e65 | 59,331 |
def RMSpropConfig(argument_parser):
"""
Set CLI arguments
:param argument_parser: argument parser
:type argument_parser: ```ArgumentParser```
:returns: argument_parser
:rtype: ```ArgumentParser```
"""
argument_parser.description = """Implements RMSprop algorithm.
Proposed by G. Hinton... | 733faf8005c5260ee2443fe6d42bfb85c3ba5979 | 59,332 |
def create_from_input(fluid: Fluid, filename=""):
"""Adds Density and Velocity to a Fluid from an input file.
Args:
fluid (Fluid): The Fluid object to be modified.
filename (str, optional): The name of the file to be read without the extension. Defaults to "".
Returns:
[str, str, l... | 3c4a3f99cb26b12d40185b3ac268e033bd66a0d7 | 59,333 |
def remove_stale_events(data):
"""
Parse an event dictionary and remove transitions to the same state:
.. code::
event_dict = {
(entity_id, cohort interval) : [(time, state), ..., (time, state)]
(entity_id, cohort interval) : (time, state), ..., (time, state)]
}
:para... | be80965efc7077e06d6e9b2ab5fb8ddc65df79a9 | 59,334 |
def get_L_dashdash_ba2_d(L_dashdash_ba2_d_t):
"""# 1日当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/d)
Args:
L_dashdash_ba2_d_t(ndarray): 1時間当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/h)
Returns:
ndarray: 1日当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/d)
"""
return np.sum(L_dashdash_ba2_d_t.reshape((365, 24)), axis=1) | 0ba4ef903ef69cb755eeee657e1eb9d6c72f6ead | 59,335 |
def im2col_indices(x, field_height, field_width, padding=0, stride_y=1, stride_x=1):
""" An implementation of im2col based on some fancy indexing """
# Zero-pad the input
p = padding
x_padded = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant')
k, i, j = get_im2col_indices(x.shape, field_height, fi... | 717fae3eec42b5514f912be8abb71cc8b0f2c821 | 59,336 |
from typing import Dict
import os
import json
def read_config_stream(config_stream) -> Dict:
"""Read config stream. May be a path to a YAML or JSON file, or a str containing JSON or the name
of an env variable, or even a JSON object directly
:param config_stream:
:return:
"""
if isinstance(c... | d92ade7bddb15d92774589623e5d011617bd67c0 | 59,337 |
import os
def env_fallback(*args, **kwargs):
"""Load value from environment variable"""
for arg in args:
if arg in os.environ:
return os.environ[arg]
raise AnsibleFallbackNotFound | 9c1f27f46d3ff00b68d8dd33af20f1ff8f4c23f4 | 59,338 |
import sqlite3
def sqlite3get_table_names(sql_conn: sqlite3.Connection):
"""For a given sqlite3 database connection object, returns the table names within that database.
Examples:
>>> db_conn = sqlite3.connect('places.sqlite')\n
>>> sqlite3get_table_names(db_conn)\n
['moz_origins', 'm... | 0cb1ba2ba475268d39fef8bdbe044436f51c4f07 | 59,339 |
def add_eDOO_to_summary(df, delay_don=3, delay_dpl=2, blur=1):
"""Add eDOO column - estimated DOO - to summary dataframe.
Also add sDON and sDPL columns, which are estimated shifted
DON/DPL values (with blurring).
Parameters:
- delay_don: assumed delay (days) from date of notification -> day of o... | 7331f559d9933c617b044c1bba695c3435ba4215 | 59,340 |
from operator import and_
def vulns_by_product(vendor_id=None, product_id=None):
"""View vulns associated to product."""
if product_id is None or product_id is None:
return abort(404)
nvd_ids = (
db.session.query(Cpe.nvd_json_id)
.filter(and_(Cpe.vendor == vendor_id, Cpe.product ==... | 51041bdcb193b956deac619176e70b6e08a76912 | 59,341 |
def calc_hcore_matrix(Tuv_, Vuv_):
"""
calc_hcore_matrix - Computes the 1 electron core matrix
Arguments:
Tuv_: The Kinetic Energy 1e integral matrix
Vuv_: The Nuclear Repulsion 1e integrals matrix
Returns:
h_core: The one electron hamiltonian matrix
"""
h_core = Tuv_ +... | 5c2dbd61b938a235f6c11b7647e157777fa18428 | 59,342 |
def _fit_lines(spectrum, model, fitter=fitting.LevMarLSQFitter(),
exclude_regions=None, weights=None, window=None):
"""
Fit the input model (initial conditions) to the spectrum. Output will be
the same model with the parameters set based on the fitting.
spectrum, model -> model
Par... | 84bddc75c562bf9df44269c9b687a0212b512f8e | 59,343 |
def rivm(path="rivm/report.csv", **kwargs):
""" DataFrame: Daily new cases from RIVM (Netherlands) PDF report. """
kwargs.setdefault('parse_dates', ['date'])
kwargs.setdefault('index_col', 'date')
return (
read_csv(DATADIR / path, **kwargs)
.rename_axis(None).sort_index(axis=1)
... | d7117d9d33009c0f2915149c1f9db68913ceb1cb | 59,344 |
def vector(x, y, z):
"""
Make a 3-vector from components
x, y, z : vector components
"""
return tf.stack([x, y, z], axis=0) | 4e7ddb6a9f0de0ddfc8f72e4a874465d0075e080 | 59,345 |
def _to_sequence_example(image, decoder, vocab, config):
"""Builds a SequenceExample proto for an image-caption pair.
Args:
image: An ImageMetadata object.
decoder: An ImageDecoder object.
vocab: A Vocabulary object.
Returns:
A SequenceExample proto.
"""
with tf.gf... | cdd8a0d6a1ec3a16e46a0dd2ab9828754f190f26 | 59,346 |
def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text):
"""Returns tokenized answer spans that better match the annotated answer."""
# tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
tok_answer_text = " ".join([sw for w in whitespace_tokenize(orig_answer_t... | 10ed5493260ba9f2fba51d3f0b3509ee35e4f684 | 59,347 |
def _step_const_v_1d(dt, x0, v, x_lim):
"""
Evaluate daisy pattern step at `x0` with step `dt`.
Parameters
----------
dt :
The step size.
x0 :
The initial position, signed.
v :
The velocity, signed
x_lim :
The limit of x such that -x_lim < x < x_lim.
... | 36dfd7cff56d3e69d58a121b6977080ebd3c8b00 | 59,348 |
def get_confusion_matrix_intersection_mats(groundtruth, predicted):
"""
Returns a dictionary of 4 boolean numpy arrays containing True at TP, FP, FN, TN.
"""
confusion_matrix_arrs = {}
groundtruth_inverse = np.logical_not(groundtruth)
predicted_inverse = np.logical_not(predicted)
confusion... | ad7a3351f18a412894ce6261f7cba57acc90bb18 | 59,349 |
def run_command(runtime, timeout=0.01):
"""
Run a command, read stdout and stderr, prefix with timestamp. The returned
runtime contains a merged stdout+stderr log with timestamps
http://stackoverflow.com/questions/4984549/merge-and-sync-stdout-and-stderr/5188359#5188359
"""
PIPE = subprocess.PI... | d66f8769e407417c24ffca74baf22368f760a233 | 59,350 |
from pathlib import Path
def parse_uri_path(uri: str) -> str:
"""Parse a URI starting with 'file:///' to a posix path."""
return Path(url2pathname(urlparse(unquote(uri)).path)).as_posix() | d5a35fad0388d2b534f871d985a590159b3f1927 | 59,351 |
def make_key_frames():
"""
make key frames for the regions
"""
key_frames = {}
key_frames[0] = [100, 200, 300]
key_frames[1] = [50, 150]
return key_frames | 3b551b7bb7fb22fab8e35abc54b2c524bdfa36fd | 59,352 |
from typing import Dict
def get_registered_commands() -> Dict[ str, Command ]:
"""
Gets the registered commands.
"""
global _lock, _plugin_importer
with _lock:
if _plugin_importer is None:
_plugin_importer = PluginImporter( plugins )
_plugin_importer.import_module... | 39eafb0c13f1c1face66e7bbcc72943a8ec89291 | 59,353 |
def _get_cov_blocks_ordering(probes):
"""
Utility function to get the ordering of the covariance matrix blocks
"""
cl_index = _get_cl_ordering(probes)
def find_index(a, b):
if (a, b) in cl_index:
return cl_index.index((a, b))
else:
return cl_index.index((b, a... | 660d255c6426172486914a0efe2d53f502b0e43c | 59,354 |
def use_uber_files(ctx, section_name, option_name, value):
""" Configure the usage of UberFiles """
if not _is_user_input_allowed(ctx, option_name, value):
Logs.info('\nUser Input disabled.\nUsing default value "%s" for option: "%s"' % (value, option_name))
return value
info_str = ['UberFil... | 5dc44c03268dbacca11132f01623653088922269 | 59,355 |
import os
def get_drive_service():
"""Get a Google Drive service for making Google Drive API calls.
"""
creds = None
if _token_file and os.path.exists(_token_file):
creds = Credentials.from_authorized_user_file(_token_file, SCOPES)
elif _token_data:
creds = Credentials.from_authori... | 14e7f7484fde682d298b5c2a699e853252d22405 | 59,356 |
from typing import List
def _generate_list_of_keywords_to_prepend(
keywords_visible_to_user: List[str],
keywords_not_visible_to_user: List[str], title: str,
language: str) -> List[str]:
"""Determines which performant keywords need to be prepended and sorts them.
Args:
keywords_visible_to_user: ke... | ba9e1811d75a75bbee465f663706b3226f1f67f5 | 59,357 |
import numpy
def generate_correlation(
points,
correlation_scale=0.1,
nu=0.5,
grid=True,
sparse=False,
density=0.001,
plot=False,
verbose=False):
"""
Generates symmetric and positive-definite matrix for test purposes.
**Correlation Function:... | bffc88da560491a63c70993ece8366e8abf1f86f | 59,358 |
import re
def cal_re(raw_trajs: list, final_trajs: list, min_latitude: float, min_longitude: float,
len_latitude: float, len_longitude: float, epsilon: float) -> float:
"""
calculate RE
Args:
raw_trajs : original trajectory
final_trajs : generated trajectory
min_la... | 07b34a7a932dcb47c0c05214cc3b31db1eac4160 | 59,359 |
def initialize_empty_command(help=None, formatter_class=None): # pylint: disable=redefined-builtin
"""
Initialize empty command with script for tests
"""
script = Script()
command = EmptyCommand(script)
# pylint: disable=redefined-builtin
script.add_subcommand(command, help=help, formatter... | f7d37c9cdc67138c8497abc48ffecb1337bd9dd8 | 59,360 |
from typing import List
from typing import Any
def sort(xs: List[Any]) -> List[Any]:
"""
Sort the list `xs` with the python `sort` function
and return the sorted function. The given list is not modified.
Parameters
----------
xs
A list.
Returns
-------
xs_sorted
... | 706190a533c19b6a7ea4baf540823ca73406560b | 59,361 |
def _parse_chained_types(ctxt, node):
# type: (errors.ParserContext, yaml.nodes.MappingNode) -> List[syntax.ChainedType]
"""Parse a chained types section in a struct in the IDL file."""
chained_items = []
field_name_set = set() # type: Set[str]
for [first_node, second_node] in node.value:
... | 605fa7c45fcce3dbc3e7bb1aa37d3648553ea636 | 59,362 |
def sameQ(v1, v2) -> bool:
"""Mathics SameQ"""
return get_type(v1) == get_type(v2) and v1 == v2 | f7e00876cafeca6955a03f2e8836d7e76e87b60a | 59,363 |
def read_from_file(file: str) -> list[list[str]]:
"""Read row data from the selected file."""
with open(file, 'r', encoding='utf-8') as read_file:
csv = reader(read_file)
return [row for row in csv] | f55da44817eea8c7fa01883947dead57c7a8b52e | 59,364 |
def response_200(result=None):
"""GET에 대한 반환"""
return {
'msg': 'success',
'result': result
}, 200 | 2c2acbfed5ee678536671a367c67cc7d0b1fb6ba | 59,365 |
def get_all_players():
"""Returns a Dict with all players"""
return {x.player_name: x for x in soco.discover()} | 329ec97a1a91f62e5c2aec080c010736cff97336 | 59,366 |
def zernike(img, radius, degree=8, cm=None):
"""Zernike moments.
This geometric moment derivate is based on alternative orthogonal
polynomials, which makes it more optimal wrt. information redundancy. These
are invariant to rotation.
"""
img = np.asarray(img, dtype=np.float32)
assert img.nd... | dc206872a04900e553e83b52634fb71e13de6d46 | 59,367 |
def _list_agave(uri, agave):
"""
List contents of agave URI.
Args:
uri: parsed URI to list.
agave: dict that contains:
agave_wrapper: Agave wrapper object.
Returns:
On success: a list of filenames (basenames only).
On failure: False.
"""
file_list =... | 4c721f710b26687926a613a2346b19fc8fe18cf6 | 59,368 |
def overview_of_specific_year(request, year):
"""
Get the overview of a year
"""
data_of_year = DATA.get(str(year))
context_data = {}
if not data_of_year:
return Response({'error': f'Data not found for the year {year}'}, status=status.HTTP_400_BAD_REQUEST)
else:
context_data[... | fa1b67b75947e34fd85b00b46febc500d39a7554 | 59,369 |
import os
def _image_file_name_to_date(netcdf_file_name):
"""Parses date from name of image (NetCDF) file.
:param netcdf_file_name: Path to input file.
:return: date_string: Date (format "yyyymmdd").
"""
pathless_file_name = os.path.split(netcdf_file_name)[-1]
date_string = pathless_file_nam... | fbcfbaa5af07f7c6a28204da6d413a6fea7fed2d | 59,370 |
import ast
def unparse(tree: ast.AST):
"""`ast.unparse`, but cached."""
return ast_unparse(tree) | 0690df059cb6c5f16c401e6474ba8bda6f9c8a6a | 59,371 |
def limit():
"""The number of corpus files to process, e.g ``--limit 100`."""
return '--limit 50' | 45638e81c16cc9a89a7137566581b43d7e952f46 | 59,372 |
import regex
def len_img_block(string):
""" Length of image html blocks from a string. """
all_oc = regex.findall(r'<img\s[^<>]*+>', string)
tot_len = 0
for oc in all_oc:
tot_len += len(oc)
return tot_len | 73caeed3112164a4259a38b92b2041a8a0c6dfe4 | 59,373 |
def detect_noise(sp, spt, sp_win, type="positive", max_spikes=None,
resample=1):
"""Find noisy spikes"""
spike_waves = extract.extract_spikes(sp, spt, sp_win)
if type == "positive":
threshold = calc_noise_threshold(spike_waves, 1)
spt_noise = extract.detect_spikes(sp, threshold... | f3159ef0ae7abd1612e04acaf9f9542bdce0baf5 | 59,374 |
import itertools
def check_package_attributes(container, additional_requirements=[]):
"""
container may be a ConfigurationDescription or MetadataDescription
additional_requirements are context-specific attributes to be required
Returns an AttrErrorString of problems found. Caller can treat this like a... | 064cc6e1aec3fcdf00c5e84fd187239d1c93d27b | 59,375 |
def formatArrayTrinary(*arr, **kwargs):
"""Converts all elems to -1 (if elem < 0), 0 (if elem == 0), or 1 (if elem > 1) then formats the results as densely as possible.
"""
defaults = dict([
('delimiter', ','),
('fmt', '%1d'),
('newline', '\n'),
('squeeze', False),
... | b0e75db41ecd8c44da5c6c6eeb1f788335bc282b | 59,376 |
def protected_dict_attribute(
types=(),
subtypes=False,
checked=None,
module=None,
factory=None,
serialized=None,
serializer=None,
deserializer=None,
represented=True,
key_types=(),
key_subtypes=False,
key_factory=None,
child=True,
history=None,
data=None,
... | b0e70405d039e479b06b7d7f58edb7a271b82a06 | 59,377 |
def getAllV2ELBs():
"""
This function grabs each v2 elb from each region and returns
a list of them.
"""
regions = boto3.client('ec2').describe_regions()['Regions']
logger.info(f"searching {len(regions)} region(s) for modern load balancers.")
# get list of all load balancers in each region
... | 9dcfe50a64d6e71af8b7e5800801604c03fbd06a | 59,378 |
import os
def plot_loss(loss, save_dir='', name='Loss'):
"""Plot loss values."""
# Setup figure
fh, axh = tmp.subplot_fixed(
1,
1,
[300, 300],
x_margin=[100, 100],
y_margin=[100, 100]
)
# Plot data
axh[0][0].plot(loss, color='k')
axh[0][0].set_xlabel... | 2a2035749190815f8d922943f54481e31b8f9833 | 59,379 |
def class_is_meter_band(cls):
"""
Return True if cls_name is an instruction object
"""
return _unified_by_name(cls).is_instanceof("of_meter_band") | c417d3e09e1868ed68c838e6325341265cb93726 | 59,380 |
import re
def GetRepositoryFromEbuildInfo(info):
"""Parse output of the result of `ebuild <ebuild_path> info`
This command should return output that looks a lot like:
CROS_WORKON_SRCDIR=("/mnt/host/source/src/platform2")
CROS_WORKON_PROJECT=("chromiumos/platform2")
"""
srcdir_match = re.search(r'^CROS_... | dbc609f7d2c56f0d5e231cb0a1e2eb2ab7659f44 | 59,381 |
def train_input_fn(features, labels, batch_size):
"""An input function for training"""
# Convert the inputs to a Dataset.
dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))
# Shuffle, repeat, and batch the examples.
dataset = dataset.shuffle(1000).repeat().batch(batch_size)
... | ac40034800e4b87670cb8e1d1ea508edcd178162 | 59,382 |
def add_pacient(ime, priimek, cepivo=None):
"""Funkcija v bazo vstavlja novega pacienta za sprejem v bolnišnico."""
return None | 18d302d4a926d7af194850f68425137f5ef48968 | 59,383 |
import requests
def opsgenie_add_team(thread_name,tinyId,team,f_headers,source="",
user="Alexis Automation",note=""):
"""
Adds a team to an existing tinyId
:param tinyId: target tinyId
:param team: team to add to target tinyId
:param user: (optional) override if needed
:... | a43c716714e013181344d5dc7085be56d4d8291f | 59,384 |
def cloud_shadow_confidence(arr):
"""
00 = "Not Determined" = Algorithm did not determine the status of this condition
01 = "No" = Algorithm has low to no confidence that this condition exists (0-33 percent confidence)
10 = "Maybe" = Algorithm has medium confidence that this condition exists (34-66 perc... | 7b5afe6a5787b6ef03b3acbf7ef2abaa81497282 | 59,385 |
from datetime import datetime
def load_sequence_and_metadata(kind="csv"):
"""
Returns the sequences as a list of SeqRecords, and metadata as a pandas
DataFrame.
"""
starttime = datetime.now()
sequences = [
s for s in SeqIO.parse("data/20170531-H3N2-global.fasta", "fasta")
]
if ... | 3c68327040debf0ca897185cdd5a63bf64c62ac9 | 59,386 |
def itmMatchingThree_collate(inputs):
"""Text-Image-Audio Matching dataset collate function"""
(input_ids, img_feats, img_pos_feats, attn_masks, audio_feats
) = map(list, unzip(inputs))
# text batches
txt_lens = [i.shape[0] for i in input_ids]
input_ids = pad_sequence(input_ids, batch_first=Tru... | 3226805e1c25ec5db0ca19e9f7f233a9be4f65ea | 59,387 |
def R_ratio_local(omega_par, disp_vector, passive_el, ind_passive, coord, connect, E, v, rho, const_func, aux_R=True):
""" Calculates the local strain-to-kinetic energy ratio function.
Args:
omega_par (:obj:`float`): 2 * pi * frequency.
disp_vector (:obj:`numpy.array`): Displacement.
pa... | 64eabbf73175f2fb65cd966ad7b98827b856bf2b | 59,388 |
def align(sentence, span):
"""align. Searches for span in sentence, to create character offsets
Uses heuristics if the span happens more than once in a sentence.
Prefers the earliest span that also ends on a word boundary, which
is defined as a non-alpha numeric character (e.g. a space character)
r... | eeb9e9b3aabca4c3b39efc4bd24c42547cb2e754 | 59,389 |
import ssl
import sys
def run_david(pa, path_to_ensembl_maps="/flaski/data/david"):
#database, categories, user, ids, ids_bg = None, name = '', name_bg = '', verbose = False, p = 0.1, n = 2):
# Modified from https://david.ncifcrf.gov/content.jsp?file=WS.html
# by courtesy of HuangYi @ 20110424
"""Q... | e787b5423e41c5614e0722ca9625399e489ed4de | 59,390 |
def profile(request, username):
"""
This function sets a profile.
:param request: A request
:param username: A user name
:return: A render
"""
user = User.objects.get(username=username)
treasures = Treasure.objects.filter(user=user)
return render(request, 'profile.html', {'username':... | 311c827703197f82a9523b9ffe5dfbca64e8d485 | 59,391 |
def derivatives_close(x, y):
"""
Returns True iff the AffineScalarFunc objects x and y have
derivatives that are close to each other (they must depend
on the same variables).
"""
# x and y must depend on the same variables:
if set(x.derivatives) != set(y.derivatives):
return False ... | 5555348253ce7e64a348c41ce9b65517b985bf5b | 59,392 |
from re import M
def get_norm(norm):
"""
Args:
norm (str): currently support "BN", "SyncBN", "FrozenBN" and "GN"
Returns:
M.Module or None: the normalization layer
"""
if norm is None:
return None
norm = {
"BN": M.BatchNorm2d,
"SyncBN": M.SyncBatchNorm,... | 80bdc5b1327f6718ddb371f2bda4c2ffc179077f | 59,393 |
def extraerWrfoutSerie(wrf_file: str, variable: str, x: int, y: int):
""" extrae de los arechivos wrfout listados en file_paths
para la posicion (x, y) toda la serie de la variable
seleccionada"""
dfData = pd.DataFrame()
t2 = wrf.getvar(wrf_file, variable, timeidx=wrf.ALL_TIMES)
t2_loc = t2[:,... | 445034862c38dbbb23803354e35114208af8ad8b | 59,394 |
def grad_logloss_theta_lr_weighted(label,ypred,x,weight_ar=None,C=0.03,has_l2=True,scale_factor=1.0,weights=None):
"""Return d l_i / d_theta = d l_i / d_ypred * d y_pred / d theta
Args:
label: a scalar (one sample) or an array of shape [None,]
ypred: a scalar (one sample) or an array of shape [N... | 9d718a9b46648f257a30192cee0eb5905d87802a | 59,395 |
import pickle
def read_solver(filename):
"""
This function reads a .pk1 file.
Parameters:
filename (str): A file name or path to file excluding file extension.
Returns:
Content of the loaded .pk1 file.
"""
try:
file = open(filename+'.pk1', 'rb')
except IOError:
... | da7bcfb75af1edde3d43091fdbc5c1829c13e5e0 | 59,396 |
def chi_square(logu, name=None):
"""The chi-Square Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Chi-square Csiszar-function is:
```none
f(u) = u**2 - 1
```
Warning: this function makes non-log-space calculations and may therefo... | 9c221e7e9d0c08a671b00c6809014a42d04031bd | 59,397 |
def get_ir_grgrid_map(rotations, D_diag, PS=None):
"""Return grid point index mapping table to irreducible grid points
(Generalized-regular-grid version)
Parameters
----------
rotations : array_like
SNF transformed reciprocal rotation matrices. See some more detail
in the docstring... | 8d945ffaaefeb633446dc5ca23da41bc468e01c7 | 59,398 |
import matplotlib as mpl
import matplotlib.colors # call as mpl.colors
import matplotlib.cm # call as mpl.cm
def apply_alpha(colors, alpha, elem_list, cmap=None, vmin=None, vmax=None):
"""Apply an alpha (or list of alphas) to the colors provided.
Parameters
----------
colors : color string or arra... | b798c7be205e37c114f36b64288e8e15cf32135e | 59,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.