content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
import tempfile
from pathlib import Path
async def submit_changesheet(
uploaded_file: UploadFile = File(...),
mdb: MongoDatabase = Depends(get_mongo_db),
user: User = Depends(get_current_active_user),
):
"""
Example changesheet [here](https://github.com/microbiomedata/nmdc-runtime/blob/... | ebe9306aba0fef88c906c3c584f87e7c783fe9d8 | 3,645,893 |
import json
def get_notes(request, course, page=DEFAULT_PAGE, page_size=DEFAULT_PAGE_SIZE, text=None):
"""
Returns paginated list of notes for the user.
Arguments:
request: HTTP request object
course: Course descriptor
page: requested or default page number
page_size: requ... | 3256cacd845cf2fd07027cf6b3f2547a59cefd0f | 3,645,894 |
import numpy
def convert_hdf_to_gaintable(f):
""" Convert HDF root to a GainTable
:param f:
:return:
"""
assert f.attrs['ARL_data_model'] == "GainTable", "Not a GainTable"
receptor_frame = ReceptorFrame(f.attrs['receptor_frame'])
frequency = numpy.array(f.attrs['frequency'])
data = nu... | dd816eb0730b0f9993efe07c2b28db692ac6a06e | 3,645,895 |
import pathlib
def list_files(directory):
"""Returns all files in a given directory
"""
return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')] | a8c5fea794198c17c2aff41a1a07009984a8e61f | 3,645,896 |
def condition_conjunction(conditions):
"""Do conjuction of conditions if there are more than one, otherwise just
return the single condition."""
if not conditions:
return None
elif len(conditions) == 1:
return conditions[0]
else:
return sql.expression.and_(*conditions) | acf26bd9b8e47d27ad83815be70216db0e4ad091 | 3,645,897 |
def get_claimed_referrals(char):
""" Return how many claimed referrals this character has. """
return db((db.referral.referrer==char) & (db.referral.claimed==True)).count() | 5820cdd21cbb77f6a43537ae18dc227ad4fec1b8 | 3,645,898 |
def groupsplit(X, y, valsplit):
"""
Used to split the dataset by datapoint_id into train and test sets.
The data is split to ensure all datapoints for each datapoint_id occurs completely in the respective dataset split.
Note that where there is validation set, data is split with 80% for training and 2... | e8ba393270a32e2464c30409a13b2c5e9528afdd | 3,645,899 |
import urllib
def application(environ, start_response):
"""
make Passenger interpret PATH_INFO the same way that the WSGI standard
does
"""
environ["PATH_INFO"] = urllib.parse.unquote(environ["PATH_INFO"])
return app.app(environ, start_response) | 3de57b31206a374da0378788f20e7bd8b1eca9af | 3,645,901 |
from railrl.torch.pytorch_util import set_gpu_mode
import random
def run_experiment_here(
experiment_function,
variant=None,
exp_id=0,
seed=0,
use_gpu=True,
# Logger params:
exp_prefix="default",
snapshot_mode='last',
snapshot_gap=1,
git_... | ee8b0f727027d8dcee804565606a7f82f2c77ca9 | 3,645,902 |
from typing import Tuple
def normalize_chunks(chunks: Tuple[Tuple[int, int]]) -> Tuple[Tuple[int, int]]:
"""
Minimize the amount of chunks needed to describe a smaller portion of a file.
:param chunks: A tuple with (start, end,) offsets
:return: A tuple containing as few as possible (start, end,) off... | d49d1abed0573a86e0eeee5d2e5ed2e129f3274e | 3,645,903 |
def learning_rate_schedule(adjusted_learning_rate, lr_warmup_init,
lr_warmup_step, first_lr_drop_step,
second_lr_drop_step, global_step):
"""Handles linear scaling rule, gradual warmup, and LR decay."""
# lr_warmup_init is the starting learning rate; the learnin... | 26021c7cbdb264ddc84fad94d4a01b51913f3a72 | 3,645,904 |
from typing import List
import logging
def set_power_state_server(power_state: ServerPowerState) -> List[float]:
"""Record the current power limit and set power limit using nvidia-smi."""
# Record current power limits.
if power_state.power_limit:
cmd = "nvidia-smi --query-gpu=power.limit --format... | 8a9ac60dbd58dedf5f39386a7233b88b7cc5aa79 | 3,645,905 |
from typing import Union
def score_normalization(extracted_score: Union[str, None]):
"""
Sofa score normalization.
If available, returns the integer value of the SOFA score.
"""
score_range = list(range(0, 30))
if (extracted_score is not None) and (int(extracted_score) in score_range):
... | 74501e9351296037ecc90ae647155e3c6b76ae01 | 3,645,906 |
def wrap(wrapping_key_public, plaintext):
"""
RSA-OAEP key wrapping.
Args:
wrapping_key_public: The public key of the RSA wrapping key
plaintext: The plaintext key to wrap
"""
rsa_cipher = PKCS1_OAEP.new(
key=wrapping_key_public, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1... | 171074a46440184138ccb1684754f328afc50efe | 3,645,908 |
def compute_horizontal_vessel_purchase_cost(W, D, F_M):
"""
Return the purchase cost [Cp; in USD] of a horizontal vessel,
including thes cost of platforms and ladders.
Parameters
----------
W : float
Weight [lb].
D : float
Diameter [ft].
F_M : float
Vessel ma... | 22d38ffc38dddb992d2fd7b2c20c3dc1d0ddb53d | 3,645,910 |
def format_dev_sub_dev_id(pciIdPair):
"""
pciIdPair (int pci device id, int pci sub device id or None)
"""
if pciIdPair[1] is None:
return "(0x%08X, None)" % pciIdPair[0]
return "(0x%08X, 0x%08X)" % pciIdPair | fded71eee57f4fac60175bfb015845bf1eba58f7 | 3,645,911 |
def mychats():
"""
Show Chats where I can write
:return:
{
error: 0,
chats: [...Chat]
}
"""
result = {
'error': 0,
'chats': []
}
if 'user_id' in session:
chats_rows = query_db('SELECT * FROM chats WHERE user1_id = ? OR user2_id = ?', [session['... | 4af7cd34fb8649ed10723b258e7a864e3e12edc2 | 3,645,912 |
def polynom_prmzt(x, t, order):
"""
Polynomial (deterministic) parameterization of fast variables (Y).
NB: Only valid for system settings of Wilks'2005.
Note: In order to observe an improvement in DA performance w
higher orders, the EnKF must be reasonably tuned with
There is very ... | 80d3f9563c5f8a04a65de7d2d22f5d49d35c71fe | 3,645,913 |
def decode(s):
"""
Deserialize an EDS object from an EDS string.
"""
lexer = _EDSLexer.lex(s.splitlines())
return _decode_eds(lexer) | 3c7eb8ac7e570aeb1297b052e35c804dd27b0f49 | 3,645,915 |
def allowed_file(filename):
""" Verifies if file extension is compatible """
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | 75e0047eff0787e33f687e7a9b689ad8661b7501 | 3,645,917 |
def clap_convert(txt):
"""convert string of clap values on medium to actualy number
Args:
txt (str): claps values
Returns:
number on claps (int)
"""
# Medium annotation
if txt[-1] == "K":
output = int(float(txt[:-1]) * 1000)
return output
else:
return int(txt) | 253e0e2be4f37f1994637bbfc80edfc5d72bc4e5 | 3,645,918 |
import io
def write_phase1_capsummary(inst, isStringIO=True):
"""
Write out a multiweek summary of capacity, demand, understaffing.
:param inst: Model instance
:param isStringIO: True (default) to return StringIO object, False to return string
:return: capacity summary as StringIO object or a str... | 6d6e7d083693b74ea27e7f10cec4899735f32541 | 3,645,919 |
def glorot_uniform(shape):
"""
:param shape: tuple with the shape of the wanted output (filters_amount, depth, height, width)
:return: array (it's shape=param shape) with initialized values using 'glorot uniform' initializer
"""
fan_in, fan_out = _calc_fans(shape)
scale = 1. / ((fan_in + fan_out... | 0cec12b0342db827286248a722b32852cab2bdad | 3,645,920 |
import warnings
def second_order_moments(n_components, e2, m1, alpha0):
"""Second-Order Moments
To prevent creating 2nd order moments explicitly, we construct its
decomposition with `n_components`. check reference [?] section 5.2
for details.
Parameters
----------
n_components: int
... | 4b2ac9d43352d856875d86cd1975ec59ac5664c8 | 3,645,922 |
def remove_names(df: pd.DataFrame) -> pd.DataFrame:
"""Convert personal names to numerical values."""
df = df.reset_index()
df.drop(columns='Name', inplace=True)
return df | 9dab1803a153d5effd2e08b6e6ff5df30fee8407 | 3,645,924 |
import torch
def handle_epoch_metrics(step_metrics, epoch_labels, epoch_predictions):
"""
Function that handles the metrics per epoch.
Inputs:
step_metrics - Dictionary containing the results of the steps of an epoch
epoch_labels - List of labels from the different steps
epoch_pred... | a1d0180095535eec641258dd921c90808aa6858f | 3,645,925 |
def project_disk_sed(bulge_sed, disk_sed):
"""Project the disk SED onto the space where it is bluer
For the majority of observed galaxies, it appears that
the difference between the bulge and the disk SEDs is
roughly monotonic, making the disk bluer.
This projection operator projects colors that a... | 5faf8f7d8d0d780f61586f7fae39f4ba04d3752d | 3,645,926 |
def qlog_numpy(q):
"""
Applies logarithm map to q
:param q: (4,)
:return: (3,)
"""
if all(q[1:] == 0):
q = np.zeros(3)
else:
q = np.arccos(q[0]) * q[1:] / np.linalg.norm(q[1:])
return q | 82cf0ff2054c02e4cc3dc3a6500b1c8a0e3eb870 | 3,645,928 |
def get_ML_features(df: pd.DataFrame, protease: str='trypsin', **kwargs) -> pd.DataFrame:
"""
Uses the specified score in df to filter psms and to apply the fdr_level threshold.
Args:
df (pd.DataFrame): psms table of search results from alphapept.
protease (str, optional): string specifying... | 4ac4202fa5c86b78b1bda1a2b96d5ed4b8552b4f | 3,645,929 |
def revcomp(sequence):
"""
Find reverse complementary sequence
:param sequence: The RNA sequence in string form
:return: The reverse complement sequence in string form
"""
complement = {"A": "U", "U": "A", "C": "G", "G": "C", "N": "N"}
revcompseq = ""
sequence_list = list(sequence)
s... | c66b9ad967e612fa97f18bb2932e7eb4bbee8245 | 3,645,930 |
def J(X, mean, r):
"""K-meansの目的関数(最小化を目指す)"""
summation = 0.0
for n in range(len(X)):
temp = 0.0
for k in range(K):
temp += r[n, k] * np.linalg.norm(X[n] - mean[k]) ** 2
summation += temp
return summation | 1d2dd241fc30cb5897b0224285c5c7f2f2fec675 | 3,645,931 |
import time
def timesince():
"""
Get the amount of time since 00:00 on 1 January 1970,
the raw date before formatting it.
"""
return time.time() | 7e6944d74172947c4ac990c0fa993524ab865e18 | 3,645,933 |
def gencoords_outside(N, d, rad=None, truncmask=False, trunctype='circ'):
""" generate coordinates of all points in an NxN..xN grid with d dimensions
coords in each dimension are [-N/2, N/2)
N should be even"""
if not truncmask:
_, truncc, _ = gencoords_outside(N, d, rad, True)
return ... | 0b4f3db165cb495e5d540412cb77bd36e8a42c62 | 3,645,934 |
def map_orientation(cur_orientation, cur_count):
""" . . . . . x
. . . . . x
. . . . . x
. . . . . x
. . . . . x
. . . . . x
"""
right_edge = 34905131040
""" . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
x x x ... | 5fa5e0c386da56cab336f33e560bf9591814060c | 3,645,935 |
import ctypes
def glGetShaderInfoLog( baseOperation, obj ):
"""Retrieve the shader's error messages as a Python string
returns string which is '' if no message
"""
target = GLsizei()
glGetShaderiv(obj, GL_INFO_LOG_LENGTH,target)
length = target.value
if length > 0:
log = ctypes.cr... | 0173aa2cbeac8c8b2cb9072d0d56584285af2e0d | 3,645,936 |
def _CheckGrdTranslations(grd_file, grd_lines, wanted_locales):
"""Check all <file> elements that correspond to an .xtb output file.
Args:
grd_file: Input .grd file path.
grd_lines: List of input .grd lines.
wanted_locales: set of wanted Chromium locale names.
Returns:
List of error message strin... | 49b73187cd2ac3c7b9796a8a139d89f9a74c91a3 | 3,645,937 |
def choose_diverging_palette(as_cmap=False):
"""Launch an interactive widget to choose a diverging color palette.
This corresponds with the :func:`diverging_palette` function. This kind
of palette is good for data that range between interesting low values
and interesting high values with a meaningful m... | 0c2ffc8710a56e643e6c4ccdd453bd00cc59e6a2 | 3,645,938 |
def get_lm_model(args, device, config):
"""Get language model(based on GPT-2) used for sequence prediction."""
ninp = config["ninp"]
nhead = config["nhead"]
initrange = config["initrange"]
dropout = config["dropout"]
vocab_size = config["vocab_size"]
nhid = config["nhid"]
ndecoder = con... | 071f43b9537ca8024f980271c64750e7afae864e | 3,645,939 |
def get_meminfo():
"""
Get and format the content of /proc/meminfo
"""
buf = open('/proc/meminfo').read()
buf = ','.join([v.replace(' ', '') for v in
buf.split('\n') if v])
return buf | 47a0d57d1b8c90b4907fab8e39154b8e4ad5b7ee | 3,645,940 |
def effective_area(true_energy, reco_energy, simu_area):
"""
Compute the effective area from a list of simulated energy and reconstructed energy
Parameters
----------
true_energy: 1d numpy array
reco_energy: 1d numpy array
simu_area: float - area on which events are simulated
Returns
... | b17efa390a1ae14bb8ecb959740bad8c391b1d2e | 3,645,941 |
def execute(queries, arglists, fetchone=False):
"""Execute multiple queries to the sqlite3 jobtracker database.
All queries will be executed as a single transaction.
Return the result of the last query, or the ID of the last
INSERT, whichever is applicaple.
Inputs:
queri... | a64e12262150514dbc5e6e7f4c193481ab8162aa | 3,645,942 |
def physical_cpu_mhz(vir_connection):
""" Get the CPU frequency in MHz using libvirt.
:param vir_connection: A libvirt connection object.
:type vir_connection: virConnect
:return: The CPU frequency in MHz.
:rtype: int
"""
return vir_connection.getInfo()[3] | f6a404a6d531940fbc762f493e90355e2fc78690 | 3,645,943 |
def addstream(bot, input):
"""Add a stream from the notify list"""
if not input.admin: return False
if not input.group(2): return
stream = input.group(2).lower()
if not stream in bot.config.streams:
bot.config.set_add('streams', stream)
bot.reply("Added {0} to stream list".format(stream))
else:
bot.reply("{... | 48465633ea58968efca31231eb5e1a47a537c979 | 3,645,944 |
def get_author(search):
"""
Queries google scholar to find an author given a
search string. If != 0 results are found it gives an error
"""
authors = list(scholarly.search_author(search))
if len(authors) > 1:
raise ValueError(f'Found >1 authors with search string: {searc}, try... | 8fffd75f588194db0707ddd7249823fb73324549 | 3,645,945 |
import torch
def _named_tensor_generic_operation(
tensor: torch.Tensor,
tensor_ops_pre: callable = dummy,
tensor_ops_post: callable = dummy,
name_ops: callable = dummy) -> torch.Tensor:
"""
generic base function used by others
First store the names
Args:
tensor ... | 8a343f2ab2c4aeaebcf64e8fc5e75cb3d8776241 | 3,645,946 |
def normalize_address_components(parsed_addr):
# type: (MutableMapping[str, str]) -> MutableMapping[str, str]
"""Normalize parsed sections of address as appropriate.
Processes parsed address through subsets of normalization rules.
:param parsed_addr: address parsed into ordereddict per usaddress.
... | 48730c85ee7930b27260b97a6ad876bcecf1b5cc | 3,645,947 |
def is_key_in_store(loc, key):
"""
A quick check to determine whether the :class:`pandas.HDFStore`
has datA for ``key``
:ARGS:
loc: :class:`string` of path to :class:`pandas.HDFStore`
key: :class:`string` of the ticker to check if currently
available
:RETURNS:
... | 273bd534daa0f70831e77da88808033e4f1683eb | 3,645,949 |
def transform_rows_nonlinear06(data, **kwargs):
"""
Nonlinear row transformation 06. 12 simulated data sources; Functions: 1.0, 0.5*(x+1)^2, sin(pi*x), sin(2*pi*x), cos(pi*x), cos(2*pi*x), x^5, exp2, log10(x-x.min()), boxcox(2), boxcox(4), boxcox(6).
"""
sources_transformers = [
1.0,
lam... | dd51c838d9721fe310463fa8a0cdb0505e9c4f0f | 3,645,950 |
def catch_parameter(opt):
"""Change the captured parameters names"""
switch = {'-h': 'help', '-o': 'one_timestamp', '-a': 'activity',
'-f': 'file_name', '-i': 'imp', '-l': 'lstm_act',
'-d': 'dense_act', '-p': 'optim', '-n': 'norm_method',
'-m': 'model_type', '-z': 'n_si... | ad3a25e3786b657947893f96a76e80f17eb3b0f0 | 3,645,951 |
def get_mgr_pods(mgr_label=constants.MGR_APP_LABEL, namespace=None):
"""
Fetches info about mgr pods in the cluster
Args:
mgr_label (str): label associated with mgr pods
(default: defaults.MGR_APP_LABEL)
namespace (str): Namespace in which ceph cluster lives
(default... | 8079d291d5e2b996547ecd615fbc00a8c70aa4e9 | 3,645,954 |
from typing import Union
def normalise_architecture(architecture: Union[str, int]):
"""Convert any valid architecture alias to either 'x86_64' or 'i686'.
Raise an error for invalid input.
"""
for (true_name, aliases) in architecture_aliases.items():
if architecture in aliases:
retu... | a7e99a2e8cc527028b82c7e628bd18f9c63c7f61 | 3,645,955 |
def process_m(filename, m, estimator):
"""Returns the list of file sizes and PSNR values for
compression method m.
"""
filesize, psnr = [], []
for q in range(0, 101, 5):
_size, _psnr = process_q(filename, q, m, estimator)
filesize.append(_size / 1024) # in kilobyte(s)
psnr.... | 7bf1bbcdf31709393788006d8d5cd1bef3bf5509 | 3,645,956 |
def fmt(n):
"""format number with a space in front if it is single digit"""
if n < 10:
return " " + str(n)
else:
return str(n) | 976acc22cafd6d6bdb4e251853f49a114b63ec21 | 3,645,957 |
def test_registration():
"""Test registering a magic and getting a copy of it and de-registering."""
manager.MagicManager.clear_magics()
def my_magic(cell=None, line=None):
"""This is a magic."""
if not cell:
cell = 'foo'
if not line:
line = 'bar'
return f'{cell}{line}'
my_magic.ma... | 899573442f12e6e6544f32dcd472fd495eb9dc3b | 3,645,958 |
def stop():
"""Stop cleaning
This is using docstrings for specifications.
---
definitions:
stop:
type: object
properties:
did:
type: string
siid:
type: integer
aiid:
type: integer
code:
type: in... | e9d7558f4433e73a92229fbf79628eb48357e12b | 3,645,959 |
import json
def save_key(access_key, output_filename=DEFAULT_ACCESS_KEY_FILE):
"""
saves access key to .yc json file
"""
with open(output_filename, "w+") as f:
f.write(json.dumps(access_key, indent=4))
return output_filename | 7f15a469ad9b74a39452d8bde46223ef214300d9 | 3,645,960 |
def PutObject(object_id: str):
"""Add/replace DRS object with a user-supplied ID.
Args:
object_id: Identifier of DRS object to be created/updated.
Returns:
Identifier of created/updated DRS object.
"""
return register_object(
data=request.json,
object_id=object_id,... | faf0aa633ef149c34f3fe0e80d8fdcc9df68dfec | 3,645,961 |
def get_handler_name(method: str, url_path: str, path_params: dict):
"""
Возвращает имя необходимого хендлера для рефлексифного вызова метода
:param method: Метод
:param url_path: URL
:param path_params: Параметры
:return:
"""
handler = url_path.replace('/', '_')
for key, value in pa... | e8060538a6bf73e6291ecbcbec14f11997a53507 | 3,645,962 |
import json
def plot_AP(file_path: str):
""" 绘制 AP 柱状图 """
with open(file_path, encoding='utf-8') as f:
result = json.load(f)
AP = []
classes = []
for k, v in result.items():
if k!='mAP':
AP.append(v['AP'])
classes.append(k)
fig, ax = plt.subplots(1, 1... | 7d691161d07d5f4a70c2b46b8971f54c93972a7b | 3,645,964 |
def partner_data_ingest_new_files(source, destination):
"""
:param source : list of files to process:
:param destination: destination to copy validated files
check s3 path for new file, trigger partner_data_ingest for new files.
"""
hook = S3SyncHook(aws_conn_id="aws_default", verify=True)
... | 49685cac11c12af7aa3e2e9ecc152dc46f1b2c5e | 3,645,965 |
import six
def _mofval(value, indent, maxline, line_pos=0, end_space=0):
"""
Low level function that returns the MOF representation of a non-string
value (i.e. a value that cannot not be split into multiple parts, for
example a numeric or boolean value).
If the MOF representation of the value doe... | 964e788a228ac88305fb8d82e7e9b9a4a8cd1a2f | 3,645,966 |
def to_vector(texto,model,idf):
""" Receives a sentence string along with a word embedding model and
returns the vector representation of the sentence"""
tokens = normalizer(texto).split() # splits the text by space and returns a list of words
vec = np.zeros(300) # creates an empty vector of 300 dimens... | 24f811110f9b6d9b0fc8a0f6ffcf2d37e1cd6feb | 3,645,968 |
def evaluate_interval_detection(labels, predictions, event_val, def_val, seq_length, other_vals=[]):
"""Evaluate interval detection for sequences by calculating
tp, fp, and fn.
Extends the metric outlined by Kyritsis et al. (2019) in
Modeling wrist micromovements to measure in-meal eating behavior from
... | 4149eaf357d28236077e9cfac7d7ed8ee113818c | 3,645,969 |
def _div(v):
"""Pure spatial divergence"""
return _div_id(np.vstack((v, [np.zeros_like(v[0])])), l1_ratio=0.) | 706a97e4d5930067b6524210738fce5b27f407c5 | 3,645,970 |
def _always_run(*args, **kwargs) -> bool:
""" This returns False to indicate that the step is not already completed. """
return False | db31e0ac20ac0eef410fb051928308ce7414f5b6 | 3,645,972 |
def generate_urls(search):
"""Generates a URLS in the correct format that brings to Google Image seearch page"""
return [(BASE_URL+quote(word)+GOOGLE_PICTURE_ID) for word in search] | 4d7d13cdf15fb3e029f11bb2e3f28920cf7c2f97 | 3,645,973 |
def batch_provider(data, batch_size, processor=None, worker_count=1, queue_size=16, report_progress=True):
""" Return an object that produces a sequence of batches from input data
Input data is split into batches of size :attr:`batch_size` which are processed with function :attr:`processor`
Data is split a... | 2760e9bc9977f4fcdc07624bf896d6b48ce1276d | 3,645,974 |
import random
def simplex(key, log_L_constraint, live_points_U,
loglikelihood_from_constrained,
prior_transform, sampler_state, replace_id):
"""
Samples from the prior restricted to the likelihood constraint.
This undoes the shrinkage at each step to approxima... | f88038eca201b87fdc8f4b4722357a4eafd0366e | 3,645,975 |
def has_anonymous_link(node, auth):
"""check if the node is anonymous to the user
:param Node node: Node which the user wants to visit
:param str link: any view-only link in the current url
:return bool anonymous: Whether the node is anonymous to the user or not
"""
if auth.private_link:
... | c5941bce3f0110dfcd5e9bbb19bae0682c5e731f | 3,645,976 |
def lstm(c_prev, x):
"""Long Short-Term Memory units as an activation function.
This function implements LSTM units with forget gates. Let the previous
cell state :math:`c_{\\text{prev}}` and the incoming signal :math:`x`.
First, the incoming signal :math:`x` is split into four arrays
:math:`a, i,... | 795fb92554c04be29a75f770fe0fb88d4224f94a | 3,645,977 |
import torch
import time
def hals(video,
video_factorization,
maxiter_hals=30,
nnt=False,
verbose=False,
indent='',
device='cuda',
**kwargs):
"""Perform maxiter HALS updates To Temporal & Spatial Components
Parameter:
video: LowRankVideo ... | a993f9e434c3196110c0569cb124d9edbb794dec | 3,645,978 |
def generate_random_sd(error, seq = None):
""" generates random sd with error% error rate
If seq is specified, random sd is generated from a substring of it."""
if seq == None:
seq1 = randSeq(rand(minLen, maxLen))
else:
length = rand(minLen, maxLen)
start = rand(0, len(seq) - le... | 34694895cd37e5714666c3f9f80ae5a010310d3c | 3,645,979 |
def is_successful(gsm_log):
"""
Success is defined as having converged to a transition state.
"""
with open(gsm_log) as f:
for line in reversed(f.readlines()):
if '-XTS-' in line or '-TS-' in line:
return True
return False | 9bab6837c8e6b818cceb025c5df9aed78074edcf | 3,645,980 |
def indicator(function_array_to_be_indicated, its_domain, barrier):
"""the indicator influences the function argument, not value. So here it iterates through x-domain and cuts any
values of function with an argument less than H"""
indicated = []
for index in range(len(its_domain)):
if its_domain... | 440f423b7b25b0d152bc691acd3d7dea6c785aed | 3,645,981 |
def _causes_name_clash(candidate, path_list, allowed_occurences=1):
"""Determine if candidate leads to a name clash.
Args:
candidate (tuple): Tuple with parts of a path.
path_list (list): List of pathlib.Paths.
allowed_occurences (int): How often a name can occur before we call it a cla... | 3b874e4ea6d8780483100e464e3325321c82689e | 3,645,983 |
def run_eqm(results: Results, options: Options, state: PromisedObject) -> dict:
"""Run the eqm jobs."""
# set user-defined valuess
results['job_opts_eqm'] = edit_calculator_options(
options, ['eqm', 'xtpdft', 'esp2multipole'])
cmd_eqm_write = create_promise_command(
"xtp_parallel -e eqm... | 941d51a0de22dd4d66f5de68fc315bf318d112cf | 3,645,984 |
def is_within_boundary(boundary_right_most_x, boundary_top_most_y,
boundary_left_most_x, boundary_bottom_most_y,
cursor):
"""
Checks if cursor is within given boundary
:param boundary_right_most_x:
:param boundary_top_most_y:
:param boundary_left_most_x... | d53106c9d525eb1bb51cfe4c30bc7e143ac6a517 | 3,645,985 |
def save_matchmaking_auth_key(auth_key: str) -> bool:
"""Register a new matchmaking auth key. !This will overwrite the existing matchmaking key for this chain!
Args:
auth_key: auth_key to add for matchmaking
Returns:
Boolean if successful
"""
try:
redis.set_sync(MATCHMAKING_K... | 5f18614f2b2950a942e7a98773911b7f58aabd74 | 3,645,987 |
import requests
from bs4 import BeautifulSoup
def get_game_page(url):
"""
Get the HTML for a given URL, where the URL is a game's page in the Xbox
Store
"""
try:
response = requests.get(url)
except (requests.exceptions.MissingSchema, ConnectionError):
return None
game_pag... | 40d578ce8cda0b5139515e03f8308911169e0442 | 3,645,988 |
from typing import List
import logging
import itertools
import asyncio
async def generate_spam_round_tx_xdrs(pool, prioritizers: List[Keypair], prioritized_builders, unprioritized_builders, rnd):
"""Generate transaction XDRs for a single spam round (ledger) according to given builders.
Some of the generated ... | 7e33455718f6c99ccb9fc1ad6a7c3de47964ec98 | 3,645,989 |
import collections
from datetime import datetime
def json_custom_parser(obj):
"""
A custom json parser to handle json.dumps calls properly for Decimal and Datetime data types.
"""
if isinstance(obj, Decimal):
return float(obj)
elif not isinstance(obj, basestring) and isinstance(obj, co... | fb5d14b4416df4540ed3091dcf229aa7b037003d | 3,645,990 |
def fs_open(path, flag, mode=default_file_mode):
"""
Open a file, potentially creating it. Return the new fd's id or else -1 if
file can not be opened (or potentially created)
"""
# Check if file should be created if it doesn't exist
O_CREAT = 64
create = flag & 64
# If requested, try to create the fi... | 218940a6fc14c47f7a3df6d9a4e1bbc971b6b0b5 | 3,645,992 |
def new_user():
"""
Create Instance of User class to be used by the module
"""
user_details = ['Daudi', 'Jesee', 'dj@mail.com', 'password']
user = Users(user_details)
return user | 4d5b2c4cad858113fceef150143b9688488000f4 | 3,645,993 |
import math
def normalise_angle(angle: float) -> float:
"""Normalises the angle in the range (-pi, pi].
args:
angle (rad): The angle to normalise.
return:
angle (rad): The normalised angle.
"""
while angle > math.pi:
angle -= 2 * math.pi
while angle <= -math.pi:
... | 0a4cfa6e9da58bfdbb6cd4a04e7a742e8c432002 | 3,645,994 |
def get_hdf_len(*path):
"""
Returns the number of rows in an hdf file as an int.
"""
path = construct_path(*path)
with pd.HDFStore(path) as store:
numrows = store.get_storer('data').nrows
return numrows | ad188b2733612e7ed1950a2df0ef5164f9cda021 | 3,645,995 |
def matmul(A, B, transpose_A=False, transpose_B=False, master='/gpu:0'):
"""
distributed matrix multiplication.
A: DistMat,
B: single tensor or a list of tensors.
Note: returns a single tensor or a list of tensors, Not a DistMat.
"""
if isinstance(A, tf.Tensor) or isinstance(A, tf.Variable)... | 268068cd73b56ef747142ebc2df839d124d406d5 | 3,645,996 |
def celerybeat_started():
"""
Returns true/false depending on whether the celerybeat service is started or not
"""
if is_systemd():
running = 'active' in fabric.api.sudo('systemctl is-active %s' % celerybeat_service_name())
return running
return fabtools.service.is_running(celerybea... | b3578b6dbe91b9a16342c53c488fe01fc37275cd | 3,645,997 |
def highest_greedy_score(board, disks):
"""
Compute the highest possible score that can be obtained by dropping each
of the given disks on the given board in a greedy way.
- The disks must be dropped in the order in which they appear in the
given list of disks. Each dis... | 22fc70db81d6051158bdb9bf80a42d81a215dba1 | 3,645,998 |
def normalize_and_discard(df: pd.DataFrame) -> pd.DataFrame:
"""
Normalize numeric values between 0 and 1 and discard records that are out of bounds.
"""
# ## 2. Discard values out of range of x and y
df_cleaned = df[(df.x >= 0) & (df.x <= 120) & (df.y >= 0) & (df.y <= (160 / 3))]
print(f'Shape ... | 0b1a1e6ed76c72797cf7b3f65058592c6ec95b03 | 3,645,999 |
def gravatar_url(email, size=16):
"""Return the gravatar image for the given email address."""
return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \
(md5(email.strip().lower().encode('utf-8')).hexdigest(), size) | d3e24e1898d41df791368e7909461135c8118f90 | 3,646,000 |
def x2bin(v):
"""
convert a value into a binary string
v: int, bytes, bytearray
bytes, bytearray must be in *big* endian.
"""
if isinstance(v, int):
bits = bin(v)
size = 8
elif isinstance(v, (bytes,bytearray)):
bits = bin(int.from_bytes(v, "big"))
size = l... | fcb4f1ab05b5a3878939c84074e70fc2d5ee6397 | 3,646,001 |
import re
def normalize_url(url):
"""Function to normalize the url. It will be used as document id value.
Returns:
the normalized url string.
"""
norm_url = re.sub(r'http://', '', url)
norm_url = re.sub(r'https://', '', norm_url)
norm_url = re.sub(r'/', '__', norm_url)
return norm_url | 79197b9fa1c47da601bdb9c34d626d236b649173 | 3,646,002 |
import fsspec
def is_remote_filesystem(fs: fsspec.AbstractFileSystem) -> bool:
"""
Validates if filesystem has remote protocol.
Args:
fs (``fsspec.spec.AbstractFileSystem``): An abstract super-class for pythonic file-systems, e.g. :code:`fsspec.filesystem(\'file\')` or :class:`datasets.filesystem... | c40f9bb4845bbd1fc1a4cf9fce2c1b366cd22354 | 3,646,003 |
def get_element_attribute_or_empty(element, attribute_name):
"""
Args:
element (element): The xib's element.
attribute_name (str): The desired attribute's name.
Returns:
The attribute's value, or an empty str if none exists.
"""
return element.attributes[attribute_name].va... | dbc7f5c24d321c40b46f1c78950d7cf254719b5c | 3,646,004 |
def Matcher(y_true, y_pred_logits, y_pred_bbox):
"""
y_true: GT list of len batch with each element is an array of
shape (n_gt_objects, 5) ; n_gt_objects are number of
objects in that image sample and 5 -> (cx,cy,w,h,class_label)
where cordinates are in [0,1]... | 0918becd40feca73a54ce158a3cb86946cb377ff | 3,646,005 |
import warnings
def _addBindInput(self, name, type = DEFAULT_TYPE_STRING):
"""(Deprecated) Add a BindInput to this shader reference."""
warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2)
return self.addInput(nam... | 79404122d895814f64000876e8f926ecc7d54e3e | 3,646,007 |
import mpmath
def sf(x, c, d, scale):
"""
Survival function of the Burr type XII distribution.
"""
_validate_params(c, d, scale)
with mpmath.extradps(5):
x = mpmath.mpf(x)
c = mpmath.mpf(c)
d = mpmath.mpf(d)
scale = mpmath.mpf(scale)
if x < 0:
re... | 2e2649eeb4d32739027eb6ad5a0f3b8c50f7e341 | 3,646,008 |
def substitute_word(text):
"""
word subsitution to make it consistent
"""
words = text.split(" ")
preprocessed = []
for w in words:
substitution = ""
if w == "mister":
substitution = "mr"
elif w == "missus":
substitution = "mrs"
else:
... | 0709f4223cb06ddfdc5e9704048f418f275429d1 | 3,646,009 |
import re
import requests
from bs4 import BeautifulSoup
def google_wiki(keyword, langid='en', js={}):
"""Google query targets, output if English wikipedia entry is found"""
targets = []
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0',}
googl... | 23a449b0b8825d043d1ca3722cba4c373fcc5c3c | 3,646,010 |
def escape(line, chars):
"""Escapes characters 'chars' with '\\' in 'line'."""
def esc_one_char(ch):
if ch in chars:
return "\\" + ch
else:
return ch
return u"".join([esc_one_char(ch) for ch in line]) | f69409c92eacbbcab4232f7bb0ee244c77a4f219 | 3,646,012 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.