content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def check_str_length(str_to_check, limit=MAX_LENGTH):
"""Check the length of a string. If exceeds limit, then truncate it.
:type str_to_check: str
:param str_to_check: String to check.
:type limit: int
:param limit: The upper limit of the length.
:rtype: tuple
:returns: The string it self... | 73ae59241a18c5398c041c2c332c932831a39c55 | 3,638,689 |
async def create_or_update(
hub,
ctx,
name,
resource_group,
prefix_length,
sku="standard",
public_ip_address_version="IPv4",
zones=None,
**kwargs,
):
"""
.. versionadded:: 4.0.0
Creates or updates a static or dynamic public IP prefix.
:param name: The name of the pu... | 08fb4db3f585ec8844e28e5fa90867f588cdb91a | 3,638,690 |
def _get_job_name(job_label: str = None) -> str:
"""Returns Beam runner job name.
Args:
job_label: A user defined string that helps define the job.
Returns:
A job name compatible with apache beam runners, including a time stamp to
insure uniqueness.
"""
job_name = 'tfrecorder-' + common.get_t... | 3786c532109c880ec9255b82a6a2442cf8414780 | 3,638,691 |
def all_not_none(*args):
"""Shorthand function for ``all(x is not None for x in args)``. Returns
True if all `*args` are not None, otherwise False."""
return all(x is not None for x in args) | 2d063f39e253a78b28be6857df08d8f386d8eb4a | 3,638,692 |
def weighted_photon_spec(eng):
""" Returns the weighted photon spectrum from positronium annihilation.
This assumes 3/4 ortho- and 1/4 para-, normalized to a single
annihilation.
Parameters
----------
eng : ndarray
The energy abscissa.
Returns
-------
Spectrum
T... | 39b5301d5e49f070d1128d678f4f0672b32c275d | 3,638,693 |
def get_for_tag(app_name):
"""
Retorna a tag for customizada para listar registros no template list.html
:param app_name: Nome do app que está sendo criado
:type app_name: str
"""
return "{% for " + app_name + " in " + app_name + "s %}" | 12399a148262893047bf21c20e784bfb33373c29 | 3,638,694 |
def _reloadFn(*args):
"""Placeholder callback function for :func:`_handleSIGHUP`."""
return True | 261a54f52e4e448671b8625dae4fbc67116bd546 | 3,638,695 |
def interpolation_lagrange_matrix(old_grid, new_grid):
"""
Evaluate lagrange matrix to interpolate state and control values from the solved grid onto the new grid.
Parameters
----------
old_grid : <GridData>
GridData object representing the grid on which the problem has been solved.
new... | ce219dbfa65842ad275fe22f1122474b865fcfb0 | 3,638,696 |
def optimize_shim(coils, unshimmed, mask, mask_origin=(0, 0, 0), bounds=None):
"""
Optimize unshimmed volume by varying current to each channel
Args:
coils (numpy.ndarray): X, Y, Z, N coil map
unshimmed (numpy.ndarray): 3D B0 map
mask (numpy.ndarray): 3D inte... | f9e5d88e4a54222c841b3a2a66254675218207c4 | 3,638,697 |
def _log(x1):
"""closure of log for zero arguments, sign-protected"""
with np.errstate(divide="ignore", invalid="ignore"):
x1 = np.where(np.abs(x1) > 0.001, x1, 1)
return np.where(x1 < -1, np.log(np.abs(x1)) * np.sign(x1), np.log(np.abs(x1))) | bcc782434b1e38749096d56e6b78df287a14eeb2 | 3,638,698 |
def whats_the_meaning_of_life(n_cores=23):
"""Answers the question about the meaning of life.
You don't even have to ask the question, it will figure it out for you.
Don't use more cores than available to mankind.
Parameters
----------
n_cores: int [default: 23]
The number of CPU cores... | 9b42257161ad3063bd7d8faddb6e385aa5586bf0 | 3,638,699 |
import tqdm
def get_good_start(system, numdistricts):
"""
Basically, instead of starting with a really bad initial solution for
simulated annealing sometimes we can rig it to start with a decent one...
"""
print('Acquiring a good initial solution')
solution = Solution(system, numdistricts)
... | 2c557c0505d0c442890c96ebb6186e866b5a7726 | 3,638,700 |
def search_up(word_list, matrix):
"""Search words from word_list in matrix, up direction
:param word_list - list of strings
:param matrix - list of lists
:return list of lists"""
return straight_search(word_list, matrix, True, False) | e806af0505a1cb78bf1bc181a89ccee81407c0b7 | 3,638,701 |
def int_validator(inp, ifallowed):
"""
Test whether only (positive) integers are being keyed into a widget.
Call signature: %S %P
"""
if len(ifallowed) > 10:
return False
try:
return int(inp) >= 0
except ValueError:
return False
return True | ee433a6365a0aad58cab0cd59fa05e132b669053 | 3,638,702 |
import logging
import requests
def scrape_page(url):
"""
scrape page by url and return its html
:param url: page url
:return: html of page
"""
logging.info('scraping %s...', url)
try:
response = requests.get(url)
if response.status_code == 200:
return response.t... | a09eb79ce6abe25e4eb740dcfeb7a4debfca0b88 | 3,638,703 |
def getProductionUrl(code,d0):
"""Get the url for outage data from d0 to d1."""
url = getUrl('png',code,2018,opts=[[None]])
url = url.replace('__datehere__',eomf.m2s(d0),)
return url | d7e13671494c719ecc41058d481bd8d4cef5a3ff | 3,638,704 |
def has_gaps_in_region(read, region):
"""
Returns True if the given pysam read spans the given pybedtools.Interval,
``region``.
"""
# If the given read has gaps in its alignment to the reference inside the
# given interval (more than one block inside the SV event itself), there are
# gaps in... | df1e272044d47bb610a59e80f21ad0fcca484231 | 3,638,705 |
def zha_device_joined(opp, setup_zha):
"""Return a newly joined ZHA device."""
async def _zha_device(zigpy_dev):
await setup_zha()
zha_gateway = get_zha_gateway(opp)
await zha_gateway.async_device_initialized(zigpy_dev)
await opp.async_block_till_done()
return zha_gatewa... | e8d8ac320414762416e2a105583001ac452df6b6 | 3,638,706 |
def get_all_list_data(request_context, function, *args, **kwargs):
"""
Make a function request with args and kwargs and iterate over the "next" responses until exhausted.
Return initial response json data or all json data as a single list. Responses that have a series of
next responses (as retrieved by... | dd9aea10691a553c4b36009d733c11d39ada970e | 3,638,707 |
def is_outlier(x, check_finite=False, confidence=3):
"""Boolean mask with outliers
:param x: vector
:param check_finite:
:param confidence: confidence level: 1, 2, 3 or 4, which correspond to
90%, 95%, 99% and 99.9% two-tailed confidence respectively (normal
distribution). Default: 3 (9... | 6fb1b9f157c3bf720a615892524d90df2f717096 | 3,638,708 |
def stateless_shuffle(value, seed):
"""Randomly shuffles a tensor, statelessly."""
flat_value = tf.reshape(value, [-1])
indices = tf.argsort(
tf.random.stateless_uniform(tf.shape(flat_value), seed=seed))
flat_shuffle = tf.gather(flat_value, indices)
return tf.reshape(flat_shuffle, tf.shape(v... | 4fa1ab8538ab5ab7f356c68d75c9fa61395a6e75 | 3,638,709 |
def is_one_line_function_declaration_line(line: str) -> bool: # pylint:disable=invalid-name
"""
Check if line contains function declaration.
"""
return 'def ' in line and '(' in line and '):' in line or ') ->' in line | e402cbbedc587ab0d572dfe6c074aadef6980658 | 3,638,710 |
def check_if_ended(id):
"""
Check if the course has already ended.
:param id: Id of the course that needs to be checked.
:type id: int
:return: If a course has ended
:rtype: bool
"""
course = moodle_api.get_course_by_id_field(id)
end_date = course['courses'][0]['enddate']
if(dt... | 0e67c58d2b107597f068a34c08289ce43f4d1beb | 3,638,711 |
def get_all_applications(user, timeslot):
"""
Get a users applications for this timeslot
:param user: user to get applications for
:param timeslot: timeslot to get the applications.
:return:
"""
return user.applications.filter(Proposal__TimeSlot=timeslot) | 40aec747174fa4a3ce81fe2a3a5eee599c81643a | 3,638,712 |
import requests
import webbrowser
def get_console_url(args):
""" Get a console login URL """
# Get credentials, maybe assume the role
session_creds = get_credentials(args)
# build the token request and fetch the sign-in token
url = request_signin_token(args, session_creds)
r = requests... | 0c12730f4e7f0367832f8cbe1e7b549b2582f2c6 | 3,638,713 |
def input_layer_from_space(space):
"""
create tensorlayer input layers from env.space input
:param space: env.space
:return: tensorlayer input layer
"""
if isinstance(space, Box):
return input_layer(space.shape)
elif isinstance(space, Discrete):
return tl.layers.Input(dtype=t... | 491c6d03d717bd33aa26264cd0296799f7fd242b | 3,638,714 |
def get_application_registry():
"""Return the application registry. If :func:`set_application_registry` was never
invoked, return a registry built using :file:`defaults_en.txt` embedded in the pint
package.
:param registry: a UnitRegistry instance.
"""
return _APP_REGISTRY | 64b0eeb19933cc674d4e61c27432f02d12340d6d | 3,638,717 |
import importlib
def get_dataset(cfg, designation):
"""
Return a Dataset for the given designation ('train', 'valid', 'test').
"""
dataset = importlib.import_module('.' + cfg['dataset'], __package__)
return dataset.create(cfg, designation) | 3f872d6407110cf735968ad6d4939b40fec9167d | 3,638,718 |
import uuid
def invite(email, inviter, user=None, sendfn=send_invite, resend=True,
**kwargs):
"""
Invite a given email address.
Returns a ``(User, sent)`` tuple similar to the Django
:meth:`django.db.models.Manager.get_or_create` method.
If a user is passed in, reinvite the user. For... | 46bc4d45b42d0cc2dbd80b2928f44e4926d24b77 | 3,638,719 |
def RestrictDictValues( aDict, restrictSet ):
"""Return a dict which has the mappings from the original dict only for values in the given set"""
return dict( item for item in aDict.items() if item[1] in restrictSet ) | 4333c40a38ad3bce326f94c27b4ffd7dc24ae19c | 3,638,720 |
def classify_images(images_dir, petlabel_dic, model):
"""
Creates classifier labels with classifier function, compares labels, and
creates a dictionary containing both labels and comparison of them to be
returned.
PLEASE NOTE: This function uses the classifier() function defined in
classifie... | 7d6679de95da2f7a526ae18a27d9602218f05153 | 3,638,722 |
def create_redis_fixture(scope="function"):
"""Produce a Redis fixture.
Any number of fixture functions can be created. Under the hood they will all share the same
database server.
Args:
scope (str): The scope of the fixture can be specified by the user, defaults to "function".
Raises:
... | 0e2e79c34feeb805c8300145f3a04314069b873f | 3,638,723 |
def get_heroes(**kwargs):
"""
Get a list of hero identifiers
"""
return make_request("GetHeroes",
base="http://api.steampowered.com/IEconDOTA2_570/", **kwargs) | b512377952c0c1415eb45cc05918e7d152516f83 | 3,638,724 |
from typing import Union
from typing import Optional
def gt_strategy(
pandera_dtype: Union[numpy_engine.DataType, pandas_engine.DataType],
strategy: Optional[SearchStrategy] = None,
*,
min_value: Union[int, float],
) -> SearchStrategy:
"""Strategy to generate values greater than a minimum value.
... | 751ee69c3cf396d0d2ca043bad17c6ed80b8d46d | 3,638,725 |
def get_smoker_status(observation):
"""Does `observation` represent a suvery response indicating that the patient is or was a smoker."""
try:
for coding in observation['valueCodeableConcept']['coding']:
if ('system' in coding and 'code' in coding and
coding['system'] == utils.SNOMED_SYSTEM and
... | e63f4ffc09af3af19fd493c4fbc2824ffa136a64 | 3,638,726 |
def model_input_data_api():
"""Returns records of the data used for the model."""
# Parse inputs
# Hours query parameter must be between 1 and API_MAX_HOURS.
hours = request.args.get('hours', default=24, type=int)
hours = min(hours, current_app.config['API_MAX_HOURS'])
hours = max(hours, 1)
... | 7f5d014dda1f4e778cf8df5aac453c8a19748465 | 3,638,727 |
def GetIAP(args, messages, existing_iap_settings=None):
"""Returns IAP settings from arguments."""
if 'enabled' in args.iap and 'disabled' in args.iap:
raise exceptions.InvalidArgumentException(
'--iap', 'Must specify only one of [enabled] or [disabled]')
iap_settings = messages.BackendServiceIAP()
... | bf17a15ebcaab42a930928e3a949c4357cdf718f | 3,638,728 |
def get_default_instance():
"""Return the default VLC.Instance.
"""
global _default_instance
if _default_instance is None:
_default_instance = Instance()
return _default_instance | f45a6eca003bc1b52b1c0bca1d15643898189899 | 3,638,729 |
def dirty_multi_node_expand(node, precision, mem_map=None, fma=True):
""" Dirty expand node into Hi and Lo part, storing
already processed temporary values in mem_map """
mem_map = mem_map or {}
if node in mem_map:
return mem_map[node]
elif isinstance(node, Constant):
value = nod... | f36b783041f7f6d2b7577db9160d702aa81461bd | 3,638,730 |
import json
def create_princess_df(spark_session) -> DataFrame:
"""Return a valid DF of disney princesses."""
princesses = [
{
"name": "Cinderella",
"age": 16,
"happy": False,
"items": {"weakness": "thorns", "created": "2020-10-14"},
},
{... | cded63b3882adbb48f7e39f37169f46b55a99ae3 | 3,638,731 |
from pathlib import Path
def get_sheet_names(file_path):
"""
This function returns the first sheet name of the excel file
:param file_path:
:return:
"""
file_extension = Path(file_path).suffix
is_csv = True if file_extension.lower() == ".csv" else False
if is_csv:
return [Path(... | 826ffb19f21ef117124d747c812a773f1422a10b | 3,638,732 |
def count_votes(votation_id):
"""
Count number of different vote_key. Its pourpose is to compare with voters.
"""
n = db.session.query(Vote.vote_key).filter(Vote.votation_id == votation_id).distinct().count()
return n | 81bd75c7185f9e46e0f2c2d2ed23d5717de98cbe | 3,638,733 |
def get_eng_cv_rate(low_prob):
"""Returns 'low' and 'high' probabilites for student to english I conversion
Simulated data for class enrollment.
Args:
low_prob(float): low end of probability
Returns: dict
"""
np.random.seed(123)
global eng_cv_rate_dict
eng_cv_rate_dict = {'low'... | 841653ab1d5938d1fd8e7a170fc8d6b4f0326248 | 3,638,734 |
from typing import Type
def dev_unify_nest(args: Type[MultiDev], kwargs: Type[MultiDev], dev, mode, axis=0, max_depth=1):
"""
Unify the input nested arguments, which consist of sub-arrays spread across arbitrary devices, to unified arrays
on the single target device.
:param args: The nested positiona... | 2c78c6fb3eb365c7742a134c33fa8f3bf2622bb2 | 3,638,735 |
def make_preprocessor(transforms=None, device_put=False):
"""
"""
# verify input
if transforms is not None:
if not isinstance(transforms, (list, tuple)):
transforms = (transforms)
for fn in transforms:
if not callable(fn):
raise ValueError("Each e... | 09c1b9dc027457a26f7d4b73e3a5572c206fc343 | 3,638,736 |
def timeRangeContainsRange(event1Start, event2Start, event1End, event2End):
"""
Returns true if one set of times starts and ends
within another set of times
@param event1Start: datetime
@param event2Start: datetime
@param event1End: datetime
@param event2End: datetime
@return: boolean
... | 05d25969b1f97f2f7015c9ce9bafbffcb931cb9b | 3,638,737 |
def compute_confidence_intervals(x: np.array, z: float = 1.96) -> float:
"""
Function to compute the confidence interval of the mean of a sample.
Hazra, Avijit. "Using the confidence interval confidently." Journal of thoracic disease 9.10 (2017): 4125.
Formula:
CI = x̅ ± z × (std/√n)
wh... | cd394ec2f4343ac82b16cc18a4ba280d2f57d1ad | 3,638,738 |
import socket
def SendCommands(cmds, key):
"""Send commands to the running instance of Editra
@param cmds: List of command strings
@param key: Server session authentication key
@return: bool
"""
if not len(cmds):
return
# Add the authentication key
cmds.insert(0, key)
# ... | 3db90749c3a88fd9341f6fbb9c4088d000d2d5ef | 3,638,739 |
import urllib
def esv(value, args=''):
"""
Use ESV API to get a Bible Passage
http://www.esvapi.org/v2/rest/passageQuery?key=IP&passage=Gen+1:5-10&output-format=plain-text
Looking for [[bible PASSAGE]]
Usage::
{{ text|esv}}
{{ text|esv:"option1:value,option2:value"}}
... | 5947071d3363f8308ddeb98a6f862488b942f89b | 3,638,740 |
import torch
def box_nms(bboxes, scores, labels, threshold=0.5, mode='union'):
"""Non maximum suppression.
source: https://github.com/kuangliu/pytorch-retinanet
Args:
bboxes: (tensor) bounding boxes, sized [N,4].
scores: (tensor) bbox scores, sized [N,].
threshold: (float) overlap thres... | 355262b9af52d0455089a05d90bfa7e21d5d52de | 3,638,741 |
def abs_length_diff(trg, pred):
"""Computes absolute length difference
between a target sequence and a predicted sequence
Args:
- trg (str): reference
- pred (str): generated output
Returns:
- absolute length difference (int)
"""
trg_length = len(trg.split(' '))
pr... | b5baf53609b65aa1ef3b1f142e965fa0606b3136 | 3,638,742 |
def CDLEVENINGSTAR(data: xr.DataArray, penetration: float = 0.3) -> xr.DataArray:
"""
Evening Star (Pattern Recognition)
Inputs:
data:['open', 'high', 'low', 'close']
Outputs:
double series (values are -1, 0 or 1)
"""
return multiple_series_call(talib.CDLEVENINGSTAR, data, ds.TIM... | 6da8ed1782cea60c626829fc7a33210ddd58754e | 3,638,743 |
def cern_authorized_signup_handler(resp, remote, *args, **kwargs):
"""Handle sign-in/up functionality.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response.
"""
# Remove any previously stored auto register session key
session.pop(token_session_key(re... | df2d8998acb5be4175069507832cd3bf90558824 | 3,638,744 |
def asset_from_iconomi(symbol: str) -> Asset:
"""May raise:
- DeserializationError
- UnsupportedAsset
- UnknownAsset
"""
if not isinstance(symbol, str):
raise DeserializationError(f'Got non-string type {type(symbol)} for iconomi asset')
symbol = symbol.upper()
if symbol in UNSUPP... | ae9463d1234cf409eaa52d5fbbdd158444b50b16 | 3,638,746 |
def ConvertHashType(value):
"""
Attempt to convert a space separated series of key=value pairs into a dictionary
of pairs. If any value fails to split successfully an error will be raised.
:param value: Space delimited string of key-value pairs
:return: Dictionary of key-value pairs.
"""
co... | 91cc47a855958a3ae352cd35a1eea84c5d8e45b4 | 3,638,747 |
def ts_dct_from_estsks(pes_idx, es_tsk_lst, rxn_lst, thy_dct,
spc_dct, run_prefix, save_prefix):
""" build a ts queue
"""
print('\nTasks for transition states requested...')
print('Identifying reaction classes for transition states...')
# Build the ts_dct
ts_dct = {}
... | 30d07aac9fb2c03b87017878cdb96ed750538c9d | 3,638,748 |
import re
def parse_msig_storage(storage: str):
"""Parse the storage of a multisig contract to get its counter (as a
number), threshold (as a number), and the keys of the signers (as
Micheline sequence in a string)."""
# put everything on a single line
storage = ' '.join(storage.split('\n'))
s... | 6e04091721177cdd3d40b86717eb86ebbb92a8ff | 3,638,749 |
def do_index(request):
"""Render the index page."""
projects = [
(name, path)
for name, path in config.all_projects()
if request.user.can_open(path)
]
login_block = render_login_block(request)
html = util.render_template(
config.get_path('www.index_template'... | f5ba6274ebe2e3fce875a44f727d258b536e2e46 | 3,638,751 |
from random import sample
import requests
def sample_coll(word, urns=[], after=5, before=5, sample_size = 300, limit=1000):
"""Find collocations for word in a sample of set of book URNs"""
# check if urns is a list of lists, [[s1, ...],[s2, ...]...] then urn serial first element
# else the list is a... | 37b343a82a9424fc408b9545a5875ee8bb0f4d9a | 3,638,752 |
def roll_array(arr: npt.ArrayLike, shift: int, axis: int = 0) -> np.ndarray:
"""Roll the elements in the array by `shift` positions along the given axis.
Parameters
----------
arr : :py:obj:`~numpy.typing.ArrayLike`
input array to roll
shift : int
number of bins to shift by
axis... | 79ad44163eb33408021879a0d64f3d0541e97410 | 3,638,753 |
def remove(favourites_list, ctype, pk, **options):
"""Remove a line from the favourites_list. """
instance = unpack_instance_key(favourites_list, ctype, pk)
return favourites_list.remove(instance, options=options) | 701c153d2f846c8431fae41b06ab5c28617845a3 | 3,638,754 |
def eHealthClass_airFlowWave(*args):
"""eHealthClass_airFlowWave(int air)"""
return _ehealth.eHealthClass_airFlowWave(*args) | 8af646f62c13f783c4b38524bf727fca038b0b7b | 3,638,755 |
def bp_symm_func(tensors, sf_spec, rc, cutoff_type):
""" Wrapper for building Behler-style symmetry functions"""
sf_func = {'G2': G2_SF, 'G3': G3_SF, 'G4': G4_SF}
fps = {}
for i, sf in enumerate(sf_spec):
options = {k: v for k, v in sf.items() if k != "type"}
if sf['type'] == 'G3': # Wo... | be882f791f4d4b2c9c575d836e9122604b89effa | 3,638,756 |
def create_dummy_window(show_all=True, should_quit=False, fullscreen=False):
"""
Function to create dummy window which does nothing.
:param show_all: True if window should be shown immediately
:param should_quit: True if window should quit after user closed it
:param fullscreen: True if window shou... | b8f7a2bb4bc2531bc9c49ccf8f89f0a23cd93667 | 3,638,757 |
def color_RGB_to_hs(iR: float, iG: float, iB: float) -> tuple[float, float]:
"""Convert an rgb color to its hs representation."""
return color_RGB_to_hsv(iR, iG, iB)[:2] | 14ae1cd29aca8de29bd3b776fe9a5e752015203d | 3,638,758 |
def simulation_aggreation_merge(rankings, baseline, method='od'):
"""Merge rankings by running simulation of existing rankings. This would first extract relative position of different ranking results,
and relative position are considered as simulated games. The game results are sent to another ranker that gives... | 56de703d3dc0bee0b8e77c0ac7e21e9f97a8d485 | 3,638,760 |
def maxOverTime(field,makeTimes=0):
"""Take the max of the values in each time step
If makeTimes is true (1) then we return a field mapping all of the times
to the average. Else we just return the max """
return GridMath.maxOverTime(field,makeTimes); | 53281490d0f42538564aeb701fb312bf2d22d509 | 3,638,761 |
from functools import reduce
from operator import add
def assemble_docstring(parsed, sig=None):
"""
Assemble a docstring from an OrderedDict as returned by
:meth:`nd.utils.parse_docstring()`
Parameters
----------
parsed : OrderedDict
A parsed docstring as obtained by ``nd.utils.parse_... | 90553c468a2b113d3f26720128e384b0444d5c93 | 3,638,762 |
import requests
def retrieve_unscoped_token(os_auth_url, access_token, protocol="openid"):
"""Request an unscopped token"""
url = get_keystone_url(
os_auth_url,
"/v3/OS-FEDERATION/identity_providers/egi.eu/protocols/%s/auth" % protocol,
)
r = requests.post(url, headers={"Authorization"... | 46d7eb0e057e2e8726effeeac45898c284bb2a4d | 3,638,763 |
import csv
import tqdm
def load_dataset(csv_path, relative_path):
"""
Inputs
---
csv_path: path to training data csv
relative_path: relative path to training data
Outputs
---
X: Training data numpy array
y: Training labels numpy array
"""
# Read CSV lines
lines = []
... | 01f6c639a41628ceca0a854c3096ca795a2da972 | 3,638,764 |
from typing import Dict
from typing import List
def randomly_replace_a_zone() -> rd.RouteDict:
"""
读入历史数据,把每条 high quality 的 route 的一个随机的 zone 替换成新 zone
:return: rd.RouteDict: 改过的route
"""
routeDict = rd.loadOrCreate()
rng.seed(3)
new_zone_id = 'zub_fy'
i: int
rid: str
route:... | 9bd3de2f35b6a356a610f091391726749a87cc56 | 3,638,765 |
import types
import itertools
def import_loop(schema, mutable, raw_data=None, field_converter=None, trusted_data=None,
mapping=None, partial=False, strict=False, init_values=False,
apply_defaults=False, convert=True, validate=False, new=False,
oo=False, recursive=False,... | b3849cd3e4b5cf338a3999954820c5f7d474e406 | 3,638,766 |
def resnet_50(inputs, block_fn=bottleneck_block, is_training_bn=False):
"""ResNetv50 model with classification layers removed."""
layers = [3, 4, 6, 3]
data_format = 'channels_last'
inputs = conv2d_fixed_padding(
inputs=inputs,
filters=64,
kernel_size=7,
strides=2,
data_format=dat... | 901954713b6c77334fc9050ab0c2758d9cad90dd | 3,638,767 |
def _sanitize_index_element(ind):
"""Sanitize a one-element index."""
if isinstance(ind, Number):
ind2 = int(ind)
if ind2 != ind:
raise IndexError(f"Bad index. Must be integer-like: {ind}")
else:
return ind2
elif ind is None:
return None
else:
... | 7d006d6ab0081fef01e162df63f76bcff691bbe3 | 3,638,768 |
def overlap_click(original, click_position, sr=44100, click_freq=2000, click_duration=0.5):
"""
:param click_position: Notice that position should be given in second
:return: wave
"""
cwave = librosa.clicks(np.array(click_position), sr=44100, click_freq=4000, click_duration=0.05) / 2
original, w... | 23a1668648c4b79b82088d149c6bc0b92ecd0326 | 3,638,769 |
import itertools
def vigenere(plaintext: str, *, key: str) -> str:
"""Vigenère cipher (page 48)
- `plaintext` is the message to be encrypted
- `key` defines the series of interwoven Caesar ciphers to be used
"""
plaintext = validate_plaintext(plaintext)
key = validate_key(key)
cycled_cip... | c2b0428a86673770f299842b459a44d64423ca52 | 3,638,770 |
def generateVtTick(row, symbol):
"""生成K线"""
tick = VtTickData()
tick.symbol = symbol
tick.vtSymbol = symbol
tick.lastPrice = row['last']
tick.volume = row['volume']
tick.openInterest = row['open_interest']
tick.datetime = row.name
tick.openPrice = row['open']
tick.highPrice ... | 108fbbf82eac228772cea90669fe14d90cbe8ccc | 3,638,771 |
import dataclasses
def hartigan_map_mutations(tree, genotypes, alleles, ancestral_state=None):
"""
Returns a Hartigan parsimony reconstruction for the specified set of genotypes.
The reconstruction is specified by returning the ancestral state and a
list of mutations on the tree. Each mutation is a (n... | cbdeb0bc2e23f5a0e2ca1d420a3e78c7476cabc9 | 3,638,772 |
import numpy
def padArray(ori_array, pad_size):
"""
Pads out an array to a large size.
ori_array - A 2D numpy array.
pad_size - The number of elements to add to each of the "sides" of the array.
The padded 2D numpy array.
"""
if (pad_size > 0):
[x_size, y_size] = ori_array.sh... | 28fac7ccb8fc08c3ac7cf3104fed558128003750 | 3,638,773 |
def finish_subprocess(proc, cmdline, cmd_input=None, ok_exit_codes=None):
"""Ensure that the process returned a zero exit code indicating success"""
if ok_exit_codes is None:
ok_exit_codes = [0]
out, err = proc.communicate(cmd_input)
ret = proc.returncode
if ret not in ok_exit_codes:
... | c8aa0f63f019b92b799cafd931f782a6855709ba | 3,638,774 |
def browse():
"""
A simple browser that doesn't deal with queries at all
"""
page = int(request.args.get("page", 1))
includeHistory = request.args.get("includeHistory", False)
results_per_page, search_offset = results_offset(page)
searchIndex = "history" if includeHistory else "latest"... | b579bf402d0034d950dcf2f87c08072d5a2959f9 | 3,638,775 |
from typing import cast
def argmax(pda: pdarray) -> np.int64:
"""
Return the index of the first occurrence of the array max value.
Parameters
----------
pda : pdarray
Values for which to calculate the argmax
Returns
-------
np.int64
The index of the argmax calculated ... | 9fbe515db4e40bf56373a1046a034f15f28d1849 | 3,638,776 |
import torch
def log_cumsum(probs, dim=1, eps=1e-8):
"""Calculate log of inclusive cumsum."""
return torch.log(torch.cumsum(probs, dim=dim) + eps) | 7f1ab77fd9909037c7b89600c531173dab80c11e | 3,638,777 |
def iou_coe_Slice_by_Slice(output, target, threshold=0.5, axis=(2, 3,4), smooth=1e-5):
"""Non-differentiable Intersection over Union (IoU) for comparing the similarity
"""
pre = tf.cast(output > threshold, dtype=tf.float32)
truth = tf.cast(target > threshold, dtype=tf.float32)
inse = tf.reduce_sum(... | 6292c25b8ca9c2fd78dd810703795bfa97877261 | 3,638,778 |
def splitTrainTestDataList(list_data, test_fraction=0.2, sample_size=None, replace=False, seed=None):
"""
Split a list of data into train and test data based on given test fraction.
Each data in the list should have row for sample index, don't care about other axes.
:param list_data: List of data to sa... | ae14275da02025f6c3c894c33da64d336cd0f5d1 | 3,638,779 |
def create_hyperbounds(hyperparameters):
"""
Gets the bounds of each hyperspace for sampling.
Parameters
----------
* `hyperparameters` [list, shape=(n_hyperparameters,)]
Returns
-------
* `hyperspace_bounds` [list of lists, shape(n_spaces, n_hyperparameters)]
- All combinations... | 4160e9084cd3f835f327661f4dacad80a348bd11 | 3,638,780 |
def race_from_string(str):
"""Convert race to one of ['white', 'black', None]."""
race_dict = {
"White/Caucasian": 'white',
"Black/African American": 'black',
"Unknown": None,
"": None
}
return race_dict.get(str, 'other') | 1d38469537c3f5f6a4a42712f5ec1dbd26a471bd | 3,638,781 |
def test_wrap_coordinates(coords, origin, wgs84):
""" Test whether coordinates wrap around the antimeridian in wgs84 """
lon_under_minus_170 = False
lon_over_plus_170 = False
if isinstance(coords[0], list):
for c in coords[0]:
c = list(transform(origin, wgs84, *c))
if c[0... | bd95c3bc1fd4f500e3af7a68af9d5e327656165e | 3,638,782 |
def filter_dfg_contain_activity(dfg0, start_activities0, end_activities0, activities_count0, activity, parameters=None):
"""
Filters the DFG keeping only nodes that can reach / are reachable from activity
Parameters
---------------
dfg0
Directly-follows graph
start_activities0
S... | 3969de1413e70234f76ab8f9e7a52126615d12c3 | 3,638,783 |
def generate_secret_key(length=16):
"""
Generates a key of the given length.
:param length: Length of the key to generate, in bytes.
:type length: :class:`int`
:returns: :class:`str` -- The generated key, in byte string.
"""
return get_random_bytes(length) | 76fd617e3b316321d2efc09e9f9253970e5b2d2d | 3,638,784 |
import io
def nouveau_flux(title: str, link: str, description: str) -> parse:
"""
Crée un nouveau flux RSS.
Parameters
----------
title : str
Titre du flux RSS.
link : str
Lien vers le flux RSS.
description : str
Description générale du contenu.
Returns
--... | 693f4df7c645fceddc288bd3511ec412cc7e9bd7 | 3,638,785 |
def extract_app_name_key():
"""
Extracts the application name redis key and hash from the request
The key should be of format:
<metrics_prefix>:<metrics_application>:<ip>:<rounded_date_time_format>
ie: "API_METRICS:applications:192.168.0.1:2020/08/04:14"
The hash should be of format:
... | 5ec563855fc417774368bf9027d8b853739fdc27 | 3,638,788 |
def load(filename, fs, duration, flipud = True, display=False, **kwargs):
"""
Load an image from a file or an URL
Parameters
----------
filename : string
Image file name, e.g. ``test.jpg`` or URL.
fs : scalar
Sampling frequency of the audiogram (in Hz)
durati... | 820be7b1cac4dd6e1b2e06cd28b01f47536930ad | 3,638,789 |
def get_status(lib, device_id):
"""
A function of reading status information from the device
You can use this function to get basic information about the device status.
:param lib: structure for accessing the functionality of the libximc library.
:param device_id: device id.
"""
... | 2321c1d61ec2566c4480c55c477c0fb598855df6 | 3,638,790 |
import json
from pathlib import Path
import heapq
def query_by_image_objects(image_path, weights_path, cfg_path, names_path,
confidence_threshold=0.5, save=False):
"""Processes user-uploaded image to retrieve similar images from database.
First, all the objects in the image are de... | dc718b3b5fe5f513b9281c5db30516ed32c8246f | 3,638,791 |
def suspend_supplier_services(client, logger, framework_slug, supplier_id, framework_info, dry_run):
"""
The supplier ID list should have been flagged by CCS as requiring action, but double check that the supplier:
- has some services on the framework
- has `agreementReturned: false`
- has not... | 6442bf7f287126c6e1fe445fa9bca1ccde4d142f | 3,638,792 |
def get_campaigns_with_goal_id(campaigns, goal_identifer):
"""Returns campaigns having the same goal_identifier passed in the args
from the campaigns list
Args:
campaigns (list): List of campaign objects
gaol_identifier (str): Global goal identifier
Returns:
tuple (campaign_goa... | 83d77ee2e6c1b9b5025a24e996e573fe816dd4b7 | 3,638,794 |
def tautologically_define_state_machine_transitions(state_machine):
"""Create a mapping of all transitions in ``state_machine``
Parameters
----------
state_machine : super_state_machine.machines.StateMachine
The state machine you want a complete map of
Returns
-------
dict
... | 0e7300a616811e26481b9a66ee8f22336fbd5943 | 3,638,795 |
from typing import List
def topk_errors(preds: Tensor, labels: Tensor, ks: List[int]):
"""
Computes the top-k error for each k.
Args:
preds (array): array of predictions. Dimension is N.
labels (array): array of labels. Dimension is N.
ks (list): list of ks to calculate the top acc... | 39a69f745eb789df4a47a776f7c84fa0b7a8b25a | 3,638,796 |
def extract_data_from_inspect(network_name, network_data):
"""
:param network_name: str
:param network_data: dict
:return: dict:
{
"ip_address4": "12.34.56.78"
"ip_address6": "ff:fa:..."
}
"""
a4 = None
if network_name == "host":
a4 = "127.0.0.... | 431eb3f7bda8c5e4d5580bc4be19185223d39c4d | 3,638,797 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.