content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def assert_configs_work(backend, client_config, server_config, hostname=None):
"""
Given a pair of configs (one for the client, and one for the server),
creates contexts and buffers, performs a handshake, and then sends a bit of
test data to confirm the connection is up.
Returns the client and serv... | f93b34faf7697967e3e48fff09a1140adee85146 | 41,672 |
def read_result_file(fname):
""" read file with world record distances/paces """
running_paces = []
with open(fname, 'r') as result_file:
for line in result_file:
ent = line.split()
if 'distance' in ent[0]:
continue
dist_meters = float(ent[0]) * 10... | 81daa1b83e7e2aed6d0df08e1d82f4b929391bcc | 41,673 |
def is_droid_in_network_generation(log, ad, nw_gen, voice_or_data):
"""Checks if a droid in expected network generation ("2g", "3g" or "4g").
Args:
log: log object.
ad: android device.
nw_gen: expected generation "4g", "3g", "2g".
voice_or_data: check voice network generation or... | 3e22de2bee512800d7a1b05955f181a6bc4f2b91 | 41,674 |
def _getMatricesFromDft2Outfile(outPath):
""" Parses all hamiltonian and overlap matrices from a dft2 file
Args:
outPath: Full path to the output file
Returns
allMatrices: types.SimpleNamespace with two fields, hamil and overlap. Both are lists of square numpy arrays (dtype=complex).
The ind... | de8a8a240b795f217e401222eb2df91bdbd6c72c | 41,675 |
import hashlib
def verifySignatureFromBytes(data, publicKey, signature):
"""
Verify signature.
Arguments:
data (bytes) -- data in bytes
publicKey (str) -- a public key as hex string
signature (str) -- a signature as hex string
Return bool
"""
if len(publicKey) == 66:
publicKey = uncompressEcdsaPublicKey(... | c80fb3f641b81e0b3ae7135c0bc2a437b2f298dd | 41,676 |
def limit_posts(posts, limit=POST_LIMIT):
"""Restrict posts to the <limit> most recent."""
return posts.order_by(desc(Post.published_datetime)).limit(limit).from_self() | b0f172ffbb71d2516ccadd1c3cc3611d1703cf17 | 41,678 |
def command(login_required=True):
"""a decorator for handling authentication and exceptions"""
def decorate(f):
def wrapper(self, args):
if login_required and self.api_client is None:
self.stdout.write("Please 'login' to execute this command\n")
return
... | eaab4b3fa49012726072f54a5cd68a4369b64e25 | 41,679 |
def do(ModeName, CaMap, IndentationSetup, IncidenceDb, ReloadState, dial_db):
"""________________________________________________________________________
Counting whitespace at the beginning of a line.
.-----<----+----------<--------------+--<----.
| | count ... | 870be816e5837b67f568d1f008ae580387bba09f | 41,680 |
from stat import S_ISDIR
def list_remote_files(con, directory):
"""
List the files and folders in a remote directory using an active SFTPClient from Paramiko
:param con: SFTPClient, an active connection to an SFTP server
:param directory: string, the directory to search
:return: (generator, generator), the files... | f65e4a5d48f793ff3703ea5e4fc88a0e9b7ea39d | 41,681 |
def potential_aneurysm(data, box_size=64, accuracy=0.005, neighbours=False, pix_close=10):
"""
Goes through the given image and returns a list of possible aneurysms
Parameters
----------
data : numpy.ndarray
Data array of the MRA image of interest
box_size : int
Size of one s... | 79b2f1123e33f012ddafceb90a0be660881736b8 | 41,682 |
def det_curve(y_true, scores, distances=False):
"""DET curve
Parameters
----------
y_true : (n_samples, ) array-like
Boolean reference.
scores : (n_samples, ) array-like
Predicted score.
distances : boolean, optional
When True, indicate that `scores` are actually `distan... | 8b2b08799ff3062783af5fc2e94bbc90238ae769 | 41,685 |
def _get_nary_broadcast_shape(*shapes):
"""
Broadcast any number of shapes to a result shape.
Parameters
----------
shapes : tuple[tuple[int]]
The shapes to broadcast.
Returns
-------
tuple[int]
The output shape.
Raises
------
ValueError
If the inpu... | 0669ba10cbdb824b5ca9a827d6935ddb9c9a787e | 41,686 |
def html_to_dot_sequential_name(
root: lxml.html.HtmlElement, graph_name: str, with_text: bool = False
) -> graphviz.Digraph:
"""
The names of the nodes are defined by `{tag}-{seq - 1}`, where:
tag: the html tag of the node
seq: the sequential order of that tag
ex: if it is the 2... | decd9a4b311c126b418a1be7a982475603001009 | 41,687 |
import six
def get_exception_for_sqlstate(code):
"""Translate the sqlstate to a relevant exception.
See for a list of possible errors:
http://www.postgresql.org/docs/current/static/errcodes-appendix.html
"""
if isinstance(code, six.binary_type):
code = bytes_to_ascii(code)
if code[0]... | 634e9485c19065db7f46bd76e431f303f52916a6 | 41,688 |
def action_from_policy(policy, deterministic=False):
"""
Samples an action from a given policy using numpy.
"""
if not deterministic:
return np.random.choice(range(len(policy)), p=policy)
else:
argmaxes = np.argwhere(policy == np.max(policy)).reshape(-1)
return choice(argmaxe... | 6f39eab81ef75f4a47bac792c6f3450de88423e1 | 41,689 |
def error_rate(predictions, imgs):
"""Return the error rate based on dense predictions and sparse labels."""
return 0.5 * ((predictions - imgs)**2).mean() | 22fb7ccee4facff54e41e784cdb7c317e0e3f8dc | 41,690 |
def setup_configs(args):
"""
args:
::dataset_name
::resolution
"""
ic(args)
config = Munch(
dataset_name=args.dataset_name, y_col="family", threshold=0, resolution="original"
)
target_config = Munch(
dataset_name=args.dataset_name, resolution=args.resolutio... | 502e2a60f1cac25b45804b98cf035ef544c87ae2 | 41,691 |
def fmap(func, obj):
"""fmap(func, obj) creates a copy of obj with func applied to its contents.
Override by defining obj.__fmap__(func). For numpy arrays, uses np.vectorize.
"""
obj_fmap = _coconut.getattr(obj, "__fmap__", None)
if obj_fmap is not None:
try:
result = obj_fmap(f... | 5022570ab4aa98fc6d65f8b93936902996f82fdb | 41,692 |
def last_month(date):
"""get the name of month"""
date = str(date)
date = date[:4] + '-' + date[4:]
date0 = arrow.get(date)
lastmon = date0.shift(months=-1)
lastmon = lastmon.format('YYYYMM')
return lastmon | ffa43a888cc3447c424358315c7a412fbb644704 | 41,693 |
def camera_to_sky(pos_x, pos_y, focal, pointing_alt, pointing_az):
"""
Parameters
----------
pos_x: X coordinate in camera (distance)
pos_y: Y coordinate in camera (distance)
focal: telescope focal (distance)
pointing_alt: pointing altitude in angle unit
pointing_az: pointing altitude i... | c2c15b6a1b0411e463cb8a7dabb3a3bfe0ac14c9 | 41,694 |
import dataclasses
def static_field(*args, **kwargs):
"""Substitute for dataclasses.field, which also marks a field as static."""
kwargs["metadata"] = kwargs.get("metadata", {})
kwargs["metadata"][FIELD_METADATA_STATIC_MARKER] = True
return dataclasses.field(*args, **kwargs) | 400dbfc987fa9378d71fa92da086cddf8abae112 | 41,695 |
def _standardize_overhangs_pair(overhangs):
"""Standardize a pair of overhangs (o1, o2).
Returns either ``(o1, o2)`` or its reverse complement ``(rev_o2, rev_o1)``,
whichever is smaller in alphabetical order.
"""
o1, o2 = overhangs
ro1, ro2 = [reverse_complement(o) for o in (o1, o2)]
return... | 433ac7517764d9c2614f2d87aefdb8949c835de8 | 41,696 |
import json
def unjsonb(bytes):
"""bytes -> list"""
return [json.loads(s.decode("utf-8")) for s in bytes.splitlines()] | e831851ea0149d46d73610fc1979168aba9ef1cd | 41,697 |
from datetime import datetime
def get_nixtime_from_msec(msec):
""" Convert unix epoch time in microseconds to a date string """
seconds, msec= divmod(msec, 1000000)
days, seconds = divmod(seconds, 86400)
if days > 20000 or days < 9000:
days = 0
seconds = 0
msec = 0
return d... | 6ec4f13a4296e2180eef4c0f99688ec997461739 | 41,698 |
def doHammingByte(byte):
"""Secures one byte by hamming code"""
#P1 = A1 xor A2 xor A4 xor A5 xor A7
P1 = str(
int(byte[0]) ^
int(byte[1]) ^
int(byte[3]) ^
int(byte[4]) ^
int(byte[6])
)
#P2 = A1 xor A3 xor A4 xor A6 xor A7
P2 = str(
int(byte[0]... | fca53ce3958820ac3ed122d00045edd46d7e36d8 | 41,700 |
def partial_flatten(x):
"""Flatten all but the first dimension of an ndarray."""
return np.reshape(x, (x.shape[0], -1)) | c2596b8cdc8097fb374b153da2246dc307568751 | 41,701 |
from typing import Counter
def get_spawn_day_counts(input: list[int], days: int) -> dict[int, int]:
"""Count the total number of fish after a given number of days and starting
fish (number of days until they spawn another fish).
"""
spawn_day_counter: dict[int, int] = {}
for spawn_day in range(d... | 7d43cea6c1f737d5977644715af7a2fa38f8abbb | 41,702 |
def get_all(*, db_session):
"""Returns all tickets."""
return db_session.query(Ticket) | dfc709adebe07b2be5ff56dca9eaca6c4baffd4b | 41,703 |
def _directly_configure_from_flags(fields):
"""Helper function that translate flag values to a dict."""
return {field: getattr(FLAGS, field) for field in fields} | 5a4d14486f9b7fbc97d0bc0f78fd8ba017593036 | 41,704 |
def clean_text(text):
"""
Applies all the filters to input text.
:param text: The input string.
:type text: String.
:returns: The processed String.
:return type: String.
"""
text = text.lower()
text = strip_accents(text)
text = strip_digitsAndSpecialChars(text)
retur... | 3e309ccc8784702b89bf75915ff3857def1bc5d9 | 41,705 |
def get_sleep_time(time_start, time_now, poll_int):
"""Calculate time to sleep.
Args:
time_start(datetime): Time loop started
time_now(datetime): Current time
poll_int(int): Poll interval in seconds
Returns:
sleep_time(float)
"""
time_sleep = poll_int... | 6d3a00d12c8ff5677c9625228a2150bca55762de | 41,706 |
def sqrt(node) -> Node:
"""square root of the node, np.sqrt"""
return Node(node, None, np.sqrt(node.value), 'sqrt' ) | f4be8b3c57c5467ef9cbf41cacb5a2bb40c4c17a | 41,707 |
import random
def permute_code_object(baseline):
"""Take a code object and change one byte of the bytecode."""
bytecode = list(baseline.co_code)
bytecode[random.randint(0, len(bytecode) - 1)] = random_char()
return clone_code_object(baseline, code="".join(bytecode)) | cf9444def6e2a33c7ef17b0bfaeef56295b66245 | 41,708 |
def _fix_values(key, md):
"""
Recursively search each item in metadata
and reassign values.
"""
i = md[key]
md = _set_val(i, key, md)
if isinstance(i, list):
new = []
for idx in range(len(i)):
new.append(_fix_values(idx, i)[idx])
md[key] = new
if isins... | 1b79b6ab391b64b1a8da59a78c216e744bec84b5 | 41,711 |
def imstackshow(im_stack, time_points=None,
color_mapper=None, downscale=1,
plot_height=400):
"""
Build display of image stack.
Parameters
----------
im_stack : list of tuple of 2d Numpy arrays
List of images
time_points : ndarray, default None
... | 96a9e20df9704a0d0bdfed80553f367e7c874609 | 41,712 |
def distinct_count(daskDf, columnName):
"""Counts distint number of values in Dask dataframe
Keyword arguments:
daskDf -- Dask dataframe
columnName -- Column name
Return:
return -- Distinct number of values
"""
return daskDf[columnName].drop_duplicates().size | 27a03a6eef1f9c949d22f02e5d880ef626b6acf6 | 41,713 |
def pow_3_of(number):
"""
cube input number
helper function from lalsimulation/src/LALSimIMRPhenomD_internals.h
"""
return number*number*number | 18a8a3922ec2315b7d170b00362511208792d2df | 41,714 |
def boolean_search(
query,
inverted_index
) -> list:
"""
Implementation of the boolean search by keywords: {"AND", "OR"}
:type query: str,
:type inverted_index: defaultdict
"""
resulting_index = []
# Extracting the dict of key/value pairs, where key is token
query_dict = ... | 93ac84dfea2811d637b56bb52bb8931293c1c4f9 | 41,715 |
def sample_views(nviews):
"""View sampling function.
Args:
nviews: Number of views to be sampled
Returns:
rot_trans_list: list of (rot, trans) tuples
"""
rot_trans_list = []
for _ in range(nviews):
x_cam = np.random.uniform(-0.5, 0.5)
y_cam = np.random.uniform(-0.5, 0.5)
z_cam = 0
... | edcd9ef0a30004f5d9cf03b97e26827f2f70e17a | 41,716 |
def get_step_rolling(cycle_nr=1):
""" Get the step name for rolling step in cycle cycle_nr
:param cycle_nr: The cycle number
:type cycle_nr: int
:returns: The step name
:rtype: str
"""
return 'rolling_' + cycle_str(cycle_nr) | cef011e1e1752d13eef5b96083679bd2ddf66442 | 41,717 |
def read_list_h5(h5):
"""
Read list from h5 file.
A list is a group of groups named with their index, and attributes as the data.
The format corresponds to that written in write_lattice_h5
"""
# Convert to ints for sorting
ixlist = sorted([int(k) for k in h5])
# Back to s... | df62927bf7afc0bad751a9b80b63ec2c1c944a7d | 41,718 |
def verse(num_of_bottles):
"""bottle verse"""
b = "bottle" if num_of_bottles == 1 else "bottles"
if num_of_bottles==1:
last = "No more bottles"
elif num_of_bottles==2:
last = "1 bottle"
else:
last = f'{num_of_bottles-1} bottles'
return '\n'.join([
f'{num_of_bot... | 57cf46e430a7a75deb9e6b88c5defa35991fda4e | 41,720 |
def fizz_buzz(tuple):
"""
Transform the input tuple to a string that follows
the Fizz Buzz rules
Args:
tuple: tuple
Returns:
string
"""
if tuple == 0:
return None
ret_val = ""
if tuple % 3 == 0:
ret_val += "Fizz"
if tuple % 5 == 0:
ret... | 4053cad878c05fa0430835a9a9728a6c0b8e420d | 41,721 |
def f1_score(precision, recall):
"""Creates an op for calculating the F1 score.
Args:
precision: A tensor representing precision.
recall: A tensor representing recall.
Returns:
A tensor with the result of the F1 calculation.
"""
return tf.where(
tf.greater(precision + recall, 0), 2 * (
... | 2cad9591eea0581b7076108cb50f15ddb9070c46 | 41,722 |
import math
def gradient_and_profile_with_spline(T, F, period, phase_given, time_half_transit, amplitude, spline):
"""a variant of profile wtih spline it also returns gradient"""
if period < 0.0:
print(("Invalid period in gradient_and_profile_with_spline"))
raise ValueError
elif time_half_... | 23ab0af1abf73d1adcf332418f66611954236945 | 41,724 |
def disk_to_dict(disk):
"""Converts a lxml.objectify.ObjectifiedElement disk object to a dict.
:param lxml.objectify.ObjectifiedElement disk: an object containing
EntityType.DISK XML data.
:return: dictionary representation of disk object.
:rtype: dict
"""
result = {}
result['name... | 458c243018474bd2e3e331b71b972eae4d2bc0ee | 41,725 |
def get_hashID(username, hashMode=64, tableGroup=4):
"""根据 username 确定唯一 hash 值(确定分表)
# 分组公式:64 = 每组多少个count * group需要分组的个数
# 数据所在环的位置(也就是在哪个库中):value = key mode 64 / count * count
hash(key)在0~3之间在第0号表
hash(key)在4~7之间在第4号表
hash(key)在8~11之间在第8号表
hash(key)在0~3之间在第0号库
hash(key)在4~7之间在... | 068ed14923f9fdf57d12b233e94ee7dee8bf8a12 | 41,726 |
from typing import OrderedDict
def save_chain(config, chain):
"""
Encode a chain of operation classes as json.
:param config: dictionary with settings.
:param chain: OrderedDict of operation class lists.
:return: string-encoded version of the above.
"""
di = OrderedDict()
di['__config__'] = config
for k... | d6838dfe1f079233ba8e3d93c62ddc1ebbcec5e4 | 41,727 |
def _trigger_task(options):
"""Triggers a task on the compile server by creating a file in storage."""
task = _create_task_dict(options)
# Check to see if file already exists in Google Storage.
if not _does_task_exist_in_storage(task):
_write_to_storage(task)
return task | fe611b79ebe0ed52ef940784ebd1dc1d3d951f0d | 41,728 |
def map_vcf_row(row, df_cell_vcf):
"""
get ref and UMI for each variant
row: each row from merged_vcf
"""
pos = row['pos']
chrom = row['chrom']
alt = row['alt']
df_pos = df_cell_vcf[(df_cell_vcf['pos'] == pos) & (df_cell_vcf['chrom'] == chrom)]
df_ref = df_pos[df_pos['alt'] == '.']
... | ce80e83b8a16609038c637ed815df49677ff6efc | 41,730 |
def plot_no_pooling_model(
samples: MonteCarloSamples,
query: RVIdentifier,
df: pd.DataFrame,
) -> Figure:
"""
Plot the no-pooling model.
:param samples: Bean Machine inference object.
:type samples: MonteCarloSamples
:param query: Bean Machine query object.
:type query: RVIdentifie... | 15c98eaa026b2394cde1b5c8cc96243757ccec74 | 41,732 |
import warnings
def get_space_permissions(id_value, id_type='browse_id', return_type='list'):
"""This **deprecated** function returns all of the defined permissions (aka ``appliedEntitlements``) for a space.
.. deprecated:: 2.6.0
The function has been renamed to be :py:func:`khorosjx.places.spaces.get... | c6a61298879d6a17c04905dc3dfb2de2c0670eff | 41,733 |
def validate(schema_filename, data_filename, seen_uids):
"""Validate a YAML file according to the supplied schema."""
schema = yamale.make_schema(schema_filename)
data = yamale.make_data(data_filename)
try:
print("")
print("Checking file '{}'...".format(data_filename))
yamale.va... | d23017533f485275705377952be364bd0e20c223 | 41,734 |
def register_shellcontext(app):
"""Register shell context objects."""
def shell_context():
"""Shell context objects."""
return {
'db': mongo}
app.shell_context_processor(shell_context) | 4206fa496d4593b451a333f67f81cb976aa408e8 | 41,735 |
def db_connection_string(dbconf): # type: (dict) -> str
"""
Constructs a database connection string from the passed configuration object.
"""
user = dbconf["user"]
password = dbconf["password"]
db_name = "traffic_ops" if dbconf["type"] == "Pg" else dbconf["type"]
hostname = dbconf["hostname"]
port = dbconf["por... | 3fbb52c398f5150f6101b9d0d286f1db1b8aa99f | 41,736 |
def memory_stream_one_way_pair():
"""Create a connected, pure-Python, unidirectional stream with infinite
buffering and flexible configuration options.
You can think of this as being a no-operating-system-involved
Trio-streamsified version of :func:`os.pipe` (except that :func:`os.pipe`
returns the... | 3fa29609d20ed5d55eed6ac4b8cc389b88ac2e82 | 41,737 |
def round2sigfig(num,nfig=1):
"""Round number to significant figures"""
def ndecimal(x):
if x==0 or not np.isfinite(x):
# "Behaviour not defined" => should not be relied upon.
return 1
else:
return -int(floor(log10(abs(x))))
nfig =nfig-1
n = nfig ... | 27cf8545ed33f3cca8f4da28370fd42a185e427d | 41,738 |
def _subsample_selection_to_desired_neg_pos_ratio(
indices, match, max_negatives_per_positive, min_negatives_per_image):
"""Subsample a collection of selected indices to a desired neg:pos ratio.
Arguments:
indices: an int or long tensor with shape [M],
it represents a collection of ... | b5e841fe9dd61f4ec1b3e0674dfddad758dcf7fb | 41,739 |
def normalize_units(
df,
unitsmap,
targetunit,
paramcol="parameter",
rescol="res",
unitcol="units",
napolicy="ignore",
):
"""
Normalize units of measure in a dataframe.
Parameters
----------
df : pandas.DataFrame
Dataframe contained results and units of measure d... | 89aa2692ae778eede36d02b8bea756793a55c172 | 41,740 |
def shorten(k):
"""
k an attrname like foo_bar_baz.
We return fbb, fbbaz, which we'll match startswith style if exact match
not unique.
"""
parts = k.split('_')
r = ''.join([s[0] for s in parts if s])
return r, r + parts[-1][1:] | 6d9c29849cc5a63ec466d2548ea2492d112946cf | 41,741 |
def get_time_query_for_trip_like(key, trip_like_id):
"""
Returns the query that returns all the points associated with this
trip-like (examples of trip-like objects are: raw trip, cleaned trip, raw section)
"""
trip = get_object(key, trip_like_id)
return get_time_query_for_trip_like_object(trip... | 057561a7cb014fd04be53fe1d57de5c739b36e26 | 41,742 |
def test_context_3():
"""
store and load 10 global variables, load the 10 variables again, repeat
with different values
"""
nvars = 10
numlist1 = [str(random_ndigits(10)) for _ in range(nvars)]
numlist2 = [str(random_ndigits(10)) for _ in range(nvars)]
inplist = numlist1 + ['pop'] * nva... | c91be8e3977065cfcbbca95a8086fa29a8f0f72a | 41,743 |
def drop_short_sentences(X, min_len=2):
"""
:param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return:
>>> drop_short_sentences([['ita', 'vero'], ['quid', 'est', 'veritas'], ['vir', 'qui', 'adest']])
[['quid', 'est', 'veritas'], ['vir', 'qui', 'adest']]... | 1cae9d06ca9b83ebd51df5be5ed0c32cc6973967 | 41,744 |
import re
import textwrap
def reflowed_lines(lines, regex, line_length):
"""Get the realigned lines
This method takes a list of strings and lays them out respecting the given
line length while also lining up the hanging lines
:param lines: list of strings to realign
:param regex: regex to identi... | c8972f0f42b4eb8e4ec04fa617b2783b3cb9b77a | 41,745 |
def get_current_formatted_date():
"""Get current date or previous business day"""
try:
current_time = get_current_time()
diff = 0
if current_time.weekday() == 5:
diff = 1
if current_time.weekday() == 6:
diff = 2
return format_date(current_time - ... | a4692d705612a0eece21296535dc2ca7662f371a | 41,746 |
def pdb_target_dataset(original_dataset_path, go_dataset_path,
mapping_dataset_path, human_dataset_path,
col_name_entry = 'entry_ac', col_name_pdb = 'pdb_ids'):
"""
1. original_dataset_path: the path of the target dataset, a.k.a the dataset of protein tha passed ou... | eb4888b065f4bbc46a0d79f5ef101b64eb2e3d0b | 41,747 |
def search(request):
"""
Search IETF Groups
**Templates:**
* ``groups/search.html``
**Template Variables:**
* form, results
"""
results = []
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
kwargs = {}
grou... | c0b5a558d56524f1bd65a4cf505a5632bf3625b2 | 41,748 |
from typing import List
def elitist_selection(chromosome: AbstractChromosome, mutated_chromosomes: List[AbstractChromosome],
objective: Objective) -> AbstractChromosome:
""" Selects a chromosome using the elitist strategy
Args:
chromosome (AbstractChromosome): The source chromos... | c922129c252af8e80325c4e09da6da474b3b9c11 | 41,749 |
def prettyprint_jobs_single(data: dict) -> str:
"""
Prettyprinter for single job output
"""
output = ''
job_data = data['data']['jobs'][0]
result = 'None'
exception = 'None'
if job_data['exception'] is not None and 'message' in job_data['exception']:
exception = job_data['exce... | 64818c27bb4486cf87f6ac1ce7471d447eea7093 | 41,750 |
from datetime import datetime
import time
def main(*args):
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
@param args: command line arguments
@type args: str
"""
pywikibot.output(color_format("Start: {white}{0}{default}", datetime.now()))
... | 8ef728e8f32456972b60ffdce0b41096e104d9af | 41,751 |
def extractLightNovelCafe(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Evolution Theory of the Hunter' in item['tags']:
return buildReleaseMessageWithType(item, 'Evolution Theory of t... | 12cea449bbc128842fe1ddc1e1c558e6efc28056 | 41,752 |
async def poll_control_device(zha_device_restored, zigpy_device_mock):
"""Poll control device fixture."""
cluster_id = zigpy.zcl.clusters.general.PollControl.cluster_id
zigpy_dev = zigpy_device_mock(
{1: {"in_clusters": [cluster_id], "out_clusters": [], "device_type": 0x1234}},
"00:11:22:33:... | 03a86a75e09eff4c05bafcdc7b01597c159766f8 | 41,753 |
from typing import List
def load_tf_sess_variables_to_keras_single_gpu(path: 'str', compressed_ops: List['str']) -> tf.compat.v1.keras.Model:
"""
Creates a Keras model subclass and loads the saved session, meta graph and variables to Keras model
:param path: Path to load the tf session saved using save_s... | d18f49f296a5274aafc53476c52de0c8939a6ac7 | 41,754 |
def standardizeText(line, forward=True):
"""
Remove whitespace, lowercase,
and end with termination character \r
"""
text = line.strip().lower()[:63]
return (text if forward else text[::-1]) + '\r' | 5487f416abe78385f712c7b0ec652b4548accbf0 | 41,755 |
def selstr(a, start, stop):
""" Select elements of a string from an array.
:param a: array containing a string.
:param start: int referring to the first character index to select.
:param stop: int referring to the last character index to select.
:return: array of strings
"""
if type(a... | 91400815c1be10f1691be2799ce84229d121afec | 41,756 |
from .preprocess import tokenize_docs, create_pipeline
from gensim.models import Phrases
from typing import Callable
from typing import Optional
from typing import Pattern
from typing import Iterable
import tqdm
def detect_phrases(
docs_reader: Callable,
passes: int = 1,
lowercase: bool = False,
detec... | 584031b4b20605e86740ab773a12f2fc09a72837 | 41,757 |
from typing import List
from typing import Dict
from typing import Any
def format_sents_for_output(sents: List[str], doc_id: str) -> Dict[str, Dict[str, Any]]:
"""
Transform a list of sentences into a dict of format:
{
"sent_id": {"text": "sentence text", "label": []}
}
"""
... | d6178ac48da4d95e8d3727ca9220168e06ba223e | 41,758 |
import re
def get_sale(word):
"""Convert the input into a dictionary, with keys matching
the CSV column headers in the scrape_util module.
"""
number_word = [idx for idx, val in enumerate(word) if is_number(val)]
cattle_string = word[number_word[0]+1]
# Skip lines describing sales of no... | 0c9e3d276cbc91906d66d1a8ea65fb75d25aba5d | 41,759 |
def get_all_feed_groups_detached(feed_name):
"""
Returns a list of FeedMetadata objects populated with FeedGroupMetadata objects as returned by the db, but detached from the session.
:return: list of FeedMetadata objects
"""
db_session = get_session()
try:
feeds = lookup_feed(db_session... | 0abc1d57753bed2b6392086e9e8cfe89832ad7f3 | 41,760 |
from ctypes import c_int, c_char, POINTER, byref
from mceq_config import mkl
from ctypes import c_double as fl_pr
from time import time
def solv_MKL_sparse(nsteps, dX, rho_inv, int_m, dec_m, phi, grid_idcs):
# mu_loss_handler):
"""`Intel MKL sparse BLAS
<https://software.intel.com/en-us/articles/intel-mkl... | 1e3a774747384e49c4fad7123228696e1749aeff | 41,761 |
from typing import List
from typing import Union
from typing import Dict
from typing import Set
def get_nearest_neighbors(
node_ids: List[Union[int, str]], embeddings: np.ndarray, num_nearest: int
) -> Dict[Union[int, str], Set[Union[int, str]]]:
"""
Compute similar nodes among a set of embeddings.
P... | d1bb386a9f1eb17f2a040c60fa0da219c777115d | 41,762 |
def compress_ind(x: np.ndarray, width: int):
"""
Compress array to a given size (width).
:param x:
Array
:param width:
Total size of the new array.
:return:
Compressed array.
"""
comp_arr = np.empty(width, dtype=np.float32)
comp_arr[:], ind_width, i = np.NaN, int(... | 0851ea83c27835d717a1c73fa85f4ba9d05d130f | 41,763 |
import numpy
def _op_type_domain_classifier(dtype):
"""
Defines *op_type* and *op_domain* based on `dtype`.
"""
if dtype == numpy.float32:
return 'TreeEnsembleClassifier', 'ai.onnx.ml', 1
if dtype == numpy.float64:
return 'TreeEnsembleClassifierDouble', 'mlprodict', 1
raise Run... | 2ca981cd5a4be1a2c9cc8c013a3502ba08634ccb | 41,765 |
def get_guess(guesses):
"""
This function will get the user's guess.
"""
# Get the user's guess.
guess = input("------\nGuess a letter: ")
# Check if the user has already guessed the letter.
if guess in guesses:
print("You've already guessed that letter.")
return get_guess(guesses)
# Return the guess.
re... | 04b559d3850421ef91fa1ce5d9850b2f4852f917 | 41,767 |
def primes(n):
"""Prime number less than n"""
return takewhile(lambda p: p < n, erat2()) | acf35fda04f1824662aaafbc72f10c1c214daf48 | 41,768 |
import json
def get_config(config_file: str = None) -> dict:
"""Returns the configuration from a config file
:param config_file: json file with the configurations
:type config_file: str
:return: dictionary with the configurations
:rtype: dict
"""
if not config_file:
return CONFIG
... | b4dc7d787f131990014d088cd85e07f60657b843 | 41,770 |
def browse(session, queue, timeout=0, transform=lambda m: m.content):
"""Return a list with the contents of each message on queue."""
r = session.receiver("%s;{mode:browse}"%(queue))
r.capacity = 100
try:
return [transform(m) for m in receiver_iter(r, timeout)]
finally:
r.close() | 2d09023c6b485338984b210d097e1ca50af4dbf2 | 41,771 |
import numpy
def _run_pmm_one_variable(
input_matrix, max_percentile_level=100):
"""Applies PMM to one variable.
E = number of examples (realizations over which to average)
:param input_matrix: numpy array. The first axis must have length E. Other
axes are assumed to be spatial dimension... | 4e4658b99ea2c6a2a5a27d2d1ba701709c3a7d94 | 41,772 |
def is_addon_dir(addon_dir):
""" Test if a directory contains an Odoo addon. """
return bool(get_manifest_path(addon_dir)) | 82752c8abb18ea23abf6d5886446ea7643897d21 | 41,774 |
import warnings
def stats_summary(X, sigma=5.0, n_min=5, kde=True, bw=None,
prefix=None, verbose=False, return_clipped=False):
"""
Statistical summary of an array.
"""
keys = ['low', 'upp', 'mean', 'median', 'std', 'kde', 'sigmaclip']
if prefix is not None:
keys = ['_'.jo... | 4a7a147339654f344720dafba6e11c456afe8748 | 41,775 |
def forward_pfb(timestream,nchan=NCHAN,ntap=NTAP,window=h.sinc_hanning):
"""Performs the Chime PFB on a timestream
Parameters
----------
timestream : np.array
Timestream to process
nchan : int
Number of frequencies we want out (probably should be odd
number because of Ny... | 880994d33c28e6c4dca3292ab2355a4819a5f102 | 41,776 |
def get_jsrun_launcher(num_procs, args):
"""Return the base launch command using jsrun."""
ppn, num_nodes = get_ppn_and_nodes(num_procs, args.procs_per_node)
return ['jsrun',
'--nrs', str(num_nodes),
'--rs_per_host', '1',
'--tasks_per_rs', str(ppn),
'--cpu_per... | ddf32fc1e259d41916efd4b8521bea0f2dd96bb5 | 41,777 |
def generation_solution(villes):
"""
With the cities as a list, we generate a random permutation of this list
to create a solution
"""
return np.random.permutation(villes) | 1470150729f1ffd90f586e979906b05b9fbf8cf6 | 41,778 |
from typing import Dict
from typing import Any
import yaml
def get_config(config_path: str) -> Dict[str, Any]:
"""Parse the JSON config file at the given path and return the `dict`."""
with open(config_path, 'r') as config_file:
return yaml.load(config_file) | 71d37aa71ccb110ede2e808a37be051ed625b482 | 41,779 |
def dis_gamma_ll(ab, k, theta):
"""Log-likelihood of a discrete gamma distribution
k - shape parameter
theta - scale parameter
Normalization constant is calculated based on a cuf-off (currently set at 10**5)
"""
cutoff = 1e5
gamma_sum = sum(stats.gamma.pdf(range(1, cutoff + 1), k, ... | fdc7c1757b9212042b1032c4501bf93e70f991c9 | 41,780 |
import csv
def parse_input(input_file):
"""
Parse the input with a dict reader and returns tthe data aggregated per taxid
"""
data_per_taxid = defaultdict(list)
data_per_taxid_and_assembly = defaultdict(list)
with open(input_file) as open_file:
reader = csv.DictReader(open_file, delim... | 78594c103c8acc5afbb0c0fb800bfff2943869aa | 41,781 |
from typing import Counter
def generate_common_dict(d1, d2):
"""Generate a dictionary by combining d1 and d2
Args:
d1 (list): a list of words
d2 (list): a list of words
Returns:
Counter: combined dictionary
"""
word1 = d1.copy()
word1.extend(d2)
c = Count... | 581a41f60ae47caadced8a08ef1c4356a9b7d3b8 | 41,782 |
import six
def metrics(
metrics, has_script=None, has_capability=None, matcher=None, access=None, volatile=True
):
"""
Decorator to use inside get_metrics script to denote functions
which can return set of metrics
@metrics(["Metric Type1", "Metric Type2"])
def get_custom_metrics(self, metrics... | 288fa0bc59772cb3a8c77c28f1ae1d0bc82d7e0a | 41,783 |
import functools
def build_dummy_sequential_net(fc_layer_params, action_spec):
"""Build a dummy sequential network."""
num_actions = action_spec.maximum - action_spec.minimum + 1
logits = functools.partial(
tf.keras.layers.Dense,
activation=None,
kernel_initializer=tf.random_uniform_initializ... | 9e78571da336d6e82909f355aa5e15b7e2367ab9 | 41,784 |
def calc_process_time(t1, t2):
"""Calculates difference between times
Args:
t1 (float): initial time
t2 (float): end time
Returns:
str: difference in times
"""
return str(t2 - t1) | 72e59c1a053041aae53cdb4415b241499eefdd4c | 41,787 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.