content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_documents():
"""
Queries a given page from Solr and sends them to the front end
:param page: The page number
:param num_per_page: Number of entries per page
:param sort_field: The field used for sorting (all fields in SolrDoc)
:param sort_order: asc / desc
:param search_term: string... | 0a76ff5955241c79b3db5b5c08cf034ba92ab341 | 3,624,100 |
def session_read_wamp_data_with_diff(con:Connection, eventId=None,tsBegin=None, num=10) -> list[dict]:
"""collect a number of messages from table WAMPDATA.
the first row of the result is the full data from the database and will be included "as is" (MessageType.STATE)
the following rows contain just the delt... | 5531b4d228759f94ed1f38f4f8a2c7bee073d689 | 3,624,101 |
import os
def get_random_request():
"""Random test case.
This function sets up a random test case that differs depending on whether MPI capabilities
are available or not.
"""
num_tasks = np.random.randint(5, 25)
num_proc = np.random.randint(1, num_tasks)
# We need to check whether MPI w... | 222aff93ea0ccd8ae870d141ad3e6aa7aa0cf180 | 3,624,102 |
from typing import Optional
from typing import Tuple
def random_subsample(
data: np.ndarray, n_samples: int, random_state: Optional[int] = None
) -> Tuple[np.ndarray, np.ndarray]:
"""Random uniform subsample without replacement of data.
Parameters
----------
data
point cloud
n_sample... | 55872d7faa07b24c886a8aa2b43e87aa340df267 | 3,624,103 |
def get_instance_ips():
"""
Function to get instance IPs of your servers.
Sometimes you'd want to do this, if your IPs are
allocated dynamically, e.g. an auto-scaling group
within AWS.
if you have only one system. you can simpley use localhost or its ip for that.
Returns: None
"""
r... | 92b0cc79022d60b5cd11a050b14237fb397bda86 | 3,624,104 |
def ellipse(shape):
"""
This function ...
:param shape:
:return:
"""
x_center, y_center, x_radius, y_radius, angle = ellipse_parameters(shape)
return Ellipse(Position(x_center, y_center), Extent(x_radius, y_radius), Angle(angle, u.Unit("deg"))) | aa48e64e1c369329dc7566aeefd7077baf398754 | 3,624,105 |
from typing import List
from typing import Union
def __parse_db(db_exp: str) -> List[Union[str, int]]:
"""
Parse a DB directive returning its contents as a list.
:param db_exp: DB directive command.
:return: Contents of the db as the directive.
"""
db_exp_ = db_exp.split(" ", 1)[1]
db_para... | 26337261033d9f59238c727842b8c3cbe5be2d88 | 3,624,106 |
def trimap(adata: AnnData, *args, **kwargs):
"""\
Scatter plot with trimap basis.
Parameters
----------
adata: :class:`~anndata.AnnData`
an Annodata object.
%(scatters.parameters.no_adata|basis)s
Returns
-------
Nothing but plots the pca embedding of the adata o... | fc86b113e73d5d1013db80b4770ce46880979c61 | 3,624,107 |
def _fspath(path):
"""Return the path representation of a path-like object.
If str or bytes is passed in, it is returned unchanged. Otherwise the
os.PathLike interface is used to get the path representation. If the
path representation is not str or bytes, TypeError is raised. If the
provided path i... | dfffc592e8e03095c91653327d673e424480dfcf | 3,624,108 |
def border(img, amount=1, value=0):
"""
Adds requested amount of padding in each direction.
"""
if len(img.shape) == 3:
# Handle multiple channels.
h,w,c = img.shape
out = np.zeros((h+amount*2, w+amount*2, c), dtype=img.dtype)
for i in range(c):
out[:, :, i] = border(img[:, :, i], amount, ... | 2983ec0efced1fe566b093135406bfaed5f3a069 | 3,624,109 |
from unittest.mock import patch
async def test_setup_updates_from_ssdp(hass: HomeAssistant) -> None:
"""Test setting up the entry fetches data from ssdp cache."""
entry = MockConfigEntry(domain="samsungtv", data=MOCK_ENTRYDATA_WS)
entry.add_to_hass(hass)
async def _mock_async_get_discovery_info_by_st... | a0cab1cb492fd5bcb369f983381fafa2ef7cdd53 | 3,624,110 |
def hcolor(data, thresholds):
""" Multicolor a graph according to thresholds
:param data: the data
:type data: list of tuples (info, value)
:param thresholds: dict of thresholds, format
{<threshold>: <color>,}
:type thresholds: dict
:return: the colored graph
:rtype: list of arrays
... | 00b18c204ea97a7f5d919122b08488c42a25e9da | 3,624,111 |
def rank_documents(query, idx, years, citations, n=10, k=1.2, b=0.75, y=0.1, c=1):
"""
Rank documents according the ranking function score
"""
print('Finding relevant documents to the search term: "%s"' % query)
# Stem the query before passing into the score for standardization
stemmer = nltk.stem.porter.Porte... | 7dc24c8d32118ba31fabd853ca522498890d3049 | 3,624,112 |
def get_unique_id(x):
"""Returns the creation number of the object 'x'. For objects created
by the program, it is globally unique, monotonic, and reproducible
among multiple processes. For objects created by a debug command,
this returns a (random) negative number. Right now, this returns 0
for a... | 6ff78d43e31301edd4ed48a2bbebffceadb33178 | 3,624,113 |
def euler_problem_6(n=100):
"""
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numb... | 550d29deea17b3047bc869a134837d4f5c1baf95 | 3,624,114 |
def delete_wishlists(wishlist_id):
"""
Delete a Wishlist
This endpoint will delete a wishlist based the id specified in the path
"""
app.logger.info(f'Request to delete wishlist with id: {wishlist_id}')
wishlist = WishList.find(wishlist_id)
if wishlist:
wishlist.delete()
app.lo... | b88ba1d44db158b276409185e037910019167910 | 3,624,115 |
def _parse_http_429_5xx_retry_after(result=None, **ignored):
"""Return seconds to throttle"""
assert result is not None, """
The signature defines it with a default value None,
only because the its shape is already decided by the
IndividualCache's.__call__().
In actual code path,... | 041a334af8b79e33f875251e189a4a60862f519a | 3,624,116 |
def inject_local_assets():
"""only ever run from forge-generate"""
return [
{'when': {'platform_is': 'ios'}, 'do': {'inject_local_assets': ()}},
{'when': {'platform_is': 'android'}, 'do': {'inject_local_assets': ()}},
] | 71d8df6950f4cd3e51f31fb660297916f0fa1ecc | 3,624,117 |
from re import M
def makeSnap(datfile, pngfile, \
bHeader=True, \
m_sun=1.0, \
xrange=None, \
yrange=None, \
axis="a-e", \
m_cut=0., \
m_emp=0., \
size=10., \
color0="blue",\
color1="midni... | 59e3c5a85efe547623289e54d4ff014d12ec7ce0 | 3,624,118 |
def islamic_add(request):
""" Add new package and see the list of packages """
success_message, error_message = None, None
form = IslamicForm
islamics = Islamic.objects.all()
if request.method=="POST":
form = IslamicForm(request.POST)
if form.is_valid():
obj ... | 7f456b321a7759627647d844014638317d092d8e | 3,624,119 |
def details(id):
"""
This page allows recruiters to view and edit a member's details.
Methods:
GET
POST
Args:
id (int) - id of the member to examine
Returns:
rendered template 'details.html'
"""
if not current_user.recruiter and not current_user.mentor and ... | cd15dc9690a90139fd051160dc1f9af059bc1803 | 3,624,120 |
import os
def deploy_func_two_phase(imageList, thresh, nms, approach):
"""object detection pipeline for two-phase approach
Args:
imageList (list): list of image paths to predict
thresh (float): threshold value for detector
nms (float): nms threshold value
approach (object)... | f15e12885829019359662f80a75b483e1e4bf18e | 3,624,121 |
import argparse
def pa_cmd(args, cmd):
"""List lGTWs parser method.
usage: empower-ctl.py list-lgtws <options>
optional arguments:
-h, --help show this help message and exit
-g LGTW_EUID, --lgtw_euid LGTW_EUID
show results for specified lGTW id only
... | 23640de098b613ad3657d3c9cb6f22040c742b3f | 3,624,122 |
from datetime import datetime
def notas():
"""Renders the overview of the Notas state."""
usuario = mdl.Usuario.objects.get(user_id=session['user_id'])
trimestres = mdl.Trimestre.objects
trimestre = trimestres.get(id=session.get('trimestre_id'))
notas_trim = trimestre.notas # Notas de este trimes... | 7d4af170ff9e694ad489a5b8dda6e2e7105533e8 | 3,624,123 |
def to_float(val):
"""
Parse a string to float
"""
return None if val in NULL_VALUES else float(val) | 3fd985e4aef86cc9bc8b59572f46e6bc1ddcf50a | 3,624,124 |
def freedom(L=5):
"""
DOES NOT DO ANYTHING
"""
return -1 | e612245ec6023f3710da63baedf9997c92f4e279 | 3,624,125 |
def expected_config_dict():
"""Used to validate `self_check()` and `test_yaml_config()` outputs."""
config = {
"class_name": "InferredAssetGCSDataConnector",
"data_asset_count": 2,
"example_data_asset_names": ["directory", "path"],
"data_assets": {
"directory": {
... | 4c5e5fcad531eb3a4fb6deb873586c34dfe60ff6 | 3,624,126 |
def get_num_classes(dataset_name: str) -> int:
"""
Get the number of supervised loss given a dataset name.
:param dataset_name: dataset name
:return: number of supervised class.
"""
if dataset_name == "cifar10":
return 10
elif "cifar100" in dataset_name:
return 100
else:
... | dc699aeaef87b1763c9986cda596b920156e2478 | 3,624,127 |
import numpy
import time
def syn_gemm(A, B, C, mc, kc, nc, mr=1, nr=1, gepb_mode = gepb_simple):
"""
"""
cgepb = synppc.Program()
cpackb = synppc.Program()
proc = synppc.Processor()
gepb = SynGEPB(gepb_mode)
packb = SynPackB()
M, N = C.shape
K = A.shape[0]
nc = min(nc, N)
kc = min(kc, K)... | d0a588f40b87b12b44f7ac2a6324a2e87a23dea1 | 3,624,128 |
import random
import requests
def add_task(title):
"""
Purpose:
Add Task to the board in To Do list
Args:
title (string)
"""
# Create random label category
idLabels=[]
idLabels.append(random.choice(list(task_lbls.values())))
url = "https://api.trello.com/1/cards"
p... | ec6aef394272e639935e41f167c846cf814d794a | 3,624,129 |
def config_event():
"""Configure parameters for scraping."""
print('-=-Definição do evento-=-\n')
event = str(input(
'- Opções:\n'
'38 - 2017\n'
'39 - 2019\n'
'40 - 2021\n'
'Todos\n'
'Digite o número corresponden... | 8a1f01da5c73d64922460bffd73a7195f272acf0 | 3,624,130 |
import base64
def create_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An obj... | 9990a46deff9b3a771bf3fe192bcae55ddc77c6e | 3,624,131 |
from re import VERBOSE
import sys
import csv
def read_csv(file_name, skip_header=True, char_det=False):
"""
CSVを読み込んで辞書を作成する。
1列目と2列目のみ処理をして3列目以降は無視をする。
Args:
file_name (str): CSVファイル名
skip_header (bool): 一行目をヘッダとしてスキップするかどうか
Returns:
dict: 作成した辞書
"""
db = {}
... | 52fdc92daa98d7fdd93c147d4c0ede967cdbe880 | 3,624,132 |
def get_update_status(current_version: str, versions: Versions) -> str:
"""Given a version, determine the definitive status of the application."""
if not versions:
return ""
latest = get_latest_version(versions)
if not latest or StrictVersion(latest) <= StrictVersion(current_version):
r... | 666ad0cef4d2da77cade1647420f96eb8819b829 | 3,624,133 |
def get_bsse_section(natoms_a, natoms_b, mult_a=1, mult_b=1, charge_a=0, charge_b=0):
"""Get the &FORCE_EVAL/&BSSE section."""
bsse_section = {
'FORCE_EVAL': {
'BSSE' : {
'FRAGMENT': [{
'LIST': '1..{}'.format(natoms_a)
},
{
... | 61c9398ed35eaaf2212c2c1a66e2cf43b9bbe029 | 3,624,134 |
def apply_bucketize_op(x, boundaries, remove_leftmost_boundary=False):
"""Applies the bucketize op to every value in x.
x and boundaries are expected to be in final form (before turning to lists).
Args:
x: a `Tensor` of dtype float32 with no more than one dimension.
boundaries: The bucket boundaries re... | 30cdd31d92cbc1f0d869e0a538f691749ef10bed | 3,624,135 |
def query_quadrangle(client, partition_key, *args):
"""
Iterates the values that fail within the defined quadrangle
for the geospatial key.
Arguments:
client - the Redis client instance
partition_key - the geospatial set key
bounds - the bounds as an array of [nw,se]
- or -
nw - the north we... | 0b66300a70925b142f0a2e162bfcabacb334af93 | 3,624,136 |
import re
def load_placement(placement_file):
"""
Loads VPR placement file. Returns a tuple with the grid size and a dict
indexed by locations that contains top-level block names.
"""
RE_PLACEMENT = re.compile(
r"^\s*(?P<net>\S+)\s+(?P<x>[0-9]+)\s+(?P<y>[0-9]+)\s+(?P<z>[0-9]+)"
)
... | 72b534b5c8597f4a42d02e041c69a8fc3c92e8f7 | 3,624,137 |
import os
import glob
def find_matching_geoloc_file(radiance_filename, myd03_dir):
"""
:param radiance_filename: the filename for the radiance .hdf, demarcated with "MYD02".
:param myd03_dir: root directory of MYD03 geolocational files
:return geoloc_filename: the path to the corresponding geolocation... | 622a0c8c8900d86d97355c8f44c90f583a858b3d | 3,624,138 |
def license_path(licenses):
"""Get license path."""
# return license if there is exactly one license
return licenses[0] if len(licenses) == 1 else None | b8194e099c4516627edab6c4538e5dfcdc6600a3 | 3,624,139 |
import glob
import os
def get_next_run(exp_dir):
"""
get run id by looking at current exp_dir
"""
next_run = 0
files = glob.glob(os.path.join(exp_dir, "*.log"))
for file in files:
filename = os.path.basename(file)
run = filename.split('.')[0]
id = int(run[3:])
i... | e00f19adbca5c64dddf2b9ccbe6447d4356fa7a4 | 3,624,140 |
def create_pickle_data():
"""create the pickle data"""
# custom geometry column name
gdf_the_geom = geopandas.GeoDataFrame(
{"a": [1, 2, 3], "the_geom": [Point(1, 1), Point(2, 2), Point(3, 3)]},
geometry="the_geom",
)
# with crs
gdf_crs = geopandas.GeoDataFrame(
{"a": [... | 7ab82444fb5dc66e79b56a87fc94b61964911d44 | 3,624,141 |
from datetime import datetime
def complete_month(year, month):
""" Return a string with the month number padded with zero if the month has
only one digit. It is also necessary to provide a year.
:param year:
:param month:
:return: Month number padded with zero.
:rtype: str
"""
return ... | 03915be101c0f418caa78ae6bc423273ad3af24c | 3,624,142 |
import numpy
def greater_equal(self, other):
""" Equivalent to the >= operator.
"""
return _PropOpB(self, other, numpy.greater_equal, numpy.uint8) | 0c5e9b621334e6f9154d6a972f22c49ff7a963af | 3,624,143 |
def simu_data(evoked, forward, noise_cov, n_dipoles, times, nave=1):
"""Simulate an evoked dataset with 2 sources.
One source is put in each hemisphere.
"""
# Generate the two dipoles data
mu, sigma = 0.1, 0.005
s1 = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(times - mu) ** 2 /
... | cf407bfbfd27304a90716bcfa2ecc0d9d6e2caf6 | 3,624,144 |
import glob
import os
def list_api(file_pattern):
"""
return list according to file_pattern
"""
file_list = [f for f in glob.glob(file_pattern)]
targets = []
for file in file_list:
targets.append(os.path.basename(file).split(".")[0])
return targets | 6984eeeddfffd124bd0b962d7e7d2ab955c09fcc | 3,624,145 |
import os
def refined_grid(epc_file, source_grid, fine_coarse,
inherit_properties = False, inherit_realization = None, inherit_all_realizations = False,
source_grid_uuid = None, set_parent_window = None, infill_missing_geometry = True,
new_grid_title = None, new_epc_... | 7c3eb613114896c6ebd2fabe740bf41fba57121b | 3,624,146 |
def transform(window, transform):
"""Construct an affine transform matrix relative to a window.
Parameters
----------
window: Window
The input window.
transform: Affine
an affine transform matrix.
Returns
-------
Affine
The affine transform matrix for the given ... | a9516c753809e1a22a498aa2b932d92084b747e5 | 3,624,147 |
def auto_escape_sub(match):
"""Escapes ampersands (&) in normal text."""
return escape(match.group(0)) | 0c2693e6365e24e36356f91797716f071954414b | 3,624,148 |
import sys
import os
def get_lib_dir():
"""
Anaconda specific
"""
dirname = 'DLLs' if sys.platform == 'win32' else 'lib'
libdir = os.path.join(sys.prefix, dirname)
return libdir | c13277f73b35d64e37854872e6869a4cf36a9dc7 | 3,624,149 |
def populate_form_data(form):
"""
populate form data from settings
"""
for k, _ in form.data.items():
if k == "csrf_token":
continue
value = gluu_settings.db.get(k.upper())
if value:
form[k].data = value
return form | 955387be801a6a835b56f6546f86746a9af5cd22 | 3,624,150 |
def list_cached_maps():
"""Return a list of all cached maps."""
return local_index()['maps'] | b6b430d2d61dbfec940e97011180327a5b9f36a9 | 3,624,151 |
def _viewer_size(shape):
""" Define the size of the viewer.
Returns: width_view, height_view
"""
# slices_width = sagittal_width (y) + coronal_width (x) + axial_width (x)
slices_width = shape[1] + 2 * shape[0]
# slices_height = max of sagittal_height (z), coronal_height (z), and
# axial... | 7d0da9d775f027eb8420190407735741455e7703 | 3,624,152 |
def lemma_magic(line, cell=None, local_ns=None):
"""Magic to print the LaTeX and result for a Lemma expression
made from the given form."""
if line:
expr = hy_eval_in_ns(f'(require [lemma.core [expr]])\n(expr {line})', local_ns)
return expr
elif cell:
exprs = hy_eval_in_ns(f'(req... | cd7fe6b5ace84e4d38f45f2eda12ede57cde6c9a | 3,624,153 |
import torch
def soft_render_variable_num_blocks(
primitives,
num_blocks,
stacking_program,
raw_locations,
raw_color_sharpness,
raw_blur,
num_channels=3,
num_rows=32,
num_cols=32,
):
"""
Args
primitives (list [num_primitives])
num_blocks [*shape]
sta... | c3f0fdb8116004904cd4fa21405abeaff343ddc1 | 3,624,154 |
def all_users(number=-1, etag=None):
"""Iterate over every user in the order they signed up for GitHub.
.. deprecated:: 1.2.0
Use :meth:`github3.github.GitHub.all_users` instead.
:param int number: (optional), number of users to return. Default: -1,
returns all of them
:param str etag... | 987b89afaaed94dfe91d37b2201c5e90457d1cb5 | 3,624,155 |
import itertools
def neighboring_basis_images(accord, lat):
"""Given a coordinate and the corresponding lattice, return
a list of the same coordinate within the neighboring lattice
cells (27 total, including the original coordinate)
Parameters
----------
accord : AtomCoord
lat : Lattice
... | a75a9b2c9704170ed07883dce8b85e41814667c8 | 3,624,156 |
import os
import math
def tinyimagenet():
"""
This method is adapted from https://github.com/rmccorm4/Tiny-Imagenet-200/blob/master/networks/data_utils.py
You can find the LICENSE with copyright notive below this method.
"""
path, wnids_path = 'tiny-imagenet-200', 'tiny-imagenet-200'
res... | 2049e6dc7d5115117477e75a32594dcd36d17937 | 3,624,157 |
def update_image(image, centroids):
"""
Update RGB values of pixels in `image` by finding
the closest among the `centroids`
Parameters
----------
image : nparray
(H, W, C) image represented as an nparray
centroids : int
The centroids stored as an nparray
Returns
---... | c32541a8ccafcaa62f9822210f93ccdc31a311df | 3,624,158 |
def url_for(req: Request, name: str, **kwargs) -> str:
"""
Get the URL for a route, absolute with our own BASE_URL
"""
relative_url = req.scope["router"].url_path_for(name, **kwargs)
return f"{str(conf.BASE_URL).rstrip('/')}{relative_url}" | 23f0b22215c870a61a6debf38b02e08976175755 | 3,624,159 |
def scrub_email(address):
"""
Remove the local-part from an email address
for the sake of anonymity
:param address: <str>
:return: <str>
"""
if '@' in address:
domain = address.split('@')[1]
return 'user@{}'.format(domain)
else:
return address | 90b54f3a06f3fe50b354138113c27e980c01c59c | 3,624,160 |
def Printer(print_format, out=None, defaults=None, console_attr=None):
"""Returns a resource printer given a format string.
Args:
print_format: The _FORMATTERS name with optional attributes and projection.
out: Output stream, log.out if None.
defaults: Optional resource_projection_spec.ProjectionSpec d... | 6c6873ab1aad5d99542555bb36fb53e7b12a3fa9 | 3,624,161 |
import sys
def pattern_search(search_pattern):
"""
Search for search_pattern in pattern. Convert from hex if needed
Looking for needle in haystack
@param search_pattern: pattern to serach for
"""
needle = search_pattern
try:
if needle.startswith('0x'):
# Strip off '0x', convert to ASCII and reverse
n... | 99c77c6f181c43c6706a4203c94d37adfd2e3d48 | 3,624,162 |
def construct_neighbors(taxid):
"""Construct Neighbor objects for all neighbors of a taxonomic ID.
Args:
taxid: taxonomic ID to download neighbors for
Returns:
list of Neighbor objects
"""
logger.info(("Constructing a list of neighbors for taxid %d") % taxid)
expected_col_orde... | bede1a424d86a67d039be8fdd31cd8cc125b04c7 | 3,624,163 |
import requests
def get_votes(discussion: dict) -> dict:
"""Retrieves votes on both argumentations and the thesis itself.
"""
path = f'{domain}/discussions/{discussion["id"]}/perspectives/1/votes?filter=all'
return requests.get(path).json()['votes'] | b3a9ad1586218505b1ebed747f6d3dd41036c97b | 3,624,164 |
def modify_res(res, cur):
""" Преобразует список-результат запроса в свисок словарей"""
result = list()
for ll in res:
temp_dict = dict()
for k, v in zip(cur.description, ll):
temp_dict[k[0]] = bytes(v) if type(v) is memoryview else v
result.append(temp_dict)
return r... | 20654a49ab0980fc5d6539f7079818f1a89bab9b | 3,624,165 |
def get_X_hs_out_d_t(X_NR_d_t, X_req_d_t_i, V_dash_supply_d_t_i, X_hs_out_min_C_d_t, L_star_CL_d_t_i, region):
"""(15-1)(15-2)
Args:
X_NR_d_t: 日付dの時刻tにおける非居室の絶対湿度(kg/kg(DA))
X_req_d_t_i: 日付dの時刻tにおける暖冷房区画iの熱源機の出口における要求絶対湿度(kg/kg(DA))
V_dash_supply_d_t_i: 日付dの時刻tにおける暖冷房区画iのVAV調整前の吹き出し風量(m3/h)
... | 566d3a61572c8e145999d233f53d58494107760c | 3,624,166 |
def ys_write_btor(
ctx = None,
toolchain = None,
name = None,
mode = None,
srcs = [],
deps = [],
preamble = [],
arguments = [],
multiclock = _DEFAULT_MULTICLOCK,
nomem = _DEFAULT_NOMEM,
syn = _DEFAULT_SYN):
"""Compile a Verilog ... | ab14fa47ad1d417347e454c92672e1d41aa8f069 | 3,624,167 |
def get_standard_model_list():
"""Returns the list of all models shown in the main paper figures."""
return [m for m in MODEL_SIZE.keys() if not m.startswith("bit-imagenet")] | 4852ccecf00ae935ad8710e76754eab90b45c466 | 3,624,168 |
import time
def retry(exceptions, total_attempts=3, delay=3, backoff=2):
"""Decorator for retrying function calls.
:param exceptions: expected exceptions to retry on -- class or tuple
:param total_attempts: times to run function before failure. -- int
:param delay: initial delay between retries in se... | 174d4e4129b4a0673a04f1c71b960eae7b273dc7 | 3,624,169 |
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
"""Return the sum along diagonals of the array.
If a is 2-d, returns the sum along the diagonal of self with the given offset, i.e., the
collection of elements of the form a[i,i+offset]. If a has more than two
dimensions, then the axes spe... | 6ed7c2e8e2127c26a3fd99a3db272ce78b66613a | 3,624,170 |
def forum_page_item():
"""developer item loaded from html file"""
return items.load_forum_page(fake_response_from_file('forum_page.html', url=fixtures.FORUM_URL)) | d3179a1f3d65141fe2f72e0a393f51678fef18a2 | 3,624,171 |
def make_pulse(duration, pulsechan):
"""
Configure the counter `pulsechan` to output
a pulse of the given `duration` (in seconds).
"""
pulse = daq.Task()
pulse.CreateCOPulseChanTime(
pulsechan, "", # physical channel, name to assign
daq.DAQmx_Val_Seconds, # units:sec... | 787a6e1d342bed379760253cc16b1d3199be6411 | 3,624,172 |
def disp_multiple(im1=None, im2=None, im3=None, im4=None):
"""
Combines four images for display.
"""
height, width = im1.shape
combined = np.zeros((2 * height, 2 * width, 3), dtype=np.uint8)
combined[0:height, 0:width, :] = cv2.cvtColor(im1, cv2.COLOR_GRAY2RGB)
combined[height:, 0:width, ... | b0af4b6e645b65877986a6e201016b925d46c41e | 3,624,173 |
import argparse
def params_args(args=None):
"""
Parse command line arguments
:param args: command line arguments or None (default)
:return: dictionary of parameters
"""
# parameters of model and files
params = argparse.ArgumentParser(description='Run distribute model simnet bow.')
para... | 4d114f3249da104ce10d51b4bf8b84b70df98833 | 3,624,174 |
import argparse
def parse_arguments(args):
"""Parse the commandline arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--version", action="version", version="%(prog)s 2.0")
parser.add_argument("input", help="directory to analyze")
parser.add_argument("--output", help="The direc... | e2c409db22b600477b8e7440b0f971e386518e90 | 3,624,175 |
def dump(glob,file):
"""dump global"""
glob=glob.replace('^','')
gref=iris.gref(glob)
_d=ddata(gref)
if _d[0] < 1 :
print('Global not found')
return 0
if file == "" :
file=glob+".json"
#; init file
fil=open(file,'w')
fil.write('{"gbl":"'+glob+'","n... | 750555639059bdbdd51932eb0439c3f39b3e9278 | 3,624,176 |
from typing import Dict
from typing import Any
import fsspec
import yaml
def load_config_yaml(path: str) -> Dict[str, Any]:
"""
Load yaml from local/remote location
"""
with fsspec.open(path, "r") as f:
d = yaml.safe_load(f)
return d | bbdffb6b2896500f2151c49e3011ac471511021b | 3,624,177 |
from typing import List
from typing import Tuple
def ngrams(letters: List[str], n: int) -> List[Tuple]:
"""
Given a list of letters, write a function that returns a list of all possible ngrams of length N.
>>> list(ngrams(['a'], 2))
[]
>>> list(ngrams(['a', 'b', 'c'], 2))
[('a', 'b'), ('b', '... | 82bf2b25338a099d777c62b5f272d98746410581 | 3,624,178 |
def parse_sexp(toc_input, toc_output, indent_str, i):
"""
Translate TOC in the s-exp format output by ``djvused`` to a
format understood by ``pdfbeads``.
``toc_input[i:]`` is the string to parse, and ``indent_str`` is
the string of tabulations for our current level in the output
TOC. The outpu... | eb4294b837ced9d6163c5e04e8d79ed18dcdd80c | 3,624,179 |
def symm_area(col, n):
"""
returns n + (n - 1) + ... + (n - col + 1)
i.e., the number of matrix elements below and including the diagonal and
from column 0 to column `col`
"""
return col * (2 * n - col + 1) // 2 | e5c7970ee2b612f4678952056be0358c968e06b3 | 3,624,180 |
def parse_data_pkt(pkt, tk):
"""Extract data from a WPA packet @pkt with temporal key @tk"""
TSC, TA, data = parse_TKIP_hdr(pkt)
TK = [orb(x) for x in tk]
rc4_key = gen_TKIP_RC4_key(TSC, TA, TK)
return ARC4_decrypt(rc4_key, data) | 77ae3270e5ce976a111667c1d7eb59aa6b412b9d | 3,624,181 |
import os
def finder(scenario, multiplier, conserve_total):
"""yield what we can find."""
res = []
for dirname, _dirpath, filenames in os.walk("/i/0/cli"):
for fn in filenames:
res.append(
[f"{dirname}/{fn}", scenario, multiplier, conserve_total]
)
retur... | d6d712e435140b94baca30ef9318a625efee7cc0 | 3,624,182 |
def find_device(p, tags):
"""
Find an audio device to read input from
"""
device_index = None
for i in range(p.get_device_count()):
devinfo = p.get_device_info_by_index(i)
print("Device %d: %s" % (i, devinfo["name"]))
for keyword in tags:
if keyword in devinfo["n... | 41428447dc39be8fa06ede59816a7aca9d5bffee | 3,624,183 |
import logging
def group_freeTime():
"""
Connect with the database first and get all the collection inside,
then merge each collection by calling merge function in the available time.
After merge all the free time, use them to replace the current database collection.
Since the database_Free is sorted by the star... | fa5a81737804ab9ff0d37cc0b0cc2082eafb079f | 3,624,184 |
from typing import Any
from typing import Callable
import logging
import numbers
def dict2xml_str(
attr_type: bool,
attr: dict[str, Any],
item: dict[str, Any],
item_func: Callable[[str], str],
cdata: bool,
item_name: str,
item_wrap: bool,
parentIsList: bool,
parent: str = "",
l... | 551924fad1e6e8f4539447af648658091c2a6393 | 3,624,185 |
import re
from bs4 import BeautifulSoup
def top_user_decks(pages):
"""
Gets the hearthpwn.com urls for pages worth of top-rated user-created decks
Returns a list of urls
"""
top_decks = []
main_url = "https://www.hearthpwn.com/"
search_url = "decks?filter-deck-tag=1&filter-show-constructed... | cf4d2a9b8136924f6f3c13e1c3b2c6805c3c6a47 | 3,624,186 |
from typing import Any
def fail(msg: str) -> Parser:
"""A parser that always fails with the given message."""
@parser
def g(cursor: Cursor, aux: Any):
raise Failure(msg)
return g | 5a2aea1ae9d96cfef15267200a840ff8dd61577d | 3,624,187 |
def build_model_cols(feature_dict: dict, out_vocab_dir=None, print_details=True):
"""
Builds inputs needed to specify a tf.keras.Model. The tf_cols_* are TensorFlow feature_columns. The
inputs_* are dictionaries of tf.keras.Inputs. The tf_cols_* are used to specify keras.DenseFeatures methods and
the i... | 9b80857e29829e2a327e8f350fb346f76bc1d5b9 | 3,624,188 |
def normalize_lons(l1, l2):
"""
An international date line safe way of returning a range of longitudes.
>>> normalize_lons(20, 30) # no IDL within the range
[(20, 30)]
>>> normalize_lons(-17, +17) # no IDL within the range
[(-17, 17)]
>>> normalize_lons(-178, +179)
[(-180, -178), (179... | c0d58aa7be8409d6337f0fa8b753f5ef30f531e5 | 3,624,189 |
from operator import or_
def gitless_drafts():
""" Render the gitless posts that a user has created in table form
Editors can see all the posts created via Gitless_Editing
"""
prefixes = current_app.config.get('WEB_EDITOR_PREFIXES', [])
if prefixes == []:
raise Exception('Web editing i... | 544ccf57ab1556439c90d843086ee2a5cdfab267 | 3,624,190 |
from operator import or_
def register():
""" Registers a new user. """
username = request.args.get('username')
email = request.args.get('email')
password = request.args.get('password')
if not all([username, email, password]):
msg = 'You must provide a username, email, and password to regi... | 57fb86b94977f9972ae14e53c592adc76f2f360f | 3,624,191 |
def regress_from_features(batch_features, out_dim):
"""Regress to a rotation representation from point cloud encodings.
In Zhou et al, CVPR19, the paper describes this regression network as an MLP
mapping 2048->512->512->out_dim, but the associated code implements it with
one less layer: 2048->512->out_dim. We... | 33f51809e9f75c25e6f6b1b5abf724b5d26b5132 | 3,624,192 |
import gettext
def get_object_name(trans_id):
"""
This method is used to get the object name
Args:
trans_id: unique transaction id
"""
# Check the transaction and connection status
status, error_msg, conn, trans_obj, session_obj = \
check_transaction_status(trans_id)
if ... | 1a3e91002266f0ac002951963a96eedbb1665e7f | 3,624,193 |
def input_fn(dir, subset, batch_size):
"""Create a dataset from a list of filenames and shard batches from it"""
dir1 = "G:/unaltered_TEM_crops-171x171/"
dir2 = "G:/unaltered_STEM_crops-171x171/"
with tf.device('/cpu:0'):
dataset1 = tf.data.Dataset.list_files(dir1+"*.tif") #dir+subset+"/"+"*.t... | 3c0c3d5add95890a50b3426e0424ba81f30c5e03 | 3,624,194 |
def extract_list(p):
"""Check if there is a list after p"""
for sibling in p.next_siblings:
if sibling.name == 'ul':
return [li.text for li in sibling.find_all('li')]
if sibling.name == 'p':
return None | b78a2fb9c5d6eee6a11bb0a9317cdc872f8ff92c | 3,624,195 |
import logging
import os
def download(year: str, month: str, destdir: str):
"""
Downloads on-time performance data and returns local filename
year e.g.'2015'
month e.g. '01 for January
"""
logging.info('Requesting data for {}-{}-*'.format(year, month))
url = os.path.join(SOURCE,
... | 3eb3f857db67ed4755036ddea0e25fbb99a7e62c | 3,624,196 |
from typing import Callable
def _in_simplifiable_layout(layout_idx: int) -> Callable[[Coupling], bool]:
"""
Return if (q1,q2) qubit is in simplifiable layout.
"""
if layout_idx == 0:
return lambda q: (not q[0][1] % 2) and q[0][0] == q[1][0]
if layout_idx == 1:
return lambda q: (no... | c95cd7551d1bb8cd9e4cba4c76d2d2b3fce358b5 | 3,624,197 |
from typing import Union
from typing import Iterable
from typing import Sized
def mean_squared_error(
original: Union[Iterable, Sized],
forecasted: Union[Iterable, Sized]) -> float:
"""
Рассчитывает среднюю квадратичную ошибку. Формула:
MSE = sum((o - f) ^ 2) / n
:param origin... | 3f8c6d1de276317cc1c7d39f2df80d71bc9a2f53 | 3,624,198 |
def test_fillstates():
"""Can we fill states"""
data = {"AK": 10, "HI": 30, "IA": 40, "NY": 80}
mp = MapPlot(
sector="nws",
title="Fill AK, HI, IA, NY States",
subtitle="test_fillstates",
nocaption=True,
)
mp.fill_states(data, lblformat="%.0f", ilabel=True)
return... | 74327cf6a048f2c47cb93c7fea621d88ff6e7f9d | 3,624,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.