content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def Quantizer_train(x, basis, level_codes, thrs_multiplier, nbit=2, training=False):
"""
Quantize weight.
Args:
x (torch.Tensor): a 4D tensor. [K x K x iC x oC] -> [oC x iC x K x K]
Must have known number of channels, but can have other unknown dimensions.
basis (t... | c427fab45cc7f2e5e8ae22ed14808b98b53068f6 | 3,606,053 |
def _mom_cyclic(g_step_op, base_mom=None, max_mom=None, step_size=None, gamma=0.99994, mode='triangular',
one_cycle=False, op_name=None):
"""Computes a cyclic momentum as in https://arxiv.org/abs/1803.09820. Notice we leave triangular2 and exponential ena-
bled but we do not know if this types o... | bc4bc380cb4d167ab73862e7e2d76cfd849535e6 | 3,606,054 |
def balance_error(request, pk):
""" Muestra la plantilla balance_error.html, con opciones para la corrección
de un saldo erróneo."""
cta = Account.objects.get(pk=pk)
return render(
request,
'finper/balance_error.html',
{
'request': request,
'cta': cta,... | 7a76041931f738ad9d0e47cafa3ea53d2635feaa | 3,606,055 |
from typing import Tuple
def timedelta_to_human_range(s: pd.Series) -> Tuple[pd.Series, str]:
"""Convert a pandas Series of timedeltas to a pandas Series of floats,
and derive a time unit (a string such as "years" or "minutes") that gives a nice human readable range of floats.
For example:
>>> import... | c9ebcb57a3495d7416abee08c8fd4a63429673b2 | 3,606,057 |
async def async_subscribe_to_server_originated_rpc_notification(
connection,
callback,
name,
arguments=[],
timeout_seconds=5,
defaults={},
role=RPC_ROLE_GENERIC,
session_title_display_name=None,
session_title_unique_id=None,
status_bar_comp... | 628c0fc5a419c3c89c64b5b3fb8ea9dfcb50e27b | 3,606,058 |
import time
def WaitForSigStr(serialPort, MinSigStr, Timeout):
""" Checks receive signal strength for specified time returning true when above min level or false when timeout."""
signalStr = 0
timeout = time.time() + Timeout # Set the timeout time
while time.time... | 0b30e1b3da91caadae06933b73c99ba628ba3824 | 3,606,059 |
def layer_norm(layer_inputs, hidden_size):
"""Implements layer norm from [Ba et al. 2016] Layer Normalization.
See eqn. 4 in (https://arxiv.org/pdf/1607.06450.pdf).
Args:
layer_inputs (tensor): The inputs to the layer.
shape <float32>[batch_size, hidden_size]
hidden_size (int): Dimensionality of t... | 2bc3bb741e5828c9478bfb8151292b3d0a8a6e02 | 3,606,060 |
def fit_loss(ac, fit):
"""Loss of the fit """
r = ac - fit
error = sum(r ** 2) / sum(ac ** 2)
return error | 00d41891dea7d914299d87d971fb2a41df2109ed | 3,606,061 |
from openeye import oechem, oedocking
from openeye import oequacpac
from openeye import oeomega
def dock_molecule_to_receptor(molecule, receptor_filename, covalent=False):
"""
Dock the specified molecules, writing out to specified file
Parameters
----------
molecule : oechem.OEMol
The mol... | 0848e7755a1e1a2a9153b62c11080920482d11af | 3,606,062 |
def dbus_variant_dict(dct):
"""
Build a dictionary with :class:`gi.repository.GLib.Variant` values, so it
can be used to create DBus types a{sv} objects.
"""
return {k: dbus_variant(v) for k, v in dct.items()} | e188728cf1d35db79c7597ea246a31a20fcbfffc | 3,606,063 |
def parse_condition_expression_to_tree(condition_expression: str) -> Tree:
"""
Parse a given condition expression with the help of the here defined grammar to a lark tree.
The grammar starts with condition keys, e.g. [45] and combines them with
and _/or_compositions corresponding to U/O operators or wit... | f9788fa63a803c94be483f6067a73f0572106841 | 3,606,064 |
def growth_pos_check(clods, pos):
"""for checking the position of a growing seed tip
Like position_calc but amended for growing seed
each time the seed grows there is a cheek for clod collisions
:param clods: All the clod objects in the bed
:param pos: The proposed position of the seed tip
:retu... | 743455907cc81dc3950db202b4f23a79c1eafd33 | 3,606,065 |
def comp_height_wind(self):
"""Compute the height of the winding area
Parameters
----------
self : SlotW14
A SlotW14 object
Returns
-------
Hwind: float
Height of the winding area [m]
"""
Rbo = self.get_Rbo()
# alpha is the angle to rotate P0 so ||P1,P10|| = ... | 1d7f8e87c90c7fea8eef4d4688e9f7a071643544 | 3,606,066 |
from typing import MutableSequence
def aslist(l): # type: (Any) -> MutableSequence[Any]
"""
Convenience function to wrap single items and lists.
Return lists unchanged.
"""
if isinstance(l, MutableSequence):
return l
else:
return [l] | edc375644b1e33bb6d7cc0499bba1b89dbbcfb62 | 3,606,067 |
def determine_letter(current_score):
"""
Calculates the letter grade for a given score
:param current_score: the score to be evaluated
:return: the letter grade that score falls within
"""
if current_score >= 90:
return "A"
elif current_score >= 80:
return "B"
elif curren... | 324aaa8e28a0cbc298410ecd83ea4eee6d39a970 | 3,606,069 |
from typing import Tuple
from typing import Dict
def parse_icf(icf_file: str) -> Tuple[Dict, Dict]:
"""Parse ICF linker file.
ST only provides .icf linker files for many products, so there is a need
to generate basic GCC compatible .ld files for all products.
This parses the basic features from the .... | ddc1288603d0697bf915eb82a712f210f54efacd | 3,606,070 |
def scatter_figure(
coords: pd.DataFrame, title: str, img: str, img_x: float, img_y: float, img_sizex: float, img_sizey: float
) -> Figure:
"""Extracts the three coordinates from the dataframe and create a 2D scatter plot, which is overlayed on the top of
the top-down view of the game scene with the image p... | 2d8c4342d3959ca7646fedfc810cdceff2cc4d77 | 3,606,072 |
from typing import Iterator
def variables(value: SupportsVariables) -> Iterator[Variable]:
"""Return an iterator of the variables in this object.
The same variable may be yielded in any order and may appear multiple
times. If uniqueness is desired, store the results in a set::
vars = set(variabl... | ed2f3ec6c52e01a8cc66a24ee0aa98b8fe46e844 | 3,606,073 |
def get_vars(host):
"""
parse ansible variables
- defaults/main.yml
- vars/main.yml
- vars/${DISTRIBUTION}.yaml
- molecule/${MOLECULE_SCENARIO_NAME}/group_vars/all/vars.yml
"""
base_dir, molecule_dir = base_directory()
distribution = host.system_info.distribution
... | ddedabc49841354809c1e4a64695ae757ca8f710 | 3,606,074 |
def jit_attr_none(func, kls=_internal_jit_attr):
"""
Version of :py:func:`jit_attr` decorator that forces the uncached_val
to None.
This is mainly useful so that if any out of band forced regeneration of
the value, they know they just have to write None to the attribute to
force regeneration.
... | dceeb78b381486f2ae43cca71f3a81bd51dbceff | 3,606,075 |
import collections
def _separateByFormType(d):
""" Organize form elements into a manageable collection
Turn empty dicts into None so that forms render properly
Nonrepeating fields (fields that can't be repeated into multiple forms) are:
identifier, identifier-identifierType, language, publ... | 7676aee613ce0f3f257b2f06694a62718dab47ca | 3,606,076 |
def translate(word):
"""
translates third person words into first person words
"""
forms = {"is" : "am", 'she' : 'I', 'he' : 'I', 'her' : 'my', 'him' : 'me', 'hers' : 'mine', 'your' : 'my', 'has' : 'have'}
if word.lower() in forms:
return forms[word.lower()]
return word | ac433a4db5154c065e2cec1263976dba72863ad8 | 3,606,077 |
def advance_flatten(cursors: list[Cursor], pat: Pat) -> list[Cursor]:
"""Convenience function to advance a list of cursors."""
ret = []
for c in cursors:
ret.extend(c.advance(pat))
return ret | fb3fa007c460652d60ff57e25dbbc15bd168468e | 3,606,078 |
def pca_embedded_data_frame(df: pd.DataFrame, n_components=0.9, verbose: bool = False):
"""
Embed all observations of a bearing time series using PCA.
:param df: Data frame which contains computed features or raw features.
:param n_components: Number of components to be learned from PCA
:return: PCA... | c6d79e9bd49e330bdfcbba3240011a8c02bacd6d | 3,606,079 |
from typing import Union
from typing import List
def loot(loot_id=0) -> Union[Loot, List[Loot], bool]:
"""Returns information about the loot.
Endpoint
--------
https://www.nitrotype.com/index/624/bootstrap.js
Parameters
----------
loot_id : int
The loot to access from the boo... | 8da618a0166b305a3398cacbb73dbe507c067d58 | 3,606,080 |
import math
def cal_summary_and_weight(comments):
"""
计算评论内容的摘要及其对应权重
:param comments: 需要分析的评论列表
:return: 返回列表,列表元素为元组,元组中包含摘要和其对应的权重
"""
d = {}
ret = []
for c in comments:
nlp = SnowNLP(c.content)
# 评论获赞数越多,权重越高,取对数来平滑极差
w = int(math.log(c.votes + 1) + 1) ** 2... | f58b8bef624f0ad2d670747be6042baf7505a4b7 | 3,606,081 |
def dateToEvent(date, schemakey):
"""
return birthDate and deathDate schema.org attributes
don't return deathDate if the person is still alive (determined if e.g. the date looks like "1979-")
"""
if '-' in date:
dates = date.split('-')
if date[0] == '[' and date[-1] == ']': # oh..
... | c1e0d11de3e8b2b4240cc34006de1fc3b3b40581 | 3,606,082 |
def sample_feature(df_row, id_column, df_columns, crs, res, all_touched, meta, frac, min_frac_area, feature_array=None):
"""
Samples polygon features
Args:
df_row (pandas.Series)
id_column (str)
df_columns (list)
crs (object)
res (tuple)
all_touched (bool)
... | 6552a713f298a1b076822c6ac5311b7fffcc4fe1 | 3,606,084 |
def normalize_attribute(attr):
"""
Normalizes the name of an attribute which is spelled in slightly different
ways in paizo HTMLs
"""
attr = attr.strip()
if attr.endswith(':'):
attr = attr[:-1] # Remove trailing ':' if any
if attr == 'Prerequisites':
attr = 'Prerequisite' # N... | 2cb66878547ee8a98c14bf08261f2610def57a37 | 3,606,085 |
import nipype.interfaces.fsl as fsl
import nipype.interfaces.utility as niu
import nipype.pipeline.engine as pe
from nipype.workflows.data import get_flirt_schedule
from nipype.workflows.dmri.fsl.artifacts import _xfm_jacobian
from nipype.workflows.dmri.fsl.utils import (
extract_bval,
recompose_dwi... | c0c24e6be62aa65735de3068824a48f9ccb75d8c | 3,606,086 |
def vector2cdl(vector):
"""Make a CDL string representation of a numeric 1D array."""
dtype = vector.dtype
def normalize(x):
"""Normalize a single value for CDL"""
if dtype == 'int16':
s = '{}s'.format(x)
elif dtype == 'int32':
s = str(x)
elif dtype =... | 3455670d27737eec9c9a5fc871d62b7ea4d2bb0e | 3,606,088 |
from typing import Optional
def _value_serde(serde, if_not_found=None):
""" inner function """
origin_serde = origin(serde)
if isinstance(origin_serde, list) or isinstance(origin_serde, tuple):
if len(origin_serde) == 2:
return Optional(of(origin_serde[1]))
else:
ra... | f15024c3f037156d0fe99fbb5435aacdd3c24216 | 3,606,089 |
def get_normal_vector(points: np.ndarray):
"""
Note: Direction of normal vector depends on right hand rule.
p0, p1, p2 = points
v01, v12 = p1 - p0, p2 - p1
"""
if points.shape != (3, 3):
logger.error(f"Received points matrix of size {points.shape}. Expected (3, 3).")
raise Except... | d561ad03c57efbee4a6dbeeccab22b3f9977ee25 | 3,606,090 |
def getPrefices(fileList, transferType, experiment):
""" Get the old/newPrefices as a dictionary needed for the SURL to TURL conversions """
# Format:
# prefix_dictionary[surl] = [oldPrefix, newPrefix]
# Note: this function returns oldPrefix, newPrefix, prefix_dictionary
# old/newPrefix are the fi... | a587a1e9b63a57684583b537d79a9529d8b1ee0c | 3,606,091 |
def is_lyrics_content_ok(title, text):
"""Compare lyrics text to expected lyrics for given title"""
setexpected = set(LYRICS_TEXTS[lyrics.slugify(title)].split())
settext = set(text.split())
setinter = setexpected.intersection(settext)
# consider lyrics ok if they share 50% or more with the referen... | e7e4e231081526cd560d8309d5cce429971a75dc | 3,606,092 |
def simdiag(ops, evals: bool = True, *,
tol: float = 1e-14, safe_mode: bool = True):
"""Simultaneous diagonalization of commuting Hermitian matrices.
Parameters
----------
ops : list/array
``list`` or ``array`` of qobjs representing commuting Hermitian
operators.
evals ... | d64be987216a9bd8d67c9a9b733fbba160c808f8 | 3,606,093 |
def black_clip_from_clip(clip, **blank_clip_args):
"""Creates a clip of black color in the same format as the passed in clip.
Unlike BlankClip, this takes the passed in clip's color range into account
by rendering the first frame.
"""
bit_depth = clip.format.bits_per_sample
is_integer = (clip.fo... | 9ed0ac06c2121bdeaad47c14f147afe8ed51071f | 3,606,094 |
import warnings
def vmap(map, v):
"""Transform coordinates while handling RuntimeWarning
that could be raised by NumPy when trying to transform
a zero in logarithmic scale for example"""
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
output =... | 2d525e9de47aef7ccfb6cac120c886966d2be2ab | 3,606,095 |
def palindrome(data):
"""
:param data: image data as array
:return: score referring to what extent the structure of the two image halves is symmetrical
"""
# loop over both lists simultaneously and if the counts are equal, add True, else, add False
# lastly, divide the amount of Trues by the le... | fb086c94b821e39c10eb246c566e3db35b9328cb | 3,606,096 |
def bi_latest_parent_date_modified(vc_dir, parentname):
"""
given a path to a version control directory of build instructions and the
name of the parent model, return the parent model's revision date
"""
newest_bi = newest_file(vc_dir)
meta = read_meta_data(newest_bi)
# with open (newest_bi)... | 8ecda12c5c97f767b1b4da4d72d6bd6a6034a5e4 | 3,606,097 |
def version(format_str='{short}'):
""" Returns current version number in specified format.
:param format_str: format string for the version
:type format_str: str
:return: version number in the specified format
:rtype: str
"""
major, minor, patch = version_numbers()
format_dict = ... | 15d2ea477460f7208863f673e64bf2f316054a43 | 3,606,099 |
def value_at_path(d, path):
""" access value by object path
:param d: dict or list of dict
:param path: object path like `Data.1.UHostId`
:return: any value access by path
"""
if d is None:
return
indices = path.split(".")
result = d
for i, key in enumerate(indices):
... | cc3724a21893b9f40a6a069a836bbc8a30ac369e | 3,606,100 |
def __virtual__():
"""
Only work on Windows
"""
if salt.utils.platform.is_windows():
return __virtualname__
return False | f239909adbf99047da87316176b4dcd06cfa7a77 | 3,606,101 |
from typing import List
import shutil
def _get_build_bf_command(args: dict, in_fn: List[str]) -> List[str]:
"""Helper function to compose command to get the final Bloom Filter
:arg dict args: Dict of arguments.
:arg str in_fn: Path to file where the reads will be read
:ivar dict args: Dict of argume... | 9736a1825613dd518361bb1a5ded9b266293017a | 3,606,102 |
import http
def parse_xml(body, code, headers):
"""
Return a dictionary.
Transformation is done assuming:
1. If a tag indicates its value type, we'll try to cast it.
2. Siblings with the same tag name, become a list.
3. Attributes become a dict key starting with '@'.
<duck>
<n... | 05dcbbc5912a2b87158dcfa1e70505e0d6da1137 | 3,606,103 |
def is_user_diabetic(avg_glucose_level):
"""
desc: converts avg_glucose_level to category based on ADA Guidelines https://www.diabetes.org/a1c/diagnosis
args:
avg_glucose_level (float) : glucose level in blood based on mg/dL
returns:
blood_cat (string) : blood sugar category
"""
... | 59b8a9937f620c28eb51da4ef56c493d1b2177d8 | 3,606,105 |
import time
def get_Into_School_Page(logger, school_dict, driver):
"""
进入学校界面,获取学校相关信息
:param logger:
:param school_dict: 读取包含学校名和学校链接的字典
:param driver:
:return:
dict: 课程信息字典,包含课程名、上课人数、课程链接、学校
"""
school_list = list(school_dict['校名'].values())
school_url_list = list(school... | aa1131e67b1bdfc1eee8f3066101a3dcfe3ec24f | 3,606,106 |
def id_for_fund(fund):
"""Retrieves the integer identification number for the specified fund.
Parameters
----------
fund: String.
The fund whose integer identifier is requested.
"""
cur.execute("SELECT id FROM funds WHERE fund='{}'".format(fund))
return cur.fetchone()[0] | 0cc830d45a8c4597f27cb3aa7b615fc9fb889d72 | 3,606,107 |
import hmac
def verify_cron_job(cron_domain: str, secret_key: str) -> bool:
"""verify if the executor of the cron job is authorized"""
is_domain: bool = hmac.compare_digest(
cron_domain, config_instance.CRON_DOMAIN)
is_secret: bool = hmac.compare_digest(
secret_key, config_instance.CRON_SE... | af29a82c74e66a39d0e331ed7eee4461c3f15a1d | 3,606,108 |
import re
def tokenize(text):
"""
:param text: string to tokenize
:return: text in form as clean token
"""
url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
detected_urls = re.findall(url_regex, text)
for url in detected_urls:
text = text.... | 5bc06666995920898599339a4d250c066fd36451 | 3,606,110 |
def label_sem_map(sem: np.ndarray, sort: bool=True) -> np.ndarray:
"""
Labels a given semantic segmentation map
Args:
---------
sem (np.ndarray):
semantic segmentation map. Shape (H, W)
sort (bool, default=True):
sort the semantic areas by size in descending orde... | 084237973f9bd28fce3fa2cf6f231c9d8553da57 | 3,606,111 |
import array
def formatTilePlanar(tile, nPlanes):
"""Convert an 8x8 pixel image to planar tile data, 8 bytes per plane."""
if (tile.size != (8, 8)):
return None
pixels = iter(tile.getdata())
outplanes = [array.array('B')
for i in range(nPlanes)]
for y in range(8):
... | 5ff30470a1392744139a5577f2a51a519f58ab42 | 3,606,112 |
def gen_factory(func, seq):
"""Generator factory returning a generator."""
# do stuff ... immediately when factory gets called
print("build generator & return")
return (func(*args) for args in seq) | 9188f5959ec2feb52b83f20f40474f91f4cbfe08 | 3,606,113 |
from typing import Optional
def get_api_version_set(api_management_name: Optional[str] = None,
name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetApiVersionSetResult:... | d24d5730dbd4f39dc4963616b99186a2287de8d5 | 3,606,114 |
import logging
def retrieve_inventory(vault_name):
"""Initiate an Amazon Glacier inventory-retrieval job
To check the status of the job, call Glacier.Client.describe_job()
To retrieve the output of the job, call Glacier.Client.get_job_output()
:param vault_name: string
:return: Dictionary of inf... | 97c5a6ef67139014004241558e6b07564cfd195a | 3,606,115 |
def _validate_satellite_dates(satellite, start, end):
"""Validate the start and end times for the satellite.
Uses the known operational dates of the satellites to
adjust the start date if needed. It also selects the
Amazon S3 bucket to use.
Returns: a tuple of (start, S3 bucket). If the start
... | 3fe5aaedd35f6bd1e5addf7fc54fb88341993dc0 | 3,606,116 |
def _parseExpectedWords(wordList, defaultSensitivity=80):
"""Parse expected words list.
This function is used internally by other functions and classes within the
`transcribe` module.
Expected words or phrases are usually specified as a list of strings. CMU
Pocket Sphinx allows for additional 'sen... | 83512a86ae112de79bd84e1d9ea3ebebcb4cdefd | 3,606,117 |
import json
def create_json_report(occurrences, filename, report_dir=False):
"""Create a JSON file containing the raw data that can be queried for further analysis."""
if report_dir:
report_filepath = report_dir + '/' + filename + '.json'
else:
report_filepath = ANALYSIS_DIRECTORY_PATH + '... | d958a8f2027cc2a15179fdd218e23e4e451cf342 | 3,606,118 |
def AAPIEnterPedestrian(idPedestrian, originCentroid):
"""Execute command once a pedestrian enters the Aimsun instance."""
return 0 | 7dc133cb3ed7e5dc0adcfb5ee271faa9c94b2418 | 3,606,119 |
def add_bbox_to_image(image, bbox, color='red', width=3):
"""Adds a bounding box to the image.
Args:
image: A PIL image.
bbox: (ymin, ymax, xmin, xmax) box.
color: Color to draw the box with.
Returns:
A PIL image with the bounding box drawn.
"""
output = image.copy(... | fc3a35a3bcf94ac690eef5788c98d1d825410c26 | 3,606,120 |
def registerErrorHandler(f, ctx):
"""Register a Python written function to for error reporting.
The function is called back as f(ctx, error)."""
ret = libxsltmod.xsltRegisterErrorHandler(f, ctx)
return ret | aedeedee6bfaec690574e1cbba9e446053d24d82 | 3,606,121 |
import numpy as np
from scipy.io import loadmat
import numpy as np
import h5py
from numpy import fromfile, empty, append
def reading_data(data_file, data_choice):
""" This function is adapted to take in any 3 files of the following types: .bin, .mat or h5. The reader is designed
to read in uint16 cast data. ... | 72b0a7681eda06de8c967b895676de948e9ee064 | 3,606,123 |
def split_leading_indent(line, max_indents=None):
"""Split line into leading indent and main."""
indent = ""
while (
(max_indents is None or max_indents > 0)
and line.startswith((openindent, closeindent))
) or line.lstrip() != line:
if max_indents is not None and line.startswith(... | 2bcf803b84d7d2a01929562a2376e94299389dc8 | 3,606,125 |
async def view_available_recipes():
"""
Returns the list of recipes available for the coffee machines
"""
recipes = [i for i in database.get_recipes().find()]
for i in recipes:
del i['_id']
return {"recipes": recipes} | 57ecac022799f1ff00f17bd0b93cce63b10a2a91 | 3,606,127 |
def nanmean(x, axis=0):
"""Compute the mean over the given axis ignoring NaNs.
Parameters
----------
x : ndarray
input array
axis : int
axis along which the mean is computed.
Returns
-------
m : float
the mean.
"""
x, axis = _chk_asarray(x, axis)
x = x.cop... | d024c28224927de7c86737b75179263b25ae2687 | 3,606,128 |
def _handle_doi_url(attrs: Attrs, new: bool = False) -> Attrs:
"""
Screen for reference to a DOI, and generate a URL.
If the :ref:`.DOI` pattern is used, it will generate a link with the
doi as a the target. We need to intercept these links, and generate
a real URL.
"""
href = attrs[(None, ... | d4dfbe800569aa2ec126a063f965f001869b2374 | 3,606,129 |
from scipy.linalg import cho_solve
def regression(objectsA, objectsB, xyarr, P, scale, amp, chol):
""" Perform regression on the gaussian processes for the
the distortion map. This uses the input data to push known
values onto a new grid, using the covariance properties of
the GP."""
# Compute e... | 8026047406736c0327dc308584a0a6caa8c744a5 | 3,606,130 |
def convert_bbox_from_coco(bbox):
"""Convert a bounding box array from the COCO format [x1, y1, w, h] to the
format [x1, y1, x2, y2].
"""
x1, y1 = (bbox[0], bbox[1])
x2, y2 = (x1 + bbox[2], y1 + bbox[3])
return np.array([x1, y1, x2, y2]) | 53405114df8903d4013bcb4a2558b39830c232ef | 3,606,131 |
def make_csd(shape, scale, npart):
"""Create cell size distribution and save it to file.
Log-normal distribution from scipy is used. Creates ``diameters.txt`` file
with sphere diameters.
Args:
shape (float): shape size parameter of log-normal distribution
scale (float): scale size para... | dcf1b8ca969f9028d5a8e61a5c545843ecf8adc2 | 3,606,132 |
def ISNA(cell) -> func_xltypes.Boolean:
"""Returns True if the cell is #N/A.
Don't call validate_args here because we allow errors to be
passed in.
"""
return isinstance(cell, xlerrors.NaExcelError) | 10ce93efdc7243072a09c02e6ff2ecf6d3d7aba8 | 3,606,133 |
from typing import Optional
def get_compartment(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCompartmentResult:
"""
This data source provides details about a specific Compartment resource in Oracle Cloud Infrastructure Identity service.
Gets th... | 6cab80b11c0426acb744dc1e2e2bb8947a38db78 | 3,606,134 |
import logging
def get_tabula_Umean() -> pd.DataFrame:
"""Return building_stock dataframe"""
pth = path_tabula_Umean()
if not pth.exists():
logging.warning(f"file: {pth} not found... start downloading it")
download.download_population()
tab = pd.read_csv(pth, sep="|", index_col=0)
... | 20a7661fad75a87d11eceac6d932459be03906c3 | 3,606,135 |
import requests
def sign_in_to_server(server, username, password, site="", ssl_cert_pem=None):
"""
Signs in to the server specified with the given credentials
'server' specified server address
'username' is the name (not ID) of the user to sign in as.
Note that most of the functions i... | 1e2b68609264f7c27ba8937e1b1f845e37523fb8 | 3,606,136 |
def test_wait_until_true_once_found(mock_time_sleep):
"""wait_until_true max_attempts 1."""
mock = MagicMock()
mock.side_effect = [
'expected value',
'test string 2',
]
def decorate_me(arg1, arg2):
"""Test static decorator syntax."""
assert arg1 == 'v1'
asser... | 76e64fe0ab9d0c0f1b3b704994e5a5fa9933cb5c | 3,606,137 |
def latest(treant):
"""Get the latest data file available based on a sort.
"""
return pipe(
treant.glob('*.nc'),
sorted,
last,
lambda leaf: leaf.abspath,
) | 5abff0b89a3aa7ea269c14f8d590c2057fc50161 | 3,606,138 |
import functools
def admin_required(f):
"""
Decorator to apply to views that require an admin to access.
"""
@login_required
@functools.wraps(f)
def wrapper(request, *args, **kw):
if action_allowed(request, amo.permissions.ADMIN_TOOLS):
return f(request, *args, **kw)
... | 333112eddf1372b7997f20a26a359bdaa175effb | 3,606,139 |
def is_upper_diff(text: str) -> bool:
"""Check if some words are all caps while others aren't.
Args:
text (str): Text to parse through and check if some words are capitalized while others aren't
Returns:
bool: True if some words all caps while others aren't, False otherwise
"""
current_word = ""
upper_word... | d50e42795961d9d0a0c409cf9ff61dac5b709151 | 3,606,141 |
import requests
def delete_menu(access_token):
"""
删除菜单 请谨慎使用
http请求方式:GET
https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN
:param str access_token: ACCESS_TOKEN
:rtype: json
"""
menu_url = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={ac... | fb52f406d52b2dad2aedfd8c04913a3ca94b6ca1 | 3,606,142 |
def _generate_trades_df_response(trades_df):
"""
Generates JSON response from trades
Attributes
----------
trades_df: DataFrame of Trades
"""
trades_df = trades_df.drop(
columns=["symbol", "trade_id", "stop_loss", "take_profit"]
)
trades_df = trades_df.rename(
colum... | 34244801babedeb75ec21001ea99a9e8aef863e2 | 3,606,143 |
def measurement(qreg=int(0),
creg=int(0)):
"""Generate QASM that takes a measurement from a qubit and stores it in a classical register.
Args:
qreg(int): Number of the Qubit to measure. (default 0)
creg(int): Number of the Classical Register to store the measurement to. (default... | 9a9a24f390bf0745e7cdfe80bb1893f77161c171 | 3,606,145 |
import urllib
def unparse_transport_url(transport, secure=True):
"""
Unparse a transport URL; that is, synthesize a transport URL from
a dictionary similar to that one returned by
parse_transport_url().
:param transport: The dictionary containing the transport URL
components... | dba2e123908e3cf98ce4c1a415ac33b54475bd6b | 3,606,146 |
def get_vplex_port_parameters():
"""This method provide parameter required for the ansible port
module on VPLEX"""
return dict(
cluster_name=dict(required=True, type='str'),
port_name=dict(required=True, type='str'),
enabled=dict(required=False, type='bool'),
state=dict(requi... | 9533cf6ff8eedd943b88c9cd08ea16407aa9ee64 | 3,606,147 |
def projection_error(p1, p, pt, pt1):
"""
Based on Hartley and Zisserman p.285 this function triangulates
image correspondences and computes the reprojection error
by back-projecting the points into the image.
This is the classic cost function (minimization problem) into
the gold standard metho... | 76046d81d270c98cc9f6f68fe36c9c22b257d9c3 | 3,606,148 |
def createMainSizer(parent, granparent, ID, title, pos, size, style):
"""
Function to create control dialogs.
"""
pre = _precreate(granparent, ID, title, pos, size, style)
return _postcreate(parent, pre) | 71ff10b4d4d8cf4b4ed42decf2fee46f2fece9fc | 3,606,150 |
def _arr(*shape):
""" Construct an array of a specified consisting of values [0, _arr.size)
filled in row-major order.
Parameters
----------
*shape : int
Returns
-------
numpy.ndarray"""
return np.arange(np.prod(shape)).reshape(shape) | c364ce0da3ee43b5cdb96cb1600ea98346ca4620 | 3,606,152 |
def fixedtext_features(X, target_keynames, align):
"""
Extract fixed-text features (press-press latency and key-hold duration) from the raw data sample X, given the
target key sequence and keystroke alignment (correspondence) method.
"""
timepress, timerelease = timepressrelease(X, target_keynames, ... | 898a16d348613ba454d7cbed23a7ac9265927110 | 3,606,153 |
def sset_list(args):
""" List sample sets in a workspace """
return __get_entities(args, "sample_set") | 5ba593935829a3350ee804426372e1f299095df1 | 3,606,154 |
def _GetNodeDiskState(_, node):
"""Converts node's disk state for query result.
"""
disk_state = node.disk_state
if disk_state is None:
return _FS_UNAVAIL
return dict((disk_kind, dict((name, value.ToDict())
for (name, value) in kind_state.items()))
for (disk... | d9efd107b00df05db76f0fcefc1a615ed52fd5ad | 3,606,156 |
def dylan_stretchy_vector_size(vector):
"""Return size of a stretchy vector"""
representation = dylan_slot_element_by_name(vector, 'stretchy-representation')
return dylan_integer_value(dylan_slot_element(representation, SIMPLE_OBJECT_VECTOR_SIZE)) | 3f928c575117480596d3a45747987ec6fa617d85 | 3,606,157 |
def remote_ip(local_ip):
"""
Given an IP address, this function calculates the remaining available
IP address under the assumption that it is a /30 network.
In other words, given one link net address, this function returns the
other link net address.
:type local_ip: string
:param local_ip:... | d784ef13f9625c5f5285193af82ac056b66929b7 | 3,606,158 |
def generate_mixture_indicator(number_obeservations):
"""Generate the variable that will be used for mixture generation
Args:
- number_obeservations : number of obeservations
Returns:
- mixture_indicator: mixture indicator variable
"""
mixture_indicator = np.random.randint(0, 2, (number_o... | 34e65e64ba3dafbc4809fc5cb0a3c2ab10cac81b | 3,606,159 |
def __local_pa(soup):
"""
Gets the most read news from Pará Local News (Rede Liberal)
:param soup: the BeautifulSoup object
:return: a list with the most read news from Rede Liberal page
"""
return __get_local_g1_news(soup) | 5c9b44175ec9321eda290ae403bbbaf732f54a3c | 3,606,160 |
def adjacent(p):
"""Return the positions adjacent to position p"""
return (
(p[0] + 1, p[1], p[2]),
(p[0] - 1, p[1], p[2]),
(p[0], p[1] + 1, p[2]),
(p[0], p[1] - 1, p[2]),
(p[0], p[1], p[2] + 1),
(p[0], p[1], p[2] - 1),
) | 988597e0abd150ae60b556e52a217bd8a136707b | 3,606,161 |
async def goodbye():
""" used in our randomized redirect """
return {"message": "Goodbye"} | 2a0ce1fe99497b55cfd9a9853cd75a0c7eddac40 | 3,606,162 |
def to_stereo(waveform):
""" Convert a waveform to stereo by duplicating if mono,
or truncating if too many channels.
:param waveform: a (N, d) numpy array.
:returns: A stereo waveform as a (N, 1) numpy array.
"""
if waveform.shape[1] == 1:
return np.repeat(waveform, 2, axis=-1)
if ... | 03478d970e7be1d4eb24201deeb3e5c330ab00af | 3,606,163 |
def metrics_from_stats(stats):
"""Compute metrics to report to hyperparameter tuner."""
labels, probs = stats['labels'], stats['probs']
# Reshape binary predictions to 2-class.
if len(probs.shape) == 1:
probs = np.stack([1-probs, probs], axis=-1)
assert len(probs.shape) == 2
predictions = np.argmax(pro... | 932116c02f54bee9ff2ee953cb91d19b20de5fc7 | 3,606,164 |
def prepare_ocp(
biorbd_model: biorbd.Model,
final_time: float,
n_shooting: int,
use_sx: bool,
weights: np.ndarray,
use_excitations=False,
use_collocation=False,
) -> OptimalControlProgram:
"""
Prepare the ocp
Parameters
----------
biorbd_model: str
The path to t... | 8bda9f58789dc5f2ce6a286b7cef0ac3f2f9d2d9 | 3,606,165 |
def update_pubmed(pub_uri, doi=None, pmid=None, inVivo=True):
"""
Given the uri of a pub in VIVO and a module concept dictionary,
update the PubMed attributes for the paper, and include RDF
to add to the concept dictionary if necessary
"""
ardf = ""
srdf = ""
if inVivo:
# Get the pa... | 1eda48fbb5d561f9a53e6b18732153180c58a087 | 3,606,166 |
def ldns_resolver_set_tsig_keydata(*args):
"""LDNS buffer."""
return _ldns.ldns_resolver_set_tsig_keydata(*args) | 72519065a9a1e33584b05eb063f406f4c048e0e3 | 3,606,167 |
def make_table(*list_of_list):
"""
:param list_of_list: list of list of strings
:returns: a valid rst table
"""
lcols = [len(x) for x in list_of_list[0]]
for li in list_of_list : # compute the max length of the columns
lcols = [ max(len(x), y) for x,y in zip(li, lcols)]
form = '| ' ... | 77153451571e70a77d6bd525bd252aa7efe1c693 | 3,606,168 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.