content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def isinteger(x):
"""
determine if a string can be converted to an integer
"""
try:
a = int(x)
except ValueError:
return False
else:
return True | 180cea2f61733ada26b20ff046ae26deffa5d396 | 3,640,639 |
from typing import Tuple
from typing import List
def unmarshal_tools_pcr_values(
buf: bytes, selections: TPML_PCR_SELECTION
) -> Tuple[int, List[bytes]]:
"""Unmarshal PCR digests from tpm2_quote using the values format.
Args:
buf (bytes): content of tpm2_quote PCR output.
selections (TPML... | 3a5b9dd36ca787026bb9bade4b5e5cc175add9e9 | 3,640,640 |
def new_topic(request):
"""添加新主题"""
if request.method != 'POST':
#未提交数据,创建一个新表单
form = TopicForm()
else:
#POST提交的数据,对数据进行处理
form = TopicForm(request.POST)
if form.is_valid():
new_topic = form.save(commit = False)
new_topic.owner = request.user
new_topic.save()
form.save()
return HttpResponse... | 8d41cb1926d809742e89ec7e79ef7bd1ed14443c | 3,640,641 |
from typing import Union
from typing import List
from typing import Any
from typing import Optional
def address(lst: Union[List[Any], str], dim: Optional[int] = None) -> Address:
"""
Similar to :meth:`Address.fromList`, except the name is shorter, and
the dimension is inferred if possible. Otherwise, an e... | ef9e21bb3ef98b12c8ad02c75ccf2cbf6552fd44 | 3,640,642 |
import io
def create_scenario_dataframes_geco(scenario):
"""
Reads GECO dataset and creates a dataframe of the given scenario
"""
df_sc = pd.read_csv(io["scenario_geco_path"])
df_sc_europe = df_sc.loc[df_sc["Country"] == "EU28"]
df_scenario = df_sc_europe.loc[df_sc_europe["Scenario"] == scenar... | 8a17d452feeb506bc2c2bf61a91e8473f2097649 | 3,640,644 |
def escape_env_var(varname):
"""
Convert a string to a form suitable for use as an environment variable.
The result will be all uppercase, and will have all invalid characters
replaced by an underscore.
The result will match the following regex: [a-zA-Z_][a-zA-Z0-9_]*
Example:
"my.pri... | c1e57ff3b9648e93a540202f00d0325f91bccde1 | 3,640,645 |
def rms(signal):
"""
rms(signal)
Measures root mean square of a signal
Parameters
----------
signal : 1D numpy array
"""
return np.sqrt(np.mean(np.square(signal))) | 6643ad464b4048ad71c7fb115e97b42d58a84a9c | 3,640,646 |
def get_config(
config_path, trained: bool = False, runner="d2go.runner.GeneralizedRCNNRunner"
):
"""
Returns a config object for a model in model zoo.
Args:
config_path (str): config file name relative to d2go's "configs/"
directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_F... | e6d2b57bcadd833d625bd0a291fbb8de9d333624 | 3,640,648 |
from typing import Optional
def make_game(
width: int = defaults.WIDTH,
height: int = defaults.HEIGHT,
max_rooms: int = defaults.MAX_ROOMS,
seed: Optional[int] = defaults.SEED,
slippery_coefficient: float = defaults.SLIPPERY_COEFFICIENT,
default_reward: float = defaults.DEFAULT_REWARD,
goa... | 908c772cdc3af5a891bce8c169d744e335da6e61 | 3,640,649 |
def weighted_var(x, weights=None):
"""Unbiased weighted variance (sample variance) for the components of x.
The weights are assumed to be non random (reliability weights).
Parameters
----------
x : np.ndarray
1d or 2d with observations in rows
weights : np.ndarray or None
1d ar... | 2166b214351da22117bf395fda950f1c79ccf0d1 | 3,640,650 |
def start_detailed_result_worker_route():
"""
Add detailed result worker if not exist
:return: JSON
"""
# check if worker already exist
if check_worker_result(RABBITMQ_DETAILED_RESULT_QUEUE_NAME) == env.HTML_STATUS.OK.value:
return jsonify(status=env.HTML_STATUS.OK.value)
if 'db_nam... | 567595574a09ce99f3feb11988bed0ba403b04cd | 3,640,651 |
def _find_next_pickup_item(not_visited_neighbors, array_of_edges_from_node):
"""
Args:
not_visited_neighbors:
array_of_edges_from_node:
Returns:
"""
# last node in visited_nodes is where the traveling salesman is.
cheapest_path = np.argmin(
array_of_edges_from_node[not... | 06dc80e09d5b87cbc94558bee53677c887844b4b | 3,640,652 |
def deformable_conv(input,
offset,
mask,
num_filters,
filter_size,
stride=1,
padding=0,
dilation=1,
groups=None,
deformable_groups=None,
... | 0dce5c2333a0a3dcaa568a85f3a6dec1536d2cfb | 3,640,653 |
def ieee():
"""IEEE fixture."""
return t.EUI64.deserialize(b"ieeeaddr")[0] | b00b13bb16c74bc96e52ad067dc0c523f5b5a249 | 3,640,654 |
def is_in(a_list):
"""Returns a *function* that checks if its argument is in list.
Avoids recalculation of list at every comparison."""
def check(arg): return arg in a_list
return check | 34afbc269c164f0e095b1cbbf4e9576bafc7a9e1 | 3,640,655 |
def get_log_record_extra_fields(record):
"""Taken from `common` repo logging module"""
# The list contains all the attributes listed in
# http://docs.python.org/library/logging.html#logrecord-attributes
skip_list = (
'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename',
'func... | 95fe6a74cd169c14ac32728f0bb1d16a2aa9e874 | 3,640,656 |
def ldap_is_intromember(member):
"""
:param member: A CSHMember instance
"""
return _ldap_is_member_of_group(member, 'intromembers') | d858afac4870cacc18be79a0b2d6d7d51dd33e07 | 3,640,657 |
def details(request, slug):
"""
Show product set
"""
productset = get_object_or_404(models.ProductSet, slug=slug)
context = {}
response = []
variant_instances = productset.variant_instances()
signals.product_view.send(
sender=type(productset), instances=variant_instances,... | 9ac9b3f975a6501cfb94dd5d545c29c63a47a125 | 3,640,658 |
def applies(platform_string, to='current'):
""" Returns True if the given platform string applies to the platform
specified by 'to'."""
def _parse_component(component):
component = component.strip()
parts = component.split("-")
if len(parts) == 1:
if parts[0] in VALID_PL... | 4692fb0d302948e07a1b2586f614dfcfa5618503 | 3,640,659 |
import threading
def _GetClassLock(cls):
"""Returns the lock associated with the class."""
with _CLASS_LOCKS_LOCK:
if cls not in _CLASS_LOCKS:
_CLASS_LOCKS[cls] = threading.Lock()
return _CLASS_LOCKS[cls] | 98b034a0984431a752801407bfbc5e5694ad44ae | 3,640,660 |
from apysc._expression import event_handler_scope
def _get_expression_table_name() -> TableName:
"""
Get a expression table name. This value will be switched whether
current scope is event handler's one or not.
Returns
-------
table_name : str
Target expression table name.
"""
... | 61d3207d51264e876a472cbd2eea43de730508ac | 3,640,661 |
import gc
import time
import joblib
def make_inference(input_data, model):
"""
input_data is assumed to be a pandas dataframe, and model uses standard sklearn API with .predict
"""
input_data['NIR_V'] = m.calc_NIR_V(input_data)
input_data = input_data.replace([np.nan, np.inf, -np.inf, None], np.na... | 472c6eaadf0f9dd705e8600ccb4939d67f387a0e | 3,640,663 |
def property_elements(rconn, redisserver, name, device):
"""Returns a list of dictionaries of element attributes for the given property and device
each dictionary will be set in the list in order of label
:param rconn: A redis connection
:type rconn: redis.client.Redis
:param redisserver: The redis... | 70ee3de0a18a84e9f21df341c685c1380a4ab164 | 3,640,664 |
def _dtype(a, b=None):
"""Utility for getting a dtype"""
return getattr(a, 'dtype', getattr(b, 'dtype', None)) | c553851231f0c4be544e5f93738b43fa98e65176 | 3,640,665 |
def parse_garmin_tcx(filename):
""" Parses tcx activity file from Garmin Connect to Pandas DataFrame object
Args: filename (str) - tcx file
Returns: a tuple of id(str) and data(DataFrame)
DF columns=['time'(datetime.time), 'distance, m'(float), 'HR'(int),
'cadence'(int), 'speed, m/s'(int)]
"""... | bc8052850b9aa9fdab82de2814d38ae62aa298c6 | 3,640,666 |
def get_decay_fn(initial_val, final_val, start, stop):
"""
Returns function handle to use in torch.optim.lr_scheduler.LambdaLR.
The returned function supplies the multiplier to decay a value linearly.
"""
assert stop > start
def decay_fn(counter):
if counter <= start:
return... | d84c0f0305d239834429d83ba4bd5c6d6e945b69 | 3,640,667 |
from typing import Optional
async def is_logged(jwt_cookie: Optional[str] = Cookie(None, alias=config.login.jwt_cookie_name)):
"""
Check if user is logged
"""
result = False
if jwt_cookie:
try:
token = jwt.decode(
jwt_cookie,
smart_text(orjson.du... | e6e3ed4003dc6b60f3b118a98b0fbfb3bcb3b60a | 3,640,668 |
from typing import List
def cached_query_molecules(
client_address: str, molecule_ids: List[str]
) -> List[QCMolecule]:
"""A cached version of ``FractalClient.query_molecules``.
Args:
client_address: The address of the running QCFractal instance to query.
molecule_ids: The ids of the mole... | 33d8c336daba7a79ba66d8823ba93f35fa37c351 | 3,640,669 |
def _domain_to_json(domain):
"""Translates a Domain object into a JSON dict."""
result = {}
# Domain names and bounds are not populated yet
if isinstance(domain, sch.IntDomain):
result['ints'] = {
'min': str(domain.min_value),
'max': str(domain.max_value),
'isCategorical': domain.is_... | c1d9d860ea1735feacfb7349f4516634e217ea5b | 3,640,670 |
def draw_point(state, x, y, col=COLORS["WHITE"], symb="▓"):
"""returns a state with a placed point"""
state[y][x] = renderObject(symb, col)
return state | 64b500fdacda30b0506397d554e8ce6d3b7b4a66 | 3,640,671 |
def _vars_to_add(new_query_variables, current_query_variables):
"""
Return list of dicts representing Query Variables not yet persisted
Keyword Parameters:
new_query_variables -- Dict, representing a new inventory of Query
Variables, to be associated with a DWSupport Query
current_query_vari... | fd5ea2209b374ab9987a05c139ba1f28805f3eff | 3,640,672 |
def Ak(Y2d, H, k):
"""
Calculate Ak for Sk(x)
Parameters
----------
Y2d : list
list of y values with the second derived
H : list
list of h values from spline
k : int
index from Y2d and H
Returns
-------
float
A... | baea453b9c7b023b78c1827dc23bacbd8fd6b057 | 3,640,673 |
def cycle_list_next(vlist, current_val):
"""Return the next element of *current_val* from *vlist*, if
approaching the list boundary, starts from begining.
"""
return vlist[(vlist.index(current_val) + 1) % len(vlist)] | 48e2ac31178f51f981eb6a27ecf2b35d44b893b4 | 3,640,674 |
def _cal_hap_stats(gt, hap, pos, src_variants, src_hom_variants, src_het_variants, sample_size):
"""
Description:
Helper function for calculating statistics for a haplotype.
Arguments:
gt allel.GenotypeArray: Genotype data for all the haplotypes within the same window of the haplotype to be... | 10c3105fe582078d1f24cd740600ccf3c6863407 | 3,640,675 |
import json
def read_cfg(file):
"""Read configuration file and return list of (start,end) tuples """
result = []
if isfile(file):
with open(file) as f:
cfg = json.load(f)
for entry in cfg:
if "start" in entry:
filter = (entry["start"], entry.get("end... | bb9c20b03e95f45708eab17313bc446cc1540308 | 3,640,676 |
import scipy
def least_l2_affine(
source: np.ndarray, target: np.ndarray, shift: bool = True, scale: bool = True
) -> AffineParameters:
"""Finds the squared-error minimizing affine transform.
Args:
source: a 1D array consisting of the reward to transform.
target: a 1D array consisting of ... | 5a6d6d69400327c30d21ae205cab88fd95d856d6 | 3,640,677 |
def mark_item_as_read(
client: EWSClient, item_ids, operation="read", target_mailbox=None
):
"""
Marks item as read
:param client: EWS Client
:param item_ids: items ids to mark as read
:param (Optional) operation: operation to execute
:param (Optional) target_mailbox: target mailbox
... | 80b3fc0b47a9a0044538a2862433a50d5ad36edb | 3,640,678 |
import math
def AIC_score(y_true, y_pred, model=None, df=None):
""" calculate Akaike Information Criterion (AIC)
Input:
y_true: actual values
y_pred: predicted values
model (optional): predictive model
df (optional): degrees of freedom of model
One of model or df is requr... | 6b59dea007f414b0bdc6b972434cb1c2def40bb2 | 3,640,679 |
def to_rgb(data, output=None, vmin=None, vmax=None, pmin=2, pmax=98,
categorical=False, mask=None, size=None, cmap=None):
"""Turn some data into a numpy array representing an RGB image.
Parameters
----------
data : list of DataArray
output : str
file path
vmin : float or list... | 477241dd890b78d7bbf56d3095b42f106af694a7 | 3,640,680 |
import requests
def id_convert(values, idtype=None):
"""
Get data from the id converter API.
https://www.ncbi.nlm.nih.gov/pmc/tools/id-converter-api/
"""
base = 'http://www.pubmedcentral.nih.gov/utils/idconv/v1.0/'
params = {
'ids': values,
'format': 'json',
}
if idtype... | a60698fb20ba94445bbd06384b8523e92bfb91a3 | 3,640,681 |
import base64
def authenticate_user():
"""Authenticate user"""
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username, password=password).first()
if user is not None:
ma_schema = UserSchema()
user_data = ma_schema.dum... | 8e15a3bddf4700c1b207798e3162e3fcef0e7d79 | 3,640,682 |
import typing
import inspect
import warnings
def map_signature(
r_func: SignatureTranslatedFunction,
is_method: bool = False,
map_default: typing.Optional[
typing.Callable[[rinterface.Sexp], typing.Any]
] = _map_default_value
) -> typing.Tuple[inspect.Signature, typing.Opti... | e0655bab739b59b0fad94772654a70ce4e6f84fd | 3,640,683 |
def get_random(X):
"""Get a random sample from X.
Parameters
----------
X: array-like, shape (n_samples, n_features)
Returns
-------
array-like, shape (1, n_features)
"""
size = len(X)
idx = np.random.choice(range(size))
return X[idx] | e493b68ae5b7263786a1a447a0cff78d1deeba24 | 3,640,684 |
def get_secondary_connections(network, user):
"""
Finds all the secondary connections (i.e. connections of connections)
of a given user.
Arguments:
network: the gamer network data structure.
user: a string containing the name of the user.
Returns:
A list containing the secondary connecti... | 4e53f6e43f2fb132932381370efa4b3a3cd4793c | 3,640,686 |
def get_regression_function(model, model_code):
"""
Method which return prediction function for trained regression model
:param model: trained model object
:return: regression predictor function
"""
return model.predict | fca4a0767b1e741952534baf59ac07cece2c9342 | 3,640,687 |
def beam_motion_banding_filter(img, padding=20):
"""
:param img: numpy.array.
2d projection image or sinogram. The left and right side of the image should be
empty. So that `padding` on the left and right will be used to create an beam motion
banding image and be ... | 5191c1f3022711459ce81cfbf0c4d6c6fb7dcd41 | 3,640,688 |
def log(session):
"""Clear nicos log handler content"""
handler = session.testhandler
handler.clear()
return handler | 086e362c8195b917c826fc8b20d3095210ac82fd | 3,640,689 |
def calculate_dvh(dose_grid, label, bins=1001):
"""Calculates a dose-volume histogram
Args:
dose_grid (SimpleITK.Image): The dose grid.
label (SimpleITK.Image): The (binary) label defining a structure.
bins (int | list | np.ndarray, optional): Passed to np.histogram,
can be ... | 007c7eb9c2ddca9809ac2c86f7bf6d34ed14d41b | 3,640,691 |
def dataframe_with_new_calendar(df: pd.DataFrame, new_calendar: pd.DatetimeIndex):
"""
Returns a new DataFrame where the row data are based on the new calendar (similar to Excel's VLOOKUP with
approximate match)
:param df: DataFrame
:param new_calendar: DatetimeIndex
:return: DataFrame
"""
... | 4f5b39494080f3eae9083c78d6dd1666c1945e35 | 3,640,693 |
def get_language_titles():
""" Extract language and title from input file. """
language_titles = {}
input_file = open("resources/events/%s.tsv" % args.event).readlines()
for line in sorted(input_file):
try:
language, title = line.split('\t')[0], line.split('\t')[1].strip()
except IndexError:
language, t... | dedfa8720194aef1b27c7762041692625c2955e7 | 3,640,694 |
def _find_additional_age_entities(request, responder):
"""
If the user has a query such as 'list all employees under 30', the notion of age is
implicit rather than explicit in the form of an age entity. Hence, this function is
beneficial in capturing the existence such implicit entities.
Returns a ... | 971bc0805c607134b6947e0d61ebab6f217c6961 | 3,640,695 |
def merge_local_and_remote_resources(resources_local, service_sync_type, service_id, session):
"""
Main function to sync resources with remote server.
"""
if not get_last_sync(service_id, session):
return resources_local
remote_resources = _query_remote_resources_in_database(service_id, sess... | 1809caa17c3a8a32a5a3236b313c575ec939c0d8 | 3,640,696 |
def alertmanager():
"""
to test this:
$ curl -H "Content-Type: application/json" -d '[{"labels":{"alertname":"test-alert"}}]' 172.17.0.2:9093/api/v1/alerts
or
$ curl -H "Content-Type: application/json" -d '{"alerts":[{"labels":{"alertname":"test-alert"}}]}' 127.0.0.1:5000/alertmanager
"""
alert_json=request.get_... | 1e204bd6dce8368c3401cb7e13ea062abebafd71 | 3,640,697 |
def RefundablePayrollTaxCredit(was_plus_sey_p, was_plus_sey_s,
RPTC_c, RPTC_rt,
rptc_p, rptc_s, rptc):
"""
Computes refundable payroll tax credit amounts.
"""
rptc_p = min(was_plus_sey_p * RPTC_rt, RPTC_c)
rptc_s = min(was_plus_sey_s * RP... | e282139921045fe8e286abbde6bb4ae44151a50d | 3,640,699 |
def is_stable(A, domain='z'):
"""Determines if a linear state-space model is stable from eigenvalues of `A`
Parameters
----------
A : ndarray(n,n)
state matrix
domain : str, optional {'z', 's'}
'z' for discrete-time, 's' for continuous-time state-space models
returns
------... | 8b073fa021b0f50363d4f5f1a7bf3722a62ae71b | 3,640,700 |
def email_sent_ipn(path: str) -> tuple:
"""
**email_sent_ipn**
Delivered ipn for mailgun
:param path: organization_id
:return: OK, 200
"""
# NOTE: Delivered ipn will end up here
if path == "delivered":
pass
elif path == "clicks":
pass
elif path == "op... | 4bbfed4f86916ddc2b68ade0c8739e25a562bbda | 3,640,701 |
import json
def load_posts_view(request):
"""Load posts view, handles asynchronous queries to retrieve more posts.
"""
if request.method == 'GET':
results, start = get_more_posts(request.GET)
json_result = json.dumps({'posts': results,
'start': start
... | 832f2a04b23eb78ad25ad7db2d3cabfdaa61b075 | 3,640,703 |
def create_dataset(m, timestep, var='all', chunks=(10, 300, 300)):
"""
Create xarray Dataset from binary model data
for one time step. This also incorporates all model
grid information and dimensions, regardless of the variable selected.
Parameters
----------
m : LLCRegion
Model cla... | 02dd6a4e7ff520e5ae65c7a3a9e3bd2b92d58629 | 3,640,704 |
def mummer_cmds_four(path_file_four):
"""Example MUMmer commands (four files)."""
return MUMmerExample(
path_file_four,
[
"nucmer --mum -p nucmer_output/file1_vs_file2 file1.fna file2.fna",
"nucmer --mum -p nucmer_output/file1_vs_file3 file1.fna file3.fna",
"n... | 65262a16f47b952796f79dcb9bba37c5dcbaed0b | 3,640,706 |
def Exponweibull(a=1, c=1, scale=1, shift=0):
"""
Expontiated Weibull distribution.
Args:
a (float, Dist) : First shape parameter
c (float, Dist) : Second shape parameter
scale (float, Dist) : Scaling parameter
shift (float, Dist) : Location parameter
"""
dist = core... | 64871830101df96f8148ef6ee0b8735813793306 | 3,640,707 |
def authed_request_for_id(gplus_id, request):
"""Adds the proper access credentials for the specified user and then makes an HTTP request."""
# Helper method to make retry easier
def make_request(retry=True):
token = get_access_token_for_id(gplus_id)
request.headers['Authorization'] = 'Bear... | f727cc818fd3d5b70fba80b00dfb09cf1f182275 | 3,640,708 |
def _bool_method_SERIES(op, name, str_rep):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
def na_op(x, y):
try:
result = op(x, y)
except TypeError:
if isinstance(y, list):
y = lib.list_to_object_array(y)
... | d6dec673d9a0f8384c3510bdda449f8e4157c96e | 3,640,709 |
def get_playlist_by_id(playlist_id):
""" Returns a playlist by playlist id """
return Playlist.query.filter(Playlist.playlist_id == playlist_id).first() | 28fd295a5d096b1da40391193e6333cc48b14ea2 | 3,640,710 |
def section_cfield(xs, x_a, c_field, rmax = 60e3):
"""
extract a section of a sound speed transcet for use in xmission calculation
"""
x_i = np.bitwise_and(x_a >= xs, x_a <= xs + rmax)
return x_a[x_i], c_field[:, x_i] | c4c213293f7aee7735a9a6209f671aae6d8e3989 | 3,640,711 |
def shared_dropout(shape, use_noise, trng, value):
"""
Shared dropout mask (pervasive dropout)
:param shape:
:param use_noise:
:param trng:
:param value:
:return:
"""
return tensor.switch(use_noise,
trng.binomial(shape, p=value, n=1,
... | 51373285b3c708cedd1ebf2a613237deaa7b6dab | 3,640,712 |
def setup_flow_assembler(gb, method, data_key=None, coupler=None):
"""Setup a standard assembler for the flow problem for a given grid bucket.
The assembler will be set up with primary variable name 'pressure' on the
GridBucket nodes, and mortar_flux for the mortar variables.
Parameters:
gb: G... | 6e1baaf91e06679ef760932f6ae27e0c606e4f21 | 3,640,713 |
def get_article(article_id: str, db: Session = Depends(deps.get_db),
current_user: schemas.UserVerify = Depends(
deps.get_current_user)) -> JSONResponse:
""" Return Single Article"""
data = crud_articles.get_article(article_id=article_id, db=db)
if data is None:
r... | e78af6052b112c5da5811a0c92fe462743bb5c7e | 3,640,714 |
def _get_sp_instance():
"""Create an spotify auth_manager and check whether the current user has
a token (has been authorized already). If the user has a token, then they
are authenticated -- return their spotipy instance. If the user does not have
a token, then they are not authenticated -- raise an ex... | b2117c709169192626efdf2b699a9a1c2c501ecc | 3,640,715 |
def get_func_global(op_type, dtype):
"""Generate function for global address space
Used as `generator(op_type, dtype)`.
"""
op = getattr(dppy.atomic, op_type)
def f(a):
op(a, 0, 1)
return f | 72816c78bc36f7aa630551ae161fa0870acefe36 | 3,640,716 |
def klucb(x, d, div, upperbound, lowerbound=-float("inf"), precision=1e-6):
"""The generic klUCB index computation.
Input args.:
x,
d,
div:
KL divergence to be used.
upperbound,
lowerbound=-float('inf'),
precision=1e-6,
"""
l = max(x, lowerbound)
u = upperbound
while... | 82aa51e248568d201e0d9d5621bf043532df8572 | 3,640,717 |
def convert_pk_to_index(pk_tuples, indices):
"""
For a list of tuples with elements referring to pk's of indices,
convert pks to 0-index values corresponding to order of queryset
:param pk_tuples: list of tuples [(row_pk, col_pk), ... ]
:param indices: list of querysets
:return: list of tuples [... | 81837ded50d4cd086b9330ea5c709fb3bd93ca0f | 3,640,718 |
from typing import Union
def device_path_to_str(path: Union[bytes, str]) -> str:
"""
Converts a device path as returned by the fido2 library to a string.
Typically, the path already is a string. Only on Windows, a bytes object
using an ANSI encoding is used instead. We use the ISO 8859-1 encoding t... | 76d0d3d50e978d998ef68e0c509c3933f94778d9 | 3,640,719 |
def empirical(X):
"""Compute empirical covariance as baseline estimator.
"""
print("Empirical")
cov = np.dot(X.T, X) / n_samples
return cov, np.linalg.inv(cov) | 67c8c1f42590ee6c8d56f5f1e53253c5eff74376 | 3,640,720 |
def emitir_extrato(contas, numero_conta, movimentacoes, data_inicial):
"""
Retorna todas as movimentações de <movimentacoes> feitas pela conta
com o <numero_conta> a partir da <data_inicial>
"""
historico_movimentacoes = []
if numero_conta in contas:
minhas_movimentacoes = movimentac... | 0caa46aaed0ccfa506f8caa9b82625649d116ce1 | 3,640,721 |
def wavelength_to_energy(wavelength):
"""
Converts wavelength (A) to photon energy (keV)
"""
return 12.39842/wavelength | 4e2d11f2de8ed4890df5d885801cd492644817d8 | 3,640,722 |
def calculate_hash_512(filepath, verbose):
"""
SHA512 Hash Digest
"""
if verbose:
print 'Calculating hash...'
sha512_hash = hashlib.sha512()
with open(filepath, 'rb') as f:
statinfo = os.stat(filepath)
block_size = 100 * (2**20) #Magic number: 100 * 1MB blocks
... | 4bf153275d9791112f39d3629e9cc94f54177dc4 | 3,640,723 |
def _crop_after_rotation(im, angle, xres, yres, surroundings):
"""Crop image to the bounding box of bite's surroundings.
Arguments:
im: PIL.Image, rotated map part
angle: by which the map has been rotated, in degrees (counterclockwise)
xres: width of one tile in pixels
yres: height of one tile... | eeeda2c5c8d868e813a67584c72561560409e1b3 | 3,640,724 |
import copy
def get_custom_scorer(metric, gib=True, needs_proba=False, needs_threshold=False):
"""Get a scorer from a str, func or scorer.
Scorers used by ATOM have a name attribute.
Parameters
----------
metric: str, func or scorer
Name, metric or scorer to get ATOM's scorer from.
... | a698798302ec0ed7ad469b76d6893e85e669905e | 3,640,725 |
def julian_day(t='now'):
"""
Wrap a UTC -> JD conversion from astropy.
"""
return Time(parse_time(t)).jd | fa2f0d707798227e8e7f67b21cf2e4dc42308093 | 3,640,726 |
from typing import Counter
def add_stop_words(dataframe: pd.DataFrame,
k_words: int) -> list:
"""
Получить список стоп-слов, которые наиболее часто встречаются в документе
:param dataframe:
:param k_words: кол-во наиболее часто повторяющихся уникальных слов
:return:
"""
... | 3ca7fbe1221b55e2a072d49f01c553af1786ca8f | 3,640,727 |
import torch
def get_batch(data_iterator):
"""Build the batch."""
# Items and their type.
keys = ['text', 'types', 'labels', 'is_random', 'loss_mask', 'padding_mask']
datatype = torch.int64
# Broadcast data.
data = next(data_iterator) if data_iterator is not None else None
data_b = mpu.b... | fad3b181c685e3e57fa185c1eb790517536527ec | 3,640,728 |
def pool(sparkdf, start_column, end_column, var):
"""
Generate pools and calculate maximum var unpooled.
:param sparkdf: Input Spark dataframe.
:param start_column: Start time column name.
:param end_column: End time column name.
:param var: Variable for which to calculate metric.
:return: A... | 913094bebc6f91ad023d83186084d858a7332531 | 3,640,730 |
def jwt_response_payload_handler(token, user=None, request=None):
"""
自定义jwt返回
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'user': UserSerializer(user, context={'request': request}).data
}
:param token:
:param... | 972f4cbd39d9bd049fcd7a99bfc168e6c825572a | 3,640,731 |
import requests
def query_yelp_lookup(biz_id):
""" Lookup resturant using id """
headers = {'Authorization': ('Bearer '
'w5JFtwCUKq05GlSpm8cKo51dBYDQ6r9tyzo-qRsKt4wDyB5'
'_ro6gW5gnG9hS6bvnNHNxOQLHfw7o_9S1e86nkvgcU7DQI_'
'sM6GVt9rqcq_rRYKtagQrexuH0zsU0WXYx')}
ur... | ab2087d42833f0092229870ab3208a24bd041b95 | 3,640,732 |
def dashboard(request, condition='recent'):
"""Dashboard"""
post_count = settings.DASHBOARD_POST_COUNT
comment_count = settings.DASHBOARD_COMMENT_COUNT
if condition == 'recent':
order = '-id'
elif condition == 'view':
order = '-view_count'
elif condition == 'like':
order... | fc5422bf580a4608e921b7d59caf7f0ea58a50fd | 3,640,733 |
def read_manifest(path):
"""Read dictionary of workflows from the Packal manifest.xml file."""
workflows = {}
tree = ET.parse(path)
root = tree.getroot()
for workflow in root:
data = {"packal": True}
for child in workflow:
if child.tag == "short":
data["de... | 8f91126f4a48c0b1af357487ffe791ba790c7745 | 3,640,734 |
def _load_v1_txt(path):
"""Parses a SIF V1 text file, returning numpy arrays.
Args:
path: string containing the path to the ASCII file.
Returns:
A tuple of 4 elements:
constants: A numpy array of shape (element_count). The constant
associated with each SIF element.
centers: A n... | 9f7ea3f0059ef3688cc962e9836a558debebf80f | 3,640,735 |
def split_model_name(model):
"""
Split model names by _
Takes into account packages with _ and processor types with _
"""
model = model[:-3].replace('.', '_')
# sort by key length so that nertagger is checked before tagger, for example
for processor in sorted(ending_to_processor.keys(), key... | 305a70899eb8eb3c5beca4c7e7403010a008a80d | 3,640,736 |
from .divine1983 import JupiterD4Field
from .distributions import DG83Distribution
from .integrate import FormalRTIntegrator
from .synchrotron import NeuroSynchrotronCalculator
def dg83_setup(
ghz = 95,
lat_of_cen = 10,
cml = 20,
n_alpha = 10,
n_E = 10,
E0 = 0.1,
... | 94aea682df900d600e922ff560109255e2b69ac7 | 3,640,737 |
def compute() -> int:
"""
Returns the sum of all numbers whose
sum of the factorials of all digits
add up to the number itself.
>>> compute()
40730
"""
return sum(
num
for num in range(3, 7 * factorial(9) + 1)
if sum_of_digit_factorial(num) == num
) | c2460158eb7d32142b4f59801bdc307a0ba1d4ff | 3,640,738 |
import heapq
def dijkstra(matrix, start=None, end=None):
"""
Implementation of Dijkstra algorithm to find the (s,t)-shortest path between top-left and bottom-right nodes
on a nxn grid graph (with 8-neighbourhood).
NOTE: This is an vertex variant of the problem, i.e. nodes carry weights, not edges.
... | 96338e6c65e1ff88025971361e2b36c0f1efe2af | 3,640,739 |
def is_finally_visible_segm(*args):
"""is_finally_visible_segm(segment_t s) -> bool"""
return _idaapi.is_finally_visible_segm(*args) | 9050bd583208824859e71e84f02169237b3ac9f2 | 3,640,740 |
def get_undisbursed_principal(loan):
"""Gets undisbursed principal"""
principal = frappe.get_value("Microfinance Loan", loan, "loan_principal")
if not principal:
raise frappe.DoesNotExistError("Loan: {} not found".format(loan))
return principal - get_disbursed(loan) | 7829b93eb1e6298e8640290c94b2b2aacb0de8bd | 3,640,742 |
def northing_and_easting(dictionary):
"""
Retrieve and return the northing and easting strings to be used as
dictionary keys
Parameters
----------
dictionary : dict
Returns
-------
northing, easting : tuple
"""
if not 'x' and 'y' in dictionary.keys():
northing = 'l... | 2f41d8b681d27f6ef29265c1945591ea18bba79f | 3,640,743 |
import math
def affine(p, scale, theta, offset):
""" Scale, rotate and translate point """
return arcpy.Point((p.X * math.cos(theta) - p.Y * math.sin(theta)) * scale.X + offset.X,
(p.X * math.sin(theta) + p.Y * math.cos(theta)) * scale.Y + offset.Y) | 2d1cd34ed94ee0c4e7ecbb786510c0165b9fca9d | 3,640,746 |
def GetMarkedPos(slot):
"""
Get marked position
@param slot: slot number: 1..1024 if the specifed value is <= 0
range, IDA will ask the user to select slot.
@return: BADADDR - the slot doesn't contain a marked address
otherwise returns the marked address
"""
curlo... | 2c6fc7bac4a389c0cafd119fbef537e135b7f745 | 3,640,747 |
def elslib_CylinderParameters(*args):
"""
* parametrization P (U, V) = Location + V * ZDirection + Radius * (Cos(U) * XDirection + Sin (U) * YDirection)
:param Pos:
:type Pos: gp_Ax3
:param Radius:
:type Radius: float
:param P:
:type P: gp_Pnt
:param U:
:type U: float &
:param... | 5fa697d09866747be2ef98b1b913b7aeb59fcf79 | 3,640,748 |
def totaled_no_review_url(cc, sql_time_specification): # pragma: no cover
"""Counts the number of commits with no review url in a given timeframe
Args:
cc(cursor)
sql_time_specification(str): a sql command to limit the dates of the
returned results
Return:
count(in... | 027f49b13316ecb36eed3e7dde880848b261e3b4 | 3,640,749 |
import warnings
def is_sat(formula, solver_name=None, logic=None, portfolio=None):
""" Returns whether a formula is satisfiable.
:param formula: The formula to check satisfiability
:type formula: FNode
:param solver_name: Specify the name of the solver to be used
:type solver_name: string
:... | 9121747de68aa531c7c7e9c9f683cd1f1518e54b | 3,640,750 |
import math
def bounds(*tile):
"""Returns the bounding box of a tile
Parameters
----------
tile : Tile or tuple
May be be either an instance of Tile or 3 ints (X, Y, Z).
Returns
-------
LngLatBbox
"""
tile = _parse_tile_arg(*tile)
xtile, ytile, zoom = tile
Z2 = ... | ed2eb5865d21033029ddfcdd133663c9d222687d | 3,640,751 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.