content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def light_probe_sampling_variance_minimization_Viriyothai2009(
light_probe, lights_count=16, colourspace=RGB_COLOURSPACES['sRGB']):
"""
Sample given light probe to find lights using *Viriyothai (2009)* variance
minimization light probe sampling algorithm.
Parameters
----------
light_pro... | c74fd4ad700d9abef2d8f48f0eab78e644ed0296 | 42,475 |
def view_diff(request, uid):
"""
View most recent diff to a post.
"""
# View most recent diff made to a post
post = Post.objects.filter(uid=uid).first()
diffs = Diff.objects.filter(post=post).order_by('-pk')
# Post has no recorded changes,
if not diffs.exists():
return ajax_su... | b506adcee3ca709d8967e5848069fff89cc1c7fc | 42,476 |
def str2bool(val):
"""Convert string to boolean value
"""
try:
if val.lower() in ['false', 'off', '0']:
return False
else:
return True
except AttributeError:
raise TypeError('value {0} was not a string'.format(type(val))) | 01d97b141686a79d310ab59a4acb318250b0746b | 42,477 |
import torch
def make_gaussian_filter_tensor(single_filter, angles, device='cuda'):
"""
Generates 3D tensor of size (M, M, number_angles) with stack of rotated Fourier filters to be used for
datacube extraction.
:param single_filter: Initial filter as numpy array of size (M, M)
:param angles: list... | 1b48fe94e240525f367af42e59192d1dedd3f87c | 42,478 |
def remove_outliers(df):
"""Summary Line.
Extended description of function.
Args:
arg1: Function will remove 1.5 IQR outliers from data set.
Returns:
Will return a data set with outliers within the 1.5 IQR range removed.
"""
q1 = df.quantile(0.25)
q3 = df.quantile(0.75)
iq... | 6333665ddfc4f77b12604c4161ba56c0818663eb | 42,479 |
def loadfactory(theclass, *args):
"""Returns an extended instance of `theclass` initiated from dlite
instance or storage.
If `*args` is a dlite instance, the returned object is initiated form
it. Otherwise `*args` is passed to dlite.Instance()
"""
inst = args[0] if isinstance(args[0], Instance... | 1d59a7eacab9acc126cdbf40d84dc2e8f8de0d84 | 42,481 |
def find_diagonal_blocks(mat: np.ndarray) -> np.ndarray:
"""
Find perfect diagonal sub-blocks in a block-diagonalized binary matrix.
Parameters
----------
mat : (n,n) np.ndarray
binary matrix
Returns
-------
inds : (n,) np.ndarray[int]
all elements comprising a unique p... | aa149a15c433c04e9801ed05ed2dac8c2177f72e | 42,482 |
def categorical_evaluation(prediction: np.ndarray, target: np.ndarray, metric_name: str, mask=None) -> pd.DataFrame:
"""
Evaluates a regression prediction with the F1 score
on quantile-based categories
Args:
prediction: shape [n_classes, X]
target: shape [n_classes, ... | 10c03240d6751b33386c6f12a14f4b7259775f59 | 42,483 |
def get_layers(net_param):
"""Get layers information.
Parameters
----------
net_param : caffe_pb2.NetParameter
A pretrined network description.
Returns
-------
layers : list
description of the layers.
version : string
version information of the pretrained model.
... | 6af46460f0ba9fa41111e265cd5e63a14b8ad5cb | 42,484 |
from pathlib import Path
def get_project_root() -> Path:
"""
Get project root directory with assumed structure as:
${PACKAGE_ROOT}/core/common/path.py
"""
return Path(__file__).resolve().parent.parent.parent | 89dde9a9257c8c3a97104cb883a2ee92a1e9d011 | 42,485 |
def cvSubdiv2DEdgeOrg(edge):
"""CvSubdiv2DPoint cvSubdiv2DEdgeOrg( CvSubdiv2DEdge edge )
Returns edge origin
[ctypes-opencv] returns None if no point is found
"""
ev = edge.value
e = pointer(CvQuadEdge2D.from_address(ev & ~3))
return pointee(e[0].pt[ev & 3]) | f01fc5a4081ce8e1f48b607296c6390a23afad7a | 42,486 |
async def kill_process(op: Operation, host: ObservedHost, pid: int, job_run_until_success) -> bool:
"""
Kills the specified process pid on the desired host
Args:
op: The operation currently being run
host: The host to run the command on
pid: The pid to kill
job_run_until_succ... | 31984551c360b3e9c8c7a5a4607df770f8f0526a | 42,487 |
def delete(consul_url=None, token=None, key=None, **kwargs):
"""
Delete values from Consul
:param consul_url: The Consul server URL.
:param key: The key to use as the starting point for the list.
:param recurse: Delete values recursively beginning at the value of key.
:param cas: This flag is u... | 4743e821ec2ffb27f3170937599b1d0dc032d340 | 42,488 |
def indexCube(nodes, gridSize, n=None):
"""
Returns the index of nodes on the mesh.
Input:
nodes - string of which nodes to return. e.g. 'ABCD'
gridSize - size of the nodal grid
n - number of nodes each i,j,k direction: [ni,nj,nk]
Output:
index - index in th... | e7fda79032b8cbb4c9242d4d67aa29c9f1e81f90 | 42,490 |
def encode_cf_datetime(dates, units=None, calendar=None):
"""Given an array of datetime objects, returns the tuple `(num, units,
calendar)` suitable for a CF compliant time variable.
Unlike `date2num`, this function can handle datetime64 arrays.
See also
--------
netcdftime.date2num
"""
... | 9c950904f32b4fb6ba663bf484b581e585988957 | 42,491 |
def aggclus(X, THRESHOLD):
"""
agglomerative clustering using single link
X is the n x m vector where n is the number of samples
uses euclidian distance
"""
clustering = AgglomerativeClustering(n_clusters=None, distance_threshold=THRESHOLD).fit(X)
return clustering.labels_,clustering.n_clust... | a6d41762bd6b5132e4348845b13c13fe9f91c3f0 | 42,492 |
def calc_pval(x, y, nulls):
"""
Calculates p-values for simulations in `x` and `y` using `spatnull`
Parameters
----------
{x, y} : (N,) array_like
Simulated GRF brain maps
nulls : (N, P) array_like
Null versions of `y` GRF brain map
Returns
-------
pval : float
... | 382e1b52d75c9770c680b64004a8e7d183af9ba5 | 42,493 |
def norm_bbox(img, bbox, x_corr=0.025, y_corr=0.025):
"""Add adition value for bbox results in x and y-axis
In order to ensure the detected region can cover all the table, we will add an addition value for both x and y axis of the bbox
Using the correlation value x_corr for x-axis and y_corr for y-axis
... | 193e0a9dd13ca2b2b212c23ea73724e9a5e0c121 | 42,495 |
def get_latest_draft_version(version):
"""Get latest draft version of version object
"""
drafts = Version.objects.filter_by_content_grouping_values(version.content).filter(
state=DRAFT
)
return drafts.first() | d10789125a0906687dff7547f66d40c6ec5e6076 | 42,497 |
from typing import Optional
def delete_datasource_mapping(connection: Connection, id: str, error_msg: Optional[str] = None):
"""Delete a datasource mapping based on id.
Args:
connection: MicroStrategy REST API connection object
id (string): ID of the mapping meant to be deleted.
error... | cd77c4ed46c11d5c2c4fd05967928b04dedb16b4 | 42,498 |
from typing import Union
from typing import Mapping
from typing import Any
from typing import Sequence
def _build_entity_object_ids(entities: Union[str, Mapping[str, Any], Sequence[str]]) -> str:
"""
Builds the string of object ids as required by the GetObject transaction request. See
section 5.3 for the ... | 95d15f23377046f573a0853f612ab87b75d552c4 | 42,499 |
def get_all_coords(rdmol):
"""Function to get all the coordinates for an RDMol
Returns three lists"""
conf = rdmol.GetConformer()
x_coords = []
y_coords = []
z_coords = []
for atm in rdmol.GetAtoms():
x_coords.append(conf.GetAtomPosition(atm.GetIdx()).x)
y_coords.append(conf.... | 14399748a77d565f2d65f8ae8f47ec2924c64683 | 42,500 |
from typing import BinaryIO
from typing import Any
def make_sized_bytes(size):
"""
Create a streamable type that subclasses "hexbytes" but requires instances
to be a certain, fixed size.
"""
name = "bytes%d" % size
def __new__(self, v):
v = bytes(v)
if not isinstance(v, bytes)... | 24f2da59ef3ce64419dfbf585fba51cbd368f417 | 42,502 |
def evaluations(ty, pv):
"""
evaluations(ty, pv) -> ACC
Calculate accuracy using the true values (ty) and predicted values (pv).
"""
if len(ty) != len(pv):
raise ValueError("len(ty) must equal to len(pv)")
total_correct = total_error = 0
for v, y in zip(pv, ty):
if y == v:
... | 021c80dab1d4ed97876bebc882db3423af107ea5 | 42,503 |
def _is_member_of(cls, obj):
"""
returns True if obj is a member of cls
This has to be done without using getattr as it is used to
check ownership of un-bound methods and nodes.
"""
if obj in cls.__dict__.values():
return True
# check the base classes
if cls.__bases__:
f... | c5bfb2920efc3992a92da236471f1de85cdb27a1 | 42,504 |
from typing import Union
from typing import List
def get_base_info(stock_codes: Union[str, List[str]]) -> Union[pd.Series, pd.DataFrame]:
"""
Parameters
----------
stock_codes : Union[str, List[str]]
股票代码或股票代码构成的列表
Returns
-------
Union[Series, DataFrame]
- ``Series`` : 包... | a0d0064eaf0abdadbc9bf5a2cd6a4769085a7421 | 42,505 |
def photom(data,stars,uncertainty=None,rad=[3],skyrad=None,display=None,
gain=1,rn=0,mag=True,utils=True) :
""" Aperture photometry of input image with current star list
"""
# input radius(ii) in a list
if type(rad) is int or type(rad) is float: rad = [rad]
# uncertainty either speci... | e1a79fd63f3ac6be2e6c52eec800e771c586b8b9 | 42,506 |
def discount_cumsum(x, dones, gamma):
"""
computing discounted cumulative sums of vectors that resets with dones
input:
vector x, vector dones,
[x0, [0,
x1, 0,
x2 1,
x3 0,
x4] 0]
output:
[x0 + discount * x1... | ee72c39586cca74ff64b00ed3c97b426c8756c8e | 42,508 |
from typing import Iterable
import itertools
def determine_resolves_to_generate(
all_known_user_resolve_names: Iterable[KnownUserResolveNames],
all_tool_sentinels: Iterable[type[GenerateToolLockfileSentinel]],
requested_resolve_names: set[str],
) -> tuple[list[RequestedUserResolveNames], list[type[Generat... | 7ba59edece64a71d01a0651747cf7fc160ea035e | 42,509 |
import torch
def prepare_laplacian(laplacian):
"""Prepare a graph Laplacian to be fed to a graph convolutional layer
"""
def estimate_lmax(laplacian, tol=5e-3):
r"""Estimate the largest eigenvalue of an operator."""
lmax = sparse.linalg.eigsh(laplacian, k=1, tol=tol,
... | 4bd310141f3b19306f1749b80ed8a4c5b01d41f3 | 42,510 |
import hmac
def hash_str(s):
"""Hash the user_id and SECRET (a constant) to create a cookie hash."""
return hmac.new(SECRET, s).hexdigest() | 8df6dfc971788940807ce2762e86feaddb1705bb | 42,511 |
from typing import Optional
from typing import Any
from typing import Tuple
def transition_kernel_wrapper(
current_state: 'fun_mc_lib.FloatNest', kernel_results: 'Optional[Any]',
kernel: 'tfp.mcmc.TransitionKernel') -> 'Tuple[fun_mc_lib.FloatNest, Any]':
"""Wraps a `tfp.mcmc.TransitionKernel` as a `Transiti... | ed67dfe84f211545f73e4e74e16a991eda479557 | 42,512 |
def get_valid_output_response(data):
"""
Returns success message correct processing of post/get request
:param str data: message
:return: response
:rtype: object
"""
response = {"status": 200, "message": "Success", "data": data}
return response | d4b44feafbae82570819595a79205acd765920f0 | 42,513 |
def _get_column_data_type(dataframe: pd.DataFrame):
"""
Returns
-------
when krx.read_date(date='2021-06-22')
{'종목명': 'str',
'시장구분': 'str',
'소속부': 'str',
'종가': 'np.int64',
'대비': 'np.int64',
'등락률': 'float',
'시가': 'np.int64',
'고가'... | 88c3da9999ca8332b05f3035805c25e98c4b5106 | 42,514 |
from typing import Dict
from typing import Any
async def create_pr(
maintainer_can_modify: bool = True,
draft: bool = False,
*,
owner: str,
repo: str,
head: str,
base: str,
title: str,
body: str,
app: Application,
logger: BoundLogger,
) -> Dict[str, Any]:
"""Create a Gi... | b20492f803625d526d3c30afe4ea65bc86f61249 | 42,515 |
def build_metadata_table(city_names):
"""Return the name of a temp file with metadata from the given city."""
metadata = get_complete_metadata(uploadable=True)
city_metadata_rows = metadata[COLUMNS.CITY].str.lower().isin(city_names)
city_metadata = metadata[city_metadata_rows]
city_metadata_file_han... | 234eb9ba29c6918de9063a6f616b026dba0b1c52 | 42,516 |
from datetime import datetime
def format_log_entry(msg):
"""Add timestamp and align msg for logging purposes"""
timestamp = str(datetime.datetime.now())
# Align colon (msg must begin with 'CTRL', 'SEM' or '3VIEW'):
try:
i = msg.index(':')
except:
i = 0
return (timestamp[:22] + ... | 048d878a6a12b4d1e1f0e569f4d09696bf414dcd | 42,517 |
from ldap3.extend import StandardExtendedOperations
from anima.utils import authenticate
def test_authenticate_with_stalker_and_ldap_authenticates_an_existing_ldap_user(ldap_server, create_db, monkeypatch):
"""testing if the anima.utils.authenticate() function will authenticate a
ldap user without a problem
... | 8ea9a4ae5ee8d03eaa869e5f2a0d7101ab2b58cc | 42,518 |
def multi_quat_diff(nq1, nq0):
"""return the relative quaternions q1-q0 of N joints"""
nq_diff = np.zeros_like(nq0)
for i in range(nq1.shape[0] // 4):
ind = slice(4*i, 4*i + 4)
q1 = nq1[ind]
q0 = nq0[ind]
nq_diff[ind] = quaternion_multiply(q1, quaternion_inverse(q0))
ret... | 2b99a73f01ba0c712930990b56cd2737390ad8a8 | 42,520 |
def index(path):
"""UI base view."""
return render_template('invenio_app_ils/index.html') | 729f67884dc6996d64bb55ef89c9a7f3a5a40910 | 42,523 |
def wrap_exceptions(callable):
"""Call callable into a try/except clause so that if an
OSError EPERM exception is raised we translate it into
psutil.AccessDenied.
"""
def wrapper(self, *args, **kwargs):
try:
return callable(self, *args, **kwargs)
except OSError, err:
... | 074720b53329f11a79712619f9b24364e93147eb | 42,524 |
def multi_multi_log_loss(predicted,
actual,
class_column_indices=BOX_PLOTS_COLUMN_INDICES,
eps=1e-15):
""" Multi class version of Logarithmic Loss metric as implemented on
DrivenData.org
"""
class_scores = np.ones(len(clas... | 676e7481bcbd5506e526fef449a8f16cd0742609 | 42,525 |
def filter_production_brand(production_id):
"""
产品品牌
:param production_id:
:return:
"""
production_info = get_production_row_by_id(production_id)
return production_info.production_brand if production_info else '-' | 0ffb27e2f615e621c31c58a34cb917c06786b249 | 42,526 |
def print_sami(s, idfile, queryText, outFile=True, verbose=True):
# ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
""" Define a Row Iterator for screen output """
# Prepare some variables.
counter = 0
idlist = []
# Iterate over all supplied rows.
if outFile:
... | 9fda3b8db21bacdc8c845a69b123610145fb3687 | 42,527 |
def extract_tables(sql):
"""
获取sql语句中的库、表名
:param sql:
:return:
"""
tables = list()
for i in extract_tables_by_sql_parse(sql):
tables.append({
"schema": i.schema,
"name": i.name,
})
return tables | 73e9ecbd5f1a243561e64d42d9ec89c630e1770d | 42,528 |
import traceback
def session_wrapper(send_message=True, private=False):
"""Create a session, handle permissions, handle exceptions and prepare some entities."""
def real_decorator(func):
"""Parametrized decorator closure."""
@wraps(func)
def wrapper(update, context):
sessio... | 6a69a802021fce0d6c621441fdd53a08205000c9 | 42,529 |
import requests
def fetch_j_league_schedule(year: int = 1992) -> pd.DataFrame:
"""Load J League schedule dataset."""
url = "https://data.j-league.or.jp/SFMS01/search"
params = {"competition_years": year, "lang": "en"}
response = requests.get(url, params=params)
attrs = {"class": "table-base00 sea... | c1777c989ce8d9a9b8609d4fb0e8c4ffe5378487 | 42,530 |
def cancel_job(request, job_id):
"""
Cancels the current job.
:param request: Django request object.
:param job_id: id of the job.
:return: Redirects to relevant view.
"""
should_redirect = False
# to decide which page to forward if not coming from any http referrer.
# this happens... | da13f47b55cba8a99314043bc87ec0a3ed725b6f | 42,531 |
from typing import Optional
from typing import Dict
from typing import List
def scripts(page_content: Optional[Dict]) -> List[str]:
"""
.. _`example reference server`: https://github.com/stellar/django-polaris/tree/master/example
Replace this function with another by passing it to
``register_integrat... | 8e591eace462a5649533811bf1c54575f5714174 | 42,532 |
def simplesubspec(signal, wlen, inc, NIS, a, b):
"""
simple spectral subtraction denoise
:param signal: noisy speech signal
:param wlen: frame length
:param inc: frame shift
:param NIS: leading unvoiced segment frame number
:param a: over subtraction factor
:param b: gain compensation factor
:return output: de... | dc5982f5bb76095650b8dc5aee05788fb673c065 | 42,533 |
def get_possible_topologies(no_ami_fgs, no_alde_fgs):
"""
Determine possible topologies based on the FGs in BBs.
"""
if no_ami_fgs == 2 and no_alde_fgs == 3:
pos_topo = ['2p3', '4p6', '4p62', '6p9']
elif no_ami_fgs == 3 and no_alde_fgs == 3:
pos_topo = ['1p1', '4p4']
return po... | 99078a354408de8c10bbf0b46dde53b6188d8ac2 | 42,534 |
import requests
def hits(batter_id=None):
"""Get the number of hits for each historical batter. If batterId is specified, only that batter is returned.
`batter_id` is a single string UUID or list of string UUIDs.
Returns dictionary {batter_id: count}"""
params = {}
if batter_id:
params['b... | b0435098eefbb3a48d348beb50d9d4592996920d | 42,536 |
def valid_axes(
draw,
ndim,
pos_only=False,
single_axis_only=False,
permit_none=True,
min_dim=0,
max_dim=None,
):
""" Hypothesis search strategy: Given array dimensionality, generate valid
`axis` arguments (including `None`) for numpy's sequential functions.
Examples from this s... | d5b42530b09fb37df094fd6f1d9ad22cf58cb063 | 42,537 |
def index_intellectuels() :
"""
Route permettant l'affichage de l'index des intellectuels enregistrés
:return : affichage du template index_intellectuels.html
"""
titre="index_intellectuels"
#On vérifie que la base de données n'est pas vide
intellectuells = Intellectuel.query.all()
if len(intellectuells) ==... | 84badd1c1a219d28b44c6f0c513f5c98e4795476 | 42,538 |
import time
def random_split_by_user(dataset,
user_id='user_id',
item_id='item_id',
max_num_users=1000,
item_test_proportion=.2,
random_seed=0):
"""Create a recommender-friendly train-test ... | d511ca6a75dcf3aaedf1cdf6ec4480f3e97cce37 | 42,540 |
from typing import Union
from typing import List
from typing import Any
import yaml
def read_yaml(content: Text, reader_type: Union[Text, List[Text]] = "safe") -> Any:
"""Parses yaml from a text.
Args:
content: A text containing yaml content.
reader_type: Reader type to use. By default "safe"... | b4e5b463df4a8044b3e65a6afc9613dd220c6bbf | 42,541 |
def _GetSheriffForTest(test):
"""Gets the Sheriff for a test, or None if no sheriff."""
if test.sheriff:
return test.sheriff.get()
return None | daa272df6a1882e1379531b2d34297da8bec37b3 | 42,543 |
def smooth_surround_LS_v1(p, is_obs, sd_dv):
"""
Smooth via LS on each vic in a loop.
:param p: n, n_vic
:param is_obs: n, n_vic
:param sd_dv:
:return:
x: n, n_vic, 2
"""
n, n_vic = p.shape
x0 = np.zeros((n_vic, 2))
P0 = np.zeros((n_vic, 2, 2))
P0[:] = np.eye(2) * 1e8... | 5688eabd580a6decbc83e5c6f8dc69a2e6c013d2 | 42,544 |
def booth(args):
""" Booth function
Global minimum: f(1.0,3.0) = 0.0
Search domain: -10.0 <= x, y <= 10.0
"""
return (args[0] + 2*args[1] - 7)**2 + (2*args[0] + args[1] - 5)**2 | 8adf94d9e96ee19758a6e495775d8bdb10330794 | 42,545 |
import fnmatch
def is_cms_app(app_name):
"""
Return whether the given application is a CMS app
"""
for pat in appsettings.FLUENT_DASHBOARD_CMS_APP_NAMES:
if fnmatch(app_name, pat):
return True
return False | 80ed2925a9c7464909e336f8f44b1459ab0c8151 | 42,546 |
def deeplabv3_resnet101(pretrained=False, progress=True,
num_classes=21, aux_loss=None, **kwargs):
"""Constructs a DeepLabV3 model with a ResNet-101 backbone.
Args:
pretrained (bool): If True, returns a model pre-trained on COCO train2017 which
contains the same clas... | f07eec8f6abfdc8703875de0f67ed5784bf2849f | 42,547 |
def query_model(master_df, query_sid):
"""
NOTE: Fields containing enzyme, compound PubChem sid, and SMILES string must be named
['entry', 'PubChem', 'SMILES'] respectively
"""
# get query SMILES string & pair query compound with each unique enzyme in the master DataFrame
updated_df = pair_q... | 7daf570e477e4545b05924f543da98556802a539 | 42,548 |
def makeset(weatherpart):
"""
with open("WeatherWear/clothes.csv") as f:
reader = csv.reader(f)
next(reader)
data = []
for row in reader:
data.append(
[float(cell) for cell in row[:13]]
)
clothes = data
"""
clothes = [[0.0... | be8ca4b1e64585fed368bde0baa447a13d2da7e3 | 42,549 |
import requests
from bs4 import BeautifulSoup
def create_soup(url):
"""
Create soup object from url
"""
try:
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
return soup
except Exception as e:
print("[ERROR] Error occurred in requesting htm... | 43c6478754807763a74b03bf346d8735bcbf5ba5 | 42,550 |
def get_vtk_edges(vtkdata):
"""
Get mesh edges.
Parameters
----------
vtkdata : VTK object
Mesh, scalar, vector and tensor data.
Returns
-------
edges : VTK object
Mesh, scalar, vector and tensor data.
"""
edges = vtk.vtkExtractEdges()
if vtk_version < 6:
... | cf9a27c8844e5e51b90fb4b51af79dce200768df | 42,551 |
def DispatchKeyForTagSpecOrNone(tag_spec):
"""For a provided tag_spec, generates its dispatch key.
If the value (or value_casei) is used, uses the first value from the
protoascii.
Args:
tag_spec: an instance of type validator_pb2.TagSpec.
Returns:
a string indicating the dispatch key, or None.
""... | 00a43e14a8a66e218b51b535a3617675a4c3d571 | 42,552 |
def convert_column_to_input(column: Column) -> InputField:
"""Converts a sqlalchemy column into a graphql field or input field"""
sqla_type = type(column.type)
gql_type = convert_input_type(sqla_type)
return InputField(gql_type) | e8237205682c8ce45eacd2822babed21427e5d12 | 42,553 |
import math
def rainbow_search(x, y, step):
"""Returns RGB color tuple
"""
xs = math.sin((step) / 100.0) * 20.0
ys = math.cos((step) / 100.0) * 20.0
scale = ((math.sin(step / 60.0) + 1.0) / 5.0) + 0.2
r = math.sin((x + xs) * scale) + math.cos((y + xs) * scale)
g = math.sin((x + xs) * s... | dc1d05f24fe9fb44857210c9fd962ffa4465e1f9 | 42,554 |
def check_codes(df, col, schema_codes):
"""
Get values not in list of codes.
Parameters
----------
df : pd.DataFrame
col : str
pd.DataFrame column name
schema_codes : array_like
List of allowed values
Returns
-------
array_like
Invalid values
>>> in... | 4ed277e7275678f2487697120828e1bb2c72d8cc | 42,555 |
from typing import Optional
def orbit_number_validator(orbit_number: str) -> Optional[str]:
"""Validates the parameter to check whether it is a valid orbit number
(1 To 999999)
Args:
orbit_number::str
Value that could be orbit number either single value or a range
Returns:
... | 3376816f393711bf0345646c231743d043bcb933 | 42,556 |
def get_result(data: bytes):
"""start the thrift client and transform data to server through the client"""
with TransportClient(host=config.THRIFT_HOST, port=config.THRIFT_PORT) as client:
res = client.send(data)
return res | 6dd3d78451edae58567d4ec32aae8ece463c361a | 42,557 |
def generate_pwd(number=8):
"""
Generate radom secure password
:return: random string for pasword
"""
generater = pwgen.pwgen
password = generater(number)
return password | 690a21dc4cc7185dd394900ef8b77fc7f32daf19 | 42,558 |
def map_remove_by_value_rank_range_relative(
bin_name, value, offset, return_type, count=None, inverted=False):
"""Create a map remove by value rank range relative operation
Create map remove by value relative to rank range operation.
Server removes and returns map items nearest to value and greate... | 0bf1f6542dc6bf327c681beb401c524e7470e0ef | 42,560 |
def _has_scf_convergence_message(output_str):
""" Assess whether the output file string contains the
message signaling successful convergence of the SCF procedure.
:param output_str: string of the program's output file
:type output_str: str
:rtype: bool
"""
pattern = 'Conve... | e2f9b7b5a89e6de6d7bf500b61f5e1d8a1c3155d | 42,561 |
from typing import List
from re import I
from typing import Union
def append_measure_register(program: Program,
qubits: List = None,
trials: int = 10,
ham: PauliSum = None) -> Program:
"""Creates readout register, MEASURE instruct... | 71e1c37aee863a3f941d741bf2b9f32a58e6359b | 42,562 |
def recursive_any_to_dict(anyElement):
"""
Recursive any nested type into a dict (so that it can be JSON'able).
:param anyElement: Just about any 'attrs-ized' instance variable type in Python.
:return: A dict structure
"""
if isinstance(anyElement, dict):
simple_dict = {}
for key... | 7e94c93c9470c218781ee0a0059f8b95b0f663e5 | 42,564 |
from typing import OrderedDict
def genListHeaders(P4Graph):
""" Generate the dictionnary of headers.
P4Graph : JSon imported file
Name, size
"""
headers = OrderedDict()
return headers | 6077d41968dc8958ebf1f0d55d1c05607d77915c | 42,566 |
def colorize(s, color, bold=False, reverse=False, start=None, end=None):
"""
Colorize a string with the color given.
:param string s: The string to colorize.
:param color: The color to use.
:type color: :class:`Colors` class
:param bool bold: Whether to mark up in bold.
:param bool reverse:... | ae50e9d2720d05e99e2ed55e5cd68e6dfd97a4d3 | 42,567 |
def join_url(url, *paths):
"""
Joins individual URL strings together, and returns a single string.
Usage::
>>> join_url("pillar:5000", "shots")
'pillar:5000/shots'
"""
assert isinstance(url, string_type), 'URL must be string type, not %r' % url
url_parts = [url.rstrip('/')]
... | a44dac12ec3be2e72c8c69c9cd11f0798c8d1c66 | 42,569 |
def has_liked(obj, user_or_id):
"""whether the objects is liked by an user.
:param obj: Any Django model instance.
:param user_or_id: :class:`~hashup.users.models.User` instance or id.
"""
obj_type = get_obj_type_for_model(obj)
if isinstance(user_or_id, get_user_model()):
user_id = use... | 9a99267072f943f2927e069cc787f3d582fdf7c8 | 42,570 |
def _int_to_riff(i: int, length: int) -> bytes:
"""Convert an int to its byte representation in a RIFF file.
Represents integers as unsigned integers in *length* bytes encoded
in little-endian.
Args:
i (int):
The integer to represent.
length (int):
The number of... | 9c382486be14af3e5ec22b5aed7c2d9dc3f21d57 | 42,573 |
def read(filename):
"""
Read the file
"""
if "time" not in filename.name:
args = dict(unpack=True, comments="P", skiprows=2)
else:
args = dict(unpack=True, delimiter=":", usecols=1)
data = np.loadtxt(filename, **args)
return data | ee95c2915972efb0012e51ab8146403829223590 | 42,574 |
from typing import List
def get_site_surveys(client: SymphonyClient, location: Location) -> List[SiteSurvey]:
"""Retrieve all site survey completed in the location.
Args:
location ( `pyinventory.consts.Location` ): could be retrieved from getLocation or addLocation api
Returns:
... | c1107abca990800bb86685753377b3c6da7d4658 | 42,575 |
def backwardEliminationP(x, y, sl):
"""Function that applies a Backward Elimination
on a model with p-values only
Arguments:
x {Array} -- The Predictors values
y {Array} -- The Dependent Variable
sl {Float} -- The Significance Level
Returns:
Array -- The New Optimized M... | 0c304dde0c3be264f81331ab3c2ff426ca18c24b | 42,577 |
import pathlib
def sample_odb_fixture():
"""Get the fully qualified path to the sample odb file."""
return str(pathlib.Path(__file__).parent.parent / "resources" / "sample.odb") | 12bb3567dc5c5e86bfd6c1042c1c4c3fe310b95a | 42,578 |
def day_of_week(df):
"""Return weekday/weekend using NHTSA convention."""
hr = df['HOUR']
day = df['DAY_WEEK']
conditions = [
(((day == 2) & hr.between(6, 23)) | day.isin([3, 4, 5]) |
((day == 6) & (hr.between(0, 17) | (hr == 24)))),
(((day == 6) & hr.between(18, 23)) | day.isi... | 5642b2aa96094cecbd33dc3fad04908f689bc41f | 42,579 |
def C_r(m_pert, m_c, a, j1, j2):
""" Constant from resonant part of disturbing function (M+D equation 8.32) """
alpha = (j2/(j2-1))**(2/3)
P = 2*np.pi*np.sqrt(a**3/m_c)
n = 2*np.pi/P
return (m_pert/m_c)*n*alpha*f_d(j1, alpha) | bc6386c474e1eeb2b295c4100b3bbd0a40bd0212 | 42,580 |
import six
import collections
def to_iterable(item):
"""Converts an item or iterable into an iterable."""
if isinstance(item, six.string_types):
return [item]
elif isinstance(item, collections.Iterable):
return item
else:
return [item] | 6d672d231c84c2254b84d5618f35eaf47b7ac71c | 42,581 |
def reproject(link, node, epsg):
"""
reporoject link and node geodataframes
for nodes, update X and Y columns
"""
link = link.to_crs(epsg=epsg)
node = node.to_crs(epsg=epsg)
node["X"] = node["geometry"].apply(lambda p: p.x)
node["Y"] = node["geometry"].apply(lambda p: p.y)
retur... | 5ead99d074ea1d643f598d790b083dda511caa1a | 42,582 |
def conv2d(conv_input, n, kernel, stride, pad, name='', bias=True, init_method=None, scale=0.1):
"""
define simple 2d convlution
"""
if init_method == 'kaiming_normal':
std = nn.initializer.calc_normal_std_he_forward(
conv_input.shape[1], n, kernel=(kernel, kernel))
w_init =... | b2e8fbb4e2c1d050b3009728705aeda708178077 | 42,584 |
import tqdm
def get_accuracy(params_repl, nbr_samples):
"""Returns accuracy evaluated on the test set."""
good = total = 0
steps = nbr_samples // batch_size #20000 // batch_size
for _, batch in zip(tqdm.trange(steps), ds_test.as_numpy_iterator()):
predicted = vit_apply_repl(params_repl, batch['image'])
... | c2bb6bfcdd380e132049e01bd86c63c72c2fcdb2 | 42,585 |
from typing import cast
def binary_search(ib, sequence_offset, search_range, sorted_sequence, value, right, out_dtype):
"""Common IR generator for binary search used by CPU and GPU backends.
`sorted_sequence` is a N-D Buffer whose innermost dimension we want to search for `value`,
and `search_range` is t... | 2fbd4e100e2eb63251502249255d5d3993168b45 | 42,586 |
import re
def genbank_features_parser(input_filename):
""" Return dictionary with features contains inside a genbank file.
:param str input_filename: genbank formated file
"""
logger.warning("deprecated. please use GenBank.genbank_features_parser instead")
new_feature = {}
records = {}
fe... | 06be96c2734cff0916bbd10f43297632fc4cf0ed | 42,587 |
def guess_shape(dic):
"""
Determine data shape and complexity from Bruker dictionary.
Returns
-------
shape : tuple
Shape of data in Bruker binary file (R+I for all dimensions).
cplex : bool
True for complex data in last (direct) dimension, False otherwise.
"""
# determ... | f76006f17d8deac09752ed8e7299c33dfc19f950 | 42,588 |
def diff_element_with_children():
"""Construct a DiffElement that has some diffs of its own as well as a child diff with additional diffs."""
# parent_element has differing "role" attribute, while "location" does not differ
parent_element = DiffElement("device", "device1", {"name": "device1"})
parent_el... | 618d50580885c4f8792bd51fda0424b191157e6f | 42,589 |
def cohort_preview():
"""List the samples, cases, and counts a given set of cohort filters would produce"""
code = None
response_obj = None
st_logger.write_text_log_entry(log_name, activity_message.format(request.method, request.full_path))
try:
cohort_counts = get_cohort_counts()
... | 911abe454c2405654e0d7418eddc1167a93466fd | 42,590 |
def rle(inarray):
""" run length encoding. Partial credit to R rle function.
Multi datatype arrays catered for including non Numpy
returns: tuple (runlengths, startpositions, values) """
ia = np.asarray(inarray) # force numpy
n = len(ia)
if n == 0:
return (None, ... | b78b2d65e6862c6299bac3bed3435ffdd320ab63 | 42,591 |
def extract_coordinates_combined(ref, trj, sel_string, out_name, start_frame=0, verbose=False):
"""
Extracts selected coordinates from several trajectory files.
Parameters
----------
ref : list of str
File names for the reference topologies.
Can read all MDAnalysis... | ca7e62735710e0b144e9d40deb99fbe54eab44d0 | 42,592 |
def route_search(search_string):
"""
Searches through titles.
Parameters
----------
search_string : str
The search string.
Returns
-------
A JSON string that contains a list of the found titles grouped by categories.
"""
result = _search_video_titles(search_string)
... | e9000eab782ec0ce6efefff05f7759e5b2cbdbc4 | 42,593 |
def katamari():
"""creates and returns the katamari object"""
k = Katamari()
return k | 307acda287717b681de4b1189016be98d45d80b0 | 42,594 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.