content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _kp(a, b):
"""Special case Kronecker tensor product of a[i] and b[i] at each
time interval i for i = 0 .. N-1
It is specialized for the case where both a and b are shape N x m x 1
"""
if a.shape != b.shape or a.shape[-1] != 1:
raise(ValueError)
N = a.shape[0]
# take the outer pro... | b133557d88deac2d9357731d820de0522521d6f3 | 3,647,073 |
def strategy(history, alivePlayers, whoami, memory):
"""
history contains all previous rounds (key : id of player (shooter), value : id of player (target))
alivePlayers is a list of all player ids
whoami is your own id (to not kill yourself by mistake)
memory is None by default and t... | f211a0961269808d9a7b0a08758273d4a03b9136 | 3,647,074 |
def parse_fn(serialized_example: bytes) -> FeaturesType:
"""Parses and converts Tensors for this module's Features.
This casts the audio_raw_pcm16 feature to float32 and scales it into the range
[-1.0, 1.0].
Args:
serialized_example: A serialized tf.train.ExampleProto with the features
dict keys dec... | 54e841987986027dc6d4d989fe6442ceecd022b8 | 3,647,075 |
import click
def cli(ctx: click.Context) -> int:
"""
Method used to declare root CLI command through decorators.
"""
return 0 | be5016c5c38f435b8a213a6ce39b5571aee809f1 | 3,647,076 |
def parse_clock(line):
"""Parse clock information"""
search = parse(REGEX_CLOCK, line)
if search:
return int(search.group('clock'))
else:
return None | a4464c979d31bab463f949bec83da99e72af6ca6 | 3,647,077 |
import requests
def block_latest(self, **kwargs):
"""
Return the latest block available to the backends, also known as the tip of the blockchain.
https://docs.blockfrost.io/#tag/Cardano-Blocks/paths/~1blocks~1latest/get
:param return_type: Optional. "object", "json" or "pandas". Default: "object".
... | a14fc3512138c1d15b32b09bd20ea03678964437 | 3,647,078 |
def get_courses():
"""
Route to display all courses
"""
params = format_dict(request.args)
if params:
try:
result = Course.query.filter_by(**params).order_by(Course.active.desc())
except InvalidRequestError:
return { 'message': 'One or more parameter(s) does ... | 6dcdcb5df4d0010661ffe92f55522638ae51a2b8 | 3,647,079 |
def zero_adam_param_states(state: flax.optim.OptimizerState, selector: str):
"""Applies a gradient for a set of parameters.
Args:
state: a named tuple containing the state of the optimizer
selector: a path string defining which parameters to freeze.
Returns:
A tuple containing the new pa... | 8a7cb65028866e4a7f3a03b589fa1bf5798a25e0 | 3,647,080 |
from bs4 import BeautifulSoup
def get_stock_market_list(corp_cls: str, include_corp_name=True) -> dict:
""" 상장 회사 dictionary 반환
Parameters
----------
corp_cls: str
Y: stock market(코스피), K: kosdaq market(코스닥), N: konex Market(코넥스)
include_corp_name: bool, optional
if True, returnin... | c8e0242e1ddfcc4f32514f131f3a9797694202c1 | 3,647,082 |
def evaluate_template(template: dict) -> dict:
"""
This function resolves the template by parsing the T2WML expressions
and replacing them by the class trees of those expressions
:param template:
:return:
"""
response = dict()
for key, value in template.items():
if key == 'qualifier':
response[key] = []
... | 596516f9dfb81170212020cfb053339ddb49b716 | 3,647,083 |
def get_CommandeProduits(path, prefix='CP_',cleaned=False):
"""
Read CSV (CommandeProduits) into Dataframe. All relevant columns are kept and renamed with prefix.
Args:
path (str): file path to CommandeProduits.csv
prefix (str): All relevant columns are renamed with prefix
Returns:
... | 18c5c7e375abcc57c2cfcbc4f2c58ecec5aecf59 | 3,647,084 |
def hist_equal(image, hist):
"""
Equalize an image based on a histogram.
Parameters
----------
image : af.Array
- A 2 D arrayfire array representing an image, or
- A multi dimensional array representing batch of images.
hist : af.Array
- Containing the histogram o... | 70aeeb1822752c2f7fb5085d761bb9b309d29335 | 3,647,085 |
def get_close_icon(x1, y1, height, width):
"""percentage = 0.1
height = -1
while height < 15 and percentage < 1.0:
height = int((y2 - y1) * percentage)
percentage += 0.1
return (x2 - height), y1, x2, (y1 + height)"""
return x1, y1, x1 + 15, y1 + 15 | 78b65cdeeb4f6b3a526fd5dd41b34f35545f1e9d | 3,647,086 |
def train_model(network, data, labels, batch_size,
epochs, validation_data=None, verbose=True, shuffle=False):
"""
Train
"""
model = network.fit(
data,
labels,
batch_size=batch_size,
epochs=epochs,
validation_data=validation_data,
shuffle=s... | a2b093aef1b607cd34dd30e8c5f126e1efb3d409 | 3,647,087 |
def taoyuan_agrichannel_irrigation_transfer_loss_rate():
"""
Real Name: TaoYuan AgriChannel Irrigation Transfer Loss Rate
Original Eqn: 0
Units: m3/m3
Limits: (None, None)
Type: constant
Subs: None
This is "no loss rate" version.
"""
return 0 | 9fd8a84ae79cbeaf8c8259da815f9322f27b253f | 3,647,088 |
def lambda_handler(event, context):
"""
Find and replace following words and outputs the result.
Oracle -> Oracle©
Google -> Google©
Microsoft -> Microsoft©
Amazon -> Amazon©
Deloitte -> Deloitte©
Example input: “We really like the new security features of Google Cloud”.
Expected ... | 66dc2914dd04a2e265ed21542bd462b61344d040 | 3,647,089 |
def update_inv(X, X_inv, i, v):
"""Computes a rank 1 update of the the inverse of a symmetrical matrix.
Given a symmerical matrix X and its inverse X^{-1}, this function computes
the inverse of Y, which is a copy of X, with the i'th row&column replaced
by given vector v.
Parameters
----------
... | c811dbf699d8f93fa2fa5b3f68c5b23cf4131e9f | 3,647,090 |
import csv
def read_barcode_lineno_map(stream):
"""Build a map of barcodes to line number from a stream
This builds a one based dictionary of barcode to line numbers.
"""
barcodes = {}
reader = csv.reader(stream, delimiter="\t")
for i, line in enumerate(reader):
barcodes[line[0]] = i ... | 545a0d02dd76e774ba0de86431113ad9f36a098e | 3,647,091 |
def match_in_candidate_innings(entry, innings, summary_innings, entities):
"""
:param entry:
:param innings: innings to be searched in
:param summary_innings: innings mentioned in the summary segment
:param entities: total entities in the segment
:return:
"""
entities_in_summary_inning =... | 3551212f79c6ecb298ec6b55aa7b68213b950394 | 3,647,092 |
from typing import Optional
from typing import Union
from typing import Callable
from typing import Any
def checkpoint(
name: Optional[str] = None,
on_error: bool = True,
cond: Union[bool, Callable[..., bool]] = False,
) -> Callable[[Callable], Any]:
"""
Create a checkpointing decorator.
Args... | 39bab1a33523c34b04a2ed7f2efd6467de63b27b | 3,647,093 |
def return_int(bit_len, unsigned=False):
"""
This function return the decorator that change return value to valid value.
The target function of decorator should return only one value
e.g. func(*args, **kargs) -> value:
"""
if bit_len not in VALID_BIT_LENGTH_OF_INT:
err = "Value of bit_le... | 66121d389a389c6152fd4491ed8a698336e042a2 | 3,647,094 |
def get_integral_curve(f, init_xy, x_end, delta):
"""
solve ode 'dy/dx=f(x,y)' with Euler method
"""
(x, y) = init_xy
xs, ys = [x], [y]
for i in np.arange(init_xy[0], x_end, delta):
y += delta*f(x, y)
x += delta
xs.append(x)
ys.append(y)
return xs, ys | 0526643acd37b8d7c2646d3a21d54e9d9f16ef58 | 3,647,095 |
def compute_atime_posteriors(sg, proposals,
global_srate=1.0,
use_ar=False,
raw_data=False,
event_idx=None):
"""
compute the bayesian cross-correlation (logodds of signal under an AR noise model... | 1029f57fe500ef6f08eec56ab34539d3f9a80637 | 3,647,096 |
def search4vowels(pharse :str) -> set:
""""Return any vowels found in a supplied word."""
vowels = set('aeiou')
return vowels.intersection(set(pharse)) | 8a45c50828b6ba8d173572ac771eb8fe5ddc5a42 | 3,647,097 |
def rsort(s):
"""Sort sequence s in ascending order.
>>> rsort([])
[]
>>> rsort([1])
[1]
>>> rsort([1, 1, 1])
[1, 1, 1]
>>> rsort([1, 2, 3])
[1, 2, 3]
>>> rsort([3, 2, 1])
[1, 2, 3]
>>> rsort([1, 2, 1])
[1, 1, 2]
>>> rsort([1,2,3, 2, 1])
[1, 1, 2, 2, 3]
... | d9f67d713e55d50cd4468ad709f04c7bfea05c71 | 3,647,098 |
def read_starlight_output_syn_spec(lines):
""" read syn_spec of starlight output """
Nl_obs = len(lines)
wave = Column(np.zeros((Nl_obs, ), dtype=np.float), 'wave')
flux_obs = Column(np.zeros((Nl_obs, ), dtype=np.float), 'flux_obs')
flux_syn = Column(np.zeros((Nl_obs, ), dtype=np.float), 'flux_syn')... | e25aed3ff9294f07b1549b610030241895b78f67 | 3,647,100 |
def get_stations_trips(station_id):
"""
https://api.rasp.yandex.net/v1.0/schedule/ ?
apikey=<ключ>
& format=<формат>
& station=<код станции>
& lang=<язык>
& [date=<дата>]
& [transport_types=<тип транспорта>]
& [system=<текущая система кодирования>]
& [show_systems=<коды в ответе>]
"""
params = {
'apikey': RASP... | 8b841f19b135e7792e2f8d3aad642f38b2a6cd74 | 3,647,101 |
def _compute_pairwise_kpt_distance(a, b):
"""
Args:
a, b (poses): Two sets of poses to match
Each "poses" is represented as a list of 3x17 or 4x17 np.ndarray
"""
res = np.zeros((len(a), len(b)))
for i in range(len(a)):
for j in range(len(b)):
res[i, j] = pck_dista... | aaf4696292bb7d1e9377347d93d97da321787c6f | 3,647,102 |
def _extract_dialog_node_name(dialog_nodes):
"""
For each dialog_node (node_id) of type *standard*, check if *title exists*.
If exists, use the title for the node_name. otherwise, use the dialog_node
For all other cases, use the dialog_node
dialog_node: (dialog_node_title, dialog_node_type)
In... | 23121efa486c2da16a54b2441bb1435eec5b8b49 | 3,647,103 |
from typing import Dict
from typing import List
def search_all_entities(bsp, **search: Dict[str, str]) -> Dict[str, List[Dict[str, str]]]:
"""search_all_entities(key="value") -> {"LUMP": [{"key": "value", ...}]}"""
out = dict()
for LUMP_name in ("ENTITIES", *(f"ENTITIES_{s}" for s in ("env", "fx", "script... | ca24b50524cc96b35a605bebc5ead0d8d4342314 | 3,647,105 |
import re
def is_probably_beginning_of_sentence(line):
"""Return True if this line begins a new sentence."""
# Check heuristically for a parameter list.
for token in ['@', '-', r'\*']:
if re.search(r'\s' + token + r'\s', line):
return True
stripped_line = line.strip()
is_begin... | 68a6a2151b4559f0b95e0ac82a8a16bd06d9d1ff | 3,647,106 |
def default_attack_handler(deck, discard, hand, turn, supply, attack):
"""Handle some basic attacks in a default manner. Returns True iff the
attack was handled."""
covertool.cover("domsim.py:219")
if attack == COUNCIL_ROOM:
# Not really an attack, but this is an easy way to handle it.
... | 79745f30b5607348771ee6d5778202370e553a7b | 3,647,107 |
def hello_world():
"""return bool if exists -> take in email"""
email = request.json['email']
c = conn.cursor()
c.execute("select * from Users where Users.email = {}".format(email))
result = False
conn.commit()
conn.close()
return result | c28b33c5106b51144d4b58f3bffd2ea128dd948a | 3,647,110 |
from typing import Callable
from typing import Optional
import torch
def get_model_relations(
model: Callable,
model_args: Optional[tuple] = None,
model_kwargs: Optional[dict] = None,
):
"""
Infer relations of RVs and plates from given model and optionally data.
See https://github.com/pyro-ppl... | b0cc8f58a70575492ba0c5efe7f282b0e9ab0a4e | 3,647,111 |
from typing import Any
def is_valid_dim(x: Any) -> bool:
"""determine if the argument will be valid dim when included in torch.Size.
"""
return isinstance(x, int) and x > 0 | 09b8dd41b20a835583cd051868f13756e8383342 | 3,647,113 |
def compute_alpha(n, S_d, d_min):
"""
Approximate the alpha of a power law distribution.
Parameters
----------
n: int or np.array of int
Number of entries that are larger than or equal to d_min
S_d: float or np.array of float
Sum of log degrees in the distribution that are lar... | 9df2c39ccaa70e729b1bf2f7bfcc78cde0f649de | 3,647,114 |
from typing import Optional
def _head_object(
s3_conn: S3Client, bucket: str, key: str
) -> Optional[HeadObjectOutputTypeDef]:
"""Retrieve information about an object in S3 if it exists.
Args:
s3_conn: S3 connection to use for operations.
bucket: name of the bucket containing the key.
... | 3b7b239ea09bf3df75c9c9a3e3e19cba505d67a5 | 3,647,115 |
from operator import add
def Residual(feat_maps_in, feat_maps_out, prev_layer):
"""
A customizable residual unit with convolutional and shortcut blocks
Args:
feat_maps_in: number of channels/filters coming in, from input or previous layer
feat_maps_out: how many output channels/filters this bl... | cfb7345340785a8fc7b3068c2baa0e5452b189aa | 3,647,116 |
from typing import List
from datetime import datetime
def clean_detail_line_data(detail_row: List[str], date: str) -> List[str]:
"""
:param detail_row: uncleaned detail row
:param date: job data to be added to data
:return: a cleaned list of details fields
"""
if not detail_row:
print... | ff9c3b8f5079674bf9a727f4baedc264443dbdeb | 3,647,117 |
def lammps_prod(job):
"""Run npt ensemble production."""
in_script_name = "in.prod"
modify_submit_lammps(in_script_name, job.sp)
msg = f"sbatch submit.slurm {in_script_name} {job.sp.replica} {job.sp.temperature} {job.sp.pressure} {job.sp.cutoff}"
return msg | faa122a6e22f54028cd536f78c17094f9c1f07b4 | 3,647,118 |
def gather_tensors(tensors, indices):
"""Performs a tf.gather operation on a set of Tensors.
Args:
tensors: A potentially nested tuple or list of Tensors.
indices: The indices to use for the gather operation.
Returns:
gathered_tensors: A potentially nested tuple or list of Tensors with the
sa... | 68fd88121cdca7beb13f3f5633401ddb420f34d4 | 3,647,119 |
import types
def is_iterator(obj):
"""
Predicate that returns whether an object is an iterator.
"""
return type(obj) == types.GeneratorType or ('__iter__' in dir(obj) and 'next' in dir(obj)) | db57a2a1f171a48cc43ba4c248387191780dfd04 | 3,647,121 |
import shutil
def delete_entries(keytab_file: str, slots: t.List[int]) -> bool:
"""
Deletes one or more entries from a Kerberos keytab.
This function will only delete slots that exist within the keylist.
Once the slots are deleted, the current keylist will be written to
a temporary file. Th... | cc488778abdc75a9814702642fcfc9b245b6a99c | 3,647,122 |
def detect(environ, context=None):
"""
parse HTTP user agent string and detect a mobile device.
"""
context = context or Context()
try:
## if key 'HTTP_USER_AGENT' doesn't exist,
## we are not able to decide agent class in the first place.
## so raise KeyError to return NonMo... | 2977cb2847c4917904cc096c5787b6ddb3a889b9 | 3,647,123 |
async def get_product(id: UUID4): # noqa: A002
"""Return ProductGinoModel instance."""
return await ProductGinoModel.get_or_404(id) | f7988faf08da081a1922f8df24b843be67658c16 | 3,647,125 |
def LSIIR_unc(H,UH,Nb,Na,f,Fs,tau=0):
"""Design of stabel IIR filter as fit to reciprocal of given frequency response with uncertainty
Least-squares fit of a digital IIR filter to the reciprocal of a given set
of frequency response values with given associated uncertainty. Propagation of uncertainties is
carried o... | d262065fdfe49514101ff65a6c4ea7329e8aef84 | 3,647,126 |
import time
def genMeasureCircuit(H, Nq, commutativity_type, clique_cover_method=BronKerbosch):
"""
Take in a given Hamiltonian, H, and produce the minimum number of
necessary circuits to measure each term of H.
Returns:
List[QuantumCircuits]
"""
start_time = time.time()
term_r... | 1128592a61da7601e41c0328abbf8770f187d009 | 3,647,127 |
def run_test(session, m, data, batch_size, num_steps):
"""Runs the model on the given data."""
costs = 0.0
iters = 0
state = session.run(m.initial_state)
for step, (x, y) in enumerate(reader.dataset_iterator(data, batch_size, num_steps)):
cost, state = session.run([m.cost, m.final_state]... | 681a11e7cd52c0f690a3ad79e69fac4951906796 | 3,647,128 |
def table_to_dict(table):
"""Convert Astropy Table to Python dict.
Numpy arrays are converted to lists. This Can work with multi-dimensional
array columns, by representing them as list of list.
e.g. This is useful in the following situation.
foo = Table.read('foo.fits')
foo.to_pandas(... | 8ad9206222101bbd4d40913e3b43c8ffee9dd6ad | 3,647,129 |
def margin_loss(y_true, y_pred):
"""
Margin loss for Eq.(4). When y_true[i, :] contains not just one `1`, this loss should work too. Not test it.
:param y_true: [None, n_classes]
:param y_pred: [None, num_capsule]
:return: a scalar loss value.
"""
L = y_true * K.square(K.maximum(0., 0.9 - y_... | 252c26949b6255742df90cc9c83a586dfcbb8ac6 | 3,647,130 |
def strip_quotes(string):
"""Remove quotes from front and back of string
>>> strip_quotes('"fred"') == 'fred'
True
"""
if not string:
return string
first_ = string[0]
last = string[-1]
if first_ == last and first_ in '"\'':
return string[1:-1]
return string | 7e10d37e5b5bb4569c88b4de17ffde31a4456e15 | 3,647,131 |
from xclim.core.indicator import registry
def generate_local_dict(locale: str, init_english: bool = False):
"""Generate a dictionary with keys for each indicators and translatable attributes.
Parameters
----------
locale : str
Locale in the IETF format
init_english : bool
If True,... | 34398b297bb269df4668a09d055a69d409fe7bec | 3,647,132 |
import csv
def generate_scheme_from_file(filename=None, fileobj=None, filetype='bson', alimit=1000, verbose=0, encoding='utf8', delimiter=",", quotechar='"'):
"""Generates schema of the data BSON file"""
if not filetype and filename is not None:
filetype = __get_filetype_by_ext(filename)
datacache... | 5a160dabd6141724075e3645342b804b556094d6 | 3,647,133 |
def getTests():
"""Returns a dictionary of document samples for the Entity Types Person, Location, and Organization.
Returns:
[type] -- Returns a dictionary of document samples for the Entity Types Person, Location, and Organization.
"""
personDocument = gtWorkingCopy.find_one({"$and": [{'enti... | 63d1ff2e2f77f33ef634d495a1d318f688a1d51b | 3,647,134 |
def ts_cor(a, b, min_sample = 3, axis = 0, data = None, state = None):
"""
ts_cor(a) is equivalent to a.cor()[0][1]
- supports numpy arrays
- handles nan
- supports state management
:Example: matching pandas
-------------------------
>>> # create sample data:
>>> from pyg_... | 217b8c2196c270ffe22905884586b7466eb59c88 | 3,647,135 |
def get_robin_bndry_conditions(kappa,alpha,Vh):
"""
Do not pass element=function_space.ufl_element()
as want forcing to be a scalar pass degree instead
"""
bndry_obj = get_2d_unit_square_mesh_boundaries()
boundary_conditions=[]
ii=0
for phys_var in [0,1]:
for normal in [1,-1]:
... | 65bb3f9d216ddc146866cf8aa570c2ee73e6d7f2 | 3,647,136 |
def get_prop_datatypes(labels, propnames, MB=None):
"""Retrieve the per-property output datatypes."""
rp = regionprops(labels, intensity_image=MB, cache=True)
datatypes = []
for propname in propnames:
if np.array(rp[0][propname]).dtype == 'int64':
datatypes.append('int32')
e... | b706e724bee867a23c290580f2b865d967946d1b | 3,647,137 |
from typing import Tuple
def parse_html(html: str) -> Tuple[str, str]:
"""
This function parses the html, strips the tags an return
the title and the body of the html file.
Parameters
----------
html : str
The HTML text
Returns
-------
Tuple[str, str]
A tuple of (... | a57e5ae50c8eae16c06333a3de5cc388524504ab | 3,647,138 |
from .._common import header
def block(keyword, multi=False, noend=False):
"""Decorate block writing functions."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
head_fmt = "{:5}{}" if noend else "{:5}{}\n"
out = [head_fmt.format(keyword, header)]
... | 5a0ec1cdec6c2f956d47d13f7beea41814a0db5d | 3,647,139 |
def data(path):
"""Get the file from the specified path from the data directory.
Parameters
----------
path : str
The relative path to the file in the data directory.
Returns
-------
file : File
The requested file.
"""
return send_from_directory(app.config['DATA_DI... | 8f1cde6d248026fbadd2a81519f8f2beed7ab308 | 3,647,140 |
import requests
import logging
def search_software_fuzzy(query, max=None, csv_filename=None):
"""Returns a list of dict for the software results.
"""
results = _search_software(query)
num = 0
softwares = []
while True:
for r in results:
r = _remove_useless_keys(r)
... | ef0124670b02b148f918d3f573e22ca3f646cf96 | 3,647,141 |
def fitCirc(x,y,xerr = None, rIni = None, aveR=False):
"""
Performs a circle fit to data using least square residuals.
Parameters
----------
x : An array of length N.
y : An array of length N.
xerr : None or an array of length N,
If provided, it is the standard-deviation of poi... | fd384526b385f33a8ddd91c7c631afb204afa0db | 3,647,142 |
def get_clients():
"""
Return current clients
---
tags:
- clients
operationId: listClients
produces:
- application/json
schemes: ['http', 'https']
responses:
200:
description: List of clients
schema:
type: array
items:
$re... | e38c8da6094303415bc285f847b9915a4a55f7e7 | 3,647,143 |
def GetInstanceListForHypervisor(hname, hvparams=None,
get_hv_fn=hypervisor.GetHypervisor):
"""Provides a list of instances of the given hypervisor.
@type hname: string
@param hname: name of the hypervisor
@type hvparams: dict of strings
@param hvparams: hypervisor parameters... | b42e19af31d17ff6ca2343ce274572f15950c8d5 | 3,647,144 |
def is_nersc_system(system = system()):
"""Whether current system is a supported NERSC system."""
return (system is not None) and (system in _system_params.keys()) | 6ac968e45f7d586d56b28578eb685f705abafe0f | 3,647,145 |
def is_string_type_suspicious_score(confidence_score, params):
"""
determine if string type confidence score is suspicious in reputation_params
"""
return not isinstance(confidence_score, int) and CONFIDENCE_LEVEL_PRIORITY.get(
params['override_confidence_level_suspicious'], 10) <= CONFIDENC... | 9282ca6e58638fb240ca4c0b752a6dddbaa05255 | 3,647,146 |
def align_embeddings(base_embed, other_embed, sample_size=1):
"""Fit the regression that aligns model1 and model2."""
regression = fit_w2v_regression(base_embed, other_embed, sample_size)
aligned_model = apply_w2v_regression(base_embed, regression)
return aligned_model | 3e017f1a0049cac40f6f7311be2dd531895fc436 | 3,647,147 |
def data_unmerged():
"""
Load HEWL diffraction data from APS 24-ID-C
"""
datapath = ["data", "data_unmerged.mtz"]
return load_dataset(datapath) | f7fb453f617191e19f948fc9097d10bc104478b3 | 3,647,149 |
def copy(object, *args):
"""Copy the object."""
copiedWrapper = wrapCopy( object )
try: copiedWrapper.name = copiedWrapper.name + "_Copy"
except AttributeError: pass
return copiedWrapper.createAndFillObject(None, *args) | fd5e7dfb3e5d6c920ebcb73477d19c9a8be152d3 | 3,647,150 |
def convert_to_n0(n):
"""
Convert count vector to vector of "greater than" counts.
Parameters
-------
n : 1D array, size K
each entry k represents the count of items assigned to comp k.
Returns
-------
n0 : 1D array, size K
each entry k gives the total count of items at... | c75ce9e68bc949ef9fed55283c4dd2a424acadc7 | 3,647,151 |
def application(environ, start_response):
"""Serve the button HTML."""
with open('wsgi/button.html') as f:
response_body = f.read()
status = '200 OK'
response_headers = [
('Content-Type', 'text/html'),
('Content-Length', str(len(response_body))),
]
start_response(status, ... | 97f1f793f234dbd3c29e9c4a791a224ba32c984b | 3,647,152 |
def get_handler():
"""
Return the handler configured by the most recent call to
:func:`configure`.
If :func:`configure` has not yet been called, this returns ``None``.
"""
return current_handler | 0508343f6775544204de9a35186d92ddf829533f | 3,647,153 |
def display_rf_feature_importance(cache, save_location: str = None):
"""
Displays which pixels have the most influence in the model's decision.
This is based on sklearn,ensemble.RandomForestClassifier's feature_importance array
Parameters
----------
save_location : str
the location to s... | 86fc921f4f3ffcd004a2995b0a82f69ba3088e5a | 3,647,154 |
def first_order(A, AB, B):
"""
First order estimator following Saltelli et al. 2010 CPC, normalized by
sample variance
"""
return np.mean(B * (AB - A), axis=0) / np.var(np.r_[A, B], axis=0) | 3a94fdcf17a10242fb07d60e1468a21e17182a25 | 3,647,155 |
import array
def mod_df(arr,timevar,istart,istop,mod_name,ts):
"""
return time series (DataFrame) from model interpolated onto uniform time base
"""
t=timevar.points[istart:istop]
jd = timevar.units.num2date(t)
# eliminate any data that is closer together than 10 seconds
# this was requir... | 6740d74bcfa82a3f813b991b8593b9c2cd5fddb5 | 3,647,156 |
def hydrate_reserve_state(data={}):
"""
Given a dictionary, allow the viewmodel to hydrate the data needed by this view
"""
vm = State()
return vm.hydrate(data) | 203c9c4143713cf8f386a2ac95d91b50a9525a3c | 3,647,157 |
def get_devstudio_versions ():
"""Get list of devstudio versions from the Windows registry. Return a
list of strings containing version numbers; the list will be
empty if we were unable to access the registry (eg. couldn't import
a registry-access module) or the appropriate registry keys weren... | ad02e38e216649cb0f29cfffe256aee7b79d80ea | 3,647,158 |
def mapDictToProfile(wordD, tdm):
"""
Take the document in as a dictionary with word:wordcount format, and map
it to a p profile
Parameters
----------
wordD : Dictionary
Dictionary where the keys are words, and the values are the corrosponding word
count
tdm : termDocMatrix o... | df178e7a6857ff9f85caedbfb5abac77e4f04d55 | 3,647,159 |
from typing import VT
from typing import Tuple
from typing import List
def _to_tikz(g: BaseGraph[VT,ET],
xoffset:FloatInt=0, yoffset:FloatInt=0, idoffset:int=0) -> Tuple[List[str],List[str]]:
"""Converts a ZX-graph ``g`` to a string representing a tikz diagram.
The optional arguments are used by :func:`t... | 0c5fab1fcd0f5db9e8b7d267de5e4b5ea2444046 | 3,647,160 |
def _fix_server_adress(raw_server):
""" Prepend http:// there. """
if not raw_server.startswith("http://"):
raw_server = "http://" + raw_server
return raw_server | 64171be5033930fd5ecb3cd275cc0d859b7e6ca0 | 3,647,161 |
def _parse_output_keys(val):
"""Parse expected output keys from string, handling records.
"""
out = {}
for k in val.split(","):
# record output
if ":" in k:
name, attrs = k.split(":")
out[name] = attrs.split(";")
else:
out[k] = None
return ... | abd739026574b1a3fa87c42d2719d172e36a1c4a | 3,647,162 |
import sqlite3
def check(sync_urls: list, cursor: sqlite3.Cursor, db: sqlite3.Connection, status: str):
"""Checking update in the back.
Args:
sync_urls: URL(s) to be checked as a list
cursor: Cursor object of sqlite3
db: Connection object of sqlite3
status: 'viewed' or 'unview... | a9d7160d7f08d51b4ef596692fa10136f1f21375 | 3,647,163 |
from typing import Dict
from typing import Tuple
from typing import OrderedDict
from typing import Type
import torch
def _get_output_structure(
text: str,
model: PreTrainedModel,
tokenizer: PreTrainedTokenizer,
tokenizer_args: Dict,
) -> Tuple[OrderedDict, Type]:
"""Function needed for saving in a... | 0f268b3fb9208b8f447b0c030744b9ce310049e6 | 3,647,164 |
def encode_board(board):
""" Encode the 2D board list to a 64-bit integer """
new_board = 0
for row in board.board:
for tile in row:
new_board <<= 4
if tile is not None:
new_board += tile.val
return new_board | 2c85964902dc3b2d097e30b71f11e7c17b80297a | 3,647,165 |
def get_symbol(i):
"""Get the symbol corresponding to int ``i`` - runs through the usual 52
letters before resorting to unicode characters, starting at ``chr(192)``.
Examples
--------
>>> get_symbol(2)
'c'
>>> oe.get_symbol(200)
'Ŕ'
>>> oe.get_symbol(20000)
'京'
"""
if ... | e6e9a91fa48e04ed591b22fba62bf2ba6fd5d81f | 3,647,166 |
def longest_common_substring(string1, string2):
"""
Function to find the longest common substring of two strings
"""
m = [[0] * (1 + len(string2)) for i in range(1 + len(string1))]
longest, x_longest = 0, 0
for x in range(1, 1 + len(string1)):
for y in range(1, 1 + len(string2)):
... | f567c629f5bd02143f0ed6bbbdc11f0e59e5f4bd | 3,647,167 |
def elapsed_time_id(trace, event_index: int):
"""Calculate elapsed time by event index in trace
:param trace:
:param event_index:
:return:
"""
try:
event = trace[event_index]
except IndexError:
# catch for 0 padding.
# calculate using the last event in trace
... | 7e94531f13458fc32ca5d971178b79fc13aa65f8 | 3,647,168 |
def build_candidate_digest(proof, leaf_hash):
"""
Build the candidate digest representing the entire ledger from the Proof hashes.
:type proof: dict
:param proof: The Proof object.
:type leaf_hash: bytes
:param leaf_hash: The revision hash to pair with the first hash in the Proof hashes list.
... | 1434cf5e1da9edbd6b41caacd42a67df235267f5 | 3,647,169 |
from typing import Iterable
import torch
def confusion_matrix_eval(cnn, data_loader):
"""Retrieves false positives and false negatives for further investigation
Parameters
----------
cnn : torchvision.models
A trained pytorch model.
data_loader : torch.utils.data.DataLoader
A data... | 411a7d95f7713ff00dbcb7b25db7bd497f427593 | 3,647,170 |
import hashlib
def match_by_hashed_faceting(*keys):
"""Match method 3 - Hashed Faceted Search"""
matches = []
hfs = []
for i in range(len(__lookup_attrs__)):
key = [x for x in keys if x[0] == __lookup_attrs__[i]]
if key:
hfs.append(key[0])
hashed_val = hashlib.sha256(str(hfs).encode('utf-8')).... | b2b849583e732747b42a4d4e7ec56c1090ddb1a8 | 3,647,171 |
def get_derivative_density_matrix(mat_diag,mat_Rabi,sigma_moins_array,**kwargs):
"""
Returns function for t-evolution using the numerical integration of the density matrix
\dot{\rho}=-i(H_eff \rho-\rho H_eff^{\dagger})
+\Gamma \sum_j \sigma_j^_ \rho \sigma_j^+
"""
dim=len(mat_diag)
tunneling... | 1dc1321a6578b6bd9b3c5e937f9c7ed8a787f5a6 | 3,647,172 |
def area_of_polygon(polygon):
"""
Returns the area of an OpenQuake polygon in square kilometres
"""
lon0 = np.mean(polygon.lons)
lat0 = np.mean(polygon.lats)
# Transform to lamber equal area projection
x, y = lonlat_to_laea(polygon.lons, polygon.lats, lon0, lat0)
# Build shapely polygons... | bc57bd58b2ae64b33e34b1bee4582e3c6733fe4d | 3,647,174 |
def build_dataset_values(claim_object, data_value):
""" Build results with different datasets.
Parameters:
claim_object (obj): Onject to modify and add to rows .
data_value (obj): result object
Returns:
Modified claim_boject according to data_value.type
"""
... | f3d267a4e9ac099f6d2313deffb2f45d35b90217 | 3,647,175 |
def gen_csrv_msome(shape, n_parts, mic_rad, min_ip_dst):
"""
Generates a list of 3D coordinates and rotations a CSRV pattern
:param shape: tomogram shape
:param n_parts: number of particles to try to generate
:param mic_rad: microsome radius
:param min_ip_dst: minimum interparticle distance
... | ba0033859e4e18b55d877a6db957b64674171d74 | 3,647,177 |
def electra_model(request):
"""Exposes the command-line option to a test case."""
electra_model_path = request.config.getoption("--electra_model")
if not electra_model_path:
pytest.skip("No --electra_model given")
else:
return electra_model_path | 9273ddfe253c7dc0ab3307b4fb6f009aa806821b | 3,647,178 |
def By_2d_approximation(x, w, d, j):
"""Approximation of By_surface valid except near edges of slab."""
mu0_over_4pi = 1e-7
return 2e-7 * j * d * np.log((w/2 + x) / (w/2 - x)) | 2d64957d0dbec677b6d8b6e825c18ac32b25f7e7 | 3,647,179 |
from typing import Dict
from pathlib import Path
from typing import List
def read_lists(paths: Dict[str, Path]) -> Dict[str, List[str]]:
"""Return a dictionary of song lists read from file.
Arguments:
paths {Dict[str, Path]} -- A dictionary of type returned by find_paths.
Returns:
Dict[s... | 13d6618293e17e5a7388ca9f3d44ffffe913f482 | 3,647,180 |
def learningCurve(theta, X_train, y_train, X_cv, y_cv, lambda_param):
"""
:param X_train:
:param y_train:
:param X_cv:
:param y_cv:
:param lambda_param:
:return:
"""
number_examples = y_train.shape[0]
J_train, J_cv = [], []
for i in range(1, number_examples + 1):
th... | c15f5b3af34beb4c20982c2b339919c50b3336b1 | 3,647,181 |
def reduce_labels(y):
"""Reduziert die Themen und Disziplinen auf die höchste Hierarchiestufe"""
labels = [] # new y
themes = []
disciplines = []
for i, elements in enumerate(y):
tmp_all_labels = []
tmp_themes = []
tmp_disciplines = []
#print("... | 9dc5d3b1d07f7fd7f72911b891533d90bae4ad63 | 3,647,182 |
def api_get_categories(self):
"""
Gets a list of all the categories.
"""
response = TestCategory.objects.all()
s = ""
for cat in response:
s += b64(cat.name) + "," + b64(cat.description) + ","
return HttpResponse(s.rstrip(',')) | f7c523437c8f9d538bb4c5411232458ae3e10450 | 3,647,183 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.