content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Annotated
def fast_fitting_predicate(
page_width, # Ignored.
ribbon_frac, # Ignored.
min_nesting_level, # Ignored.
max_width,
triplestack
):
"""
One element lookahead. Fast, but not the prettiest.
"""
chars_left = max_width
while chars_left >= 0:
... | 5ebb7847f7841236c9fc991e592f9504074f981a | 48,100 |
def fallout_rate(y_true, y_pred, sample_weight=None):
"""
The fallout rate is also known as the False Positive Rate.
At the present time, this routine only supports binary
classifiers with labels taken from {0, 1}.
By definition, this is the complement of the
Specificity, and so uses :any:`speci... | aacf7c56f371e80b8196ac3ff1246c2d9338423d | 48,101 |
from typing import Callable
import operator
def get_side_operator(side, invert=False) -> Callable:
"""
generic operator selection when comparing odds
- if side is 'BACK', returns gt (greater than)
- if side is 'LAY', returns lt (less than)
- set invert=True to return the other operator
"""
... | 61c105b585cb3fa127eff51ce4651168c292a1e8 | 48,102 |
import random
def search_dag(G,edge_a,edge_b):
"""Operador de reparo: Verfica se o grafo possui ciclo, se tiver um ciclo
ele retira uma aresta do circulo que não seja a ultima que foi adicionada.
Entrada: G=Grafo
edge_a e edge_b= nós da ultima aresta adicionada, sendo a->b.
Saída: Gráfo... | 013ca6eed206ba6f26610e7516129d239c4940ef | 48,103 |
import re
def collapse_namespace(namespaces, cell):
"""TODO"""
uf_link = """<a href=\"{}" target=\"_blank\">{}</a>"""
or_statement = "|".join([uri for _, uri in namespaces])
pattern = f"({or_statement}).*"
quick_check = re.match(pattern, str(cell))
if quick_check:
for term, uri in nam... | 9d580485673d60da2626b22984a01eff59a58f0e | 48,104 |
import gzip
def read_ids(filename):
"""
Read record IDs from a file.
Parameters
----------
filename : str
Filename containing record IDs.
"""
if filename.endswith('.gz'):
f = gzip.open(filename)
else:
f = open(filename)
ids = [line.strip() for line in f]
... | 588fd86a3fd8b504cf5419924032b25c81e52004 | 48,105 |
import json
def dumps(obj):
"""
Serialize ``obj`` to a JSON formatted ``str``.
序列化对象
"""
return json.dumps(obj) | 8fa77ad5615531eea0e2190abf9eaf27196a2337 | 48,106 |
def from_grid_range(x):
"""from [-1,1] to [0,1]"""
return (x + 1) / 2.0 | a36e3ccace6fe385eeef1f4b5bf64c00f7b971ba | 48,107 |
def ddpg(
# Common settings
device="cuda",
discount_factor=0.98,
last_frame=2e6,
# Adam optimizer settings
lr_q=1e-3,
lr_pi=1e-3,
# Training settings
minibatch_size=100,
update_frequency=1,
polyak_rate=0.005,
# Replay Buffer... | c80c0b6802fb548721598eb36d6c24e16cbbb022 | 48,108 |
import re
def escaped_split(inp_str, split_char):
"""
Split inp_str on character split_char but ignore if escaped.
Since, return value is used to write back to the intermediate
data file, any escape characters in the input are retained in the
output.
:param inp_str: String to split
:param... | 13eaf77ffff52fdd6cfaa83ee08fc773f241be17 | 48,109 |
import torch
def dataloader_msrvtt_train(args, tokenizer):
"""return dataloader for training msrvtt-9k
Args:
args: hyper-parameters
tokenizer: tokenizer
Returns:
dataloader: dataloader
len(msrvtt_train_set): length
train_sampler: sampler for distributed training
... | 4519b8b00c751982c1c7b7de79bdb78b32419cea | 48,110 |
def read_num_axm(input_string):
"""
"""
pattern = ('NumAXM' +
one_or_more(SPACE) + capturing(one_or_more(INTEGER)) +
one_or_more(SPACE) + capturing(one_or_more(INTEGER)) +
one_or_more(SPACE) + capturing(one_or_more(INTEGER)))
block = _get_system_info_section... | 161ccd1dbd4f95d01f2571669ffb52f343b574a8 | 48,111 |
def ids_filter(doc_ids):
"""Create a filter for documents with the given ids.
Parameters
----------
doc_ids : |list| of |str|
The document ids to match.
Returns
-------
dict
A query for documents matching the given `doc_ids`.
"""
return {'filter': [ids_selector(doc... | 1e8f7cc6e1d5afd13cca3c3f10a0c6847a2ac041 | 48,112 |
def dup_div(f, g, K):
"""Polynomial division with remainder in `K[x]`. """
if K.has_Field or not K.is_Exact:
return dup_ff_div(f, g, K)
else:
return dup_rr_div(f, g, K) | e1b620ca567dc1cd7a7f5cc94d94873ccbd0bee5 | 48,113 |
from io import StringIO
def bdf_merge(bdf_filenames, bdf_filename_out=None, renumber=True, encoding=None, size=8,
is_double=False, cards_to_skip=None, log=None, skip_case_control_deck=False):
"""
Merges multiple BDF into one file
Parameters
----------
bdf_filenames : List[str]
... | 113c52dd106ac68527557b81d8444b1c050f48de | 48,114 |
def decoding_layer(dec_embed_input, dec_embeddings, encoder_state, vocab_size, sequence_length, rnn_size,
num_layers, target_vocab_to_int, keep_prob):
"""
Create decoding layer
:param dec_embed_input: Decoder embedded input
:param dec_embeddings: Decoder embeddings
:param encoder_... | b75d7f7d908523774a5baa7c1ae310873da1ae79 | 48,115 |
import logging
import json
def main(req: func.HttpRequest) -> func.HttpResponse:
"""main function"""
logging.info("Getting table data")
datatype = req.route_params.get("datatype")
if not datatype:
logging.error("No datatype provided")
return func.HttpResponse(
body='{"sta... | aaeb840015b42b05b219f2d2a082e14a91eb4d04 | 48,116 |
from typing import Optional
def parse_message_timestamp(date_str) -> Optional[dt.datetime]:
"""Parses the message timestamp string and converts to a python datetime object.
If the string cannot be parsed then None is returned."""
timestamp: Optional[dt.datetime] = None
try:
timestamp = dt.da... | 380f7042bbb76d6550f2aa2e2ad4d767e56e0f1b | 48,117 |
def expectation_values_to_real(expectation_values: ExpectationValues) -> ExpectationValues:
"""Remove the imaginary parts of the expectation values
Args:
expectation_values (zquantum.core.measurement.ExpectationValues object)
Returns:
expectation_values (zquantum.core.measurement.Expectatio... | ee6b6761e61f4ad21ef0a5a7a6b847fb900a8f38 | 48,118 |
def dbpool():
"""
Returns the unique database pool for this process. Most often there is only
a single pool per-process, so we provide this function as a global starting
point for getting connections. Use it like this:
from antipool import dbpool
...
conn = dbpool().connection()
... | bada157c08eeeab498b7ada625ee0a959d948ea4 | 48,119 |
import requests
def view_group_email(group_name):
"""View for email form to members"""
if request.method == "GET":
# Get group information
group = get_group_info(group_name, session)
# Get User's Group Status
unix_name = session["unix_name"]
user_status = get_user_group... | 7df3d98cfb06f25b489ab6b24f661e9a44883aba | 48,120 |
import functools
def vgg_net(inputs,
num_classes=1000,
spatial_squeeze=True,
name='vgg_a',
global_pool=True,
pruning_method='baseline',
init_method='baseline',
data_format='channels_last',
width=1.,
prune_last_... | 2a5c52a5d0ac3ad048788021ab0327e6a1b1f1c3 | 48,121 |
import requests
from bs4 import BeautifulSoup
def get_articles(url):
"""Returns article links, images, and titles as a list of dictionaries"""
page = requests.get(url)
page_content = page.content
soup = BeautifulSoup(page_content, features="html.parser")
posts = soup.find_all("div", {"class": "t... | f01824204e49fff042c3f6e788cc58d64fb88067 | 48,122 |
def present_species(species):
"""Given a vector of species of atoms, compute the unique species present.
Arguments:
species (:class:`torch.Tensor`): 1D vector of shape ``(atoms,)``
Returns:
:class:`torch.Tensor`: 1D vector storing present atom types sorted.
"""
present_species = sp... | e597cdcf75ef912c266fc92861779d550f664616 | 48,123 |
def linkcheck_status_filter(status_message):
"""
Due to a long status entry for a single kind of faulty link,
this filter reduced the output when display in list view
:param status_message: error description
:type status_message: str
:return: a concise message
:rtype: str
"""
if not... | 07bd5cff212dbf3c764c71dc22d46caca34df4d6 | 48,124 |
def complex_pad_simple(xfft, fft_size):
"""
>>> # Typical use case.
>>> xfft = tensor([[[1.0, 2.0], [3.0, 4.0], [4.0, 5.0]]])
>>> expected_xfft_pad = tensor([[[1.0, 2.0], [3.0, 4.0], [4.0, 5.0],
... [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]])
>>> half_fft_size = xfft.shape[-2] + 3
>>> fft_size = (... | 30da547fe53fb4ab4926373885479ffca20986f9 | 48,125 |
def extract_result(log):
"""Extracts the name of each test condition run"""
module_name = log['testInfo']["testName"]
str=""
for d in log['results']:
src = d['src']
if src == 'WebRunner' or src == 'BROWSER' or src == module_name:
# these are asyncronous and the order isn't pr... | 4f4b5311c0dc27b7b178488bee81abeabf4e434d | 48,126 |
def prepare_y_train(add_noise_trajectory: Traj) -> np.ndarray:
"""
Prepare y values for training, which are (cy, cx) of data points in noise-added trajectory.
:param add_noise_trajectory: the trajectory with noise added
:return: x values for training, of size n x 1
"""
return prepare_y_values(a... | 389a097e19560081890ad2a3966bf0ca53868361 | 48,127 |
def extract_barrier_polygons(gdb_path, target_crs):
"""Extract NHDArea records that are barrier types.
Parameters
----------
gdb_path : str
path to the NHD HUC4 Geodatabase
target_crs: GeoPandas CRS object
target CRS to project NHD to for analysis, like length calculations.
... | 6c14d1db4c4d3a64c3d106f42e048db799ed3f8f | 48,128 |
def p2pv(p):
""" Extend a p-vector to a pv-vector by appending a zero velocity.
:param p: p-vector to extend.
:type p: array-like of shape (1,3)
:returns: pv-vector as a numpy.matrix of shape 2x3.
.. seealso:: |MANUAL| page 142
"""
pv = _np.asmatrix(_np.zeros(shape=(2,3), dtype=float, ord... | d752f3598f49870977de432889fc51bea2078b76 | 48,129 |
def create_experiment(
database_session: Session, experiment: schema_experiment.ExperimentBase
):
"""Add Experiment to DB"""
db_experiment = models.Experiment(**experiment.dict())
database_session.add(db_experiment)
database_session.commit()
database_session.refresh(db_experiment)
return db_... | fee8bf74397804c2c6a73e630584fefb26f4db1a | 48,130 |
def apply_filter(signal, window):
"""Apply filter window to a signal.
for now datatype should be using numpy types such as 'np.int16'
the entire file is read assuming datatype so header length should
be specified in words of the same bit length
filter_frequency should be supplied in units of sampling rate
fil... | db63db61a6d6561836676cb202feb6307df8739a | 48,131 |
def compute_affinity_matrix(X):
"""Compute the affinity matrix from data.
Note that the range of affinity is [0,1].
Args:
X: numpy array of shape (n_samples, n_features)
Returns:
affinity: numpy array of shape (n_samples, n_samples)
"""
# Normalize the data.
l2_norms = np.... | daa6f0b823d8476cd9e3a757a0d0a1755c3c9f29 | 48,132 |
import os
def auto_add(repo, autooptions, files):
"""
Cleanup the paths and add
"""
# Get the mappings and keys.
mapping = { ".": "" }
if (('import' in autooptions) and
('directory-mapping' in autooptions['import'])):
mapping = autooptions['import']['directory-mapping']
# ... | ea23ba2a48172b76fe31f3571858eb99ac6ec6b6 | 48,133 |
def trace_fn(current_state, kernel_results, summary_freq=10, callbacks=()):
"""
Can be passed to the HMC kernel to obtain a trace of intermediate
kernel results and histograms of the network parameters in Tensorboard.
"""
# step = kernel_results.step
# with tf.summary.record_if(tf.equal(step % s... | b129e3487304bc7dd6f36446841bfa28e5d4c699 | 48,134 |
def pyramid_settings():
"""Return the default app settings."""
return {"sqlalchemy.url": TEST_DATABASE_URL} | 2873301eef18a60d365b65f61229ca29b15d6144 | 48,135 |
def train(action_set, level_names):
"""Train."""
if is_single_machine():
local_job_device = ''
shared_job_device = ''
is_actor_fn = lambda i: True
is_learner = True
global_variable_device = '/gpu'
server = tf.train.Server.create_local_server()
server_target = FLAGS.master
filters = ... | 0a90f5258a1b9932b1b16b5d250c61fdbf8ab3bc | 48,136 |
def get_uniqueid(scan, x_grid, y_grid):
"""Reads the student's ID from the form.
"""
uniqueid = []
for char_num in range(8):
bubble_intensities = [read_bubble(scan,
x_grid[UNIQUEID_X+char_num],
y_grid[UNIQUEID_Y+y]) for y in range(36)]... | 4f0ffa6d41178fc65c1e653a9764853b3d8f6ef9 | 48,137 |
def _init_redis(app):
"""Initializes Redis client from app config."""
app.config.setdefault('REDIS_HOST', 'localhost')
app.config.setdefault('REDIS_PORT', 6379)
app.config.setdefault('REDIS_DB', 0)
app.config.setdefault('REDIS_PASSWORD', None)
return redis.Redis(host=app.config['REDIS_HOST'],
... | 6c947003d4e9b4845e550508f6f0c24c973c282e | 48,138 |
def _add_cmdline_quotes(cmd_str: str) -> str:
"""Add extra quotes to command line string containing SQL variables.
DB_PATH='C:\\temp\\crdm\\data\\BD:mdf' => DB_PATH="'C:\\temp\\crdm\\data\\BD:mdf'"
Arguments
---------
cmd_str
Command line string containing SQL variables.
Returns
-... | 87fc70f2450e3742481ab28b7dbcdb448c3641ed | 48,139 |
def _log_unnormalized_prob_logits(logits, counts, total_count):
"""Log unnormalized probability from logits."""
logits = tf.convert_to_tensor(logits)
return (-tf.math.multiply_no_nan(tf.math.softplus(-logits), counts) -
tf.math.multiply_no_nan(
tf.math.softplus(logits), total_count - count... | 1c294d16dd905b267da0ff42dc8c234bc05692f1 | 48,140 |
def eom_spfs(nel,nmodes,nspfs,npbfs,spfstart,spfend,uopspfs,copspfs,copips,
huelterms,hcelterms,spfovs,A,spfs,mfs=None,rhos=None,projs=None):
"""Evaluates the equation of motion for the mctdh single particle funcitons.
"""
# create output array
spfsout = np.zeros(nel, dtype=np.ndarray)
... | 4e4db33ea3e85e320ceaeb4d6cabac9306de1451 | 48,141 |
def state_view(decoy: Decoy) -> StateView:
"""Get a mocked out StateView."""
return decoy.mock(cls=StateView) | 4d199bff45a8525044a0c41c7cd4879838e8a816 | 48,142 |
import json
from datetime import datetime
def _tweet_for_template(tweet, https=False):
"""Return the dict needed for tweets.html to render a tweet + replies."""
data = json.loads(tweet.raw_json)
parsed_date = parsedate(data['created_at'])
date = datetime(*parsed_date[0:6])
# Recursively fetch rep... | f87f75a66dfba5314c66aa8c96475898412353fd | 48,143 |
from typing import Union
from pathlib import Path
from typing import Optional
import os
def add_mask(
adata: AnnData,
imgpath: Union[Path, str],
key: str = "mask",
copy: bool = False,
) -> Optional[AnnData]:
"""\
Adding binary mask image to the Anndata object
Parameters
----------
... | 58b37b50e8a0eb1da49b9f9d5d1f5f55c331d3a6 | 48,144 |
from pathlib import Path
def response_page():
"""Fixture to response page."""
txt = read_file(str(Path(__file__).parent / "data/page.txt"))
resp = Response()
resp.status_code = 200
resp._content = str.encode(txt)
return resp | 85d31872fef77eb23afc98d2a0e1fe150ddcf6d7 | 48,145 |
import logging
import re
def create_list_of_mass_balances_engine(
list_species,
element_list,
idx_control,
feed_list,
closing_equation_type,
initial_feed_mass_balance,
fixed_elements,
):
"""
Gives the list of mass balances
Possible equations (besides reactions and charge):
... | 35386c7a6bb8f6522a0a2f8d352e363c9e8115e3 | 48,146 |
import os
def get_module_root(path):
"""
Get closest module's root beginning from path
# Given:
# /foo/bar/module_dir/static/src/...
get_module_root('/foo/bar/module_dir/static/')
# returns '/foo/bar/module_dir'
get_module_root('/foo/bar/module_dir/')
# retur... | 19c7836f375b544b8057cbd5db8c6d469d42b8bb | 48,147 |
def decode_text(payload, charset, default_charset):
"""
Try to decode text content by trying multiple charset until success.
First try I{charset}, else try I{default_charset} finally
try popular charsets in order : ascii, utf-8, utf-16, windows-1252, cp850
If all fail then use I{default_charset} and... | 2bdb58d2b43d7a58c795d9a3c7dad3459d5f02bb | 48,148 |
import pandas
from re import T
def pql_import_json(state: State, table_name: T.string, uri: T.string):
"""Imports a json file into a new table.
Returns the newly created table.
Parameters:
table_name: The name of the table to create
uri: A path or URI to the JSON file
Note:
... | ce3e6fc95a4f3ef7f16a6692c87725521c058a16 | 48,149 |
from typing import Tuple
def read_dataset(train_batch_size: int = 32, eval_batch_size: int = 128,
train_mode: str = 'pretrain', strategy: tf.distribute.Strategy = None, topology=None,
dataset: str = 'cifar10', train_split: str = 'train', eval_split: str = 'test',
dat... | c5abf6e45a76ed0c74503675b0c5dd051991e7b5 | 48,150 |
import os
def load(dirpath):
"""Load a saved python model."""
file_path = os.path.join(dirpath, _CONFIG_FILE)
with tf.io.gfile.GFile(file_path, 'r') as f:
config_json = f.read()
config_dict = json_utils.decode(config_json)
return deserialize_keras_object(config_dict) | 10a015979bfb831a4f01873d10040d787c75a0e8 | 48,151 |
import csv
def _get_stock_yfinance_names(stocks_ibkr_csv_p):
"""Convert IBKR short names to YF names and check if actually valid."""
with open(stocks_ibkr_csv_p, 'r') as f:
r = csv.reader(f)
symbol_col = exch_col = None
symbols_yf = {}
for row in r:
if not row or row[0] != 'Financial Instrum... | c9d73b72fe828f9814365da134a187d40a5fe9c9 | 48,152 |
from PIL import Image
def image_to_ndarray(filename, convert_grey=True, cmap=None, debug=False):
"""
Convert an image to a numpy array using pillow.
Matplotlib only supports the PNG format.
:param filename: absolute path of the image to open
:param convert_grey: if True and the number of layers ... | 8ff26597bdf0d714748a2bf5643b2abc9cfcb60f | 48,153 |
import logging
import os
def GetAverageNewRunTime(finished_seq_file, window=100):#{{{
"""Get average running time of the newrun tasks for the last x number of
sequences
"""
logger = logging.getLogger(__name__)
avg_newrun_time = -1.0
if not os.path.exists(finished_seq_file):
return avg_newr... | bc2bb309e535ef6123fc2847e17017b2258fd445 | 48,154 |
def test_run_dry_multiple_packages(murlopen, tmpfile, capsys):
"""dry run should edit the requirements.txt file and print
hashes and package name in the console
"""
def mocked_get(url, **options):
if url == "https://pypi.org/pypi/hashin/json":
return _Response(
{
... | b19e6c8f80e8533fb530bacc0df387f01ced9d12 | 48,155 |
def get_scaled_cutout_wdhtdp_view(shp, p1, p2, new_dims):
"""
Like get_scaled_cutout_wdht, but returns the view/slice to extract
from an image instead of the extraction itself.
"""
x1, y1, z1 = p1
x2, y2, z2 = p2
new_wd, new_ht, new_dp = new_dims
x1, y1, x2, y2 = int(x1), int(y1), int(x... | f639a69a8e7c0e65ac968be03b62b7de8f43dc99 | 48,156 |
def cron_expression(trigger):
"""Get a cron expression from the given trigger"""
_LOGGER.debug('trigger.fields: %r', trigger.fields)
# Need to loop through, as it is an array and not in the same Cron
# expression order, thus we need to insert into the proper order.
fields = ['*'] * len(_FIELD_NAMES)... | 5081a0d8b0112631a42f7918131c2877b29b7162 | 48,157 |
def get_tp(gold, guess):
"""
Args:
gold (Iterable[T]):
guess (Iterable[T]):
Returns:
Set[T]
"""
return get_correct(gold, guess) | b60a2ed086df6c29cbee0190b8d885c3ad467f13 | 48,158 |
import collections
def insert(container, key_path, item):
"""
>>> insert({}, ['a', '1', '2', 'world'], 'hello')
{'a': {'1': {'2': {'world': 'hello'}}}}
"""
if isinstance(container, collections.OrderedDict):
gen = collections.OrderedDict
update = lambda i, k, v: i.update({k: v})
... | 656c6a69f3f261d7598daca8bda37908ddf1527b | 48,159 |
def complementary_sequence(seq: str) -> str:
"""
>>> complementary_sequence('ATCG')
'TAGC'
"""
# TODO (gdingle): refactor with fastqs reverse_complement
seq_map = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
return ''.join([seq_map[c] for c in seq.upper()]) | 10916a27b0d1e1cf9a54c90b5306324cbd262d55 | 48,160 |
import torch
def construct_edge_feature_gather(feature, knn_inds):
"""Construct edge feature for each point (or regarded as a node)
using torch.gather
Args:
feature (torch.Tensor): point features, (batch_size, channels, num_nodes),
knn_inds (torch.Tensor): indices of k-nearest neighbour, ... | b49d26e0e7cee13952ff85f8f1f8075658fc391a | 48,161 |
def _prepare_data_fn(features, target='label', flatten=True,
return_batch_as_tuple=True, seed=None):
"""
Resize image to expected dimensions, and opt. apply some random transformations.
:param features: Data
:param target Target/ground-truth data to be r... | da9a254f9960e680dab1b1a3134058e100af81e9 | 48,162 |
def _get_sentinel_event():
"""Generate a sentinel event for terminating worker."""
return Event() | 9839575558ecec19034d41346eb1cf63c22fdc8b | 48,163 |
def _process_pip_requirements(
default_pip_requirements, pip_requirements=None, extra_pip_requirements=None
):
"""
Processes `pip_requirements` and `extra_pip_requirements` passed to `mlflow.*.save_model` or
`mlflow.*.log_model`, and returns a tuple of (conda_env, pip_requirements, pip_constraints).
... | 0e040f9a19d6e35a21ce5081edecde4f1f2ade9b | 48,164 |
def _parse_standings(d):
""" Used to parse the standings of a competition.
"""
standings = []
for o in d.get("teams", []):
info = CompetitionStanding(o)
standings.append(info)
return standings | 061263cc8959b490a585c4babcf97b8fe20a84e1 | 48,165 |
from typing import Type
from re import T
from typing import Optional
from typing import cast
def bind_prop(
prop_name: str,
prop_type: Type[Variable],
default: T,
doc: Optional[str] = None,
doc_add_type=True,
objtype=False,
) -> property:
"""Define getters and setters for a named property ... | 105b3649b2358d616d62f606eeb9cb6e8cfae4c0 | 48,166 |
def get_vpip_players(hand: Hand) -> Indications:
"""
Return an indication of the players that were VPIP for the hand.
Voluntary Put In Pot (VPIP) means the player volunteered to put money into the pot pre-flop.
"""
return _get_players_making_actions(hand.preflop, (Bet, Raise, Call)) | c609c1a125a4fae64c14cd2c4d07aa4fc2251428 | 48,167 |
import os
import re
def find_version(*file_paths):
"""Find version information in file."""
path = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(path).read()
version_pattern = r"^__version__ = ['\"]([^'\"]*)['\"]"
version_match = re.search(version_pattern, version_file, r... | 47c84af5fa2578fbbf28d6ac72fe5ab88ac2db8d | 48,168 |
def canonicalize_name(name: str) -> str:
"""
Normalize the name strings from certificates and emails so that they
hopefully match.
"""
name = name.upper()
for c in "-.,<> ":
name = name.replace(c, "")
return name | 3cfee0a655c876c037bb915098e564376f9b8cf5 | 48,169 |
from unittest.mock import patch
def test_game_play_diagonal() -> None:
"""RED should be able to fill the diagonal while YELLOW does nothing but help."""
moves = [0, 1, 1, 2, 2, 3, 2, 3, 3, 5, 3]
def mock_input(s: str) -> int:
return moves.pop(0)
game = Game()
with patch("connect_four.gam... | 19cc21e358116b6a4552117356d1268a3ce07a00 | 48,170 |
import timeit
def get_exec_time(total_execs=1, _repeat=1):
"""
basically here we calculate the
average time it takes to run this function
or block of code
"""
def inner_wrapper(_function, *args, **kwargs):
computational_times = timeit.repeat(
lambda: _function(*args, **kwargs),
number=total_execs,
... | d0826d3fb047736c5d4a5baa4d440bb7d2af2373 | 48,171 |
def find_in_map(obj, *args):
"""
It accepts the dict object and nested keys and return the value
of last key if present in nested key is present in object.
Args:
obj (dict): dict object
Returns: Value of last nested key
"""
if not isinstance(obj, dict):
# raise InvalidReque... | 20cfc2181ebe987a97a291cfef61739e6eedbeb2 | 48,172 |
import os
def get_trace_xml_filename(config, absolute=False):
"""Get the trace XML filename to put XML data into"""
trace_dir = get_trace_dir(config, absolute)
xml_filename = "%s.twx" % config["top_module"]
xml_filename = os.path.join(trace_dir, xml_filename)
return xml_filename | e48993d6f9d98c2a45dff786894d545f4c455456 | 48,173 |
def parse_from_file_msg(fp):
"""
Parsing email from file Outlook msg.
Args:
fp (string): file path of raw Outlook email
Returns:
Instance of MailParser with raw email parsed
"""
return MailParser.from_file_msg(fp) | 4de62263dfe523d63d238f78f2fc801ba51917ea | 48,174 |
def simple_5reciprocal(x, a, b):
"""
reciprocal function to fit convergence data
"""
c = 0.5
if isinstance(x, list):
y_l = []
for x_v in x:
y_l.append(a + b / x_v ** c)
y = np.array(y_l)
else:
y = a + b / x ** c
return y | 8c046fee748a03b7c17f2c62b0d5c713d5b95354 | 48,175 |
def get_user_group(user: User, user_group_id: int) -> UserGroup:
"""
Get a user group.
:param user
:param user_group_id:
:return:
"""
user_group = UserGroup.query.filter_by(id=user_group_id).first()
if user_group is None:
raise NotFoundException(f'No user group with id {user_grou... | f27dbedb6ec6bf39be451e000709db37d566d0c4 | 48,176 |
import timeit
def test_accuracy(backend, shape, ndim, axes, dtype, inplace, norm, use_lut, r2c=False, dct=False,
gpu_name=None, stream=None, queue=None, return_array=False, init_array=None, verbose=False,
colour_output=False, ref_long_double=True):
"""
Measure the
:para... | 57f51eec7646d6103e3b23492a0effe8c29fea53 | 48,177 |
def negate_value(func):
"""negate value decorator."""
def do_negation(name, value):
print("decorate: we can change return values by negating value")
return -value
return do_negation | 276981a7c668308c97ca9e54066163036cb55528 | 48,178 |
from urllib.parse import urlsplit, urlunsplit
def validate_twilio_request(f):
"""Validates that incoming requests genuinely originated from Twilio"""
@wraps(f)
def decorated_function(request, *args, **kwargs):
# Create an instance of the RequestValidator class
validator = RequestValidator(... | b6b51d0c0d9f311dc1cbdac7efec1f8967d21a21 | 48,179 |
def readable_memory_size(bytes_):
"""Convert number of bytes into human readable form, eg '1.2 Kb'.
"""
return _readable_units(bytes_, memory_divs) | a9ecd31225cd57b218be9cdc26f57af6a78f8a84 | 48,180 |
import random
import numpy
def get_labels (num, ltype='twoclass'):
"""Return labels used for classification.
@param num Number of labels
@param ltype Type of labels, either twoclass or series.
@return Tuple to contain the labels as numbers in a tuple and labels as objects digestable for Shogun.
"""
labels=[]
... | 2e083f70c4ff936f180be7b176957f04ae86d894 | 48,181 |
import struct
def read_msg(buf:bytes) -> tuple:
""" first the size prefix and then the corresponding msg payload """
if len(buf) < 4:
return (0, "", buf)
size = struct.unpack("!I", buf[0:4])[0]
logger.debug("read_msg: size: %d", size)
if len(buf) - 4 >= size:
text = struct.unpack("... | 10f7d5889610ec58cf9d73d987ea9dfa50e344ab | 48,182 |
def conv3x3(x,K):
"""3x3 convolution with padding"""
return F.conv2d(x, K, stride=1, padding=1) | fcc4daee5b9b76714f561af0e2064c26c45afea9 | 48,183 |
def alert_factory(site, rule, data_point):
""" Creating an alert object """
# Getting the last alert for rule
point = rule.alert_point.last()
alert_obj = None
# If the last alert exists does not exist
if point is None:
alert_obj = create_alert_instance(site, rule, data_point)
# i... | 5ebc2fb30fc9616a9690be709022806affa95ab8 | 48,184 |
def _get_average_time(callable_name):
"""Returns the average_time in seconds for the passed-in callable name.
:param str callable_name: The name of the callable.
:returns: The average_time in seconds for the passed-in callable name.
:rtype: float
"""
return _ProfilingStatCollection.get_stats_... | e17279ca1112f975320e8877fdc40943cc341cac | 48,185 |
def rolling_integral(x0, periods, function=None):
"""
Integrate a function over a rolling window ending in the interval.
:param x0: Variable or Parameter; the interval under consideration
:param periods: the width of the rolling window
:param function: a function from float to float to be integrate... | c7a01f9b986362cf1aab78d17c2ee9910ec3e6ba | 48,186 |
def build_app_models_environment():
"""
Build a full test model environment for vcftestmodels.
Uses vcftestmodels.models.get_app_models_environment, which returns
an empty base.tests.helpers.AppModelsEnvironment object. Model
classes are created here but must by initialized via the object's
`mi... | 9a195e0665409150c5155d000e78c33920646818 | 48,187 |
import os
def extract_feats(ffs, direc="train", global_feat_dict=None):
"""
arguments:
ffs are a list of feature-functions.
direc is a directory containing xml files (expected to be train or test).
global_feat_dict is a dictionary mapping feature_names to column-numbers; it
should only... | e084dde13ad43ced5d486ac133f3f449905acc3a | 48,188 |
import torch
def create_random_direction(weights, args, ignore='biasbn', norm='filter', model=None):
"""
Setup a random (normalized) direction with the same dimension as the weights.
Args:
weights: the given trained model
ignore: 'biasbn', ignore biases and BN parameters.
... | 2f82feca5a81c57c9b9736502d0bc406e9ad2b3d | 48,189 |
import functools
def wait_key_pressed_logical(key_name, timeout: float = None) -> bool:
"""Wait for a key or mouse/joystick button logical state to be pressed."""
return _wait_for(timeout, functools.partial(is_key_pressed_logical, key_name)) or False | f0d13eeecef02864695247178d99eb30fa6c6e54 | 48,190 |
def calc_fc_from_fixed_Q_Brune(event_inv_params, Qs_curr_event, density, Vp, A_rad_point, surf_inc_angle_rad=0., verbosity_level=0):
"""Function to calculate fc by fitting Brune model to spectra with fixed Q."""
# Calculate f_c based on curve-fit of spectra with Brune model for fixed Q:
# Setup some data ou... | 68c0c02d10f5d7ba8ed2cc7af68a3a86f4c9183c | 48,191 |
import os
def github_tree():
"""return `github_tree` string for a current directory. git remote required"""
fullname = github_name.get()
if not fullname:
return ""
relpath = os.path.relpath(os.getcwd(), git_root())
return "/".join([fullname, "tree/master", relpath]) | 6cdb495b97e7e083bb28cc840f7d634048c78276 | 48,192 |
from typing import Optional
from typing import Iterable
from typing import Union
import pathlib
import os
def GetDefaultGithubAccessToken(
extra_access_token_paths: Optional[Iterable[Union[str, pathlib.Path]]] = None
) -> AccessToken:
"""Get a Github access token from environment variables or flags.
This funct... | c43c915148922548c68de741c26cf88a7cff7a52 | 48,193 |
def compute_d(a, b):
"""Compute value d for golden section search."""
d = a + ((b - a) / 1.618)
return d, f(d) | 544b1c6bfc1244a4d0c5c62f340e165701579b21 | 48,194 |
def convert_2D_polar_line_to_conformal_line(rho, theta):
""" Converts a 2D polar line to a conformal line """
line_val = val_convert_2D_polar_line_to_conformal_line(rho, theta)
return layout.MultiVector(line_val) | 170b16f522d2c97ea933e97405c3ef08746d5901 | 48,195 |
def B_m_def(tau, phi, **params):
"""
Implements Eq. 9.159 from Nawalka, Beliaeva, Soto (pg. 471)
"""
beta1 = beta1m(**params)
beta2 = beta2m(beta1, **params)
beta3 = beta3m(beta1, **params)
beta4 = beta4m(phi, beta1, **params)
exp_term = np.exp(beta1 * tau)
denominator = beta2 * bet... | 2adbca8682ddba7d12055e7dc59439fe4aa70f3e | 48,196 |
import os
def get_lsf_master_url(run):
"""
path to master script
"""
d=get_lsf_dir(run)
return os.path.join(d,'%s.sh' % run) | 49aafd0a1535a032f2e551a2950329df5285df8c | 48,197 |
import pickle
import ast
def capture_value(value, name):
"""Hygienically capture a run-time value. Used by `h[]`.
`value`: A run-time value. Must be picklable.
`name`: For human-readability.
The return value is an AST that, when compiled and run, returns the
captured value (even in another Pyth... | edb5d384bc22d4dcfdc3e422931bbfc2a01eebd3 | 48,198 |
def delete_crime_collection():
"""
Helper function to delete crime collection in db.
"""
count = len(Crime.objects())
check_crime_duration()
for crime in Crime.objects():
duration = check_filter(crime.incident_type_primary)
if (crime.duration == None or crime.duration == 30) and ... | 287830498f42f983fc4597694262e719ca62a9f7 | 48,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.