content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import base64
def print_anycli(**kwargs):
"""
List the number of deployed scripts on remote device
:param kwargs:
keyword value: value to display
:return: display the result of AnyCLI
:Example:
result = cli(url=base_url, auth=s, command="show vlan")
print_anycli(result)
"""
... | 3d0d34da4e1f6ca347d4503fb242b8485268641a | 44,210 |
def create_virus_total_headers_from_config():
""" Creates a dictionary called virus_total_headers that contains the formatted header needed to submit an query to VirusTotal.
Requires an VirusTotal API Key to use. It is free to sign up for one but has restrictions on daily limits.
Reads in the Vir... | 02552b1c03108a137dd1e314f3d1e1c318e51eb4 | 44,211 |
import select
from operator import and_
def add(existing_account_customer, new_account_customer, Session):
"""Add a second customer to the account of an existing customer."""
with Session() as session:
# get existing account
firstname, lastname = split_name(existing_account_customer)
... | 6ff604a7d18ca40d8dbb911c33a4b79eab80db38 | 44,212 |
def get_shape_not_match_message(shape_error_type, value):
"""
Function Description:
get shape not match message
Parameter:
input:the value
shape_error_type: the shape error type
Return Value:
not match message
"""
message = ""
if shape_error_type == InputShape... | a20b51a36b723aea0a3bd5bd26b60d5934a70ce3 | 44,214 |
def extract_projstring(proj_string):
"""
Import an OSR supported projection string into
a spatial reference object
Parameters
----------
proj_string : string
Projection String in some OSR supported format
Returns
-------
srs : object
OSR spatial referenc... | 65b32e02803e7549359bff4fe6a9f4750101c10e | 44,215 |
def show_bookmarks_related(context, title, url, object, description=""):
"""
Displays the bookmarks with counter.
"""
if not isinstance(object, models.Model):
raise TypeError, "object must be a valid Model"
if not url.startswith('http'):
url = context['request'].build_absolute_... | 653fd96dbf522bc6c2713ceb803ed85b86262321 | 44,217 |
def is_service(hass, entry):
"""check whether config entry is a service"""
domain, service = entry.split(".")[0], ".".join(entry.split(".")[1:])
return hass.services.has_service(domain, service) | d244dc15be20a7e56a17695dbf7df4c1811650a5 | 44,218 |
from typing import Tuple
def state_to_th_vel(config: PendulumConfig, state: int) -> Tuple[float, float]:
"""Convert a state id to the angle and the angle velocity.
Args:
config (PendulumConfig)
state (int)
Returns:
theta and vel_theta values.
"""
th_res, vel_res = config.... | d987f5004f3fe44b4d05b3f119600c9edd93bccc | 44,219 |
def _dnorm(W, norm='ave'):
"""
Normalizes a symmetric kernel `W`
Parameters
----------
W : (N, N) array_like
Similarity array generated by `SNF`
norm : str, optional
Type of normalization to perform. Must be one of ['ave', 'gph'].
Default: 'ave'
Returns
-------
... | 770ee7cea3ba98714c43ab9cebbe189381852def | 44,220 |
def parse(html, path):
"""
parsing html content
:param html - string with html content:
:param path - strind with xpath query:
:return: parsered lxml objects
"""
try:
html_tree = lxml.html.fromstring(html)
result = html_tree.xpath(path)
except Exception:
abort(500... | a440e0806d529414c53305b87ca465974da8740e | 44,221 |
def image_loader(image_path: str, img_size: tuple = (128, 128)) -> Tensor:
"""
Loading and preprocessing an image
:param image_path: path to image
:param img_size: image size
:return: image format torch.Tensor
"""
loader: transforms.Compose = transforms.Compose([
transforms.Resize(im... | 0dca00365a4dc26862239ebc81bb1dce05cefd23 | 44,222 |
def slurm_parse_timestr(s):
"""
A slurm time parser. Accepts a string in one the following forms:
# "days-hours",
# "days-hours:minutes",
# "days-hours:minutes:seconds".
# "minutes",
# "minutes:seconds",
# "hours:minutes:seconds",
Returns:
Time in se... | f5a3dd5db492d78d34741a3a15ad6bebed8c8628 | 44,223 |
import json
def lambda_handler(event, context):
"""
handles request to the lambda function from frontend. parses json request
and sends to update_table function.
"""
bucket = event['bucket']
path = event['path']
response = list_all_objects(bucket, path)
# ACTUALLY USE RESPONSE HERE TO ... | 02d6ca029e70829990b01026d061d7b1dd9b26e9 | 44,224 |
def window_add_dataframe_date(date, df):
"""
Add data from a a dataframe.
Dataframe has data only from a day
Remove seconds from T_Hora_C, where time are store
:param date: day
:param df:data
:return:
"""
def filter_time(row):
return row["T_Time"][:5]
df["T_Time"] = df.ap... | 176802a1837ee8ad5c55f61edfb2aaa42636cf46 | 44,225 |
def any_in(collection, values):
"""
Check if any of a collection of values is in `collection`.
Returns boolean.
"""
for value in values:
if value in collection:
return True
return False | a8d4471940e96d2b6a307c8ccf48caaaecb10f98 | 44,226 |
def __virtual__():
"""
Only load if requests is installed
"""
if HAS_LIBS:
return __virtualname__
else:
return (
False,
'The "{0}" module could not be loaded: '
'"requests" is not installed.'.format(__virtualname__),
) | 8bfb59e44d346147be70e450581cecab10d44ccc | 44,227 |
def cdsem_straight(w, dw, spacing=5.0, length=20.0):
"""
w
dw
"""
c = pp.Component()
c.move(c.size_info.cc, (0, 0))
return c | 5f6498f2d0d7d705d7d5742bb4fd7b8f92c9940c | 44,228 |
def interpolate(
input,
size=None,
scale_factor=None,
mode='nearest',
align_corners=False,
):
"""Resize input via interpolating neighborhoods.
Specify either ``size`` or ``scale_factor`` to compute output size:
```python
x = torch.ones((1, 2, 3, 4))
y = F.interpolate(x, size=6)... | 21895b272cb430a4a07aa66c0c09cacc179cef96 | 44,229 |
def log_poisson_binomial(log_q0, log_q1):
"""
Computes the events log probabilities w.r.t. a batch of Poisson Binomial R.V.
The computation is numerically stable.
Parameters
----------
log_q0 : torch.tensor (dtype=torch.float)
The log probability of each bits to be zero. The Poisson... | e465112e4caf3ef53bfea0a7bf49af5e08b1b218 | 44,230 |
def has_rings():
"""
Determine if we can see the ring logo.
"""
pos = pyautogui.locateOnScreen('rings.png', confidence=0.5)
if not pos:
pos = pyautogui.locateOnScreen('rings2.png', confidence=0.5)
print(f"Found at: {pos}")
return pos is not None | 83bb6d16433ae8515f5caab688e36bac0ad9e6b4 | 44,231 |
def custom_tokenizer(nlp): # pragma: no cover
"""
Creates a custom spaCy tokenizer.
:param nlp: a spaCy Language object
:return:
"""
prefix_re = spacy.util.compile_prefix_regex(nlp.Defaults.prefixes)
suffix_re = spacy.util.compile_suffix_regex(nlp.Defaults.suffixes)
infix_re = spacy.ut... | 354de8cd229f6c43c843b09afb9302a920ebc72e | 44,233 |
def choose_barrier(x, reverse=False):
"""
Choose the scenario where the AV hits the barrier.
If there is no such scenario, abstain.
:param reverse: If false, choose to hit the barrier. Else choose not to.
"""
if x["Passenger_noint"] == 0 and x["Passenger_int"] == 0: return -1
if x["Passenge... | 5ca785d2e69b3f1dba4e38a0d95d3cf3b4e90cd8 | 44,234 |
def _find_user_traceback_depth(tb):
"""Returns the depth of user-specific code in a traceback.
This is the depth from wich we find a frame where __name__ is '__p1__'.
Args:
tb: A traceback object.
"""
depth = 0
while tb:
# Find the topmost frame
frame = tb.tb_frame
... | fcfd3227430f51b3120f2d84d6d2d3c9e45c968c | 44,235 |
def load_config(cfg_path: str) -> DictConfig:
"""
Load configuration file. `base_config.yaml` is taken as a base for every config.
:param cfg_path: Path to the configuration file
:return: Loaded configuration
"""
base_cfg = OmegaConf.load('legoformer/config/base_config.yaml')
curr_cfg = ... | 39eab3a3802eb6f849b93696f128789618a4d87d | 44,236 |
def source_vectors(theta, phi):
"""
Produces vectors along the polarization axes and the direction of GW
propagation for sources at (theta, phi).
"""
# theta, phi is the direction to the source
# everything below needs the direction of GW propagation
theta_prop = np.pi - theta
phi_prop =... | 2d88c60b0e5ea09280dec8082e32dbd0d8132adc | 44,237 |
def get_gradient_thresh(img):
"""
Calculate a gradient threshold of an image
:param img: BGR image
:return: Binary gradient threshold image
"""
ksize = 5
img = undistort_image(img, mtx, dist)
#hls = cv2.cvtColor(img, cv2.COLOR_BGR2HLS).astype(np.float)
#s_channel = hls[:, :, 2]
g... | 640615a0279a4f60a220bbf6a6030d9fa753724f | 44,238 |
from typing import List
def do_split(s, sep):
"""
Divides an input string into an array using the argument as a separator.
split is commonly used to convert comma-separated items from a string to an
array.
https://github.com/Shopify/liquid/blob/b2feeacbce8e4a718bde9bc9fa9d00e44ab32351/lib/liquid/s... | 84c2ce6d53adce7d3929bb1c56afb21df5bb6787 | 44,240 |
import csv
from datetime import datetime
def process_covid_csv_data(covid_csv_data: csv) -> tuple[int, int, int]:
"""
(For Test) Processes covid data from a csv file.
Arguments:
covid_csv_data: A csv file of all the data.
Parameters:
last7days_cases: The number of cases in the last 7 days wi... | ff0f8a355ba3ca4212fc561a36e2e0c499971826 | 44,241 |
def _FormatLabelsArgsToKeyValuePairs(labels):
"""Flattens the labels specified in cli to a list of (k, v) pairs."""
labels = [] if labels is None else labels
labels_flattened = []
for labels_sublist in labels:
labels_flattened.extend([label.strip() for label in labels_sublist])
labels_flattened_unique = ... | 3a7bb78cf303498153828484e5c15a3a9add4cf9 | 44,242 |
def get_syncitems():
"""Run the loop to get all 'syncitems' entries.
Returns a list of (syncitem, time) tuples."""
syncitems = lj.run('syncitems')
items = []
total = int(syncitems['sync_total'])
print '%d/%d syncitems' % (len(items), total)
lastsync = None
while len(items) < total:
... | 2909cf0506019146883b11122fe503ffd5b87168 | 44,243 |
def router_id(conn, ref, required=True):
"""Fetch ID of Router identified by reference dict `ref`. Use
OpenStack SDK connection `conn` to fetch the info. If `required`,
ensure the fetch is successful.
Returns: the ID, or None if not found and not `required`
Raises: openstack's ResourceNotFound whe... | 60c0e8b07012554846fdbb6dd2cced0d1dcd7722 | 44,244 |
def read_examples(examples, is_training, shuffle_examples,
skip_n_initial_records, hparams):
"""Returns a tf.data.Dataset from TFRecord files.
Args:
examples: A string path to a TFRecord file of examples, a python list of
serialized examples, or a Tensor placeholder for serialized examp... | 56a9692af7641e866fc717bd8d0edfc78642a213 | 44,245 |
from typing import Optional
def model_data(
train_samples: int, targets: Optional[list[str]] = None
) -> tuple[list[str], Data]:
"""
Get the training and testing data to be used for the model.
Inputs
------
train_sample : int
How many samples per example
targets : Optional[list[st... | 2f503eeadd38fc6a2b32556e7250789783535e57 | 44,246 |
def retention(retention):
"""
Parses a retention object give in JSON to Retention type
:param retention: retention in JSON
:return: PropertyInstance.Retention
"""
if retention is None:
return None
context = None
if retention.get('context') is not None:
context = Property... | 0f88fbc36cbc75feb959970ae42127a16c6556d4 | 44,247 |
def get_ansible_vars(host):
"""Define get_ansible_vars"""
repository_role = "file=../../vars/main.yml name=repository_role"
tomcat_role = "file=../../../tomcat/vars/main.yml name=tomcat_role"
java_role = "file=../../../java/vars/main.yml name=java_role"
common_vars = "../../../common/vars/main.yml n... | 04300ced184729d4eda3ee5e62ff269ed553ab89 | 44,248 |
import warnings
from typing import Concatenate
def DilatedSpatialPyramidPooling(dspp_input,
num_filters=256,
dilation_rates=[1,6,12,18]):
"""
Instantiates the Atrous/Dilated Spatial Pyramid Pooling (ASPP/DSPP)
architecture for the DoubleU-N... | cd8430eeec713f991454679c0fd700e00d690edb | 44,251 |
import re
def cleanup_whitespace(text_content):
"""clean up junk whitespace that comes with every table cell"""
return re.sub(REGEX_WHITESPACE, ' ', text_content.strip()) | 05ceb282e763cca2b03c60fad0c4858930659857 | 44,252 |
def filter(request, site, condition, val):
"""
分类显示
:param request:
:param site:
:param condition:
:param val:
:return:
"""
user_home = models.Blog.objects.filter(site=site).select_related('user').first()
if not user_home:
return redirect('/')
template_name = "home_su... | a490238f96ca0e1833a6216e23c931498003601f | 44,253 |
def sst_ERSSTv5():
"""
get the sea surface temperature from the ERSST-v5 data set
"""
data = xr.open_dataset(join(rawdir, 'sst.mnmean.nc'))
data.sst.attrs['dataset'] = 'ERSSTv5'
return data.sst | 20469451b55bbf48a77f096a15999500663a090b | 44,254 |
from datetime import datetime
def _week_value(dt, as_string=False):
"""
Mixpanel weeks start on Monday. Given a datetime object or a date string of format YYYY-MM-DD,
returns a YYYY-MM-DD string for the Monday of that week.
"""
dt = datetime.datetime.strptime(dt, '%Y-%m-%d') if isinstance(dt, comp... | ce65657fa47623ca5f9bc6bbf36dbae2471db8e7 | 44,255 |
def swap_AL(peptide:str)->str:
"""
Swaps a A with L. Note: Only if AA is not modified.
Args:
peptide (str): peptide.
Returns:
str: peptide with swapped ALs.
"""
i = 0
while i < len(range(len(peptide) - 1)):
if peptide[i] == "A":
peptide[i] = peptide[i + 1... | 9f5410de25e00712a69876917a69d76d1130f115 | 44,256 |
import torch
def mpgm_loss(target, prediction, l_A=1., l_E=1., l_F=1., zero_diag: bool=False, softmax_E: bool=True):
"""
Modification of the loss function described in the GraphVAE paper.
The difference is, we treat A and E the same as both are sigmoided and F stays as it is softmaxed.
This way we can... | fe90570a84b41eea2da2582ba0f1ac003be43c4b | 44,257 |
def show_menu_item_by_id(item_id): # noqa: E501
"""Info for a specific menu item
# noqa: E501
:param item_id: The id of the menu item to retrieve
:type item_id: str
:rtype: MenuItem
"""
if (item := models.MenuItem.query_by_id(int(item_id))) :
return item.serialize()
else:
... | 6831e3e57bf31d0d36cf730b7daafcecf5484cb6 | 44,259 |
import numpy
def get_minmax(Data):
"""
Get daily minima and maxima on days when no 30-min observations are missing.
Days with missing observations return a value of c.missing_value
Values returned are sample size (Num), minimum (Min) and maximum (Max)
Usage qcts.get_minmax(Data)
... | 89e273288e70c1bad8e4f83c753ae3b12f755adb | 44,260 |
def padding_box(rect, padding):
"""
Get a new Rect where rect is enlarged by padding width.
:param Rect rect
:param int padding
:return enlarged Rect
:rtype Rect
"""
top_left, bottom_right = rect
return (add_positions(top_left, (-padding, -padding)),
add_positions(bott... | 7b9a29ec9350ad92858e9442056c8f9e82b14360 | 44,261 |
def binarize(y, label):
"""Binarize array-like data according to label."""
return (np.array(y) == label).astype(int) | 62cb481208ffd685b64507ab24fab266d450efe4 | 44,262 |
def buy():
"""Buy shares of stock"""
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
if not request.form.get("symbol"):
return apology("must provide stock’s symbol", 400)
elif not request.form.get("shares"):
return apolo... | 62bc97cc7e4bbac0a3bb44a02006bd74498f169f | 44,263 |
from bokeh.transform import linear_cmap
def bokeh_bands(bandsdata,
*,
k_label='kpath',
eigenvalues='eigenvalues_up',
weight=None,
xlabel='',
ylabel=r'E-E_F [eV]',
title='',
special_kpoints=N... | d2afcb7e0b432e0d2ac72d0012c49e4af56a0e93 | 44,264 |
def monitor_saturation(model):
"""Monitor the saturation rate."""
monitors = {}
for name, p in model.named_parameters():
p = F.sigmoid(p)
sat = 1 - (p - (p > 0.5).float()).abs()
monitors['sat/' + name] = sat
return monitors | 8c84b5e57e218985dec1d70d3e48d582244ac977 | 44,265 |
def dict2kvtable(obj, env):
"""Generate an HTML table from a dictionary"""
return "XXX table" | 4cb88b5259e7bab7ad3f106251371c5f80bcccd9 | 44,267 |
import math
def u_law_expend(arr):
"""
Expend compressed array.
:param arr: given array
:return: expended array
"""
u = 255
max_in_arr = np.amax(arr)
out = np.array(arr, dtype=float)
for i in range(0, len(arr)):
p = math.log(256) * abs(arr[i]) / max_in_arr
o = max... | 9150d2c54e36eb63c2e22ad855f68b49b5017ad6 | 44,268 |
async def get_attentions_and_preds(
model: str, sentence: str, layer: int, request_hash=None
) -> api.AttentionResponse:
"""For a sentence, at a layer, get the attentions and predictions
Args:
request['model']: Model name
request['sentence']: Sentence to get the attentions for
r... | c4a1ef4b193121a067454dccf92881a2761ccc46 | 44,269 |
def brick_get_connector_properties(multipath=False, enforce_multipath=False):
"""Wrapper to automatically set root_helper in brick calls.
:param multipath: A boolean indicating whether the connector can
support multipath.
:param enforce_multipath: If True, it raises exception when mul... | 1f00e446d0effd6fbc077c464a83575d8ec49ee9 | 44,272 |
def vandermond(X):
"""
Create a vandermond matrix(nxn) by x values
Parameters
----------
X : list
list of x values
Returns
-------
np.array
vandermond matrix
"""
n = len(X)
V = np.zeros((n, n))
for i in range(n):
V[i, :] = [X[i... | 9912601b0cfae4b0b380585f8a6f7541336a436f | 44,273 |
def fn_col_mapping_dict_for_rename(df):
"""Return a column mapping dictionary with column name and associated column index number.
This can be used to assign new column names"""
return {c[1]:c[1] for c in enumerate(df.columns)} | 973dbbc6cb5ae6bb52dcc0e5cec3b310b139ec96 | 44,276 |
import yaml
def do_query(archives, config_file=None, logger=None, context=None):
"""
Gets concordance and collocation analysis for keywords giving a target word, and it groups the results by date.
The window variable can be used for specifying the number of words to the right and left to take.
... | 3db0398dbcf0fe531e76615dc8544e3b2bf2b48f | 44,277 |
def first_inside_quotes(s):
"""
Returns the first substring of s between two (double) quotes
A quote character is one that is inside a string, not one that
delimits it. We typically use single quotes (') to delimit a
string if want to use a double quote character (") inside... | 77a43d8bc2a88c44051f653add184d2bb705425f | 44,278 |
def pc_upsampling(xyz_upsample,
xyz,
feat,
scope='upsampling'):
""" Fully connected layer with non-linear operation.
Args:
xyz_upsample: 3-D tensor B x N2 x 3
xyz: 3-D tensor B x N x 3
feat: 3-D tensor B x N x C
Returns:
feat_upsample: 3-... | a1544d542138d3294b84e4823f6a3054098154e1 | 44,279 |
def prob3(num=600851475143):
"""
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
a = []
b = 1
i = 3
while True:
if b == num:
break
elif num % i == 0:
b *= i
a.append(i)... | f0689232bf53152d87a6e28ffe4cce98908bca4f | 44,281 |
def save(eid):
"""
Saves the coworker to the database. This function calls on the
`app.utils.update_coworker_info` function.
:param eid: The `eid` of the song to be saved.
:type eid: int
:returns: Redirects to the `/coworkers/` page (master table).
"""
update_coworker_info(request=requ... | d7a3155589dfd3aea0598dcd5b4f61e65e8434ca | 44,282 |
from typing import Type
from pydantic import BaseModel # noqa: E0611
def is_compatible_type(type: Type) -> bool:
"""Returns `True` if the type is opyrator-compatible."""
try:
if issubclass(type, BaseModel):
return True
except Exception:
pass
try:
# valid list type... | 09383adcc4c93f05e1509cc97b181ae1ba98cec6 | 44,283 |
from typing import Sequence
from typing import Tuple
def get_all_namespaces_for_service(
service: str, soa_dir: str = DEFAULT_SOA_DIR, full_name: bool = True
) -> Sequence[Tuple[str, ServiceNamespaceConfig]]:
"""Get all the smartstack namespaces listed for a given service name.
:param service: The servic... | 595efe335de763069257f00d5bcb05b75cf6bbdc | 44,284 |
def normal(shape, mean, stddev, seed=0):
"""
Generates random numbers according to the Normal (or Gaussian) random number distribution.
It is defined as:
Args:
shape (tuple): The shape of random tensor to be generated.
mean (Tensor): The mean μ distribution parameter, which specifies th... | 1d5422b2f9fe742ab27aeabb81ac5598626270fd | 44,285 |
def circle(**kwargs) -> Expando:
"""
Draw a circle.
See https://developer.mozilla.org/en-US/docs/Web/SVG/Element/circle
Args:
kwargs: Attributes to use for the initial render. SVG attributes, snake-cased.
Returns:
Data for the graphical element.
"""
return _el('c', kwargs) | 2f52334cc232d45bcce9b47aba0954312c189625 | 44,286 |
def display_loss_curve(losses, save_location: str=None):
"""
Plots and displays the loss curve (usually for Neural Network models)
Parameters
----------
save_location : str
the location to save the figure on disk. If None, the plot is displayed on runtime and not saved.
losses : numpy.a... | 901d7f2e01ece1a62e7e2b92b6bae7334be6ddbc | 44,288 |
def is_turkish_id(x):
"""
checks if given id is valid TC ID
"""
if len(str(x)) != 11:
return False
str_id = str(x)
# first 10 digit sum mod 10 equals 11th digit control
lst_id = [int(n) for n in str_id if n.isdigit()]
if lst_id[0] == 0:
return False
# first 10 digit... | c24b233fd74b5c45f6aff752bb57ae12a296d6b5 | 44,289 |
def L_p ( x ):
"""
Calculates the sound pressure level from the sound pressure squared:
L_p = 10 lg x/4e-10
Parameters
----------
x: array of floats
The squared sound pressure values
Returns
-------
array of floats
The corresponding sound pressure levels... | 286ed236b9414ac2ab040a1cda9a4acfa429b0b7 | 44,290 |
def get_abs_path(path: str) -> str:
"""
Returns absolute path
Parameters
----------
path : str
.
"""
return os_path.abspath(path) if path else None | 3b6fd0aba5eaafc9e1ed8239a9eca9fcd0ee1599 | 44,291 |
import time
def index():
"""
This function renders the Index page for application. It shows list of all
messages logged by all bots and also provides a form for filtered
messages. Upon filtering, it redirects to a page showing filtered messages.
:return: ../index
"""
# get all messages.
... | 61f23e94dd25732f4bae9092b5c978b4fecbf323 | 44,292 |
def _make_unique(l):
"""Check that all values in list are unique and return a pruned and sorted list."""
return sorted(set(l)) | 18ae627f2a8f5dc8c61a332b73d8bd99c41d5ced | 44,293 |
import ast
def parse_preproc_line(line, preproc_defs):
"""Parse a preprocessor line into a tree that can be evaluated"""
# Scan line and translate to python syntax
inchar = None # Character context
line_len = len(line)
pline = ""
index = 0
while index < line_len:
if (line[index] ==... | ce15b82d1162d7b064204dee45fed048b66e9ffa | 44,294 |
def group_by_area(units):
"""Create a dictionary containing lists of UnitGroup objects by area."""
areas = [ID_area(i.ID) for i in units]
groups = {i: [] for i in sorted(set(areas))}
for a, u in zip(areas, units): groups[a].append(u)
return groups | 8f12827411ea0656bd3eefd13ea99d736f16a571 | 44,295 |
def render_to_mail(template, context, **kwargs):
"""
Renders a mail and returns the resulting ``EmailMultiAlternatives``
instance
* ``template``: The base name of the text and HTML (optional) version of
the mail.
* ``context``: The context used to render the mail. This context instance
... | 8c587535f202d8b66996d075704b64a6df2f3549 | 44,296 |
def filledprf(x0, y0, sigma, n=0.2, res=100):
"""
Fill the pRF centered in x0, y0 and radius sigma
Arguments
---------
x0 : int
column for center
y0 : int
row for center
sigma : float
standard deviation of the pRF
n : float
power exponent
res : int
... | 1a5c3c903f63a9ffda2f23b13e2c23752470d7c8 | 44,297 |
def post_info(request, post, put_content=False):
"""Return a hash with post fields (content is omitted for performance)."""
data = {
'title': post.title,
'subject': post.subject,
'publication_date': post.pub_date,
'author': post.author.username,
'path': post.path,
... | 4092b20a76c8a1b140a9b6faa534ffe9e5c2aac4 | 44,298 |
def get_CommodityDef():
""" get commodity definition settings """
file_country = "../Input/2_commodity/01_MainCommodity.csv"
dt_data = genfromtxt(file_country, dtype = str, skip_header=1, delimiter=',')
lsCommodity = list()
for row in dt_data:
lsCommodity.append(cls_misc.Commodity(... | f7516e94a451b0f7e89d4ead735cac0fff60eb24 | 44,299 |
def dispatch_per_device(games):
"""Helper fo split dataset per device."""
num_games = list(games._asdict().values())[0].shape[0]
num_devices = jax.local_device_count()
batch_size = batch_size_per_device(num_games, num_devices=num_devices)
def dispatch(x):
if hasattr(x, 'shape'):
return jnp.reshap... | dc43bbe11ed6dfd10f2e8418d941310e7271b047 | 44,300 |
def xml_prettify(elem):
"""Return a pretty-printed XML string for the XML element."""
text = ET.tostring(elem, "utf-8")
reparsed = minidom.parseString(text)
return reparsed.toprettyxml(indent=" ") | 28c71c0d22b60c7d4f8f9aee905707b4f37c32a8 | 44,301 |
def fix_matrix_gauge(emat):
"""Fix gauge of an energy matrix such that the minimum value
of each column is zero (columns correspond to positions), and
overall matrix norm is equal to 1."""
# fix mean
for j in range(emat.shape[1]):
emat[:,j] = emat[:,j] - sp.mean(emat[:,j])
# fix sum of v... | dcdf722c398d858789ff80c188383bff18833b66 | 44,302 |
import re
def clean_html(X):
""" Strip html
:texts: collection - the collection of texts to change
:returns: list of texts cleaned from html
"""
return [re.sub('(\\<.*?\\>)','',text) for text in X if text!=None] | 5881fa4e7df0b3a8d1c6cfcaaa17bc3d381230d0 | 44,303 |
from datetime import datetime
def parse_datetime(value):
"""Parses a string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raises ``ValueError`` if the input isn't well formatted.
"""... | 672d0f831374a27489af8a38e253c7dc76a9f51a | 44,304 |
def post(host, path, body=None, headers={}):
"""
HTTPS POST request
"""
return request('POST', host, path, body, headers) | 418f7ecc14fafada0c3962ea07920ae3060edf4a | 44,305 |
def issiso(sys, strict=False):
"""
Check to see if a system is single input, single output
Parameters
----------
sys : LTI system
System to be checked
strict: bool (default = False)
If strict is True, do not treat scalars as SISO
"""
if isinstance(sys, (int, float, compl... | ad72fe7661d3aba91a99c9bf3af606b3e0077c03 | 44,306 |
def get_optimizer(encoder, model, args, learning_rate, remove_pooler=False):
"""
get BertAdam for encoder / classifier or BertModel
:param model:
:param classifier:
:param args:
:param remove_pooler:
:return:
"""
param_optimizer = list(encoder.named_parameters())
param_optimizer... | f886b2b2dc632fdb85b75d1905e339905c1177a4 | 44,307 |
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
:return: None
"""
if STRIPE_PLANS is None:
return None
for _, value in STRIPE_PLANS.iteritems():
plan = PaymentPlan.retrieve(value.get('id'))
if plan:
PaymentPlan.update(id=value.get('id'),
... | 329c8f8e2f0dc7c7950278ce1a2c0e07878ef58d | 44,308 |
import binascii
def b32decode(todecode, casefold=False, map01=None):
"""Decode a Base32 encoded byte string.
todecode is the byte string to decode. Optional casefold is a flag
specifying whether a lowercase alphabet is acceptable as input.
For security purposes, the default is False.
RFC 3548 a... | 2720d19e608e8dee9142c5a19829847ff492c5cb | 44,309 |
def check_visitors(cls):
"""Check that a checker's visitors are correctly named.
A checker has methods named visit_NODETYPE, but it's easy to mis-name
a visit method, and it will never be called. This decorator checks
the class to see that all of its visitors are named after an existing
node class... | 704d1c2c73cfa1c38b4e07b626329a8359c9ca9b | 44,311 |
def flesch_reading_ease(n_syllables, n_words, n_sents, lang=None):
"""
Readability score usually in the range [0, 100], related (inversely) to
:func:`flesch_kincaid_grade_level()`. Higher value => easier text.
Note:
Constant weights in this formula are language-dependent;
if ``lang`` is ... | 34f474a3eeb06a8453f9b21b4b324dcfe0f7582f | 44,312 |
def shufflenetv2_x1_5(pretrained=False, **kwargs):
"""shufflenetv2_x1_5 model
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
Examples:
.. code-block:: python
from paddle.vision.models import shufflenetv2_x1_5
# build ... | cf45e4490d1339d8ba0cad84d51e33e6e1ee5ffb | 44,313 |
def gen_snv_transition_matrix(ts_tv_p=0.71,
ts_hm_ht_p=0.5,
tv_l_p=0.5,
tv_hm_ht_p=0.8):
""" Function to compute SNV matrix of transition probabilities,
default rates follow SInC reference (Fig1.a) """
G_ref = {'AA':0... | 26b5ab2d58c0d9c7364bd098967e1f8f8937203c | 44,314 |
import random
import copy
import hashlib
def make_event(action_type, device, file, timestamp, opt=None):
"""Create an audit event."""
if action_type == ACT_WRITE:
# Simulate writing data to the file. Create a new randomized file and
# copy _some_ of it's attributes.
mutation = make_fil... | 2f8c11f9901494bf389c986a21b9a34241f586b8 | 44,315 |
import yaml
def parse_config_file(config_file) -> dict:
"""Read config.yaml file with params.
Returns
-------
dict
Dict of config
"""
with open(config_file, 'r') as stream:
try:
CONFIG = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(... | 8f1fb9bcda94ef5c21edbf5e5bf95b327efd8c96 | 44,316 |
def Property(func): # pylint: disable = C0103
"""
Property with improved docs handling
:Parameters:
`func` : ``callable``
The function providing the property parameters. It takes no arguments
as returns a dict containing the keyword arguments to be defined for
``property``. Th... | 061b5f6b4ec151888a64a590e2b5c974d2666301 | 44,317 |
def add_files(struct: Structure, opts: ScaffoldOpts) -> ActionParams:
"""Add .pre-commit-config.yaml file to structure
Since the default template uses isort, this function also provides an
initial version of .isort.cfg that can be extended by the user
(it contains some useful skips, e.g. tox and venv)
... | 1f0a5f836bbc5e2596b3bd1a4bb2d6607f9ea831 | 44,318 |
import csv
def get_entities_sentence(dataset_file, sentence):
"""
:param dataset_file:
:param sentence:
:return: sentence : [[entity1, id, char1, char2], [entity2, id, char3, char4],
relation], [[entity1, id, char1, char2], [entity2, id, char3, char4],
... | 10762f373ff42123fb42e14fa3768a83bcf13797 | 44,320 |
def ground(expr, env):
"""Replace all variables with their values in expr."""
if scheme_symbolp(expr):
resolved = lookup(expr, env)
if expr != resolved:
return ground(resolved, env)
else:
return expr
elif scheme_pairp(expr):
return Pair(ground(expr.fir... | 230f4eb9c27170ec84df04dc63ca90776b55d4a6 | 44,321 |
def parse_maintainers_line(line):
"""Parse one line of Maintainers.txt, returning any match group and its key."""
for key, expression in EXPRESSIONS.items():
match = expression.match(line)
if match:
return key, match.group(key)
return None, None | 3f2b15ef310f87eed50e59a1c1dbb3521ced5ab9 | 44,322 |
def open(name, mode="copyonwrite", memmap=0):
"""Factory function to open a FITS file and return an HDUList object.
name: Name of the FITS file to be opened.
mode: Open mode, 'readonly' (default), 'update', or 'append'.
memmap: Is memmory mapping to be used? default=0.
"""
# instantia... | 7aef96b47426e96916e490b2c18f8298ee45cbce | 44,323 |
from typing import get_args
def query_other_gene_name():
"""
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Alternative short ... | 1a6151ee2677b2b6964c72bec1173ab0b38c1d7b | 44,324 |
def cbc_cloud_api():
"""Create CBCloudAPI singleton."""
return CBCloudAPI(url="https://example.com",
org_key="test",
token="abcd/1234",
ssl_verify=False) | 16527b89ccb3c1d285c23c63404a130b1140a89b | 44,325 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.