content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def histtab(items, headers=None, item="item", count="count", percent="percent",
cols=None):
"""Make a histogram table."""
if cols is not None:
# items is a Table.
items = items.as_tuples(cols=cols)
if headers is None:
headers = cols + [count, percent]
if head... | ca6bc51d80a179f693ca84fa27753908dcf30ca8 | 3,647,184 |
from rdkit import Chem
def read_sdf_to_mol(sdf_file, sanitize=False, add_hs=False, remove_hs=False):
"""Reads a list of molecules from an SDF file.
:param add_hs: Specifies whether to add hydrogens. Defaults to False
:type add_hs: bool
:param remove_hs: Specifies whether to remove hydrogens. Defaults... | c1917b5dcdad3a88bfd2b181e6c1e757393a4de8 | 3,647,185 |
import math
def search_and_score(milvus_collection_name, mongo_name, field_name, vectors,
topk, nprobe, inner_score_mode: str):
"""
search vectors from milvus and score by inner field score mode
:param milvus_collection_name: collection name will be search
:param mongo_name: mongo... | 885d0e912e76a379dbb55b15945f898c419254bc | 3,647,186 |
def fix_simulation():
""" Create instance of Simulation class."""
return Simulation() | fc36a880342bb6e6be6e6735c3ebd09891d09502 | 3,647,187 |
def build_tree(vectors, algorithm='kd_tree', metric='minkowski', **kwargs):
"""Build NearestNeighbors tree."""
kwargs.pop('algorithm', None)
kwargs.pop('metric', None)
return NearestNeighbors(algorithm=algorithm, metric=metric,
**kwargs).fit(vectors) | 42df608eb0e4e5f420bd0a8391ad748b18eb5f4f | 3,647,188 |
def _expectedValues():
"""
These values are expected for well exposed spot data. The dictionary has a tuple for each wavelength.
Note that for example focus is data set dependent and should be used only as an indicator of a possible value.
keys: l600, l700, l800, l890
tuple = [radius, focus, width... | 7ddd7031313ac5c90f022a6a60c81ad12b4d5dac | 3,647,189 |
import time
def storyOne(player):
"""First Story Event"""
player.story += 1
clear()
print("The dust gathers around, swirling, shaking, taking some sort of shape.")
time.sleep(2)
print("Its the bloody hermit again!")
time.sleep(2)
clear()
print("Hermit: Greetings, " + str(player.nam... | fbaff47f27c5ec474caa73d2f87d77029f4814a4 | 3,647,190 |
import h5py
import torch
import tensorflow
from typing import Dict
from typing import Union
def get_optional_info() -> Dict[str, Union[str, bool]]:
"""Get optional package info (tensorflow, pytorch, hdf5_bloscfilter, etc.)
Returns
-------
Dict[str, Union[str, False]]
package name, package ver... | 07255d4e889b669497628cd9b9c6e102ceb22bbf | 3,647,192 |
import timeit
def epsilon_experiment(dataset, n: int, eps_values: list):
"""
Function for the experiment explained in part (g).
eps_values is a list, such as: [0.0001, 0.001, 0.005, 0.01, 0.05, 0.1, 1.0]
Returns the errors as a list: [9786.5, 1234.5, ...] such that 9786.5 is the error when... | 7aabe10dd97f594533a2da4a901b61790c8435f8 | 3,647,193 |
def infer_scaletype(scales):
"""Infer whether `scales` is linearly or exponentially distributed (if latter,
also infers `nv`). Used internally on `scales` and `ssq_freqs`.
Returns one of: 'linear', 'log', 'log-piecewise'
"""
scales = asnumpy(scales).reshape(-1, 1)
if not isinstance(scales, np.n... | 50e961118a3c97835d279832b399ef72946f4b4a | 3,647,194 |
from googleapiclient.http import build_http
import google
def authorized_http(credentials):
"""Returns an http client that is authorized with the given credentials.
Args:
credentials (Union[
google.auth.credentials.Credentials,
oauth2client.client.Credentials]): The credential... | 21d7a05e9d99f0a6e8414da5925f0d69224f846c | 3,647,195 |
from typing import Optional
from typing import List
from typing import Tuple
from typing import Callable
def add_grating_couplers_with_loopback_fiber_array(
component: Component,
grating_coupler: ComponentSpec = grating_coupler_te,
excluded_ports: Optional[List[str]] = None,
grating_separation: float ... | 4452851ecc05f46ebf46cd92d6edbea9062bae35 | 3,647,196 |
import pytz
from datetime import datetime
import json
def auto_update_function(cities):
"""Auto-update weather function
The function takes a list of the cities to update.
If the error connecting to sources - an error with
a status of 500 and JSON with the cause of the error and URL.
... | 6c57685b1d4a4c62d6225df17dd1bbee6c1a3934 | 3,647,198 |
def absolute_sum_of_changes(x):
"""
Returns the sum over the absolute value of consecutive changes in the series x
.. math::
\\sum_{i=1, \ldots, n-1} \\mid x_{i+1}- x_i \\mid
:param x: the time series to calculate the feature of
:type x: pandas.Series
:return: the value of this featur... | b9cc5109335b754d7d6c8014af5d84e75cd94723 | 3,647,199 |
def start_v_imp(model, lval: str, rval: str):
"""
Calculate starting value for parameter in data given data in model.
For Imputer -- just copies values from original data.
Parameters
----------
model : Model
Model instance.
lval : str
L-value name.
rval : str
R-v... | 113266955e5115b0eb43d32feaa506a2b0c93e14 | 3,647,201 |
def get_image_features(X, y, appearance_dim=32):
"""Return features for every object in the array.
Args:
X (np.array): a 3D numpy array of raw data of shape (x, y, c).
y (np.array): a 3D numpy array of integer labels of shape (x, y, 1).
appearance_dim (int): The resized shape of the app... | fa5cb730227b20b54b8d25270550c9dae9fc1348 | 3,647,202 |
def deactivate_text(shell: dict, env_vars: dict) -> str:
"""Returns the formatted text to write to the deactivation script
based on the passed dictionaries."""
lines = [shell["shebang"]]
for k in env_vars.keys():
lines.append(shell["deactivate"].format(k))
return "\n".join(lines) | 0a75134a55bf9cd8eceb311c48a5547ad373593d | 3,647,203 |
from typing import get_origin
def is_dict(etype) -> bool:
""" Determine whether etype is a Dict """
return get_origin(etype) is dict or etype is dict | a65af54bf6b24c94906765c895c899b18bf5c1eb | 3,647,204 |
import scipy
def t_plot_parameters(thickness_curve, section, loading, molar_mass, liquid_density):
"""Calculates the parameters from a linear section of the t-plot."""
slope, intercept, corr_coef, p, stderr = scipy.stats.linregress(
thickness_curve[section],
loading[section])
# Check if ... | 46d2f65cac5a424b2054359dc8b083d3a2138cc6 | 3,647,205 |
import requests
def get_data(stock, start_date):
"""Fetch a maximum of the 100 most recent records for a given
stock starting at the start_date.
Args:
stock (string): Stock Ticker
start_date (int): UNIX date time
"""
# Build the query string
request_url = f"https://api.pushs... | aafdc913d80346e82a21767cdb7b5e40f2376857 | 3,647,206 |
def depart_people(state, goal):
"""Departs all passengers that can depart on this floor"""
departures = []
for departure in state.destin.items():
passenger = departure[0]
if passenger in goal.served and goal.served[passenger]:
floor = departure[1]
if state.lift_at == ... | f3a18ad9a6f884a57d0be1d0e27b3dfeeb95d736 | 3,647,207 |
def get_topic_for_subscribe():
"""
return the topic string used to subscribe for receiving future responses from DPS
"""
return _get_topic_base() + "res/#" | 346841c7a11f569a7309b087baf0d621a63b8ae9 | 3,647,208 |
from Crypto import Random
def generate_AES_key(bytes = 32):
"""Generates a new AES key
Parameters
----------
bytes : int
number of bytes in key
Returns
-------
key : bytes
"""
try:
return Random.get_random_bytes(bytes)
except ImportError:
print('PyCryp... | 4435aeea860bb3bca847156de0626c2cacde93e0 | 3,647,209 |
def make_column_kernelizer(*transformers, **kwargs):
"""Construct a ColumnKernelizer from the given transformers.
This is a shorthand for the ColumnKernelizer constructor; it does not
require, and does not permit, naming the transformers. Instead, they will
be given names automatically based on their t... | cfddec675782a6e70d1921372961abbb7853fa09 | 3,647,213 |
def plugin_info():
""" Returns information about the plugin.
Args:
Returns:
dict: plugin information
Raises:
"""
return {
'name': 'PT100 Poll Plugin',
'version': '1.9.2',
'mode': 'poll',
'type': 'south',
'interface': '1.0',
'config': _DEF... | f6d54b5ff64013ae17364db604cf1cb6b5204aba | 3,647,214 |
def get_engine(isolation_level=None):
"""
Creates an engine with the given isolation level.
"""
# creates a shallow copy with the given isolation level
if not isolation_level:
return _get_base_engine()
else:
return _get_base_engine().execution_options(isolation_level=isolation_le... | 32e055b2a4a1d0e7ecbc591218bb61c721113a09 | 3,647,215 |
from selenium.webdriver import PhantomJS
def phantomjs_driver(capabilities, driver_path, port):
"""
Overrides default `phantomjs_driver` driver from pytest-selenium.
Default implementation uses ephemeral ports just as our tests but
it doesn't provide any way to configure them, for this reason we basi... | 5c6453f4d753cd765fa7c9fff47b61c6c6efac04 | 3,647,216 |
import time
def parse(address, addr_spec_only=False, strict=False, metrics=False):
"""
Given a string, returns a scalar object representing a single full
mailbox (display name and addr-spec), addr-spec, or a url.
If parsing the entire string fails and strict is not set to True, fall back
to tryin... | b6516d530892a7db405b816987598ce53a0dc776 | 3,647,219 |
import requests
def unfreeze_file(user, data):
""" unfreeze a file.
:return: status code, response data
"""
r = requests.post('%s/unfreeze' % URL, json=data, auth=(user, PASS), verify=False)
return r.status_code, r.json() | 4ee59dd44f42685a02907dec766dc8026f939da2 | 3,647,220 |
def prompt_url(q):
"""
:param q: The prompt to display to the user
:return: The user's normalized input. We ensure there is an URL scheme, a domain, a "/" path,
and no trailing elements.
:rtype: str
"""
return prompt(q, _url_coerce_fn) | dfe810a4552c880d71efabffb2f9167bfce0ad8a | 3,647,221 |
def eval_mnl_logsums(choosers, spec, locals_d, trace_label=None):
"""
like eval_nl except return logsums instead of making choices
Returns
-------
logsums : pandas.Series
Index will be that of `choosers`, values will be
logsum across spec column values
"""
trace_label = tra... | d9b00c2f5f436a0825cbe3bdd60c6b2257c769b3 | 3,647,222 |
def find_zeroed_indices(adjusted, original):
"""Find the indices of the values present in ``original`` but missing in ``adjusted``.
Parameters
----------
adjusted: np.array
original: array_like
Returns
-------
Tuple[np.ndarray]
Indices of the values present in ``original`` but ... | c01b91ec8be0d1bc22aad9042328a451b7424996 | 3,647,223 |
def inventory_update(arr1, arr2):
"""Add the inventory from arr2 to arr1.
If an item exists in both arr1 and arr2, then
the quantity of the item is updated in arr1.
If an item exists in only arr2, then the item
is added to arr1. If an item only exists in
arr1, then that item remains unaffected.... | febba1d2dac6c79fabf4e8aaad8c0fd482478b50 | 3,647,224 |
import re
from bs4 import BeautifulSoup
def racaty(url: str) -> str:
""" Racaty direct link generator
based on https://github.com/SlamDevs/slam-mirrorbot"""
dl_url = ''
try:
link = re.findall(r'\bhttps?://.*racaty\.net\S+', url)[0]
except IndexError:
raise DirectDownloadLinkExcepti... | 8c0df1dd9bf96fcb63be7f59db20ae6c9e4cef00 | 3,647,225 |
from typing import List
def build_tree(tree, parent, counts, ordered_ids):
"""
Recursively splits the data, which contained in the tree object itself
and is indexed by ordered_ids.
Parameters
----------
tree: Tree object
parent: TreeNode object
The last... | 8957ef481ef6b2ba02b6e60c97165a25231d89ae | 3,647,228 |
def get_perf_measure_by_group(aif_metric, metric_name):
"""Get performance measures by group."""
perf_measures = ['TPR', 'TNR', 'FPR', 'FNR', 'PPV', 'NPV', 'FDR', 'FOR', 'ACC']
func_dict = {
'selection_rate': lambda x: aif_metric.selection_rate(privileged=x),
'precision': lambda x: aif_metr... | d4b861c882d6f5502798d211c2ab1322e19cf9b2 | 3,647,229 |
from datetime import datetime
def hello_world(request):
"""Return a greeting."""
return HttpResponse('Hello, world!{now}'.format(
now=datetime.now().strftime('%b %dth, %Y : %M HttpResponses')
)) | bcdf4c504d44883c7afc75c8a76ff052cd0b246d | 3,647,230 |
import mimetypes
import zlib
def getfile(id, name):
"""
Retorna um arquivo em anexo.
"""
mime = mimetypes.guess_type(name)[0]
if mime is None:
mime = "application/octet-stream"
c = get_cursor()
c.execute(
"""
select files.ticket_id as ticket_id,
files.si... | 1ce8322301b33a0d6762aa545344d4c0fe38269c | 3,647,231 |
def get_default_wavelet():
"""Sets the default wavelet to be used for scaleograms"""
global DEFAULT_WAVELET
return DEFAULT_WAVELET | 0c403b5b7a21bedbd55c0cbd6faa6a3648c3a0cc | 3,647,232 |
def check_output(file_path: str) -> bool:
"""
This function checks an output file, either from geomeTRIC or
from Psi4, for a successful completion keyword. Returns
True if the calculation finished successfully, otherwise
False.
"""
with open(file_path, "r") as read_file:
text = read_... | 2f0dea67216aff945b1b0db74e0131022acc3019 | 3,647,233 |
def dumps(value):
"""
Dumps a data structure to TOML source code.
The given value must be either a dict of dict values, a dict,
or a TOML file constructed by this module.
"""
if not isinstance(value, TOMLFile):
raise RuntimeError(
'Can only dump a TOMLFile instance loaded by... | f92b906b502bc2b0ba2b8bf3840083bafce14086 | 3,647,234 |
def calc_graph(dict_graph):
"""
creates scatter of comfort and curves of constant relative humidity
:param dict_graph: contains comfort conditions to plot, output of comfort_chart.calc_data()
:type dict_graph: dict
:return: traces of scatter plot of 4 comfort conditions
:rtype: list of plotly.g... | 19a277db0f59e2b871130099eab3b714bd5b94b9 | 3,647,235 |
def generate_arrays(df, resize=True, img_height=50, img_width=200):
""" Generates image array and labels array from a dataframe """
num_items = len(df)
images = np.zeros((num_items, img_height, img_width), dtype=np.float32)
labels = [0] * num_items
for i in range(num_items):
input_... | 2a50fd84d5b8da2845205b65cd12f61868bd421d | 3,647,237 |
def compute_cosine_distance(Q, feats, names):
"""
feats and Q: L2-normalize, n*d
"""
dists = np.dot(Q, feats.T)
# print("dists:",dists)
# exit(1)
idxs = np.argsort(dists)[::-1]
rank_dists = dists[idxs]
rank_names = [names[k] for k in idxs]
return (idxs, rank_dists, rank_n... | e15007fb6fc73aab27db00d7cf283300077dd1c7 | 3,647,238 |
def phase(ifc, inc_pt, d_in, normal, z_dir, wvl, n_in, n_out):
""" apply phase shift to incoming direction, d_in, about normal """
try:
d_out, dW = ifc.phase(inc_pt, d_in, normal, z_dir, wvl, n_in, n_out)
return d_out, dW
except ValueError:
raise TraceEvanescentRayError(ifc, inc_pt, ... | 6289674f20718ed4e1e78b1a4da0fe5d4b89df75 | 3,647,239 |
from typing import Iterator
def generate_udf(spec: "rikai.spark.sql.codegen.base.ModelSpec"):
"""Construct a UDF to run sklearn model.
Parameters
----------
spec : ModelSpec
the model specifications object
Returns
-------
A Spark Pandas UDF.
"""
def predict(model, X):
... | ceab18240abc73c361108b859817723c08bdd0e3 | 3,647,240 |
def ssl_loss_mean_teacher(labels_x, logits_x, logits_teacher, logits_student):
"""
Computes two cross entropy losses based on the labeled and unlabeled data.
loss_x is referring to the labeled CE loss and loss_u to the unlabeled CE loss.
Args:
labels_x: tensor, contains labels correspondi... | 016192ea6cf1002a0aa8735003e76a7c2af7526c | 3,647,241 |
from typing import Tuple
def _sch_el(self, *wert, **kwargs):
"""Element einer Schar; für einen Parameter"""
if kwargs.get('h'):
print("\nElement einer Schar von Matrizen\n")
print("Aufruf matrix . sch_el( wert )\n")
print(" matrix Matrix")
... | 8e88e04ee6e4f1b4be658c120a1bc66060aafc81 | 3,647,242 |
def scsilun_to_int(lun):
"""
There are two style lun number, one's decimal value is <256 and the other
is full as 16 hex digit. According to T10 SAM, the full 16 hex digit
should be swapped and converted into decimal.
For example, SC got zlinux lun number from DS8K API, '40294018'. And it
should... | 2022938ccb5abbc89d5fb6f5f109d629e980c0ba | 3,647,244 |
def ordered_indices(src_sizes,tgt_sizes,common_seed,shuffle=True,buckets=None):
"""Return an ordered list of indices. Batches will be constructed based
on this order."""
if shuffle:
indices = np.random.RandomState(common_seed).permutation(len(src_sizes)).astype(np.int64)
else:
indices = ... | 469d7f963134d7df9c72be07182e7ba4e2533472 | 3,647,245 |
import io
def get_predictions(single_stream, class_mapping_dict, ip, port, model_name):
"""Gets predictions for a single image using Tensorflow serving
Arguments:
single_stream (dict): A single prodigy stream
class_mapping_dict (dict): with key as int and value as class name
ip (str):... | 631c21878df03c240d32556279d9b31ebc6d723f | 3,647,246 |
import itertools
def interaction_graph(matrix):
"""Create a networkx graph object from a (square) matrix.
Parameters
----------
matrix : numpy.ndarray
| Matrix of mutual information, the information for the edges
is taken from the upper matrix
Returns
-------
graph : ne... | d1da8b6f0e269c1118f56840173e7895d5efb587 | 3,647,247 |
import torch
def weight_inter_agg(num_relations, self_feats, neigh_feats, embed_dim, weight, alpha, n, cuda):
"""
Weight inter-relation aggregator
Reference: https://arxiv.org/abs/2002.12307
:param num_relations: number of relations in the graph
:param self_feats: batch nodes features or embedding... | c664bd88fbd8abf30b050ca93c264a3e5ead147b | 3,647,250 |
def ho2ro(ho):
"""Axis angle pair to Rodrigues-Frank vector."""
return Rotation.ax2ro(Rotation.ho2ax(ho)) | be3ce1dd6ac9e0815a4cb50ff922f0816320fcae | 3,647,251 |
def get_ratio(old, new):
# type: (unicode, unicode) -> float
"""Return a "similiarity ratio" (in percent) representing the similarity
between the two strings where 0 is equal and anything above less than equal.
"""
if not all([old, new]):
return VERSIONING_RATIO
if IS_SPEEDUP:
r... | 28648934701445c9066e88b787465ccc21aa6ba5 | 3,647,252 |
def sample2D(F, X, Y, mask=None, undef_value=0.0, outside_value=None):
"""Bilinear sample of a 2D field
*F* : 2D array
*X*, *Y* : position in grid coordinates, scalars or compatible arrays
*mask* : if present must be a 2D matrix with 1 at valid
and zero at non-valid points
*undef_va... | 746782b7712ff28f76db280e9c55977e81a370a5 | 3,647,253 |
def rotations_to_radians(rotations):
"""
converts radians to rotations
"""
return np.pi * 2 * rotations | 15beacbccbbe6d22ac4f659aa5cf22a4e63b503e | 3,647,255 |
def _expect_ket(oper, state):
"""Private function to calculate the expectation value of
an operator with respect to a ket.
"""
oper, ket = jnp.asarray(oper), jnp.asarray(state)
return jnp.vdot(jnp.transpose(ket), jnp.dot(oper, ket)) | c7b261852f0e77bda7dcb3cae53939f637e1dca7 | 3,647,256 |
def resnet152(pretrained=False, last_stride=1, model_path=''):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet(pretrained=pretrained... | ad2837271ef98861dc8f2c3eae9687fc71d435b6 | 3,647,257 |
def check_wheel_move_during_closed_loop(data, wheel_gain=None, **_):
""" Check that the wheel moves by approximately 35 degrees during the closed-loop period
on trials where a feedback (error sound or valve) is delivered.
Metric: M = abs(w_resp - w_t0) - threshold_displacement, where w_resp = position at r... | 6b696158a086cf899cc23d207b0c6142f1f50a65 | 3,647,258 |
def next_fast_len(target: int) -> int:
"""
Find the next fast size of input data to `fft`, for zero-padding, etc.
SciPy's FFTPACK has efficient functions for radix {2, 3, 4, 5}, so this
returns the next composite of the prime factors 2, 3, and 5 which is
greater than or equal to `target`. (These ar... | e00aa69ffd425489cceef5f50b77c977e18b4a1f | 3,647,259 |
def human_format(val : int, fmt = '.1f') -> str :
""" convert e.g. 1230 -> 1.23k """
units = ['', 'K', 'M', 'G']
base = min(int(np.floor(np.log10(val)))//3, len(units))
if base==0:
return str(val)
val = val/10**(3*base)
res = ('{{:{}}} {}'.format(fmt, units[base])).format(val)
ret... | 73dfffa4f9afaa2c294ebceeabda4947d3a6cbe1 | 3,647,260 |
def random_choice(number: int) -> bool:
"""
Generate a random int and compare with the argument passed
:param int number: number passed
:return: is argument greater or equal then a random generated number
:rtype: bool
"""
return number >= randint(1, 100) | d88e7e23bcff89b0f33a43e34b2ba640589fb0e3 | 3,647,262 |
from typing import Any
def request_l3_attachments(session, apic) -> Any:
"""Request current policy enformation for encap for Outs"""
root = None
uri = f"https://{apic}/api/class/l3extRsPathL3OutAtt.xml"
response = session.get(uri, verify=False)
try:
root = ET.fromstring(response.text)
... | 0623ffde29a67e0f96ec5284b0a27109bff5b1aa | 3,647,263 |
def bet_plot(
pressure,
bet_points,
minimum,
maximum,
slope,
intercept,
p_monolayer,
bet_monolayer,
ax=None
):
"""
Draw a BET plot.
Parameters
----------
pressure : array
Pressure points which will make up the x axis.
bet_points : array
BET-tr... | 751abe12683ceff72066b3b2cd6938d6e9a67507 | 3,647,264 |
from typing import Optional
def paged_response(
*,
view: viewsets.GenericViewSet,
queryset: Optional[QuerySet] = None,
status_code: Optional[int] = None,
):
"""
paged_response can be used when there is a need to paginate a custom
API endpoint.
Usage:
class UsersView(ModelViewS... | 73c38abbedf8f22a57bb6bda1b42d6013520885a | 3,647,265 |
def getObjectPositions(mapData, threshold, findCenterOfMass = True):
"""Creates a segmentation map and find objects above the given threshold.
Args:
mapData (:obj:`numpy.ndarray`): The 2d map to segment.
threshold (float): The threshold above which objects will be selected.
findCent... | d070f70270837ec1b1ff6f29eedc21deb2b4846c | 3,647,266 |
def specific_humidity(p,RH,t,A=17.625,B=-30.11,C=610.94,masked=False):
"""
From Mark G. Lawrence, BAMS Feb 2005, eq. (6)
q = specific_humidity(p,RH,t,A,B,C)
inputs: p = pressure (Pa)
RH = relative humidity (0-1)
t = temperature (K)
keywords: A, B and C are optional fi... | 2cfd4cad24a0f412d8021fdfdbc9874823093dcc | 3,647,267 |
from typing import Optional
from typing import Literal
def build_parser():
"""
Build a pyparsing parser for our custom topology description language.
:return: A pyparsing parser.
:rtype: pyparsing.MatchFirst
"""
ParserElement.setDefaultWhitespaceChars(' \t')
nl = Suppress(LineEnd())
i... | 1eccb042b18c3c53a69a41e711a4347a6edf55b9 | 3,647,269 |
import math
def decode_owner(owner_id: str) -> str:
"""Decode an owner name from an 18-character hexidecimal string"""
if len(owner_id) != 18:
raise ValueError('Invalid owner id.')
hex_splits = split_by(owner_id, num=2)
bits = ''
for h in hex_splits:
bits += hex_to_bin(h)
test_owner = ''
for seq... | 1460ebe3dfd2f36aa2f5e42b28b2d7651d0d2cee | 3,647,270 |
def _get_back_up_generator(frame_function, *args, **kwargs):
"""Create a generator for the provided animation function that backs up
the cursor after a frame. Assumes that the animation function provides
a generator that yields strings of constant width and height.
Args:
frame_function: A funct... | a395e91864115f69dc0a7d8d8a3bb2eb90d957e9 | 3,647,271 |
from typing import Any
from typing import Optional
def from_aiohttp(
schema_path: str,
app: Any,
*,
base_url: Optional[str] = None,
method: Optional[Filter] = None,
endpoint: Optional[Filter] = None,
tag: Optional[Filter] = None,
operation_id: Optional[Filter] = None,
skip_deprecat... | 11c7d2cf9e19e8876ef45118f3842b51fbc734b9 | 3,647,272 |
def compute_recall(true_positives, false_negatives):
"""Compute recall
>>> compute_recall(0, 10)
0.0
>>> compute_recall(446579, 48621)
0.901815
"""
return true_positives / (true_positives + false_negatives) | 876bee73150d811e6b7c1a5de8d8e4349105c59b | 3,647,274 |
def get_highest_seat_id():
"""
Returns the highest seat ID from all of the boarding passes.
"""
return max(get_seat_ids()) | 0e8f95c9455869d283acfb9d6230c8a6f2ca10eb | 3,647,275 |
def error_function_index(gpu_series, result_series):
"""
utility function to compare GPU array vs CPU array
Parameters
------
gpu_series: cudf.Series
GPU computation result series
result_series: pandas.Series
Pandas computation result series
Returns
-----
double
... | 1886df532808be8e54ffc2448c74fcb415b4424a | 3,647,276 |
def get_tipo_aqnext(tipo) -> int:
"""Solve the type of data used by DJANGO."""
tipo_ = 3
# subtipo_ = None
if tipo in ["int", "uint", "serial"]:
tipo_ = 16
elif tipo in ["string", "stringlist", "pixmap", "counter"]:
tipo_ = 3
elif tipo in ["double"]:
tipo_ = 19
elif... | d5a066b98aa56785c4953a7ec8d7052e572e5630 | 3,647,277 |
from typing import List
from typing import Dict
def fetch_indicators_command(client: Client) -> List[Dict]:
"""Wrapper for fetching indicators from the feed to the Indicators tab.
Args:
client: Client object with request
Returns:
Indicators.
"""
indicators = fetch_indicators(clie... | eb59b68362e0b30fdc5643259a1ddf757b7afce1 | 3,647,278 |
def hr_lr_ttest(hr, lr):
""" Returns the t-test (T statistic and p value), comparing the features for
high- and low-risk entities. """
res = stats.ttest_ind(hr.to_numpy(), lr.to_numpy(), axis=0, nan_policy="omit", equal_var=False)
r0 = pd.Series(res[0], index=hr.columns)
r1 = pd.Series(res[1], inde... | 86ccbbf3119ce7fc809ec68d50b57d514efb29b2 | 3,647,279 |
def _is_empty(str_: str) -> bool:
"""文字列が空か
文字列が空であるかを判別する
Args:
str_ (str): 文字列
Returns:
bool: 文字列が空のときはTrue,
空でないときはFalseを返す.
"""
if str_:
return False
return True | f0eff540767028a80a3042e2d5bc6951ad28fe24 | 3,647,280 |
import random
def energy_generate_random_range_dim2(filepath,dim_1_low,dim_1_high,dim_2_low,dim_2_high,num=500):
"""
6, 8 and 10
"""
queryPool=[]
query=[]
for _ in range(num):
left1 = random.randint(dim_1_low, dim_1_high)
right1 = random.randint(left1, dim_1_high)
query... | cdcafba427dbbab9b9e318f58f54a3a3c834bbd3 | 3,647,281 |
from typing import Optional
from typing import Sequence
def get_waas_policies(compartment_id: Optional[str] = None,
display_names: Optional[Sequence[str]] = None,
filters: Optional[Sequence[pulumi.InputType['GetWaasPoliciesFilterArgs']]] = None,
ids: O... | 4ab181b9776226a96b93757feb124c10b68eacc8 | 3,647,283 |
def _get_output_type(output):
"""Choose appropriate output data types for HTML and LaTeX."""
if output.output_type == 'stream':
html_datatype = latex_datatype = 'ansi'
text = output.text
output.data = {'ansi': text[:-1] if text.endswith('\n') else text}
elif output.output_type == 'er... | 4940f931f7ac3b87b68a5e84a5038feea331dac1 | 3,647,284 |
import gc
def cat_train_validate_on_cv(
logger,
run_id,
train_X,
train_Y,
test_X,
metric,
kf,
features,
params={},
num_class=None,
cat_features=None,
log_target=False,
):
"""Train a CatBoost model, validate using cross validation. If `test_X` has
a valid value, ... | d4a1248463d7fa1f9f8f192cc9fa02f8fcdcf020 | 3,647,285 |
def find_left(char_locs, pt):
"""Finds the 'left' coord of a word that a character belongs to.
Similar to find_top()
"""
if pt not in char_locs:
return []
l = list(pt)
while (l[0]-1, l[1]) in char_locs:
l = [l[0]-1, l[1]]
return l | 8e924f301203bcad2936d4cf4d82c6e21cbebb16 | 3,647,286 |
import pathlib
import urllib
def make_file_url(file_id, base_url):
"""Create URL to access record by ID."""
url_parts = list(urlparse.urlparse(base_url))
url_parts[2] = pathlib.posixpath.join(
DATAVERSE_API_PATH, DATAVERSE_FILE_API
)
args_dict = {'persistentId': file_id}
url_parts[4] =... | e4b60f2cfd31a9617ee775d7d8ca0caaa9c692fd | 3,647,287 |
def std_func(bins, mass_arr, vel_arr):
"""
Calculate std from mean = 0
Parameters
----------
bins: array
Array of bins
mass_arr: array
Array of masses to be binned
vel_arr: array
Array of velocities
Returns
---------
std_arr: array
Standard devia... | 13e53952af3106fb7891859f81c146d4bc92703b | 3,647,288 |
def log_neg(rho,mask=[1,0]):
""" Calculate the logarithmic negativity for a density matrix
Parameters:
-----------
rho : qobj/array-like
Input density matrix
Returns:
--------
logneg: Logarithmic Negativity
"""
if rho.type != 'oper':
raise TypeError("In... | b8ed0cd54dd879985ef6265085b789e91beceba7 | 3,647,289 |
def create_polygon(pixels_selected: set, raster_path: str) -> gpd.GeoDataFrame:
"""
It allows to transform each of the indexes of the
pixel data in coordinates for further processing
the answer polygon
Parameters
--------------
pixels_selected: set
Set with the pixels selected for t... | f2484afcfb73a3adbdaaeacf25287c1c2ce1584a | 3,647,290 |
import copy
def read_output(path_elec,path_gas):
"""
Used to read the building simulation I/O file
Args:
path_elec: file path where data is to be read from in minio. This is a mandatory parameter and in the case where only one simulation I/O file is provided, the path to this file should be indi... | 7ec4ce2d9776946e310fd843e722d0189c4ebcb2 | 3,647,291 |
def parse_lmap(filename, goal, values):
"""Parses an LMAP file into a map of literal weights, a LiteralDict object,
the literal that corresponds to the goal variable-value pair, and the
largest literal found in the file."""
weights = {}
max_literal = 0
literal_dict = LiteralDict()
for line i... | db6a0e5f56817e7dd0ef47b5e72b2ea30256b2a3 | 3,647,292 |
def read_image(path: str):
"""
Read an image file
:param path: str. Path to image
:return: The image
"""
return imageio.imread(path) | 8f3342f2454a3d3e821962d7040eebdbaee502cf | 3,647,293 |
def electrolyte_conductivity_Capiglia1999(c_e, T, T_inf, E_k_e, R_g):
"""
Conductivity of LiPF6 in EC:DMC as a function of ion concentration. The original
data is from [1]. The fit is from Dualfoil [2].
References
----------
.. [1] C Capiglia et al. 7Li and 19F diffusion coefficients and therma... | ea487399aba6cd1e70d1b5c84dd6f9294f8754b9 | 3,647,294 |
import random
def random_bdays(n):
"""Returns a list of integers between 1 and 365, with length n.
n: int
returns: list of int
"""
t = []
for i in range(n):
bday = random.randint(1, 365)
t.append(bday)
return t | 7871548db569d435a5975bfa118ad6c262406333 | 3,647,295 |
def int_to_charset(val, charset):
""" Turn a non-negative integer into a string.
"""
if not val >= 0:
raise ValueError('"val" must be a non-negative integer.')
if val == 0: return charset[0]
output = ""
while val > 0:
val, digit = divmod(val, len(charset))
output += chars... | ec30e014aaf42b6cc3904f13776b4226b0b75a5b | 3,647,296 |
def search(tabela, *, parms='*', clause=None):
""" Função que recebe como parâmetro obrigatório o nome da tabela a ser consultada,
como parâmetro padrão recebe os filtros da pesquisa e retorna todas as linhas encontradas """
banco = Banco()
banco.connect()
banco.execute(f"SELECT {parms} FROM {t... | 0cb0dad5fe0661ee7027ab8b43c28b0351d42a48 | 3,647,297 |
def hash(data):
"""run the default hashing algorithm"""
return _blacke2b_digest(data) | e12433388a0d392f16a8e11ba812629ed4573ace | 3,647,299 |
def _insert_text_func(s, readline):
"""Creates a function to insert text via readline."""
def inserter():
readline.insert_text(s)
readline.redisplay()
return inserter | 06532be051cb69b92fa79ef339edb733b8f31c15 | 3,647,300 |
def dumps(ndb_model, **kwargs):
"""Custom json dumps using the custom encoder above."""
return NdbEncoder(**kwargs).encode(ndb_model) | 0f0a74cdaedd81a95874f745ad1bc24881d1fb73 | 3,647,301 |
def create_critic_train_op(hparams, critic_loss, global_step):
"""Create Discriminator train op."""
with tf.name_scope('train_critic'):
critic_optimizer = tf.train.AdamOptimizer(hparams.critic_learning_rate)
output_vars = [
v for v in tf.trainable_variables() if v.op.name.startswith(... | 4c33ba79dacebff375971c123e5bbafd34f5ab91 | 3,647,305 |
def interpolate(data, tstep):
"""Interpolate limit order data.
Uses left-hand interpolation, and assumes that the data is indexed by timestamp.
"""
T, N = data.shape
timestamps = data.index
t0 = timestamps[0] - (timestamps[0] % tstep) # 34200
tN = timestamps[-1] - (timestamps[-1] % tstep)... | ae1fde01529a4d11ea864b0f5757c9cde096a142 | 3,647,306 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.