content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import ast
import json
def strtojson(intxt):
"""str to json function"""
out = {}
try:
out = ast.literal_eval(intxt)
except ValueError:
out = json.loads(intxt)
except SyntaxError as ex:
raise Exception("SyntaxError: Failed to literal eval dict. Err:%s " % ex) from ex
ret... | d4b1ba11dd6a064f46d4e07284b54f59072e15ef | 3,605,343 |
def build_input_data(u_text, i_text, vocabulary_u, vocabulary_i):
"""
Maps sentences and labels to vectors based on a vocabulary.
就是把一个个review的单词换成vocab里的id
"""
l = len(u_text)
u_text2 = {}
for i in u_text.keys():
u_reviews = u_text[i]
u = np.array([[vocabulary_u[word] for wo... | 8b0aa34944357d061742b8c16350bf6717cb7458 | 3,605,344 |
def calculate_numerical(atoms, spring_constant, eq_len, time):
""" Calculates the Newtonian using a form of Euler's Method. Returns
the first atoms force, position, and velocity.
:param atoms: [description]
:type atoms: [type]
:param spring_constant: [description]
:type spring_constant: [type]
... | 88383d7d73bae830f1b951816989292a298dd6bd | 3,605,345 |
def _matrix_constrainer(support):
"""Helper for `constrainer` for matrix supports."""
constrainers = {
Support.MATRIX_UNCONSTRAINED:
identity_fn,
Support.MATRIX_POSITIVE_DEFINITE:
positive_definite,
Support.MATRIX_LOWER_TRIL_POSITIVE_DEFINITE:
lower_tril_positive_defi... | e7e8928d3756c73af96fd88bbb3e745e6884e2dd | 3,605,346 |
def _fetch_development_fmri_participants(data_dir, url, verbose):
"""Helper function to fetch_development_fmri.
This function helps in downloading and loading participants data from .tsv
uploaded on Open Science Framework (OSF).
The original .tsv file contains many columns but this function picks only... | 13db7ae5839c9ad5c10f45d1828c92c2bf8cb888 | 3,605,347 |
import hashlib
def git_hash_data(data, typ='blob'):
"""Calculate the git-style SHA1 for some data.
Only supports 'blob' type data at the moment.
"""
assert typ == 'blob', 'Only support blobs for now'
return hashlib.sha1(b'blob %d\0%s' % (len(data), data)).hexdigest() | b3195de0c04444a811308e8b2b79b5d136095ea8 | 3,605,348 |
def jaccard_index(a, b):
"""a and b must be binary!"""
aaa = np.asarray(a)
baa = np.asarray(b)
u = aaa.copy()
u[baa > 0] = 1
return float(np.sum(aaa * baa)) / u.sum() | bf944eeffa2606aba523a202edac5de81afc2049 | 3,605,349 |
from datetime import datetime
def create_post(post_author, post_title, days, slug):
"""
Create a post with the given `post_text` and published the
given number of `days` offset to now (negative for post published
in the past, positive for post that have yet to be published).
"""
time = timezon... | e309e0a3df070891a7b3f4956d2cfdca845b0222 | 3,605,350 |
def db_batch_lookup(kind, entity_names):
"""Get multiple entities from the datastore
Args:
kind: GCP datastore entity kind.
entity_names: entity names to find.
Returns:
The found entities if any.
"""
logger.info("In db_batch_lookup handler.")
keys = [db.key(kind, entity_n... | 9c2f8094861dfd724254f2f26f4310fbe7cdf4d4 | 3,605,351 |
def read_sa_cmd_helps_from_register_response(pdu: list) -> list:
"""Read TaiSEIA SA device supported commands from register response protocol data."""
register = SARegisterPacket.from_pdu(pdu)
report = []
for service in register.services:
_help = service.to_cmd_help()
assert isinstance(_... | 8876113bab72324899b71269a757ca2987e9a835 | 3,605,352 |
def fill_large_gaps(ds, shift):
"""
Fill up large gaps with load data from the previous week.
This function fills gaps ragning from 3 to 168 hours (one week).
"""
shift = Delta(shift)
nhours = shift / np.timedelta64(1, 'h')
if (consecutive_nans(ds) > nhours).any():
logger.warning('T... | b983b032063747eef51a63e961f28fdb7741a343 | 3,605,353 |
def _vector_clock_equal(clock1, clock2):
"""
Compares two vector clocks, ignoring the timestamp field, which may be skewed.
"""
clock1_entries = dict((entry.node_id, entry.version) for entry in clock1.entries)
clock2_entries = dict((entry.node_id, entry.version) for entry in clock2.entries)
ret... | 2402724d75f7e3b48b05764e056756bdb883ef2e | 3,605,354 |
def random(options=('trapezoid', 'sin'),
fractionwithextremelc=0.01, fractionwithrotation=None,
fractionwithtrapezoid=None, fractionwithcustom=0.0, **kw):
"""
random() returns random Lightcurve.
random() makes use of these keyword arguments:
options=['trapezoid', 'sin'] (a li... | 55133ebb6b329ae7b0773bb0dd6a939a268bc61e | 3,605,355 |
def create_lattice(optics_mode=default_optics_mode, simplified=False):
"""Return lattice object."""
# -- selection of optics mode --
strengths = get_optics_mode(optics_mode=optics_mode)
# -- shortcut symbols --
marker = _pyacc_ele.marker
drift = _pyacc_ele.drift
sextupole = _pyacc_ele.sextu... | 074b1dc12099b56beb3c7affe5b1818469926e52 | 3,605,356 |
def npv_score(y_true, y_pred):
"""
A function provides npv given the prediction and the truth
"""
tn, _, fn, _ = confusion_matrix(y_true = y_true,
y_pred = y_pred).ravel()
return tn/(tn + fn) | 0cc951f296fb5e23bc05df0963edb9602b3e650b | 3,605,358 |
def load_data(filename_path, class_id_path, dataset_path, embeddings_path, size):
"""Loads the Dataset.
"""
class_id, filenames = load_class_ids_filenames(class_id_path, filename_path)
embeddings = load_text_embeddings(embeddings_path)
bbox_dict = load_bbox(dataset_path)
x, y, embeds = [], [], []
for i, filena... | 247a818ed5c08a3ddb2117ea1df5ec412da74195 | 3,605,359 |
async def root():
"""
Show this docs
"""
return RedirectResponse(url='/docs') | de97f3eb111747044847b25aca8653ed0cb30e08 | 3,605,360 |
def Euler2Rotation(phi, theta, psi):
"""
Converts euler angles to rotation matrix (R_b^i, i.e., body to inertial)
"""
# only call sin and cos once for each angle to speed up rendering
c_phi = np.cos(phi)
s_phi = np.sin(phi)
c_theta = np.cos(theta)
s_theta = np.sin(theta)
c_psi = np.c... | 73890a603a5a0639e0cd9f57beb3f41232784dfc | 3,605,361 |
from typing import OrderedDict
def groupAddData(data, group_by="run.configuration,sample.description"):
"""
Addition of counts and monitor from different datasets,
assuming all datasets were taken under identical conditions
(except for count time)
Groups by the metadata fields in "group_by" (comm... | 8f4f44034a71bf7e92b059418a815dfe1d930241 | 3,605,362 |
import pickle
from datetime import datetime
def find_dex(sar_file, dex_list, dex_type):
"""
Find the corresponding DEX file for a given sar_file.
:param sar_file: path to a SAR file
:param dex_list: list of paths to DEX files
:param dex_type: DEXA or DEXI
:return: data contained in the corresp... | be5c53e33df1e4dd0f9fa9b73718dd3a548d5095 | 3,605,363 |
import select
def latest_remote_checkpoints(db, user_id):
"""
Get the latest version of each file for the user.
"""
query_fields = [
remote_checkpoints.c.id,
remote_checkpoints.c.path,
]
query = select(query_fields).where(
remote_checkpoints.c.user_id == user_id,
)... | bc788a47bcb0e1812aa41849938a086c8c0b3d1f | 3,605,364 |
import array
def ReadTrans(filename, fh_info):
"""Read the self-energy index file Sigind and the local transformation matrix CF from a file"""
fh = open(filename, 'r')
data = fh.readlines()
(n1,n2) = map(int, data[0].split()[:2])
Sigind=[]
for i in range(n1):
Sigind.append( map(i... | d9090e83ded597dfc86c96224b8dcb49cdb51068 | 3,605,365 |
import urllib
import webbrowser
import json
def authenticate(scopes="public_profile"):
"""
Open browser to allow user to login, get authentication code,
exchange to get (and return) access token.
"""
scopes = urllib.quote(scopes)
LOGIN_URL = "https://www.facebook.com/dialog/oauth" \
... | ad1fa4d0a1e6bb6c3ee336dc290215ccc48699b1 | 3,605,366 |
def wltc_class_pipeline(aug: autog.Autograph = None, **pipeline_kw) -> Pipeline:
"""
Pipeline to provide `p_m_ratio` (Annex 1, 2).
.. graphtik::
:height: 600
:hide:
:name: wltc_class_pipeline
>>> pipe = wltc_class_pipeline()
"""
aug = aug or wio.make_autograph()
... | 70c13592e1bbecc43a283fc3d6958c02135afad0 | 3,605,368 |
from pathlib import Path
def db_init(db_file: Path) -> sessionmaker:
"""
Initializes the database and returns a session factory
"""
logger.info(f"Creating database file: {db_file}")
engine = create_engine(f"sqlite:///{db_file}")
Base.metadata.create_all(engine)
return sessionmaker(bind=e... | 4bf0c7a64d4d747459d858ffaf9fccf42e0aca83 | 3,605,369 |
import requests
def submit_textarea():
"""
Endpoint to create a new transaction via our application
"""
global errors
name = request.form["name"]
year = request.form["year"]
brand = request.form["brand"]
post_desc = request.form["description"]
materials = request.form["materials"... | 8496bbee086242ccc1bfdd2d37dce9088dcf85b2 | 3,605,370 |
def handle_response(response):
"""
Correct the response datatype if returned incorrectly
:response Requests.models.Response: a response from the api
:return: response ready for consumption from wrapper
"""
print
data = response.json()
if data['err_no'] == 0:
return data['data']
... | f18b26d2df8e6abf7625d1ad1153877eae6ecd64 | 3,605,371 |
def presale_fund_collector(chain, presale_freeze_ends_at, team_multisig) -> Contract:
"""In actual ICO, the price is doubled (for testing purposes)."""
args = [
team_multisig,
presale_freeze_ends_at,
to_wei("50", "ether"), # Minimum presale buy in is 50 ethers
]
tx = {
... | 93140948017c0bbefb44f66d73e1e4c33ea972bf | 3,605,373 |
def check(token_fst,entries):
"""Return the list of conflicting attribute-value pairs between a
treebank feature structure for a token and a list of dictionary
entries for this token. If the structures unify with at least one
entry, return the empty list. Otherwise return the inconsistencies
collect... | 0f8efc54ef07c3983cbb1b0112a0fdfc1a7f033f | 3,605,376 |
def transpose(table):
"""Returns: copy of table with rows and columns swapped
Precondition: table is a (non-ragged) 2d List"""
new_table = []
n_row = len(table)
n_col = len(table[0])
for col in range(n_col):
each_col = []
for row in range(n_row):
each_col.append(table... | 11c74863d8b1941f1a74fb1c054f67b8dd2f22e8 | 3,605,377 |
import math
def my_shaded_trace(
fig: go.Figure, df: DataFrame, d: str, color: str, grps: list, key: str, col=None, row=None, show_legend=True
):
"""
Add a shaded trace to a plotly figure
Parameters
----------
fig : go.Figure
The figure to which the trace will be added
df : DataFr... | 66cd6b6bc88b6a40337366758895aa131ed09758 | 3,605,378 |
def resize_with_aspectratio(img, out_height, out_width, scale=87.5, inter_pol=cv2.INTER_LINEAR):
"""
resize image with aspect ratio
"""
height, width, _ = img.shape
new_height = int(100. * out_height / scale)
new_width = int(100. * out_width / scale)
if height > width:
w = new_width
... | 01fd07c197e7f264f673f46dc301430f822268a4 | 3,605,379 |
def _algebraic_error(x_w_rotated, x_cam, weight):
"""Computes the residual of Umeyama in 3D.
Args:
x_w_rotated: The given 3D points rotated with the predicted camera.
x_cam: the lifted 2D points y
weight: Batch of non-negative weights of
shape `(minibatch, num_point)`. `None`... | e1a09bccbc8af157630c70facd334e40d1ceca4d | 3,605,380 |
def num_processes():
""" Return the number of MPI processes
(not used for SpiNNaker, always returns 1)
"""
return 1 | 51bcd083a57cbce544b52cc1f1ef3772fb0d362c | 3,605,381 |
def specgrid(params, fit):
"""
Calculate emission from each cell of a planetary grid, as a
fraction of stellar flux, NOT
accounting for visibility. Observer is assumed to be looking
directly at each grid cell. For efficiency, never-visible cells
are not calculated. Function returns a spectrum o... | 69b66b9c73d8662aeca3238cb84f60923dee9272 | 3,605,382 |
import tqdm
def calcSS(f, bs=20000, winSize=500000, cut=0,mcut=-1,hic=False):
"""
Calculation of correlation matrix insulation score, output as .bedGraph file.
@param bs: bin size
@param winSize: sliding matrix width half size
@param cut: distance cutoff for PETs
"""
key, mat = parseIxy(f,... | 05e7c041bf56cceb907aa30df798ab312c256a34 | 3,605,383 |
def hash_generator(token_to_id, tokens):
"""Generate hash for tokens in 'tokens' using 'token_to_id'.
Args:
token_to_id: dict. A dictionary which maps each token to a unique ID.
tokens: list(str). A list of tokens.
Returns:
int. Hash value generated for tokens in 'tokens' using 'to... | d9a059e22ab8574fd3c49dfa594cd903edb64d8b | 3,605,384 |
def ndsnap_regular(points, *grid_axes):
""" Snap points to the 2d grid determined by grid_axes
"""
# https://stackoverflow.com/q/8457645/717525
snapped = []
for i, ax in enumerate(grid_axes):
diff = ax[:, np.newaxis] ... | c2d9644c59877e04f1367a7ef5e95ad9de84be95 | 3,605,385 |
import uuid
import random
import base64
def create_captcha():
""" Generates a captcha image.
Returns a tuple with a token and the base64 encoded image """
token = str(uuid.uuid4())
captchagen = ImageCaptcha(width=250, height=70)
if random.randint(1, 50) == 1:
captcha = random.choice(
... | 0ba0405eb05748862fd363d29d2707b65dd3d7eb | 3,605,386 |
from typing import Tuple
def get_missingdays(station: int, tabname: str = "readings") -> Tuple[list, list]:
"""
Retrieves
:param station: the station to assess
:param tabname: name of the table where the readings are stored, defualts to "readings"
:return: hit set with the data calculated and list... | d45616b0116f13a4b2ca08ccd03a8621c3451734 | 3,605,387 |
def search_for_entry(string_2_serch, file_in, nline=0):
"""
Extract from the input file (file_in) up to the line number nline (if declared) the value assigned to string_2_serch.
Input:
string_2_serch = string (or list of string) containing the variable to search (e.g. 'HEIGHT=')
file_in = name o... | 88e9eaf80848c035b7a10e1adea9b2bc5d9b7b7f | 3,605,388 |
def get_hgnc_universe(ifh):
"""Extract all HGNC identifiers from iRefIndex data file @ifh@ and return them as a set"""
header = parse_header(ifh)
hgnc_set = set()
for line in ifh:
data = line.split("\t")
hgncs = get_hgnc(header, data)
for hgnc in hgncs:
hgnc_set.add(hgnc)
return hgnc_set | f8a3fecf8a580b8bd083ff29d62905ad1f9b57b2 | 3,605,390 |
def get_ucs_faults():
""" Get UCS Faults """
sev_critical = 0
sev_major = 0
sev_minor = 0
sev_warning = 0
handle = ucs_login()
faults = handle.query_classid("FaultInst")
for fault in faults:
if fault.severity == 'critical':
sev_critical += 1
elif fault.seve... | 8ed809ad9479108b209b4514dc7cd633fe390c5b | 3,605,391 |
def pack_varint(data):
"""Pack a VARINT for the protocol."""
return bytes([(0x40 * (i != data.bit_length() // 7)) +
((data >> (7 * i)) % 128) for i in range(1 + data.bit_length() // 7)]) | 1bdb283a787fc6b9e65e278d581b7654088ddf87 | 3,605,392 |
def _graph_reduction(adj, x, g, f):
"""we can go ahead and remove any simplicial or almost-simplicial vertices from adj.
"""
as_list = set()
as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
while as_nodes:
as_list.union(as_nodes)
for n in as_nodes:
... | 903c58e718d4f54c944f27b200000961d0dcd194 | 3,605,394 |
import re
import six
def parse_issuer_cred(issuer_cred):
"""
Given an X509 PEM file in the form of a string, parses it into sections
by the PEM delimiters of: -----BEGIN <label>----- and -----END <label>----
Confirms the sections can be decoded in the proxy credential order of:
issuer cert, issuer... | 2df56219076f928b597bb16d0abb03bd8a61dc63 | 3,605,395 |
def iter_months_days(year, month_of_year=None, day_of_month=None,
in_reverse=False):
"""Iterate over each day in each month of year.
year is an integer specifying the year to use.
month_of_year is an optional integer, specifying a start month.
day_of_month is an optional integer, s... | 33531898059220fa7855a7d0e2dedecf623a5c08 | 3,605,396 |
def get_ledger_accounts():
"""
Returns all ledger accounts.
:returns: String containing xml or an lxml element.
"""
return get_anonymous('getLedgerAccounts') | 01b190f66dcb25d9a0db13129bb4a84af856e369 | 3,605,397 |
def svn_checksum_dup(*args):
"""svn_checksum_dup(svn_checksum_t checksum, apr_pool_t pool) -> svn_checksum_t"""
return _core.svn_checksum_dup(*args) | ca6eb452f732ac1b0ba95facc1474f9174409639 | 3,605,398 |
def getSheetContent(sheet):
"""
Returns two dimensional array of all non empty content of the given
sheet. Array contains string and double values.
"""
cursor = sheet.createCursor()
cursor.gotoStartOfUsedArea(False)
cursor.gotoEndOfUsedArea(True)
return [list(row) for row in cursor.getDa... | 9a77c7dadcdf5247f30fa3dc4fa87cc5683cfee2 | 3,605,401 |
def loaddata(data_filename):
"""load matrix data"""
data = np.genfromtxt(data_filename, delimiter='\t')
data_nm = data[1:,0] #wavelength in nm
data_time = data[0,1:]
data_z = data[1:, 1:]
return data_nm, data_time, data_z | 0d3747a0ac2438c21dc7146e872e2c7728781e13 | 3,605,402 |
import time
def get_meas(pix,nside=128):
""" Get the measurements for a particular healpix."""
# objid, ra, raerr, dec, decerr, mjd
t0 = time.time()
connection = pq.connect(user="dlquery",host="db01.datalab.noao.edu",
password="",port = "5432",database = "tapdb")
cur ... | 88e51f1c42da9511e86dd872bb3f262b02fe3c08 | 3,605,403 |
import uuid
def plugin_poll(handle):
""" Extracts data from the sensor and returns it in a JSON document as a Python dict.
Available for poll mode only.
Args:
handle: handle returned by the plugin initialisation call
Returns:
returns a sensor reading in a JSON document, as a Python dic... | 735886b3c355f8a24593d0ab1dd8c6588118272d | 3,605,405 |
def sbas_nav_decode(dwrds: list) -> dict:
"""
Helper function to decode RXM-SFRBX dwrds for SBAS navigation data.
:param list dwrds: array of navigation data dwrds
:return: dict of navdata attributes
:rtype: dict
"""
return {"dwrds": dwrds} | 215d945ac939a817ae84fa08607b72e0c14a1cc9 | 3,605,406 |
def _sql(child, sql, returnresult=True, includefields=True):
"""Execute SQL statement in interactive mode.
"""
sql = sql.strip()
if '\n' in sql:
sql = ' '.join([line.strip() for line in sql.split('\n')])
if not sql.endswith(';'):
sql += ';'
child.sendline(sql)
i = child.expe... | 7a9ff1fa221c23e444d8d6189da3cd5a0927311f | 3,605,407 |
def qfunc(x, y):
"""Simple quantum function"""
qml.RX(x, wires=0)
qml.RX(y, wires=1)
qml.CNOT(wires=[0, 1])
return expval(qml.PauliZ(wires=1)) | d2f0f8c8e137da77a1c958cdb3c90bdf1bb91a92 | 3,605,408 |
def compute_overlaps_in_parallel( step ):
"""
Function used for the making the computation of overlaps parallel via python multiprocessing
"""
s_sd = step3.mapping.ovlp_mat_arb( sd_states_reindexed_sorted[step], sd_states_reindexed_sorted[step], S_ks[0][step], use_minimal=False )
s_sd = data_co... | 0afd7950efcb7a60e4f7bfd3b57c9baea84fbc8f | 3,605,409 |
def scanmeta(fstype, device):
"""Returns command for scanning metadata.
Clonemeta1 will be tried first replacing target with '/dev/null'.
"""
tup = _FILESYSTEMS[fstype]
cmd = clonemeta1(fstype, device, '/dev/null')
if cmd: return cmd
cmd = tup[2]
if cmd:
return list(cmd) + [dev... | 937f6e8bbd5cf9feec9d2439564514afed90dd8e | 3,605,410 |
def page_templates_loading_check(app_configs, **kwargs):
""" Check if any page template can't be loaded. """
errors = []
for page_template in settings.get_page_templates():
try:
loader.get_template(page_template[0])
except template.TemplateDoesNotExist:
errors.append... | 7dd30b7192d848ff6e6419ee0299676d31235f57 | 3,605,411 |
def constant(step, total_train_steps, value=1.0):
"""Constant learning rate (multiplier).
Args:
step: a tf.Scalar
total_train_steps: a number
value: a number or tf.Scalar
Returns:
a tf.Scalar, the learning rate for the step.
"""
del step, total_train_steps
return value | 53285310764c8d627ae366b2ec8e5ff98339e612 | 3,605,412 |
from typing import Any
from typing import Union
from datetime import datetime
from typing import Optional
from typing import Dict
def filter_traces_attribute_in_timeframe(log: EventLog, attribute: str, attribute_value: Any, dt1: Union[str, datetime.datetime], dt2: Union[str, datetime.datetime], parameters: Optional[D... | cdbfda0d075514870996f7d080227231fd56f5ca | 3,605,413 |
import random
def normal113(startt,endt,money,first,second,third,forth,fifth,sixth,seventh,ff1,ff2,mm1,mm2):
"""
for source and destination id generation
"""
"""
for type of banking work,label of fraud and type of fraud
"""
idvariz=random.choice(mm1)
idgirande... | d584f61556bf04c92b87ed1935d5e841e95126b5 | 3,605,414 |
def ww_sim(word, mat, topn=10):
"""find topn most similar words to word"""
indx = tok2indx[word]
# check type of 'mat'
if isinstance(mat, sparse.csr_matrix):
v1 = mat.getrow(indx)
else:
print("not sparse")
v1 = mat[indx:indx+1, :]
# using sklearn cosine similari... | 5242b9282b0699a764606c8491031009c14e30d7 | 3,605,415 |
def encriptar(frase: str, clave: str, s: str = "02468") -> str:
"""Función que encripta una frase.
:param frase: Frase a encriptar.
:type frase: str
:param clave: Clave de encriptación.
:type clave: str
:param s: Símbolo de sustitución.
:type s: str
:return: Frase encriptada.
:r... | 1e1a4e3369180418184411b4c74fa468976ff872 | 3,605,416 |
def detach_user(current_user: User, target_user: User, user_group: UserGroup) -> UserGroup:
"""
Remove a user from a user group.
:param current_user:
:param target_user:
:param user_group:
:return:
"""
if target_user is current_user or is_user_group_admin(current_user, user_group):
... | e191516409e72eb4160e67b2feecf89c08b3967d | 3,605,417 |
import random
def data_circle(num_samples, noise):
"""
Generates the two circles dataset with the given number of samples and noise
:param num_samples: total number of samples
:param noise: noise percentage (0 .. 50)
:return: None
https://github.com/hyounesy/TFPlaygroundPSA/blob/master/src/da... | 4d0ac091382bd76677207e23d422bf5fab8dfd9f | 3,605,419 |
def argmax_2d(a):
"""Return the tuple (i, j) where a[i, j] = a.max()"""
return np.unravel_index(np.argmax(a), a.shape) | c969d856b1e6482086ece5bda19476c546238399 | 3,605,420 |
from typing import Optional
def _reverse_cumsum(
x: np.ndarray, axis: Optional[int] = None
) -> np.ndarray: # pragma: no cover
""" (x0, x1, x2) -> (x0, x0 + x1, x0 + x1 + x2)"""
if axis is None:
axis = 0
return np.flip(np.cumsum(np.flip(x, axis=axis), axis=axis), axis=axis) | 370facbca5bb5cd5e4d9d329af0aed941498dda8 | 3,605,421 |
import hashlib
def prepareMessage(
message: bytes,
q: int,
hashFunction: callable = hashlib.sha256
) -> int:
"""Processes the message before signing or verifying according to FIPS 186-4.
The procedure works as follows:
1) compute zLength = min(N, outlen),
where outlen is the l... | c275455dfddaecb2480ed9c990b61804871cdb73 | 3,605,422 |
def fetch_ground_energy(bond_length):
"""Fetches exact ground state energy given the bond length.
Args:
=====
bond_length : float
Bond length for fetching correct ground state energy
Returns:
========
exact_energy : float
Exact ground state energy
"""
exact_energy =... | e90657846d2973bdf9c8bb7cc6607f3f139dc008 | 3,605,423 |
import requests
from bs4 import BeautifulSoup
def grab_record(match_id):
"""
根据比赛的id爬取比赛的文字实录
:param match_id: 比赛的id
:return: list -> Record类型的列表
"""
# 首先定义一个时间转换函数
def translate_time(time_to_end):
time = 0
if ':' in time_to_end:
time = int(time_to_end.split(':... | fcfeb871f5d801db2267aa607b8e3f57593dc501 | 3,605,424 |
def selfsigned_certificate_for_key(
key,
subject={},
serial_number=1,
digest="sha256",
length=None,
file_name=None
):
"""
Creates self-signed certificate for a given key
Args:
- key: Key to create and sign the certificate.
... | 0562f13a602acbd49ea99617696e4cb5d56e8b2d | 3,605,425 |
def unconfirmed() -> str:
"""Unconfirmed email route.
:return: Rendered auth/unconfirmed template.
"""
return render_template("auth/unconfirmed.html") | 0656df3a95447a940ae53ae685922441732b8094 | 3,605,426 |
def predict(test_img):
"""
purpose:
to leverage the recognizers to detect and identify the people
whose faces are present in the uploaded image
args:
img - the image on which the label has to be added
text - the label of the identified person
x,y - the co-ordinates of the starting point for the... | 9c1793176ae981640a688dcb21af5d4b987efb0a | 3,605,427 |
def shape(x):
"""Get a list of integers representing this tensor's shape"""
if get_backend() == "pytorch":
return [s for s in x.shape]
else:
return [s for s in x.shape] | 5bd451d21a101992f1c4dde4f56c6d5854463eb2 | 3,605,428 |
def ssh(uuid, cook_url=None, env=None, flags=None):
"""Invokes the ssh subcommand"""
args = f'ssh {uuid}'
cp = cli(args, cook_url, flags=flags, env=env)
return cp | 99e7a4cb8f77da06ac6fb9b7bc5e570bb8395685 | 3,605,429 |
def set_image(images, row, issues, pre, overrides={}, verbose=False):
"""
Update an image based on known issues.
Given an image, image metadata, and a set of known issues, determine if any
of the known issues apply to the image in question and, if they do, make
the appropriate edits to the imag... | fae11f006dc93abdc0b04dc0aaf09c2ce4642450 | 3,605,430 |
def charvectorize(word, lower=True, setsize=128):
"""
Convert a word (sequence of characters) to a n-vector of length setsize, using one-hot encoding
:param word: Word to vectorize
:param lower: Render word lowercase first before vectorizing
:param setsize: Size of character set
:return:
>>>... | 34678377645e5bb873e7947edfb7900f67713ced | 3,605,431 |
def get_downloader(start_date,
end_date,):
"""returns a downloader closure for iex cloud
:param start_date: the first day on which dat are downloaded
:param end_date: the last day on which data are downloaded
:type start_date: str in format YYYY-MM-DD
:type end_date: str in format YYY... | 3264da4d2f5309855830655f6ac4bcf31d8b5661 | 3,605,432 |
def filter_lines(filter_cmd, lines, attrs={}):
"""
Run 'lines' through the 'filter_cmd' shell command and return the result.
The 'attrs' dictionary contains additional filter attributes.
"""
def findfilter(name,dir,filter):
"""Find filter file 'fname' with style name 'name' in directory
... | 03c3cf2b49ba2785bcb8429091af5074d8caa136 | 3,605,433 |
def SPL(p):
"""Convert sound pressure to sound pressure level.
Uses the standard reference value for airborne acoustics: 20 µPa.
Note that the input is the pressure amplitude, not the RMS value.
Parameters
----------
p : numeric, complex
The complex sound pressure amplitude.
Retur... | 5ddcca44ab619aee04b55a98fb88ec957d451f7c | 3,605,434 |
def compute_variants(linelist, anyonarray):
"""
Variant construction
"""
print('generating_variants ...')
# generate variants of the poem
df = pd.DataFrame(anyonarray)
allpoemsidx = []
allpoems = []
allidx = []
nvariants = 0
for i in range(len(linelist)):
... | 15931e3b39b39d012bb5bbe21ce371ed40510928 | 3,605,436 |
def boyer_moore_preprocessing(pattern, alphabet_size=4):
"""
Bad character rule used by Boyer-Moore algorithm:
For each character x in the alphabet, let R(x) be the position of right-most occurrence of character x in P.
R(x) is defined to be zero if x does not occur in P.
"""
R = [0] * alphabet_... | 1d70891cfe0f0f55579c7a9349fb24d6954379fd | 3,605,438 |
def max_consecutive_sum(array):
"""
given an array of numbers (positive, negative, or 0)
return the maximum sum of consecutive numbers
"""
max_value = max(array)
running_sum = 0
for num in array:
if running_sum < 0:
running_sum = 0
running_sum += num
if ru... | 32e7322f8936f8399ec2ebe0702dbb10332cb529 | 3,605,441 |
def _feature_importances(clf, FEATURES):
""" finds and prints feature importances for given clf """
if hasattr(clf, "feature_importances_"):
results = {}
params = zip(FEATURES, clf.feature_importances_)
for param, importance in sorted(params, key=lambda x: x[1], reverse=True):
... | 96e218ec60c0a780624524187274a6a7e1ea61a7 | 3,605,443 |
from HHFtools.htccorrelations.seidertate import htc as htc_seidertate
from HHFtools.htccorrelations.berglesrohsenow import get_T_onb
from HHFtools.htccorrelations.berglesrohsenow import htc as htc_berglesrohsenow
from HHFtools.htccorrelations.tong75 import get_wchf as wchf_tong75
def htc(water,
geometry,
... | 39478c381aa0ae81951b487d821e2743aaadb338 | 3,605,444 |
from datetime import datetime
async def middleware(request: Request, call_next):
"""
Middleware is used to do tasks which are common to every API route
request -> middleware -> actual api route -> response -> middleware -> modified response
:param request: request to the API Server
:param call_n... | edb580a71325ff0e41d14018a57b91b677329f8b | 3,605,446 |
def policy_defaults_to_floatx():
"""Returns True if `global_policy()` will use the current value of floatx."""
return _global_policy is None and base_layer_utils.v2_dtype_behavior_enabled() | 67237570b87ef78eb3e8a27fdecfef144835092c | 3,605,448 |
def _mask_for_bits(i):
"""Generate a mask to grab `i` bits from an int value."""
return (1 << i) - 1 | 53fc285225632cce34a74536a085cfe0af10300a | 3,605,451 |
def is_column_based(fname, sep='\t', skip=0, is_multi_byte=False):
"""
Checks whether the file is column based with respect to a separator
(defaults to tab separator).
>>> fname = get_test_fname('test.gff')
>>> is_column_based(fname)
True
>>> fname = get_test_fname('test_tab.bed')
>>> i... | e88202cbe67703b63d1d7598946938a96da1fd8a | 3,605,453 |
import urllib
def _quote(s, encoding='utf-8'):
"""
Url quote as str.
>>> _quote('http://example/test?a=1+')
'http%3A//example/test%3Fa%3D1%2B'
>>> _quote(u"hello world!")
'hello%20world%21'
>>> _quote('http://example/s=中文')
'http%3A//example/s%3D%E4%B8%AD%E6%96%87'
"""
if isin... | 60ca1f098e0fb7359ef4a83badb2cc665e1803b4 | 3,605,454 |
def merge_idxs(src_idxs, dest_idxs):
"""Return source and destination index arrays, built up from
smaller index arrays and combined in order of ascending source
index (to allow us to convert src indices to a slice in some cases).
"""
assert(len(src_idxs) == len(dest_idxs))
# filter out any zero... | 0c53dc55619ddf60eb1648c8e213d0c275cc806a | 3,605,455 |
import random
def random_int(min_num=1, max_num=200):
"""
return an int inclusively between min_nim and max_num
:param min_num:
:param max_num:
:return: {int} a number
"""
return random.randint(min_num, max_num) | 0c481f889f4a40e8a72a1efa44244e113f395168 | 3,605,456 |
import ctypes
def read_dSdm(file_path, bdio_path='./libbdio.so', **kwargs):
""" Extract dSdm data from a bdio file and return it as a dictionary
The dictionary can be accessed with a tuple consisting of (type, kappa)
read_dSdm requires bdio to be compiled into a shared library. This can be achieved by
... | b13608eec0fa0d61284a87ce6b531be04e873b01 | 3,605,457 |
from typing import Iterable
from typing import BinaryIO
def _plot(predictions: Iterable[BinaryIO]):
"""Plots predictions from a file.
Parameters
----------
predictions
Files containing predictions.
"""
return plot(predictions) | f52e2190273aa88558f5de654215853305e8f1c3 | 3,605,460 |
def get_train_sentences(vocabulary_size):
"""Get training sentences with word to index map and vice versa."""
sent1_train_indices, sent2_train_indices, word_to_index, index_to_word, label_train = get_train_data(
vocabulary_size)
all_sentences = []
all_sentences.extend(sent1_train_indices)
al... | 3748e2257a9a661cfeb25f74304210861da36292 | 3,605,461 |
from io import StringIO
def extract_pandas_data_frames(remote_data):
"""
Skip convertin datetime related columns to datetime, cause pandas in case
of all parsed rows is convertin type o column to datetime64 even
dateparse returns datetime. If try to convert datetime64 to datetime
using x.astype(da... | 05a0bb33896cc98e4b18599803928ab429efb966 | 3,605,462 |
import ipaddress
import anyio
def main(**kwargs):
"""Console script for naps."""
network = ipaddress.ip_network(kwargs["network"])
anyio.run(schedule, network, kwargs["port_range_start"], kwargs["port_range_end"] + 1)
return 0 | 901103a4b2e628598e12e2e9db34d3ae9cc568c9 | 3,605,463 |
def normalize_prefix(prefix):
"""
Removes slashes from a URL path prefix.
:param str prefix:
:rtype: str
"""
if prefix and prefix.startswith("/"):
prefix = prefix[1:]
if prefix and prefix.endswith("/"):
prefix = prefix[:-1]
return prefix | 0db359f10fa213bf638fa3fca5bd58c530faf788 | 3,605,464 |
def hdf_file_path(tmpdir, test_data_dir):
"""This file contains the following:
Object Tree:
/ (RootGroup) ''
/cause (Group) ''
/population (Group) ''
/population/age_bins (Group) ''
/population/age_bins/table (Table(23,), shuffle, zlib(9)) ''
/population/structure... | bd68581f3174a80abaeef408ca844b9fbb6f7889 | 3,605,465 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.