content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def client_code(abstraction: OperationSystem) -> str:
"""
За исключением этапа инициализации, когда объект Абстракции связывается с
определённым объектом Реализации, клиентский код должен зависеть только от
класса Абстракции. Таким образом, клиентский код может поддерживать любую
комбинацию абстракц... | ce34f6256ea9282af24edcebd5ea3487d90eb5f0 | 3,620,203 |
def consistent_langevin_dynamics(rng,
model,
sigmas,
init,
epsilon,
T,
denoise=True,
infi... | 95cdb247f6ba68cd053819946df34a3b22e3c644 | 3,620,204 |
def _random_colour_masks(image):
"""
Generates a random color mask.
:param image: Image to generate the mask.
:return: Coloured mask.
"""
r = np.zeros_like(image).astype(np.uint8)
g = np.zeros_like(image).astype(np.uint8)
b = np.zeros_like(image).astype(np.uint8)
r[image == 0], g[ima... | f294dd1337ee6bfeac28681b3d42a738c7b745df | 3,620,205 |
def get_cell_numbers(contained):
"""Retrieve non-overlapping cell numbers from the output of `get_overlapping`.
None may appear at the ends of the output, indicating that the corresponding
target cells are not overlapping with any source cells. These should be ignored
when regridding.
Cell numbers... | b0bf32676ec7bfa73e04d3afd7053675f95d4abd | 3,620,206 |
def get_mos(da, da_peak_times):
"""
Takes an xarray DataArray containing veg_index values and calculates the vegetation
values (time not available) at middle of season (mos) for each timeseries per-pixel.
The middle of season is the mean vege value and time (day of year) in the timeseries
at 80% t... | 510452f4e89e2e26107f4c8bc9cc7617f7b56b61 | 3,620,207 |
def alternate_remove_duplicates(qdb: dt.QueriesTextParser):
"""Different commands, same result"""
_dup_list = []
for topic, q_vars in qdb.query_vars.items():
_dup_list.extend(qdb.queries_df.loc[qdb.queries_df['qid'].isin(q_vars)].duplicated('text'))
return qdb.queries_df[~qdb.queries_df['qid'].i... | 66904ba17296ac2db4a13220c77e0415488297de | 3,620,208 |
def to_hash_bucket_deterministic(batch, num_buckets, seed=None):
"""Buckets input examples, roughly uniformly and deterministically.
Args:
batch: a tensor of rank >= 1, containing the input examples
(batch axis = 0).
num_buckets: an integer, number of buckets.
seed: (optional) this seed will be u... | 349e0ef889aaa01e328789717077a57bd0c6def0 | 3,620,209 |
import torch
def random_training_set(chunks, revmap, volatile=False, start=0, batch_size=util.BATCH_SIZE):
"""Generate a training set from the randomized set of chunks (sequences),
returning them in descending order by size (per Torch's variable length
sequence RNN support).
If `volatile` is True, th... | 9dbacfadd6e323bb9cc7e4e20827762563bd0100 | 3,620,210 |
def verify_password(username, password):
"""Verify that user exists and that password is correct."""
user = models.User.query.get(username)
if user and verify_password_argon2id(user.password, password):
return user
return None | 4be318a31589bc1cc91f7695b3c017c17597a5d2 | 3,620,211 |
def RandomUniform(inp, low=-1.0, high=1.0):
"""
Random uniformly distributed initialization.
"""
return np.random.uniform(size=inp, low=low, high=high) | d9a9ebf9417ab2af8a4e724c25699992f7814040 | 3,620,213 |
def twdb_texuni(dataframe, drop_dcp_metadata=True, dual_well=False):
"""Parser for twdb texuni dataloggers.
Data is transmitted every 12 hours and each message contains 12 water level
measurements on the hour for the previous 12 hours
format examples:
'"\r\n+0.000,-245.3,\r\n+0.000,-245.3,\r\n+0.00... | 19d1404cae00d0596c42a7d33eaa83b798702260 | 3,620,214 |
from typing import Optional
def FromMol(
mol: Chem.Mol, useGroups: Optional[bool] = True, useFilters: Optional[bool] = True
) -> str:
"""Convert RDKit Mol to AMSR
:param mol: RDKit Mol
:param useGroups: use group symbols/abbreviations
:param useFilters: apply filters to exclude unstable or synthe... | 0c748e5d118481cea41f838c8dd9f9d57de8e391 | 3,620,215 |
import heapq
import operator
def _similar_names(owner, attrname, distance_threshold, max_choices):
"""Given an owner and a name, try to find similar names.
The similar names are searched given a distance metric and only
a given number of choices will be returned.
"""
possible_names = []
names... | 6dd891666f6e5323a0a99529f5a3c3968bde4126 | 3,620,216 |
from typing import List
import requests
def list_remote_pipelines() -> List[str]:
"""List all the repositories in the pangeo-forge organization."""
r = requests.get(f"{BASE}/orgs/pangeo-forge/repos", headers=HEADERS)
r.raise_for_status()
repos = r.json()
repos = [repo["name"] for repo in repos if ... | 7ee508ae23cebc640da070e98c0faf0c7b8c204b | 3,620,217 |
def get_amended_desc(drev, ctx, folded):
"""similar to ``getdescfromdrev``, but supports a folded series of commits
This is used when determining if an individual commit needs to have its
message amended after posting it for review. The determination is made for
each individual commit, even when they ... | 4c35145a0c46b1da49a9caae7ff6c58100756f3f | 3,620,218 |
from datetime import datetime
def todays_artist_spotlight():
"""
If there is an artist spotlight for today, return that artist object
"""
today = datetime.date.today()
# get today's artist spotlight, if there is one
try:
spotlight = ArtistSpotlight.objects.get(date=today)
except A... | cfbe4c05273ce597f3254a634d2d6b50f066cbb6 | 3,620,219 |
def _get_angle(a, b, c):
"""
Get angle between vector ba and bc
"""
ba = a - b
bc = c - b
cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
angle = np.arccos(cosine_angle)
return np.degrees(angle) | b31dc0afab798f4ad31120f5cc52e9bfb7e5996b | 3,620,220 |
def _wx(item: str) -> dict:
"""
Parses remaining weather elements
"""
ret = {'wx': []}
items = item.split()
for item in items:
if len(item) < 3:
ret['wx'].append(item)
elif item.startswith('FV'):
_, ret['flight_visibility'] = core.get_visibility([item[2:]]... | f59c3ed994f9bb3e7c918828fcd59fa5de55bbde | 3,620,221 |
import re
def tag_validate(tags, case_ids, plan_id):
"""Tests tag checking func"""
error_msg = None
tag_id = re.findall('ID_\d+|id_\d+', str(tags))
if not tag_id:
error_msg = "Wrong Tag Format:\
\nPls add tag 'ID_case_id' to this case."
elif int(tag_id[0][3:]) not in case_i... | 3428426b480f2515ca08663f94dd0f8073ed8d18 | 3,620,223 |
def generate_tree_html(tree):
"""
Given a tree representing HTML file paths, return an HTML table plotting
those paths.
"""
items = []
for node, subtree in sorted(compat_items(tree)):
if 'entry' in subtree:
html = u'<li><a href="{}">{}</a></li>'.format(subtree['entry']['relpa... | a3aad84d08484958138126a78eb19def4587ed37 | 3,620,224 |
from typing import Tuple
def return_valid_table_names() -> Tuple[str, ...]:
"""Get a tuple of valid table names."""
return tuple(_TABLE_COLUMN_PATTERNS.keys()) | e03c84096c9ad3bf574d1ae473f5d58de757dec8 | 3,620,225 |
def cached_dataset(f, url=None, version=None, paths=None):
"""Test decorator providing a clone of `url` from cache
If config datalad.tests.cache is not set, delivers a clone in a temporary
location of the original `url`. Otherwise that clone is in fact a clone of a
cached dataset (origin being the cach... | df1bedc6c3a506e67f488f0af5b95a69e04b7d1d | 3,620,227 |
def _concat_nested_arrays(arrs, cells_as_numpy=False):
"""
Helper function to nest tabular arrays from nested list of arrays.
Parameters
----------
arrs : list of numpy arrays
Arrays must have the same number of rows, but can have varying
number of columns.
cells_as_numpy : boo... | f03762832198d7932eb87ea166711e50fff74bcb | 3,620,228 |
def submit_to_remote(name, value, **options):
"""
A submit button that submits via an XMLHttpRequest call
Returns a button input tag that will submit form using XMLHttpRequest
in the background instead of regular reloading POST arrangement.
Keyword args are the same as in ``form_remote_tag``.... | a9f993df00cfa934c3fa5f2dab6a5d08efce96d8 | 3,620,229 |
def commutative_similarity(node, target, tolerance=0, *args, **kwargs):
"""Apply :func:`monosaccharide_similarity` to ``node`` and ``target`` for both
``node --> target`` and ``target --> node``, returning whether either comparison
passes the tolerance threshold.
Parameters
----------
node: :cl... | e326ec075effbe0fc7ac8af5f64fed5564d9e1f1 | 3,620,230 |
import torch
def dataloader_subset(dl, batches=1):
"""Like torch's dataset Subset but for dataloaders. This lets us easily
do things like fit on a single batch (or small number of batches) by
essentially copying an existing dataloader's options but using a smaller
dataset. A few limitations: custom sa... | 47313fdcbfb150446af46213288077dfdcc4f608 | 3,620,231 |
import functools
def FormatFieldType(type_context, field):
"""Format a FieldDescriptorProto type description.
Args:
type_context: contextual information for message/enum/field.
field: FieldDescriptor proto.
Returns:
Formatted proto field type as string.
"""
label = 'repeated ' if field.label =... | c2fdc78ccf443a9914e3ee8e443d39e6360e21fd | 3,620,233 |
import urllib
def get_ip():
"""
获取本地ip
"""
my_ip = ""
try:
my_ip = urllib.request.urlopen('http://api.ipify.org').read()
except Exception:
my_ip = urllib.request.urlopen('http://icanhazip.com').read()
return bytes.decode(my_ip).strip() | 429eeb4e013874d6d4e23b43f1df52e450768ea1 | 3,620,234 |
from typing import get_args
def get_ict_dataset(use_titles=True, query_in_block_prob=1):
"""Get a dataset which uses block samples mappings to get ICT/block indexing data (via get_block())
rather than for training, since it is only built with a single epoch sample mapping.
"""
args = get_args()
bl... | f9fc744d0081e76e51789daf6f860feec18a8286 | 3,620,235 |
import pickle
def test_parallel_pickling():
""" Check that pmap captures the errors when it is passed an object
that cannot be pickled.
"""
def g(x):
return x ** 2
try:
# pickling a local function always fail but the exception
# raised is a PickleError for python <= 3.... | a18182ddbe7e9e4733ff34465c1fc7c8c7b62681 | 3,620,236 |
from cytoolz import get # not curried version
from toolz import get
def pair_assemble(t, on_left=None, on_right=None):
""" Combine a pair of records into a single record
This is mindful to shared columns as well as missing records
Parameters
----------
t : Join
The join to combine.
... | 7ee4b0a8de9ae9925702dba987f5a6b115f4373c | 3,620,237 |
def create_OrdinalEncoderTransformer_test_df():
"""Create DataFrame to use OrdinalEncoderTransformer tests that correct values are
DataFrame column a is the response, the other columns are categorical columns
of types; object, category, int, float, bool.
"""
df = pd.DataFrame(
{
... | bee0524b10321779dbb8a5f0c4847e833786834d | 3,620,238 |
from .._tier1 import set_column
from .._tier2 import maximum_of_touching_neighbors
def local_maximum_touching_neighbor_count_map(input : Image, destination : Image = None) -> Image:
"""Takes a label map, determines which labels touch and replaces every
label with the number of touching neighboring labels.
... | 81168267fffc7261b444bcd833618ca4c3fb36c2 | 3,620,239 |
def split_to_discretized_mix_logistic_params(inputs):
"""Splits input tensor into parameters of discretized mixture logistic.
Args:
inputs: A [batch, height, width, num_mixtures*10] tensor of floats
comprising one unconstrained mixture probability, three means
(one per channel), three standard devi... | f2bfa39d1913b9145a2268508e4041ae978ffe8b | 3,620,240 |
def get_clean_urls(raw_urls):
"""
Known problems so far:
https vs http
https://www.test.de vs https://test.de
https://www.test.de/something vs https://www.test.de/something#something
https://www.test.de/something.html vs https://www.test.de/something.html?something
"""
cleaned_urls = []
... | 19e238ff382c7c3dc83b779d7d82c59ff82820e9 | 3,620,241 |
from importlib.util import find_spec
def _pytest_has_xdist() -> bool:
"""
Check if the pytest-xdist plugin is installed, providing parallel tests
"""
# Check xdist exists without importing, otherwise pytests emits warnings
return find_spec("xdist") is not None | 77cc6d04d21f76b35b183fc4e9ebc2bf6824b744 | 3,620,242 |
def collaborative_baseline(data_train, testData, corrMatrix, K):
"""
Baseline method is used to compute the reconstructed matrix
Parameters
----------
data_train :
data present in train.csv file
testData :
data in test.csv file
corrMatrix :
correla... | 86e4ce780403b0969b337a464dc66c93d16b2ff0 | 3,620,243 |
def unpack_contours(df_filename: str, threshold: float = 0.6) -> gpd.GeoDataFrame:
""" Convert multipolygon contour row above given threshold into multiple Polygon rows. """
df = gpd.read_file(df_filename)
if len(df) <= 2:
if len(df[df.amax > threshold]):
return gpd.GeoDataFrame(geometry... | 0d5643ccb9ee91185229393c92cf69bf40ab0046 | 3,620,244 |
def makedist(dist_type, *pars, **kwards):
"""
Creates a distribution class from scipy continuous distributions
See https://docs.scipy.org/doc/scipy/reference/stats.html.
Parameters
----------
dist_type: String -> Type of the distribution (see the scipy documentation)
*pars and **kwards... | b9fb48e80d51cbeac5977d3e469ea14854f94def | 3,620,245 |
def sort(left_lane_sa,right_lane_sa):
""" Sorts lane values for left and right lanes
@left_lane_sa: Left Lane values after split and Append method
@right_lane_sa: Right Lane values after split and Append method
"""
#print(len(right_lane_sa));
if (len(left_lane_sa) != 0):
left_lane_sa =... | c9cc1e6e53c6d63754eb67c685d0282ec980e174 | 3,620,247 |
def normalize_km(KM, method='cosine'):
"""
Normalize a kernel matrix to have unit diagonal.
Cosine normalization normalizes the kernel matrix to have unit diagonal.
Implements definition according to Section 5.1 in book (Page 113)
Shawe-Taylor and Cristianini, "Kernels Methods for Pattern Analysis"... | f6964b59ad44a1ed1ab39e30bf7ca7d40511723c | 3,620,248 |
def init_tags(meta_tables, diffs):
"""
Initialize executable tags.
:param list[MetaTable] meta_tables: All related meta-tables.
:param list[bool] diffs: Whether to generate diff tags.
:rtype: list, dict
"""
tags = list()
meta_info = {
'cont': list(),
'disc': list(),
... | 092d905da84b7d9c2a23ad1e0838781e18b5dffb | 3,620,250 |
def get_bprop_concat(self):
"""Generate bprop for Concat"""
axis = self.axis
def bprop(x, out, dout):
dx = ()
out_offset = G.ConcatOffset(F.tuple_len(x), axis)(x)
for i in range(F.tuple_len(x)):
slice_out = P.Slice()(dout, out_offset[i], shape_op(x[i]))
dx = ... | d55ba8a71bbb786865f46fea793016d586adc1ed | 3,620,251 |
def network_allocation_update(context, id, values):
"""Update a network allocation DB record."""
return IMPL.network_allocation_update(context, id, values) | c06873b8f624b6b0bcdf4c3fdc5e7bab6a6a7736 | 3,620,252 |
import importlib
def build_model(model_name, weights_file=None, **kwargs):
"""Build the desired model."""
mod = importlib.import_module("."+model_name, __name__)
model = mod.build_model(**kwargs)
if weights_file:
try:
model.load_weights(weights_file, by_name=True)
print("Loaded existing model:... | 23cb3d093b435dc32ecefa8b1415d2c5d4cbc4dd | 3,620,253 |
def getExistingLineStringInBounds(*args, **kwargs):
"""Return the geom of the first Path whose geom is in bounds"""
bbox = kwargs.pop('bbox', settings.SPATIAL_EXTENT)
p = Polygon.from_bbox(bbox)
return models.Path.objects.filter(geom__contained=p)[0].geom | fecc1e7ab3803aade4eed6cfcd91c77211f65acc | 3,620,254 |
def solve(_n, tree):
"""
Given a list of list of tokens:
. (empty), or # (tree), compute the
number of trees one would encounter
if one traverses the 2D grid along
a slope of (3, 1).
:param _n: The number of rows in the
2D grid.
:param tree: The 2D grid as a list of list.
... | b4dbbc5c62d5b680242997e22c7a84d4ad583848 | 3,620,255 |
def _getNodeType(node): # {{{
""" return NodeType as String """
if node.nodeType == node.ELEMENT_NODE : return "ELEMENT_NODE"
elif node.nodeType == node.ATTRIBUTE_NODE : return "ATTRIBUTE_NODE"
elif node.nodeType == node.TEXT_NODE : return... | 70bda4da9f991f17602ba2992cb6c11f19141eac | 3,620,258 |
def rotate_map(hmap, rot_theta, rot_phi):
"""
Take hmap (a healpix map array) and return another healpix map array
which is ordered such that it has been rotated in (theta, phi) by the
amounts given.
"""
nside = hp.npix2nside(len(hmap))
# Get theta, phi for non-rotated map
t,p = hp.pi... | 82acb8c2fe91537a50d8ff2535e3d057f77f7960 | 3,620,259 |
import requests
def get_request(profile, resource):
"""Do a GET request to Github's API.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connec... | fceb53c4e1f840efcd0af069b44109085145130b | 3,620,260 |
def author_case_query(qn, author):
"""
Given a query number and an author, return a query for finding author
in VIVO
"""
if qn == 1:
query = """
SELECT ?uri
WHERE {
?uri foaf:lastName "{{ln}}" .
?uri a ufVivo:UFCurrentEntity .
?uri foaf:fir... | 08770e6d1768115c62dba522b4d67e7763d6a186 | 3,620,261 |
def snake() -> dict:
""" 4x2 Sanake """
temp = {
0 : {
0 : Conway(Position(0,0),True),
1 : Conway(Position(0,1),True),
2 : Conway(Position(0,2),False),
3 : Conway(Position(0,3),True)
},
1 : {
0 : Con... | b75483cd77c9dfaf515eedba54c4601f48c43d0f | 3,620,262 |
def parse_from_any(*classes):
"""Decorator for parsing a variably-typed class instance.
Attempt to parse the input as each of the provided classes, passing
the first successfully parsed class instance to the constructor of
this class. This operation is short-circuiting. Raise ParseError if
none of ... | 3c778cdaa1db7c4e39047de26fced0a0aac198c4 | 3,620,263 |
from typing import Dict
from typing import Any
import collections
def get_obs_dict(sys,
qp: brax.QP,
info: brax.Info,
observer: str = None,
component: Dict[str, Any] = None):
"""Observe."""
obs_dict = collections.OrderedDict()
if observer == 'q... | fb8437bb7cf179f2da16532e5e795578eb359a81 | 3,620,264 |
def part_two(data):
"""Part two"""
particles = []
i = 0
for line in data.splitlines():
split = line.split('>, ')
p, v, a = read(split[0]), read(split[1]), read(split[2])
particles.append([p, v, a, i])
i += 1
for _ in range(1000):
for particle in particles:
... | 5e4f9699452998a9e0b917e95444b1a9377d6437 | 3,620,265 |
def _raw_clean_data(survey):
"""Remaps values and cleans the data for saving"""
# Remap values for vote choice 2016 and 2020
remp_2020 = {
'I am not sure/don\'t know': 'No Vote',
'I will not vote, but am eligible': 'No Vote',
'I would not vote': 'No Vote',
'I am not eligible... | 58104c0d543c2a94e11f4b4aff9489b8725b3f45 | 3,620,266 |
def HT_TRENDMODE(data: xr.DataArray) -> xr.DataArray:
"""
Hilbert Transform - Trend vs Cycle Mode (Cycle Indicators)
Input:
data: time series
Output:
time series (values are 0 or 1)
"""
return single_series_call(talib.HT_TRENDMODE, data, ds.TIME) | 328459f579881ba5100749866bfa0316a64208fd | 3,620,267 |
from typing import OrderedDict
def get_with_text(key, path):
"""Get links for generated images."""
template = app.template_service.find(key)
if template.key != key:
return redirect(route('.get', key=template.key, path=path))
text = Text(path)
if text.path != path:
return redirect(... | ee17c572e9fa3806644b2f8f73a0cd15f896ce4c | 3,620,268 |
from xpedite.types import InvariantViloation
import time
def buildTimelineStats(category, route, probes, txnSubCollection): # pylint: disable=too-many-locals
"""
Builds timeline statistics from a subcollection of transactions
:param probes: List of probes enabled for a profiling session
:param txnSubCollecti... | 6f101006bb7cb96045ebeb45f1fc01377fa7d8b7 | 3,620,269 |
import math
def get_margin(home_team, away_team, home_team_score, away_team_score):
"""
Get the multiplier for the margin of victory
"""
goal_differential = home_team_score - away_team_score
return max(1, math.log(
abs(goal_differential - .85 * ((home_team.elo - away_team.elo)/100)) + math... | 0e54ff280e8a045230b221128539a9a6c054625f | 3,620,270 |
async def async_get_actions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device actions for Humidifier devices."""
registry = await entity_registry.async_get_registry(hass)
actions = await toggle_entity.async_get_actions(hass, device_id, DOMAIN)
# Get all the integrations... | d54b20296a3166540165875ed104de9592811f20 | 3,620,271 |
def map_all(process):
"""
"""
process_params1 = set_extra_values(process['arguments'])
process_params2 = get_process_params(process['arguments'], {'ignore_nodata': 'bool'})
return map_default(process, 'all_', 'reduce', {**process_params1, **process_params2}) | 87c5448d9f3bc208dba752f34eb343f1f3ac1a91 | 3,620,272 |
def create_scales(options):
"""
Creates the scales for imfil.m. Nothing much here right now, but
custom scales ... are in the near future.
dscal = create_scales(options)
C. T. Kelley, September 15, 2008
This code comes with no guarantee or warranty of any kind."""
custom_scales = options.custom_sca... | c0e42bec16761a83a532c7799622d9b35ee72367 | 3,620,273 |
import time
from datetime import datetime
def translate_promela_to_slugsin(code):
"""Return SlugsIn code from Promela `code`."""
t0 = time.time()
spec = logic.compile_spec(code)
aut = slugs._symbolic._bitblast(spec)
s = slugs._to_slugs(aut)
t1 = time.time()
dt = datetime.timedelta(seconds=... | 6218d4425b3be50f410b0e427876b54f2ccef4da | 3,620,275 |
import math
import torch
import tqdm
def validate(val_dataloader, model, criterion, config, save_dir=None):
"""Run validation.
Args:
val_dataloader (batchgenerators.dataloading.MultiThreadedAugmenter): val data iterator.
model (torch.nn.Module): model to train.
criterion (torch.nn.Mod... | e3237f5bde593b3380f39168a9cc92f158e5f6ec | 3,620,276 |
def load_recommendations(recommendations_file):
"""
Load ratings from file.
Parameters
----------
scores_file : str
The file that contains the rating info
Returns
-------
recs : dict
A recommendations dictionary in which userID is the key.
"""
if not isfile(reco... | 6a780ec05dbdad654c31dee6150431fc049350b1 | 3,620,277 |
def cosponsored_from_offset(member_id, offset, *, verbose=False):
""" Fetches the list of bill_id cosponsored by member """
ans = _get(common.URL_COSPONS(member_id, offset), verbose=verbose)
if ans:
bills = ans["bills"]
return [bill["bill_id"] for bill in bills]
else:
return [] | 9bf659198225e4cf377b24ebb2446b86204aef3a | 3,620,278 |
async def get_all_units():
"""
Get a list of all known unit symbols.
"""
return sorted(getAllUnitSymbols()) | 0d51ea496ac098c6896040951646632d71527833 | 3,620,279 |
from exporter.storages import HMRCStorage
def hmrc_storage(s3):
"""Patch HMRCStorage with moto so that nothing is really uploaded to s3."""
return make_storage_mock(
s3,
HMRCStorage,
bucket_name=settings.HMRC_STORAGE_BUCKET_NAME,
) | 65d7fc24e1ee63eb8daa1442b8a72f9edd54bda3 | 3,620,281 |
from typing import List
from re import T
from typing import Generator
def _chunks(lst: List[T], chunk_size: int) -> Generator[List[T], None, None]:
"""return chunks of chunk_size for list lst
>>> list(chunks([0, 1, 2, 3, 4], 2))
[[0, 1], [2, 3], [4]]
"""
return (lst[i:i + chunk_size] for i in ran... | 24a301898df77f3f297cfd34d3830ee2b766ada1 | 3,620,282 |
def load_data():
""" Load the csv data """
data = pd.read_csv(DATA_URL)
data['tweet_created'] = pd.to_datetime(data['tweet_created'])
return data | b41c3be9dea24a217a47a7e9456fcbd83a528e3d | 3,620,284 |
def _sbtype_has_field(sbtype, field_name):
"""Recursive helper to have has_field search up the inheritance hierarchy."""
for f in sbtype.fields:
if f.name == field_name:
return True
for b in sbtype.bases:
if _sbtype_has_field(b.type, field_name):
return True
for b in sbtype.vbases:
if ... | 8f2ec709214c9080b96acf267c66f1671fa47da3 | 3,620,286 |
def t_s(n, costheta):
"""Fresneltransmittance for two interfaces.
**Arguments:**
- **n**: iterable with two entries for (n_0, n_1)
- **theta:** iterable with two entries for (theta_0, theta_1)
"""
i, j = 0, 1
a = 2 * n[i] * costheta[i]
b = n[i] * costheta[i] + n[j] * costheta[j]
... | ae74b459ce0bb9172ed5d66c657ddba3065f4dd7 | 3,620,287 |
def calc_linhas_largura(dict_circ_desc, ponto):
"""criar linhas de largura"""
if dict_circ_desc["tipo_circulo"] == "meio":
linha_nao_intersecta_ponto = None
point_circ = Point()
point_circ.X = dict_circ_desc["pt_medios_circ"]["x_ptm"]
point_circ.Y = dict_circ_desc["pt_medios_circ... | 90dd8ccd91b458b76021e0e36bdb0e35d4f7a275 | 3,620,288 |
import email
def rfc_1123_date() -> str:
"""
Return the date formatted as per RFC 2616, section 3.3.1, rfc1123-date, as
described in
https://library.vuforia.com/articles/Training/Using-the-VWS-API.
"""
return email.utils.formatdate(None, localtime=False, usegmt=True) | 60074971427aef77be3e6eceb5dcecb7623452ef | 3,620,289 |
async def secure_mont(a, b, r, n, n_prime):
"""Montgomery multiplication.
See mont() docstring for details.
"""
assert type(a).bit_length >= 3 * (r.bit_length()) # Ensure a*b*n_prime fits
t = a * b
t_np_mod_r = t*n_prime % r
u = (t + t_np_mod_r * n) / r
return mpc.if_else(u >= n, u - n... | 9b01bb52de4ae1b47c281ec94fb4a66c23aa3cd5 | 3,620,290 |
def slice_out_int_literals(tensor, args):
"""
Allow passing int literals to factors in place of marginal distributions.
For those args which are int, specialise the tensor to handle these integer
values & eliminate these args from the arg list.
"""
n_args = len(args)
tensor, output_size, er... | 135b15bbd823eeddbd3f0304c0c54cadd0934d99 | 3,620,291 |
def make_color_checker_image_with_system_gamma(
width=1920, height=1080, luminance=100, system_gamma=1.0):
"""
Make a ColorChecker image with system-gamma applied.
"""
color_checker_width = int(width * 0.4)
font_st_pos = np.uint16(np.array([width, width]) * 0.03)
font_size = int(width * ... | 0df13867c8f9d0ce0de326ac6182d023a26bccf9 | 3,620,292 |
def bin_bucket_sort(arr):
"""
Binary bucket sort / 2-Radix sort
Time: O(NLog2N)
Space: O(N)
input: 1D-list array
output: 1D-list sorted array
"""
bucket = [[], []]
aux = list(arr)
flgkey = 1
while True:
for ele in aux:
bucket[int(bool(ele & flgke... | 8945ef31d5705d1462ce71ed6447bcc8d76e4665 | 3,620,295 |
def _identity(store: KeyValueStore) -> KeyValueStore:
"""
Helper function for `lazy_store`.
"""
return store | f681549b88f899417371e316e654a7564baf5b56 | 3,620,297 |
def log2(x):
"""
Compute the logarithm base 2 of `x`.
Return the "principal value" (for a description of this, see
`numpy.log2`) of :math:`log_2(x)`. For real `x > 0`, this is
a real number (``log2(0)`` returns ``-inf`` and ``log2(np.inf)`` returns
``inf``). Otherwise, the complex principle val... | 3803b7d54758255692d7b2826512c39921195b40 | 3,620,299 |
def get_url(query_str: str, base_url: str, page: int = 1) -> str:
"""Create query URL for Google CSE API search.
Args:
query_str: Search term to use.
base_url: Site URL.
page: Result page to start at.
Returns:
Completed URL.
"""
return (
_API_URL
+ "... | 151c47a1680356a9c6744d774bbec70ba0d9cc3c | 3,620,300 |
def build_full_traversal():
"""
Builds a traversal spec that will recurse through all objects .. or at
least I think it does. additions welcome.
See com.vmware.apputils.vim25.ServiceUtil.buildFullTraversal in the java
API. Extended by Sebastian Tello's examples from pysphere to reach networks
a... | 03f039945d4d5d34462e8f6dc9266a730300b837 | 3,620,301 |
def tonum(s):
"""Converts a string representation of a decimal, hexadecimal, or binary number to a number value or None."""
if type(s) in (int, float):
return s
if s is None:
return 0
base = 10
if isinstance(s, str):
if "x" in s:
base = 16
elif "b" in s:... | 4878a5619fcd96897f5bec6167bb8f0b4539588a | 3,620,302 |
from pathlib import Path
def mock_derived_metadata_derivation(
path: Path, parameters: any_pb2.Any) -> symfs_pb2.Metadata:
"""Mock custom derived metadata function.
The metadata this function generates will be simply a copy of the parameters,
which is assumed to be everchanging.symfs.ext.TestMessage, with ... | 9a2a3bd79765e2b8abdb0af15990a66234744ef3 | 3,620,303 |
import typing
def has_permissions(*permissions: typing.Tuple[str]):
"""
Checks if the user has the permissions.
"""
def decorator(func: typing.Awaitable):
func.has_permissions = permissions
return func
return decorator | faf5cdc4eb63bfb8925bed8fde7d7afbe29501a5 | 3,620,304 |
from typing import Optional
from typing import Type
from typing import MutableMapping
from typing import Any
def fromtree(
tree: etree.Element,
use_builtin_types: Optional[bool] = None,
dict_type: Type[MutableMapping[str, Any]] = dict,
) -> Any:
"""Convert an XML tree to a plist structure.
Args:
... | 67861407353fbf745a547854ad76971a3ec217d3 | 3,620,305 |
def patch_with_user_globals(data, skip_noexist=True):
"""
Patch the paths.json data structure with the user's globals in place.
:param data: the paths.json data structure
:param skip_noexist: skip applying global data if it doesn't exist
otherwise raise an error for a non-existant file
:ret... | 785bddc58f6bb2d0394e79b9a11cdbf2e90957fd | 3,620,306 |
def getdeleted(ref):
"""
Return the deleted positions (p=0 or p=1) from a report file.
"""
return [int(i) for i in fopen(ref+'.rep')[7]] | 72144fdd5f6ada178b303107c6c8d966aad28115 | 3,620,308 |
def generate_permutations(ls):
"""
Question 16.3: Generate all permutations of a list
"""
if len(ls) <= 1:
return [ls]
result = []
for perm in generate_permutations(ls[1:]):
for idx in xrange(len(ls)):
result.append(perm[:idx] + ls[0:1] + perm[idx:])
return resu... | f0d622b599d8b79e4c290f00a807afb9ac32cf55 | 3,620,310 |
from typing import Callable
from typing import Iterable
from typing import Any
async def async_setup_platform(
hass: HomeAssistantType,
config: ConfigType,
async_add_entities: Callable[[Iterable[Entity]], Any],
discovery_info=None,
):
"""Set up the sensor platform"""
return False | 912aedbc1cc844a6b18c93c3e566324173a4ba10 | 3,620,312 |
from china_stock_data_api import netease
def financial_info(index):
""" get the company financial info for index
:param index: stock index
:return: data frame containing financial data by season
"""
return netease.NeteaseStockInfo.latest(index) | 14a1f85ea8ed70db11d25a0a7f5e93c991dc8969 | 3,620,314 |
import pathlib
import glob
def presto_fft(eventfile,segment_length,demod,PI1,PI2,t1,t2):
"""
Obtain the FFT files that were generated from PRESTO
eventfile - path to the event file. Will extract ObsID from this for the NICER files.
segment_length - length of the segments
demod - whether we're dea... | 48d1579dd72575214dd757750964d4eb0b24926f | 3,620,316 |
import socket
def hostname():
"""
Check the system's hostname
:rtype: str
:return: system hostname
"""
return socket.gethostname().split('.')[0] | 438ccd56367565e0cf0c9e8783bc73cb4507e83b | 3,620,317 |
def run_optimizers(args):
"""Optimize each of an iterable of PySource objects."""
sources = tuple(load_path(args.source))
for source in sources:
utils.execute(args, source.node)
return sources | 4e43a1addbf3693eb29282ed0e0c85a4d6440976 | 3,620,318 |
import csv
def import_data(file):
"""
Imports instruction data from a .csv file, at the specified filepath
:param file: file
File object, to be read by the CSV reader
:return: list
A list of dictionaries, per row in the file, with the keys specified in the headers list
below
... | 472f47c2e2111d5ce9a9d20e1ac447a504941aa2 | 3,620,319 |
import re
def filter_data(data_frame):
"""
Process string value
:param data_frame: raw data in data frame type
:return: data frame
"""
data_frame[data_frame.columns[len(data_frame.columns) - 2]] = \
data_frame[data_frame.columns[len(data_frame.columns) - 2]].apply(lambda x: int("".join... | 75e3a40c0c1d06db7da71e8b6ddb0001c5933634 | 3,620,322 |
from datetime import datetime
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None):
""" get timezone as tz_offset """
tz_offset = datetime_to_timezone(
datetime.now(), tz=tz_from).strftime('%z')
tz_offset = tz_offset[:3] + ':' + tz_offset[3:]
date = parse_date(str(date_str) + tz_off... | 35aa52eee969dd3532b50c3a3679c24f0cf4f04e | 3,620,323 |
from typing import Tuple
from typing import List
from typing import Any
def _extract_bracket_params(meta_type: str) -> Tuple[str, List[Any]]:
"""
Gets parameters from the string representation of the type
Args:
meta_type (str): The string name of the metadata type
Returns:
Tuple[str,... | 38fc3872c18bb788a54d50b09a36cf3f5925550e | 3,620,324 |
def make_classification_df(
seed: int,
n_samples: int = 10_000,
n_features: int = 25,
n_informative: int = 10,
n_redundant: int = 10,
n_repeated: int = 5,
class_sep: float = 0.2,
flip_y: float = 0.1,
target_col: str = "target",
) -> pd.DataFrame:
"""Source of default values: http... | 31ea883341dbd2900ed7bd8402a796bad490ebde | 3,620,325 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.