content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import click
from datetime import datetime
import time
def _wait_for_job(T, job, hide_progress=False):
"""
Wait for the compliance job to complete
"""
if (
job is not None
and "status" in job
and (job["status"] == "failed" or job["status"] == "expired")
):
click.ec... | 626bc582427f1e5621c5059f72dd07f937d67ad8 | 3,613,928 |
def adjust_learning_rate(lr, gamma, epoch, step_index, iteration, epoch_size):
"""Sets the learning rate
# Adapted from PyTorch Imagenet example:
# https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
if epoch < 6:
lr = 1e-6 + (lr - 1e-6) * iteration / (epoch_size * 5)
el... | 0d691893b0ebb234507940df5bc340b4855fcdd6 | 3,613,929 |
def assign_material(obj, materialname):
"""This function assigns a material to an objects mesh.
:param obj: The object to assign the material to.
:type obj: bpy.types.Object
:param materialname: The materials name.
:type materialname: str
"""
if materialname not in bpy.data.materials:
... | cd937cb0df8eaf9ed17034191acbd400a0993908 | 3,613,930 |
def make_fcc(nx=1, ny=1, nz=1, scale=1.0, noise=0.0):
"""Make a FCC crystal for testing
Args:
nx: Number of repeats in the x direction, default is 1
ny: Number of repeats in the y direction, default is 1
nz: Number of repeats in the z direction, default is 1
scale: Amount to sca... | bfd18b0858657877165995cc50d5f8cae382501d | 3,613,931 |
import pickle
def load_pickle(pickle_path: str) -> object:
"""Avoid boilerplate pickle loading.
Args:
pickle_path (str): Path of pickle file
Returns:
object: Python object unpickled
"""
assert_file_exists(pickle_path)
with open(pickle_path, "rb") as pf:
return pickle... | 81615e6671a660fc61a1192525ea02abdb5079fc | 3,613,933 |
def add_to_list(str_to_add, groups):
"""
This will add a string to the groups array if it does not exist.
It will then return the index of the string within the Array
"""
if str_to_add.replace(".", REPLACE_CHAR) not in groups:
groups.append(str_to_add.replace(".", REPLACE_CHAR))
return g... | cbd1598ad0eb4d7691f57c4df5436ad4a4df69eb | 3,613,934 |
def get_centroid(coords):
"""
Function: get centroids of given coordinates.
Input:
- coords: numpy array. mx2xn. m = number of centroids; n = number of points per centroid.
Output:
- new_coords: numpy array (mx2). centroids.
"""
new_coords = np.zeros((coords.shape[0], coords.shape[1]))
for i in range(coords.sh... | 484ad4ebbf4bbc9517ce28a98e06d95acc02e3f0 | 3,613,936 |
from typing import List
def towers_of_hanoi(n: int) -> List[Move]:
"""This is a classic CS problem that's often used as an introduction to
recursion.
"""
return towers_helper(n, 1, 3, 2) | 1fe931fdf74cecc3784b71f66e43caa5d89e98c3 | 3,613,937 |
def update_Sx(S_old, n_old, d_old, d_new, d_min):
"""
Update on the sum of log degrees S_d and n based on degree distribution resulting from inserting or deleting
a single edge.
Parameters
----------
S_old: float
Sum of log degrees in the distribution that are larger than or equal to d... | 4803aa41cd9b807212ba0c90bde618b97f2b0b1b | 3,613,938 |
import typing
def cumprod(mod: int, a: typing.List[int]) -> typing.List[int]:
"""Compute cummulative product over Modular."""
a = a.copy()
for i in range(len(a) - 1):
a[i + 1] = a[i + 1] * a[i] % mod
return a | 62a99a916c5e09187f05b9a31096037b3c53eb85 | 3,613,939 |
def is_skin_cluster(skin_cluster):
"""
Checks if the given node is a valid skinCluster
:param skin_cluster: str, name of the node to be checked
:return: bool, True if the given node is a skin cluster node
"""
if not maya.cmds.objExists(skin_cluster):
logger.error('SkinCluster "{}" does... | 429533a6b0cfa909ad2851b28046812d9fd61a80 | 3,613,940 |
def opp_move(player: Player) -> (bool, bool):
"""
Utility function to simulate opponent's moves on your board.
:param player: Player object
:return: (Bool, Bool) : change_turn and game_on booleans indicating whether to
reverse the turn and whether the game is not over.
""... | af18374964c67bec407a7c03fe4c65ca9b604250 | 3,613,941 |
def get_v50(line,epoch,velocity,evelocity):
"""
Eg:
In [1]: from epm.velocity import get_v50,vHbetatovFeII,vph50tovFe
In [2]: v50_hbeta,ev50_hbeta=get_v50("Hbeta",18.,10350,500)
In [3]: vFeII50,evFeII50=vHbetatovFeII(v50_hbeta,ev50_hbeta)
In [4]: vFeII50,evFeII50
Out[4]: (4853.111318324523,... | 71dfd8f29063b2d695a82b53b53c0e7230bd2b2b | 3,613,942 |
def is_retfp(*args):
"""
is_retfp(ea) -> bool
"""
return _ida_nalt.is_retfp(*args) | e6958d9ccdff4b8ad11d78d6c635388a059a430e | 3,613,943 |
def outbound():
"""Returns a function that generates a matrix out of bounds a given
range"""
def _outbound(low, high, size, tol=1000, nums=100):
"""Generates a matrix that is out of bounds"""
low_end = -np.random.uniform(tol, low, (nums,))
high_end = np.random.uniform(tol, high, (nu... | f291d38fa4151f54d9cb97819b648a5989488b41 | 3,613,944 |
def trans_in_lang(string, lang):
"""
Translate a string into a specific language (which can be different
than the set language).
Usage:
{{ var|trans_in_lang:"fr" }}
"""
if check_for_language(lang):
return translation(lang).ugettext(string)
return string | 97428deac0f1aa78cc0c9bbff3556d2a0355cf9d | 3,613,945 |
from typing import Union
from typing import Optional
from typing import Tuple
async def async_set_config_parameter(
node: Node,
new_value: Union[int, str],
property_or_property_name: Union[int, str],
property_key: Optional[Union[int, str]] = None,
) -> Tuple[ConfigurationValue, CommandStatus]:
"""... | 24ec40965cdb6a54518945a3fe4323ff6e408cbf | 3,613,946 |
from operator import matmul
from operator import concat
def black_out(x, t, W, samples, reduce='mean'):
"""BlackOut loss function.
BlackOut loss function is defined as
.. math::
-\\log(p(t)) - \\sum_{s \\in S} \\log(1 - p(s)),
where :math:`t` is the correct label, :math:`S` is a set of negat... | c352426a648ecea86c3254718bf5c8f1d8b2f43f | 3,613,947 |
def has_instance(cls, typeclass):
"""Test whether a class is a member of a particular type-class.
:param cls: The class or type to test for membership.
:param typeclass: The typeclass to check. Must be a subclass of
`Typeclass`:class:.
:returns: True if cls is a member of typeclass, and F... | 548264ca54407b8451f55553eab020148f33343e | 3,613,948 |
def two_fermion(emat, lb, rb):
"""
Build matrix form of a two-fermionic operator in the given Fock basis,
.. math::
<F_{l}|\sum_{ij}E_{ij}\hat{f}_{i}^{\dagger}\hat{f}_{j}|F_{r}>
Parameters
----------
emat : 2d complex array
The impurity matrix.
lb : list or array
... | 5ee4a625b92ef0d894a2db095042bdc080b99cda | 3,613,949 |
def leakyRelu(X):
"""
Apply Leaky Rectified Linear Unit on X Vector.
PARAMETERS
==========
X: ndarray(dtype=float, ndim=1)
Array containing Input Values.
RETURNS
=======
ndarray(dtype=float,ndim=1)
Output Vector after Vectorised Operation.
"""
return np.maximu... | 2ce205eb4df832106ab8460a8b59a2cd1f8e73b1 | 3,613,950 |
def box_read(path_out, sim_id):
"""Read in ChemEvol instance from box<sim_id>.pck file.
Args:
path_out (str): directory of pickle file.
sim_id (str): simulation ID number.
Returns:
object: instance of ChemEvol class ('box' object).
"""
fname = _make_sim_path(path_out, sim_i... | fc89b4c43aff8a90d071e75a47c7128668362ae5 | 3,613,951 |
def second(str_number):
"""
:param str_number: str
:return int
"""
list_number = list(str_number)
total = list_number.__len__()
half = total/2
result = 0
for key, x in enumerate(list_number):
index_y = int((key + half) % total)
if x == list_number[index_y]:
... | 92ffd31c72f4c0f5bc09c244b2e03acaea2d45e3 | 3,613,952 |
def get_active_psupport():
""" Returns all active prod support tests """
results = []
experiences = get_experiences()
for exp in experiences:
if len(exp["splits"]) == 1:
exp_name = exp["experience_name"]
external_link = create_external_link(exp_name, exp["id"])
... | 4cdc41a325908f8f9f976f73a58e59a46c9c0fc8 | 3,613,953 |
import ipaddress
def is_valid_ipv4(address):
"""Check an IPv4 address for validity"""
try:
ip = ipaddress.ip_address(address)
except ValueError:
return False
if not isinstance(ip, ipaddress.IPv4Address):
return False
warning = None
if ip.is_loopback:
warning = "... | fd095d8903cd0a44bfd6a7eb02fa95217a60077a | 3,613,954 |
def two_pts_to_line(pt1, pt2):
"""
Create a line from two points in form of
a1(x) + a2(y) = b
"""
pt1 = [float(p) for p in pt1]
pt2 = [float(p) for p in pt2]
try:
slp = (pt2[1] - pt1[1]) / (pt2[0] - pt1[0])
except ZeroDivisionError:
slp = 1e5 * (pt2[1] - pt1[1])
a1 =... | d607008c41eaa052c0988a7ac66588b464aab8e0 | 3,613,955 |
def unstandardize_set(var_list, sample_array):
"""
Inputs: var_list- list of variables
sample_array- array with one sample corresponding to each variable
Takes an array of standardized values, unstandardizes them, and returns the
array of unstandardized values.
"""
var_count, i... | 3378609a7451819a998531be8da5d5fa6d1a9bab | 3,613,956 |
import json
def get_policy(request, log, tenantId, groupId, policyId):
"""
Get a scaling policy which describes an id, name, type, adjustment, and
cooldown, and links. This data is returned in the body of the response in
JSON format.
Example response::
{
"policy": {
... | f275a751026bbca5b6b12650aa0b686a372839f5 | 3,613,957 |
def loss(*, target_sfs, events, n, key, nreps=20):
"""
Mean squared error between ``target_sfs`` and simulated sfs
when simulating with the given ``events``, averaged over ``nreps``
replicate simulations.
"""
avg_sfs = jnp.zeros(n + 1)
for key in jax.random.split(key, nreps):
pi, tau... | 46ec73c249fb1271e63231e81ea744b466fdf7ab | 3,613,958 |
from typing import Callable
def profile(func: Callable) -> Callable:
"""
A decorator that uses cProfile.Profile class to profile a function.
:param func: function
:return: function
"""
def inner(*args, **kwargs):
pr = Profile()
pr.enable()
result = func(*args, **kwargs... | b3c3cdce4aa1650a803039facc6e8a8468a0abec | 3,613,959 |
import numpy as np
def yield_function(E,species='W'):
"""
use: Y = yield_function(E,species='W')
This method implements the modified Bohdansky formula for physical sputtering
with incidence angle 0. See for example
Y. Marandet et. al. PPCF 58 (2016) 114001
input:
E: Energy of incoming... | 71c562fa24960838ae58c9d7ed6ba37c3744e13c | 3,613,960 |
from datetime import date
def get_current_day():
"""
return the current day number value from (1-7).
"""
return date.today().isocalendar()[2] | 52558cf9c1cab283abe496845ce778eac4802980 | 3,613,961 |
def _load_with_pydub(file, audio_format=None):
"""
Open compressed audio or video file using pydub. If a video file
is passed, its audio track(s) are extracted and loaded.
Parameters
----------
file : str
path to audio file.
audio_format : str, default: None
string, audio/vi... | 8d06a6b743f0c4ef03e0b9ceecc9afb55d57f49e | 3,613,962 |
import re
def findpath(name):
"""Resolves absolute path of module"""
path = import_module(name).__file__
# adjust file extension
path = re.sub('.pyc$', '.py', path)
# strip trailing "__init__.py"
path = re.sub('__init__.py$', '', path)
return path | 4864eaa2a85d8faf10c56a2a32bd48b4dc015fb3 | 3,613,963 |
def sets_k_fold_pattern(rdms, pattern_descriptor='index', k=5, random=False):
""" generates training and test set combinations by splitting into k
similar sized groups. This version splits in the given order or
randomizes the order. For k=1 training and test_set are whole dataset,
i.e. no crossvalidatio... | ec95136844cfd9ebf5e7b8217621e46436b08db9 | 3,613,964 |
import json
def lambda_handler(event, context):
"""This is a sample Annotation Consolidation Lambda for custom labeling jobs. It takes all worker responses for the
item to be labeled, and output a consolidated annotation.
Parameters
----------
event: dict, required
Content of an example ... | 1c2e3a2bc5f70e22be5768dbcbce2db56166a19b | 3,613,965 |
from typing import Iterable
def convert_dtypes(df: DataFrame, keys: Iterable[str]) -> DataFrame:
"""
Wrapper around df.astype(), cast DataFrame columns to the appropriate type for each key.
Use mapping from TX_KEY_DTYPES global.
"""
return df.astype({key: TX_KEY_DTYPES[key] for key in keys}, copy=... | 77e8d5ad98932d72c06ba3c06ccdd4ad885f6586 | 3,613,966 |
from qcodes.dataset.data_set import load_by_id
def diff_param_values_by_id(left_id: RunId, right_id: RunId) -> ParameterDiff:
"""
Given the IDs of two datasets, returns the differences between
parameter values in each of their snapshots.
"""
# Local import to reduce load time and
# avoid circu... | 1fa84900b59ab2003a096b071e9c5893593f9b00 | 3,613,967 |
def get_band_num(color, satellite):
"""Get the image band # from the color and satellite
Parameters
----------
color: string
color band name i.e. red, green, nir1
satellite: string
code for satellite (supports quickbird, geoeye 1 and worldview 2/3)
Returns
-------
int
... | e23fafccccf99d2cf5dee12295e233aa1ab614fd | 3,613,969 |
def ResNet50(parameters, num_channel=3, num_classes=10, att=False, mean=False):
"""
Function that creates a ResNet 50 model
:param parameters (list or tuple): List of parameters for the model
:param num_channel (int): Number of channels in input specimens
:param num_classes (int): Number of classes... | 54c509970d500984bda98c4c3aabf005a0e50f79 | 3,613,970 |
from typing import List
def read_file_list(path: str) -> List[str]:
"""读取文件列表(包含\\n字符)"""
with open(path, 'r', encoding='utf-8') as f:
content = f.readlines() # 包含\n字符
return content | 5dbb082f9d228cd2ef227d51603a232508ee74dd | 3,613,971 |
import torch
def letterbox_resize_tensor(src, dst_h, dst_w):
# https://stackoverflow.com/a/66539730
# It seems GPU is not helpful in this case
"""Resize with same aspect ratio as source image.
Args:
src: `torch.tensor`, source image which has a size of (N, C, H, W).
dst_h: `int`, heig... | f615c22cbbab4735f390e5469932e11da71e5094 | 3,613,972 |
def get_target(words, idx, window_size=5):
"""
Get a list of words in a window around an index
Input:
* words: the dictionary of words
* idx: the index for the word of interest
* window_size: (Optional) the number of words to include
Output:
* returns the words of interest that fall into the window
""... | 01d0e052bd6adfb1a8f32a3104c801ee68211801 | 3,613,973 |
def define_inputs():
"""
In this function, the user must define all the inputs that are required to run a simulation.
Returns:
"""
# Define the required inputs.
req_inputs = {'B': 0.0467,
'Lambda': 1.,
'E0': 0.99,
'C_R': 1e3,
... | 04db80abb9751d0b39dbdd053220295c18398c79 | 3,613,974 |
import six
def FSeek(params, ctxt, scope, stream, coord):
"""Returns 0 if successful or -1 if the address is out of range
"""
if len(params) != 1:
raise errors.InvalidArguments(
coord,
"{} args".format(len(params)),
"FSeek accepts only one argument",
)
... | 2b3aec837ed2436c911b100aea9af76863d6f9a7 | 3,613,975 |
def processFocusNVDAEvent(obj,force=False):
"""Processes a focus NVDA event.
If the focus event is valid, it is queued.
@param obj: the NVDAObject the focus event is for
@type obj: L{NVDAObjects.NVDAObject}
@param force: If True, the shouldAllowIAccessibleFocusEvent property of the object is ignored.
@type force:... | d4fdd05bdaa0d73955e35d99b41bc0db79537e9d | 3,613,976 |
def filter_results(TAP_df, print_targets=True):
"""
Add a few new useful columns to the pandas.DataFrame with the query results from the PyVO TAP service and
return the full query DataFrame and optionally a summary of the results.
Parameters
----------
TAP_df : pandas.DataFrame
This is... | 9b2fb713e0b01c0cc08a5e883fe18446f065a71e | 3,613,977 |
def node_list(request):
"""Retrieve a list of nodes.
:param request: HTTP request.
:return: A list of nodes.
http://docs.openstack.org/developer/python-ironicclient/api/ironicclient.v1.node.html#ironicclient.v1.node.NodeManager.list
"""
node_manager = ironicclient(request).node
return node... | 7e24434304c92a498ae62b6baa2bf6fda6baf365 | 3,613,978 |
import torch
def random_input(in_features: int) -> ByteTensor:
"""Return a random bit tensor of length 'in_features.'"""
state = np.random.randint(0, 2, (in_features, )).astype(np.int32)
return torch.from_numpy(state).byte() | 7a371db6628c1a178a1f0749857bdd9ed9d78546 | 3,613,979 |
def semi_split(s):
""" Split 's' on semicolons.
"""
return map(lambda x: x.strip(), s.split(';')) | f81eff42e170c7b760a75d86d5d0d9326365ca8e | 3,613,980 |
from typing import Optional
def get_implementation() -> Optional[PythonImplementation]:
"""Determine the current Python implementation.
:return: The appropriate :class:`~PythonImplementation` instance if found
:rtype: Optional[PythonImplementation]
"""
try:
return PythonImplementation(py... | 7b7298f3c8fd7f27585c42f5f4ef1db60af44ee7 | 3,613,981 |
def sample_passwds():
"""Pre-generates password hashes for `sample_users`. This drastically speeds up any tests
relying on sample users, as bcrypt is intentionally very slow."""
pwds = dict(
admin='a',
mod='b',
arch='c',
user='d',
)
for k, pwd in pwds.items():
... | 39f42be8b4a3a58de9410490cea81e4a3a2dc4ec | 3,613,982 |
def well_formed(expr):
"""Check that each Var is only bound once (well formed).
Parameters
----------
expr : tvm.relay.Expr
The input expression
Returns
-------
well_form : bool
Whether the input expression is well formed
"""
return _ffi_api.well_formed(expr) | c826792e6477f62dfa8cea0200c7b758424dfee9 | 3,613,983 |
def call_function(ctx,
node,
func_var,
args,
fallback_to_unsolvable=True,
allow_noreturn=False):
"""Call a function.
Args:
ctx: The abstract context.
node: The current CFG node.
func_var: A variable of the possibl... | da7f614bd70bb6695f7d8f0f94a25db05c9d28e0 | 3,613,984 |
def login():
"""Log user in."""
# forget any user_id
session.clear()
# if user reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# ensure username was submitted
if not request.form.get("username"):
return apology("Must provide usern... | 5d6fa63efaf3ef14529328b5a3fd47d94f940b53 | 3,613,985 |
from operator import inv
def _system_mat3d(fmatin, cmat, fmatout):
"""Computes a system matrix from a characteristic matrix Fin-1.C.Fout"""
fmatini = inv(fmatin)
out = bdotdm(fmatini,cmat)
return bdotmd(out,fmatout) | 0e792ddc6b5dc636bc51ad0fe25696bd6ce990f1 | 3,613,986 |
def grad(phit):
"""Returns the spatial derivatives of a Fourier transformed variable.
Returns (∂/∂x[F[φ]], ∂/∂y[F[φ]]) i.e. (ik F[φ], il F[φ])"""
global ik, il
phixt = ik*phit # d/dx F[φ] = ik F[φ]
phiyt = il*phit # d/dy F[φ] = il F[φ]
return (phixt, phiyt) | d70f93018fbf630dd9380ef31cf70788c309e9dc | 3,613,987 |
import csv
import numpy as np
import logging
def csv_reader(data_file):
"""returns np.array(time), np.array(voltage)
This function reads in csv files.
The for loop reads each row of the time and voltage lists and
converts them from strings to floats. If a string can't be
converted, a ValueError ... | 93540368516ba13e1a7c7e9deee1d068218dcb3a | 3,613,988 |
def KS_bucket(score, target, bucket = 10, method = 'quantile', **kwargs):
"""calculate ks value by bucket
Args:
score (array-like): list of score or probability that the model predict
target (array-like): list of real target
bucket (int): n groups that will bin into
method (str)... | b3d0312055c7b7b49a1fbd11b0eaa76ae85bd0b4 | 3,613,989 |
def create_input_data():
"""Utility function for creating input data."""
position = Coordinate2d(3.0, 4.0)
speed = Coordinate2d(2.0, 5.0)
sample_time = 0.1
return {'position': position,
'speed': speed,
'sample_time': sample_time} | aad272f153662949b81f328dab0e3f962a65f08a | 3,613,990 |
def get_metadata(**kwargs):
"""
Metadata
Account metadata
Reference: https://iexcloud.io/docs/api/#metadata
Data Weighting: ``Free``
"""
return Metadata(**kwargs).fetch() | 94b33368170b7dc2b47e68a97169d2c02646016f | 3,613,991 |
from scipy.misc import comb
def polyConvMatrix(n, trans=(0, 1)):
"""
Return the upper triangular matrix (i,k) * b**k * a**(i-k), that
converts polynomial coeffs for x~:=a+b*x (P~ = a0~ + a1~*x~ +
a2~*x~**2 + ...) in polynomial coeffs for x (P = a0 + a1*x +
a2*x**2 + ...). Therefore, (a,b)=(0,1) gi... | 27bd03dc47af7f947d273f3d6d26a32d2b5c239c | 3,613,992 |
from typing import cast
import pandas
def get_user_activity(session):
"""Create a plot showing the inline usage statistics."""
def running_window(session, subquery):
# Create a running window which sums all users up to this point for the current millennium ;P
users = (
session.que... | 862dca86cdefe0ff512fe905de4e36568ed54c87 | 3,613,993 |
def get_log_from_policy(policy: Policy, policy_id: PolicyID) -> dict:
"""
Gets the to_log var from a policy and rename its keys,
adding the policy_id as a suffix.
"""
to_log = {}
if hasattr(policy, "to_log"):
for k, v in policy.to_log.items():
to_log[f"{k}/{policy_id}"] = v
... | 056ea2e519e1160cf828c19625ca7e869e4da51a | 3,613,995 |
def show_ridge_plot(df: pd.DataFrame, name="naked") -> sns.FacetGrid:
"""Shows the distribution of the data for different categories.
Using the output from `generate_df_for_theo_correlation_comparison`
we group the data per quantile and display it in several different
distribution plots.
Taken alm... | 4796ac0b49b43da0aeadd39e2f990f7406b52f78 | 3,613,996 |
def f2n( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uin... | ccf3b16e27e52de21b8ef39e4dad09b2c9296d37 | 3,613,997 |
def windows_details(request):
"""Get available connection details for windows hosts"""
return connection_details_for(request.param) | dda2a5b0c9ea2257bc798cf31962aa5bfded0402 | 3,613,998 |
def exclude_jobs(jobs, project, tag) -> list:
"""Returns list of jobs filtered by exclude map variables.
Args:
jobs: List of jobs
project: A project name string
tag: A tag string
Returns:
List of of jobs after being filtered with the exclude maps
"""
included_jobs =... | 6905430b83f61721208c0dbd855c845736b264a6 | 3,613,999 |
def getImage(matrix):
"""
Convert the 3d numpy array back into an image.
"""
return Image.fromarray(np.uint8(matrix)).convert('RGB') | d57a7f07d468d49d41bf40db7d066a78625e1671 | 3,614,000 |
def _get_additional_sign_content_plan(device_type):
"""
Get AdditionalSignContentPlan instance and set its related models
interfering device_types to universal one.
"""
universal_device_type = get_traffic_control_device_type(
code="123", target_model=None
)
obj = get_additional_sign_... | 3465dd44c11222034ca6f59be2081117f1a4e3b1 | 3,614,001 |
def get_org_link_by_short_link(session, short_link):
"""
Get origin link from short link
:param session: this param is session to connect to database
:param short_link: Short link
"""
origin_link = session.query(models.Url).filter(models.Url.short_link ==
... | 51fc6d0e49e5fe169b571d29207ad0e67a4b8f48 | 3,614,002 |
def _design(n, p, rho, equicorrelated):
"""
Create an equicorrelated or AR(1) design.
"""
if equicorrelated:
X = (np.sqrt(1 - rho) * np.random.standard_normal((n, p)) +
np.sqrt(rho) * np.random.standard_normal(n)[:, None])
def equi(rho, p):
if ('equi', p, rho) no... | 166dbfe8e4dc5c4fc18af5475dd5e5df151b5c08 | 3,614,003 |
def unidades_medida():
"""
Muestra las configuraciones para las unidades de medida
"""
grid = webgrid.WebGrid(crud)
grid.datasource = db(db.unidades_medida).select()
grid.pagesize = 20
#grid.fields = ['db.catmod.id', 'db.catmod.nombre', 'db.catmod.posicion']
#grid.filters = ['db.catmod.c... | 42a9a2c3be35228edba97473c204a689e562c4ac | 3,614,004 |
def unpack_shard(shard):
"""Unpack what pack_shard() did."""
replica = (shard & SHARD_REPLICA_MASK) >> SHARD_REPLICA_SHIFT
writer = (shard & SHARD_WRITER_MASK)
return (replica, writer) | bf07c091794f638c222cae98e7c16ff73edd3188 | 3,614,005 |
import ast
def set_if_chain(tree: ast.AST) -> ast.AST:
"""
Used to create ``if`` chains.
We have a problem, because we cannot tell which situation is happening:
.. code:: python
if some_value:
if other_value:
...
.. code:: python
if some_value:
... | 6508c1fb12f9c63a0995f3084751e31e50f46055 | 3,614,006 |
def poly(n, force_zero=None, **kwargs):
"""Returns a fit function that is a polynomial of degree n
y(x) = a0 + a1 * x + a2 * x^2 + ... + an * x^n
"""
if force_zero is None and len(kwargs) == 0:
# noinspection PyUnusedLocal
def pf(x, params, const_list, const_dict):
return... | 7712c0b07d6026ee9be130eae4881d1d1698ec91 | 3,614,007 |
def symptom_unreasonable_max_token_size():
"""`keystone.conf [DEFAULT] max_token_size` should be adjusted.
This option is intended to protect keystone from unreasonably sized tokens,
where "reasonable" is mostly dependent on the `keystone.conf [token]
provider` that you're using. If you're using one of... | ebbffa326de5d4f8073c12268d075d6dc4b4a58e | 3,614,008 |
def delete_channel(_, slug):
"""Unsubscribe from a channel"""
if models.YoutubeChannel.objects.filter(slug=slug).exists():
channel = models.YoutubeChannel.objects.get(slug=slug)
channel.delete()
return redirect("notifpy:home") | bd099f4ccd313d3337eb308aa9a4a513c4872597 | 3,614,009 |
def MakePDBAtomRecord(pdbmol,i):
""" Make string for PDB 'ATOM' record.
:param lst pdbmol: pdbmol data
:param int i: i-th atom
:return: string(str) - PDB 'ATOM' record
"""
blk=' '; fi4='%4d'; fi3='%3d'; fi2='%2d'; fi5='%5d'; ff8='%8.3f'; ff6='%6.2f'
s=blk*80; ires=0
seqnmb=i+1
... | 43907029e99a1612d587bb9dabe764b86c5faf06 | 3,614,011 |
def sliding_window(sequence, window_size, step_size):
"""Converts a sequence into sliding windows. Returns a list of sequences.
- sequence: a string containing only nucleotides.
- window_size: Windows of equal size sequence. Default is 500 bp.
- step_size: overlap required for sliding windows. Default is... | 3af3e5a0fb204fe019971494a8f89272fd5026d3 | 3,614,012 |
def api_contests_join():
"""
Join/Leave a contest, GET all contests a user is in
"""
if request.method == 'GET':
user = get_queryparam('user')
returnJSON = models.select_joined_contest(
params=('*'),
conditions=('{}=\"{}\"'.format(
settings.DB_... | cd5e745aa5a092dd443e5db62430430ff4b11db1 | 3,614,014 |
import math
def feat_numc_window(cmap, winsize=3, score_threshold=0.2):
""" Get distribution over number of contacts in certain window,
where the window is a 2d field around each contacts.
The distribution is represented as an array of counts for each
number of contacts with in the window (i.e. lengt... | ca52d8df9133dd60efdc955477467c0332e88433 | 3,614,015 |
def expand_item(range_list, onepass=False):
""" Expand a list of plugin:parameters into a list of hosts """
if isinstance(range_list, str):
range_list = [range_list]
# Iterate through our list
newlist = []
found_plugin = False
for item in range_list:
# Is the item a plugin
... | 1df5d27208446b1184adcb12fa9d75459240e108 | 3,614,016 |
def load_csv(filename, sep=None, header=None):
"""Opens and parses provided csv file returning the data and info for all regions
as a list of Region objects. Since no experimental information is provided in the free-form text file,
The experimental properties are set to physically miningless defaults.
T... | 421f3b283caf8c4914dfbb85d75d2480b79da142 | 3,614,017 |
def print_devices(detail_level=0):
"""
Print all platforms and device available, optionall with detailed
device information.
Parameters
----------
details : int
If >0, the function also prints device properties. Higher
levels correspond to more (and less important) detail.
... | 02cbda028126de5f3a358958d96e77dbe6fe1b4e | 3,614,018 |
def create_2dlist():
"""
create 2d list used for gamefield
"""
return [[0 for _ in range(config.NR_COLS)] for _ in range(config.NR_ROWS)] | f5c04c76505594f1942b2477bb9c46aeab1dbe34 | 3,614,019 |
def Huge():
"""
Return the largest positive integer that can be stored (before a long integer
is needed)
"""
if not hasattr(Huge, "_huge"):
# If we haven't yet calculated Huge, calculate it
Huge._huge = 1
while True:
newHuge = Huge._huge * 2
if isinstance(newHuge, int):
Huge... | 5176692c7315063d9c4741709313617e6d05de10 | 3,614,020 |
import curses
def get_next_player_move(state, gui):
"""Uses input to get the next move by a human"""
def is_valid_move(state, x):
if x == '':
return False, '\n'
s = x.split(',')
if len(s) != state.ndim:
return False, 'Not the correct number of dimensions.\n'
... | 4cbcbceeb58d94f84445402505d0b945e9000e1a | 3,614,021 |
import asyncio
import aiohttp
import math
async def dyno_usage(dyno):
"""
Get your account Dyno Usage
"""
await dyno.edit("```Checking dynos ✨```")
await asyncio.sleep(1)
useragent = (
'Mozilla/5.0 (Linux; Android 10; SM-G975F) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
... | 68143df7d3b2c50b75196ad17a01a59276c4d85e | 3,614,022 |
def unravel_trimat( raveled, unravelIndices, shape=None ):
"""
Undo's a
Note: if shape = None, M,N are taken to be the maximum values in the matrix, so if there's zero columns
on the right, or zero rows on the bottom, they will be cropped in the returned triangular matrix.
"""
if shape ==... | ab43cb73557f9a69f3266ca730fe88fa66123912 | 3,614,024 |
def index_snps(snpeff_file):
"""indexes the snps"""
success, errors = helpers.bulk(es,_get_snps_document(snpeff_file), stats_only=True, chunk_size=10000)
return success, errors | b02e0812068eefec30c52a6795fad75282c31f1b | 3,614,025 |
def raster_path_shape(raster_path):
"""Return the number of rows and columns in a raster
Args:
raster_path (str): file path of the raster
Returns:
tuple of raster rows and columns
"""
raster_ds = gdal.Open(raster_path, 0)
raster_shape = raster_ds_shape(raster_ds)
raster_ds... | 4730bf5bdb8dc3b31dbba6c9d521334970eec845 | 3,614,026 |
def mongo_to_dict(obj, exclude_fields=list()):
"""
Convert Document of MongoEngine's instance to dictionary type
:param obj: Document of MongoEngine
:param exclude_fields: field names for exclude
"""
exclude_fields.append('_cls')
return_data = {}
if obj is None:
return None
... | e465e8ea7d7af142e88a4032a5ae4c0499bb9a04 | 3,614,027 |
def reconstruct_path(goal, branch, waypoint_fn):
"""
Reconstruct a path from the goal state and branch information
"""
current_node = goal
path = [current_node]
while current_node is not None:
previous_node = branch[waypoint_fn(current_node)]
path.append(previous_node)
cu... | cdc99ebaa5b987785e86a8b277c25638af1a3e71 | 3,614,028 |
def pt_acfg(**kwargs):
""" Architecture Config (PyTorch model origin) """
bn_cfg = kwargs.pop('bn_cfg', None) or get_bn_args_pt()
return {'pad_type': 'LIKE', 'bn_cfg': bn_cfg, **kwargs} | e50f25080ba19ec935850e8668e96836f08b957c | 3,614,029 |
def prw(value):
"""Writer share, PR"""
return calculate_value(value, PRW_SHARE) | 028b8af0c5a3cd4af61056bc19d60efd92040f00 | 3,614,031 |
def get_vehicle_marker(object, header, marker_id=0, is_player=False):
"""
Return a marker msg
:param object: carla agent object (pb2 object (vehicle, pedestrian or traffic light))
:param header: ros header (stamp/frame_id)
:param marker_id: a marker id (int32)
:param is_player: True if player e... | 9069609296d70b468754a44d37828de34308604e | 3,614,032 |
def default_ssl_cacerts():
"""Path to default Certificate Authority certificates"""
return SSL_CACERTS.get() | ecc2662c9bbd2fe58995ae652f266580af902cf8 | 3,614,033 |
def vectornormalization(surface, inputarray, outputarray, iscelldata=False):
"""Add data array with the normalization of a vector field."""
calc = vtk.vtkArrayCalculator()
calc.SetInput(surface)
if iscelldata:
calc.SetAttributeModeToUseCellData()
calc.AddVectorArrayName(inputarray, 0, 1, 2)
... | 048b2c0ae94d65e3b5a7c6a1d665a9e6b1e3de27 | 3,614,034 |
def format_df(df, mhe):
"""Make a weak labels dataframe from strongly labeled (join labels)
Args:
df: pd.DataFrame, the dataframe strongly labeled with onset and offset columns (+ event_label)
mhe: ManyHotEncoder object, the many hot encoder object that can encode the weak labels
Returns:
... | 513f1055aef6dfb0d1382ca4a5f5c990f5567b49 | 3,614,035 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.