content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def handle(req):
"""handle a request to the function
Args:
req (str): request body
"""
ret_str = 'Hello OpenFaas. I received the following text:\n'
return ret_str + req | 9d4d4957bcd05c945b3e702f311cb81b8af74d73 | 49,500 |
def rlmErr(ols, w, spDcache):
"""
Robust LM error test. Implemented as presented in eq. (8) of Anselin et
al. (1996) [Anselin1996a]_
NOTE: eq. (8) has an errata, the power -1 in the denominator should be inside the square bracket.
...
Attributes
----------
ols : OLS_dev
... | edeedf967275934cc82d82369ae3ed3d4cabbdec | 49,501 |
import numpy
def max_ts(timeseries, nodata=-9999):
"""Maximum value of the time series.
:param timeseries: Time series.
:type timeseries: numpy.ndarray
:param nodata: nodata of the time series. Default is -9999.
:type nodata: int
:returns: Maximum value of time series.
"""
ts = fixs... | 77044f43b6fd8cb7fc872a18f7eb551f17225e7c | 49,502 |
def get_hole_declarations(program_vars):
"""Helper function for creating hole declaration with a grammar blow."""
grammar_spec = """
(
(Start Int (
(Variable Int)
(+ Start Start)
))
)
"""
grammar = templates.load_gramar_from_SYGUS_spec(grammar_spec... | 8c6f8161cd0e36447e65acb55963a5ae8cee93a9 | 49,503 |
def unit_scalar_to_str(value, n_digits=6):
""" Convert a UnitScalar to a string representation to display in text box.
"""
dimless_labels = [None, 'dimensionless', '1']
if value is None:
return ""
elif isinstance(value, UnitScalar):
number = value.tolist()
if isinstance(numbe... | b4512432862976bdd1327dc6d72bc8b97a9d8d9d | 49,504 |
def find_paths(iterable, searchfor, max_=0, searchtype='key', **kwargs):
"""Returns paths to 'searchfor'. If 'max_' is 0 all matches will be found"""
return objects.FindPath(iterable, searchfor, max_, searchtype, **kwargs).paths | fb458563e09085f1ef69e1d9711ff5c8ca21fc1b | 49,505 |
import csv
def process_overlap_files(inputfiles, header):
"""
:param inputfiles:
:param header:
:return:
"""
cage_cov = {'+': dict(), '-': dict()}
feat_count = col.Counter()
skip_partial = 0
for inpf in inputfiles:
with open(inpf, 'r', newline='') as infile:
row... | 1f8eb6856d261d4b845ee2967956180822dc92ac | 49,506 |
def where(cond, true_vals, false_vals=None):
"""
Use `true_vals` where `cond` is True, `false_vals` where `cond` is False
to build a merged dataset. The result will be empty where `cond` is empty.
`false_vals` are optional and if not provided, this will behave nearly the same as
`true_vals.filter(c... | 45883feeb0cfa8b24dbd53f18981677bb921d65d | 49,507 |
import ssl
def create_ssl_context(verify=True, cafile=None, capath=None):
"""Set up the SSL context.
"""
# This is somewhat tricky to do it right and still keep it
# compatible across various Python versions.
try:
# The easiest and most secure way.
# Requires either Python 2.7.9 o... | fe8db07f3d0043224cb3ca739fa43a1e3e69fdae | 49,508 |
def extract_domain(url):
"""Extract domain name from URL string"""
o = urlparse(url)
if o.scheme == '' and o.netloc == '':
o = urlparse("//" + url.lstrip("/"))
return o.netloc | 98ea9dbedb095f29e231095623baf7e24756d1f4 | 49,509 |
def diamond_graph(create_using=None):
"""Return the Diamond graph. """
description=[
"adjacencylist",
"Diamond Graph",
4,
[[2,3],[1,3,4],[1,2,4],[2,3]]
]
G=make_small_undirected_graph(description, create_using)
return G | 59909cabc48c5f7468af25ba4f045bf9440df86c | 49,510 |
def tensor_setitem_by_tuple_with_tensor(data, tuple_index, value):
"""Assigns the tensor by tuple with tensor value."""
op_name = const_utils.TENSOR_SETITEM
tuple_index = _transform_ellipsis_to_slice(data, tuple_index, op_name)
tuple_index, not_expanded_dim = remove_expanded_dims(tuple_index, F.shape(da... | fec629b57afd7b9e3ceb1ff8dd92501f2e297b03 | 49,511 |
def arpls(y, lam, ratio=1e-6, niter=1000, progressCallback=None):
"""
Return the baseline computed by asymmetric reweighted penalized least squares smoothing, arPLS.
Ref: Baseline correction using asymmetrically reweighted penalized least squares smoothing
Sung-June Baek, Aaron Park, Young-Jin Ahn a... | 94ba343ebc7ec9b039bdef2e1d1e67da2a11b521 | 49,512 |
def compressnumbers(s):
"""Take a string that's got a lot of numbers and try to make something
that represents that number. Tries to make
unique strings from things like usb-0000:00:14.0-2
"""
n = ''
currentnum = ''
for i in s:
if i in '0123456789':
#Exclude... | 952fe1a56a1864ce41031bb9bbea0fd440f9c3ef | 49,513 |
async def plot_index_bar_chart(tag_dict):
"""
Plots the index bar chart.
"""
x = np.array(list(tag_dict.keys()))
y = np.array(list(tag_dict.values()))
plt.clf()
plt.bar(x, y, color="green")
plt.xticks(fontsize=7)
plt.xlabel("Index", fontsize=7)
plt.ylabel("Number", fontsize=7)
... | 8afe547bdf55f5991b48f1f7c170e1bb5ccc3453 | 49,514 |
def _get_tile_output_shape(shape, multiples):
"""compute output shape of tile"""
if multiples is None:
return shape
if not isinstance(shape, (list, tuple)):
raise TypeError("Input shape of Tile must be of type list or tuple")
if not isinstance(multiples, (list, tuple)):
raise Ty... | ca787b55bed7591c6cf46aa6908d2c8d7053e755 | 49,515 |
from typing import Dict
import copy
def get_clinical_strat(params: Parameters, stratified_adjusters: Dict[str, Dict[str, float]]) -> Stratification:
"""
Stratify the infectious compartments of the covid model by "clinical" status, into the following five groups:
NON_SYMPT = "non_sympt"
As... | 566d5feb02f01b7082054968c73561caa758201e | 49,516 |
import requests
import logging
def service_is_ready():
"""
Used to show the "Haystack is loading..." message
"""
url = API_QUERY_ENDPOINT
try:
if requests.get(url).status_code < 400:
return True
except Exception as e:
logging.exception(e)
sleep(2) # To avoi... | 761bc784837767411c65ebedc8c054f156a08214 | 49,517 |
def medianfilt(img, kernel_shape):
"""[summary]
Aplies a median filter to an image, but adds the necessary padding to mantain the aspect ratio.
Args:
img (numpy array): Image array.
kernel_shape (tuple): Tuple indicating kernel shape.
Returns:
output (numpy array): processed... | 666ca3aa31cea2dbc8ba1dcf80ead5c1bd6a0fd0 | 49,518 |
import typing
def cik(apikey: str, cik_id: str) -> typing.List[typing.Dict]:
"""
Query FMP /cik/ API.
FORM 13F get company name by cik
:param apikey: Your API key.
:param cik_id: CIK value
:return: A list of dictionaries.
"""
path = f"cik/{cik_id}"
query_vars = {"apikey": apikey}
... | 1809dffd9a36a19f3d0c5c3e5069b476a7f122d3 | 49,519 |
def dec_indicator(encoded):
"""decode a Fudge Indicator.
Returns:
A Singleton INDICATOR object"""
return INDICATOR | 55cad8be678dd41c706c905a5d79b6e0d78cff62 | 49,520 |
import yaml
def parse(path):
"""Parse a config file for running a model.
Arguments
---------
path : str
Path to the YAML-formatted config file to parse.
Returns
-------
config : dict
A `dict` containing the information from the config file at `path`.
"""
with ope... | dbe7308ad6981ea0a4d0d5f1a6989c278320b07b | 49,521 |
def unordered_inverse(matrix):
"""
Takes in a matrix of values and maps each distinct row to a unique value
ex [[1 2 3] becomes [1,2,1]
[4 5 6]
[1 2 3]]
"""
num_rows = matrix.shape[0]
result = np.zeros((num_rows,))
state_map = dict()
state_count = 0
for index,row in enumerate(matrix):
row = row.... | 3dea723ee10375e0452d03caff64e107cea8e72e | 49,522 |
def _build_predict_signature(input_tensor, output_tensor_x, output_tensor_y):
"""Helper function for building a predict SignatureDef."""
input_tensor_info = tf.saved_model.utils.build_tensor_info(input_tensor)
signature_inputs = {"input": input_tensor_info}
output_tensor_info_x = tf.saved_model.utils.build_ten... | 481465ec77e4632cc4fd50a5c2df1f0dd83e2844 | 49,523 |
def filter_error_nodes(nodes):
"""Filter out ERROR nodes from the given node list.
:param nodes: candidate nodes for filter.
:return: a tuple containing the chosen nodes' IDs and the undecided
(good) nodes.
"""
good = []
bad = []
not_created = []
for n in nodes:
if ... | 409236f4f31abaecc999fb3fbc766d138c5c3618 | 49,524 |
def pad_sequences(x, n_padded, center_padded=True):
"""TODO(rpeloff) return the padded sequences and their original lengths."""
padded_x = np.zeros((len(x), n_padded, x[0].shape[1]), dtype=_globals.NP_FLOAT)
lengths = []
for i_data, cur_x in enumerate(x):
length = cur_x.shape[0]
if cente... | 9f4c49308f7ba8049147b4f97d804dd23a577c1b | 49,525 |
def ds_cnn_params():
"""Parameters for toy "depthwise convolutional neural network" stride model."""
params = Params()
params.model_name = 'ds_cnn'
params.cnn1_kernel_size = '(3,2)'
params.cnn1_dilation_rate = '(1,1)'
params.cnn1_strides = '(2,1)'
params.cnn1_padding = 'same'
params.cnn1_filters = 4
p... | 086f34623b8500dbff09a13a724f7f6eaa957b63 | 49,526 |
import csv
def LoadVNSIM(nsim_csv):
"""Returns dictionary with degraded file key and mean nsim value.
The CSV should have three values: reference path, degraded path, nsim value
Args:
nsim_csv: Path to CSV file with NSIM values, format described above.
Returns:
Dictionary with degraded file key and... | 919d1dcffab7e4a78e0ced2cbeee01126d586c27 | 49,527 |
def getCharOverlapCount(from1, to1, from2, to2):
"""Calculates the number of overlapping characters of the two given areas."""
#order such that from1 is always prior from2
if from1 > from2:
tmp = from1
from1 = from2
from2 = tmp
tmp = to1
to1 = to2
to2 = tmp
... | 66ea7cbc9408d41de002c96e40705d4dd45f9ad5 | 49,528 |
def getPressure():
"""
Method to get the angular position of the rocket.
This method is only activated when the route /getAng is accessed.
Data collected here is to be directly displayed as numbers on ReactApp.
"""
pressure = {'PTop':PT1,'PBottom':PT2,'P3':PT3}
f = open("./AvionicsData/pressure.txt","a+")
f... | 7ec8261c091f2f832ac31ff4e8aff7c0494bfcfa | 49,529 |
import warnings
def label_color(label):
""" Return a color from a set of predefined colors. Contains 80 colors in total.
Args
label: The label to get the color for.
Returns
A list of three values representing a RGB color.
If no color is defined for a certain label, the color gre... | d08bcecdcc3c48f58b879fbbfd44a973c031693a | 49,530 |
from pathlib import Path
def file_path(cfg):
"""
Return the directory containing the description files as an absolute path.
Returns None if the configuration does not define this.
"""
try:
desc_path = Path(cfg['descriptions_dir'])
except KeyError:
raise ConfigKeyMissingError('... | 34e8fb69fabdc6f014d52dbaf2b978dfb9022a9a | 49,531 |
import os
def rename_to_text(file_path):
"""
Appends a .txt to all files run since some output files do not have an extension
:param file_path: input file path
:return: .txt appended to end of file name
"""
file = file_path.split('/')[-1]
if file.endswith('.txt') is False:
new_fil... | 76fe32c503d93fd0277cdf61d31fc4195835e355 | 49,532 |
def angle_average(galactic_frame_func):
"""
@returns Angle-averaged function
"""
@np.vectorize
def angle_averaged(v_galactic_frame):
"""
@returns Angle-averaged evaluation of function
"""
v = v_galactic_frame * np.ones_like(COS_THETA)
integrand = galactic_fram... | 9964a21289e400dc1f147cb4a8bc625c7e1fe5ea | 49,533 |
def create():
"""Create new event."""
form = CreateEventForm(request.form, csrf_enabled=False)
print ("form received")
if form.validate_on_submit():
print ("valid")
RecEvent.create(title=form.title.data, date=form.date.data, time=form.time.data,
location=form.loca... | 71751dcae0db1b7fc70784ad6fae3fc7e22bbd18 | 49,534 |
def get_version():
"""
Obtain the version of the ITU-R P.1853 recommendation currently being used.
Returns
-------
version: int
Version currently being used.
"""
global __model
return __model.__version__ | 87eb4e26e20089976e5863b65c7457e91c6844ed | 49,535 |
import os
import re
def read_version(version_file_name):
"""
Reads the package version from the supplied file
"""
version_file = open(os.path.join(version_file_name)).read()
return re.search("__version__ = ['\"]([^'\"]+)['\"]", version_file).group(1) | c76c662e85d9a0125224a194538f8ca128d61266 | 49,536 |
import subprocess
import re
def find_ue_ip(imsi: str):
"""
Finds the UE IP address corresponding to the IMSI
"""
cmd = ["mobility_cli.py", "get_subscriber_table"]
output = subprocess.check_output(cmd)
output_str = str(output, "utf-8").strip()
pattern = "IMSI.*?" + imsi + ".*?([0-9]{1,3}\.[... | f7e051daffa693f2ad3647a76d55c4596d5ef60a | 49,537 |
import argparse
def get_args():
"""Gets parsed command-line arguments.
Returns:
Parsed command-line arguments.
"""
parser = argparse.ArgumentParser(description="plays Ms. Pac-Man")
parser.add_argument("--no-learn", default=False, action="store_true",
help="play wit... | bed5ed41a952f7c0cb56335ad4ba1d1e83c00fc0 | 49,538 |
def _random_bernoulli(shape, probs, dtype=tf.int32, seed=None, name=None):
"""Returns samples from a Bernoulli distribution."""
with tf.name_scope(name, "random_bernoulli", [shape, probs]):
probs = tf.convert_to_tensor(probs)
random_uniform = tf.random_uniform(shape, dtype=probs.dtype, seed=seed)
return... | ba60cecbcc0ac7698839e6bb60f2ebdd0b698c59 | 49,539 |
import re
def tokenize(text):
"""Return tokenized form of text
Parameters
----------
text : str
string to be tokenized
Returns
-------
list
tokens of string text
"""
# Normalize and remove punctuations and extra chars such as (, #
text = re.sub(r'[... | 3f360e4fa253249e65ce66cdcdc292d99f344610 | 49,540 |
import string
import csv
def ReadData(name):
"""
Reads data from several files.
"""
f = open('%s-n.txt' % name,'rt')
n = string.atoi(f.readline())
f.close()
gammas = []
f = open('%s-gammas.csv' % name,'rt')
for row in csv.reader(f,quoting=csv.QUOTE_NONNUMERIC):
... | 24116b6fe7e1bcc0c003a4717520aa539dd7f3a0 | 49,541 |
from typing import Optional
from typing import List
def split_and_strip_without(
string: str, exclude, separator_regexp: Optional[str] = None
) -> List[str]:
"""Split a string into items, and trim any excess spaces
Any items in exclude are not in the returned list
>>> split_and_strip_without('fred, ... | 14d4496679a1c759e8f2752c8e6b052a810ba8ea | 49,542 |
def _current_season():
"""Return the current NHL season"""
endpoint = "seasons/current"
data = _api_request(endpoint)
if data:
season = data['seasons'][0]['seasonId']
return season
else:
raise JockBotNHLException('Unable to retrieve current NHL season') | df8ab4d7df4fc4071a4738eaea398f24b9c5cd9f | 49,543 |
from typing import Tuple
def load_file(path: str) -> Tuple[TestCase, ...]:
"""Load test cases from a file.
Parameters
----------
path : str
File path.
Returns
-------
Tuple[TestCase, ...]
Test cases.
"""
with open(path, "r") as file:
return tuple(
... | 127bda88dc5aa98690a6f6bb7e5d793f3db7ac99 | 49,544 |
def get_interfaces():
"""
Returns a list of your computer's IP configuration:
['lo0', 'gif0', 'stf0', 'XHC20', 'en0', 'p2p0', 'awdl0',
'en1', 'bridge0', 'utun0']
"""
interfaces = netifaces.interfaces()
return interfaces | 7b8837c221f02baa70c6e6c3b848e8444f6daf50 | 49,545 |
import re
def clean_python_name(s):
"""Method to convert string to Python 2 object name.
Inteded for use in dataframe column names such :
i) it complies to python 2.x object name standard:
(letter|'_')(letter|digit|'_')
ii) my preference to use lowercase and adhere
... | d77eaa81607aabf8cae62e2a9c36a51e8428aac4 | 49,546 |
from typing import Optional
import io
import pickle
import torch
def broadcast_object(obj: object, src: int = 0, comm: Optional[B.BaguaSingleCommunicatorPy] = None) -> object:
"""Serializes and broadcasts an object from root rank to all other processes.
Typical usage is to broadcast the ``optimizer.state_dict... | a2fc3b1a52d9db10968b4ce6d7cf8df7f8be9324 | 49,547 |
import pickle
import os
def open_pickle_jar(directory, filename):
"""loads .pkl file"""
return pickle.load(open(os.path.join(directory, filename), 'rb')) | 89bc2be018b2e9acfcb713921b232129f9cfc1f4 | 49,548 |
import tempfile
def mktemp_dump(data):
"""Create a temporary file under the current plugin tmp directory and write
data to the file.
"""
ftmp = tempfile.mktemp(dir=HotSOSConfig.PLUGIN_TMP_DIR)
with open(ftmp, 'w') as fd:
fd.write(data)
return ftmp | 80dd7c499c6a27b1aabb90d42234f28483b7915b | 49,549 |
def get_leagues_by_team(team_ids):
"""
https://developer.riotgames.com/api/methods#!/985/3352
Args:
team_ids (str | list<str>): the team ID(s) to get leagues for
Returns:
dict<str, list<League>>: the team(s)' leagues
"""
# Can only have 10 teams max if it's a list
if isinst... | 004cb182ca85062b6552224eea35423313348fdb | 49,550 |
def generate_asset_name (asset_id, block_index):
"""Create asset_name from asset_id."""
if asset_id == 0: return config.BTC
elif asset_id == 1: return config.XCP
if asset_id < 26**3:
raise exceptions.AssetIDError('too low')
if enabled('numeric_asset_names'): # Protocol change.
if ... | 5937da288062d9d9f98894e4534c3bd36feef3a3 | 49,551 |
from typing import Deque
def parse_object(tokens: Deque[Token]) -> JSONObject:
"""Parses an object out of JSON tokens"""
obj: JSONObject = {}
# special case:
if tokens[0].type == 'right_brace':
tokens.popleft()
return obj
while tokens:
token = tokens.popleft()
if... | f7d7ac489dd03c04e6820f430c9d6cd09376c222 | 49,552 |
def calc_Asym_vs_emin_energies(det_df,
dict_index_to_det, singles_hist_e_n, e_bin_edges_sh,
bhp_nn_e, e_bin_edges,
emins, emax, angle_bin_edges,
plot_flag=True, show_flag = False, save_flag=True):
"""
Calculate Asym for variable emi... | 4fb19fee0af8f1a2c9425e59c2634f8b49b72978 | 49,553 |
def get_best_of_n_avg(seq, n=3):
"""compute the average of first n numbers in the list ``seq``
sorted in ascending order
"""
return sum(sorted(seq)[:n])/n | 6166bbeda10d81356a86151901f33a26f0ff1035 | 49,554 |
import os
def _prep_cosim(args, **sigs):
""" prepare the cosimulation environment
"""
# compile the verilog files with the verilog simulator
files = ['../myhdl/mm_maths1.v',
'../bsv/mb_maths1.v',
'../bsv/mkMaths1.v',
'../chisel/generated/mc_maths1.v',
... | d675a07390187be6a6c653beb44473d3bb8a0d90 | 49,555 |
def py2_earth_hours_left(start_date=BITE_CREATED_DT):
"""Return how many hours, rounded to 2 decimals, Python 2 has
left on Planet Earth (calculated from start_date)"""
return round((PY2_DEATH_DT - start_date) / timedelta(hours=1), 2) | e958cfbcbe3f1d6d6c00e52a26c9dd4591b7c0f0 | 49,556 |
from typing import Dict
from typing import Tuple
def merge_model_results(results: Dict[str, Dict[Tuple[str, int], pd.DataFrame]]) -> pd.DataFrame:
"""
Combine the results of running :func:`util.analyze_model` across a corpus
into a single dataframe.
:param results: Mapping from model name to dict... | f231d47bca582158ac09065966bad83ea3427a02 | 49,557 |
def _float_feature(value):
"""Wrapper for inserting float features into Example proto."""
return tf.train.Feature(float_list=tf.train.FloatList(value=value)) | 2d286fd444e16fac47f76507cd68be99919346fe | 49,558 |
def valid_bytes_128_after(valid_bytes_48_after):
"""
Fixture that yields a :class:`~bytes` that is 128 bits and is ordered "greater than" the
result of the :func:`~valid_bytes_128_after` fixture.
"""
return valid_bytes_48_after + b'\0' * 10 | 03e39e1b2d58b97184b30d57367ef5ca5b636f0e | 49,559 |
def const_coeffs(s=0.0, py=0.0, pz=0.0, px=0.0):
"""
Creates coefficients for seperated tunnelling to each orbital.
The energies are set to zero.
"""
cc = np.array([s, py, pz, px]) != 0.0
coeffs = np.empty((sum(cc),4),)
ene = np.zeros(sum(cc))
if s != 0.0:
coeffs[sum(cc[:1])-1] ... | 634d56731cdc07f28819a0e560193010457152cf | 49,560 |
from re import VERBOSE
import math
def calcIntraElectroHydrophobic(pdb, interface, depthDistances):
"""
Calculated possible electro interactions, excluding 1-2 and 1-3 interactions
(already included in angle and bond interactions
"""
HYDROPHOBIC_CHARGED_CUTOFF_DISTANCE = 6 # we could have 6?
... | a35674c36467d07c9225ae94bbc5f255a3d9c550 | 49,561 |
def positional_encoding(position: int, d_model: int) -> tf.Tensor:
"""Returns the positional encoding for a given position and timestamp"""
angle_rads = get_angles(np.arange(position)[:, np.newaxis],
np.arange(d_model)[np.newaxis, :],
d_model)
# apply... | 294281053a256d95b27066499909ec9bd78c4000 | 49,562 |
from typing import List
def add_multiple_of_row_of_square_matrix(matrix: List[List], source_row: int, k: int, target_row: int):
"""
add k * source_row to target_row of matrix m
"""
n = len(matrix)
row_operator = make_identity(n)
row_operator[target_row][source_row] = k
return multiply_matr... | 2ff7a31e0c52a34973510661a8e266f8c10abfcb | 49,563 |
import torch
def shadow_mapping(cam_results, light_results, rays, ppc, light_ppc, image_shape, batch_size, fine_sampling):
"""
cam_result: result dictionary with `depth_*`, `opacity_*`
light_result: result dictionary with `depth_*`, `opacity_*`
rays: generated rays
ppc: [Batch_size] Camera Poses:... | 8ff43760a1b09900edd70e5a9f0171d83ad756cf | 49,564 |
def get_panelists():
"""Retrieve a list of panelists and their corresponding
information"""
return panelists.get_panelists(database_connection) | db6ac71d72d3ac53f38c484a09c9ac91e3ac2ecb | 49,565 |
def count_distinct_col(curs, table_name, col='y'):
"""Queries to find number of distinct values of col column in table in
database.
Args:
curs (sqlite3.Cursor): cursor to database
table_name (str): name of table to query
col (str): name of column to find number of distinct values fo... | c346b8463eeb4faec645917831f7bde8f42ed5e1 | 49,566 |
import time
import socket
def get_info(timeout_seconds=None) -> bool:
"""
Gets information from twitch and hands it over to parsers. Also manages any
PING's sent by twitch, automatically replying with a PONG.
Args:
timeout_seconds: How long you'd like to wait for a response before
... | 2b1c9751646b98709d88204b1b7a3803bd48987f | 49,567 |
from pathlib import Path
import os
def does_file_exist(file_path: Path) -> bool:
"""Check for file existence."""
print(f"... Checking if file [{file_path}] exists")
if os.path.isfile(file_path):
print("...... File exists...")
return True
else:
return False | e5f08fccd30fdc7ace9aab2e03f13b584275a97a | 49,568 |
def reduce_dataset_by_column_value(df, colname, values):
"""Returns the passed dataframe, with only the passed column values"""
col_ids = df[colname].unique()
nvals = len(col_ids)
# Reduce dataset
reduced = df.loc[df['locus_tag'].isin(values)]
# create indices and values for probes
new_ids... | ee8411dd5e1152b1ae1a9b78a70396c03a0c0f7c | 49,569 |
def limitsSql(pageToken=0, pageSize=None):
"""
Takes parsed pagination data, spits out equivalent SQL 'limit' statement.
:param pageToken: starting row position,
can be an int or string containing an int
:param pageSize: number of records requested for this transaciton,
can be an int or... | 9b188d405afb0c367a5f61b46c50a7c7a63e4879 | 49,570 |
import scipy.io.matlab.mio
import os
def maybe_download_sbs():
"""Download the SBS dataset to its expected location if necessary"""
files = []
for channel in 1, 2:
idx = 1
for row in "ABCDEFGH":
for col in range(1, 13):
files.append("Channel%d-%02d-%s-%02d.tif" ... | be3574c000bf410ce3b50f6dd5f7687d7e1e4ea4 | 49,571 |
def split(df):
"""
Splits the given dataframe into a 8/2 split for training and testing
:param df:the dataframe you want to split
:return:
"""
training, test = train_test_split(df, test_size=0.2, random_state=42)
train, val = train_test_split(training, test_size=0.2, random_state=42)
re... | 0b4e99332a25ccc971abf099d90f3c8466741019 | 49,572 |
def test_wait_within_timeout():
"""Test that we can wait for a job terminating before timeout.
"""
i = 0
def cond():
nonlocal i
j = i
i += 1
return j
job = InstrJob(cond, 0)
assert job.wait_for_completion(refresh_time=0.01)
assert i == 2 | 48e01ca620829294e21aa54da0b0a811d89d2c52 | 49,573 |
import os
import torch
def get_lm_corpus(datadir: str, dataset: str, use_bpe=False, max_size=None, valid_custom=None) -> Corpus:
"""Factory method for Corpus.
Arguments:
max_size: .
use_bpe: OpenAI's BPE encoding
datadir: Where does the data live?
dataset: eg 'wt103' which tel... | 16a2efa71f44b063681daac708a58ec00a87d9f0 | 49,574 |
import sys
def user_prompt(question, default = "yes"):
"""Asks the user a yes/no question
Args:
question (str): Question for the user
"""
prompt = '[Y/n] '
valid = {"yes": True, "y": True, "no": False, "n": False}
while True:
sys.stdout.write(question + " " + prompt)
... | 5d0634dedaa6f5f07c688a2a06e41975a77d51c1 | 49,575 |
import os
def download_data(force_download=False):
"""Downloads the data
:param bool force_download: If true, overwrites a previously cached file
:rtype: str
"""
if os.path.exists(DATA_PATH) and not force_download:
log.info('using cached data at %s', DATA_PATH)
else:
log.info(... | 80d5fd225bf434760bb3ed33f8785275bc50153f | 49,576 |
def module_method(fn):
"""Decorates a function as a module method.
The `module_method` allows modules to have multiple methods that make use of
the modules parameters.
Example::
class MyLinearModule(nn.Module):
def apply(self, x, features, kernel_init):
kernel = self.param('kernel', (x.shap... | 02f0d422e0ca6352d56d6e3e9b05b1f288f55762 | 49,577 |
def sa_middleware(key: str = SA_DEFAULT_KEY) -> THandler:
"""SQLAlchemy asynchronous middleware factory.
:param key: key of SQLAlchemy binding. Has default.
"""
@middleware
async def sa_middleware_(
request: Request,
handler: THandler,
) -> StreamResponse:
if key in req... | aeb8c1caf7e83ec1c5bdb51da03b6a58d320da7f | 49,578 |
from typing import Union
from typing import Optional
from typing import Tuple
import os
def unset_key(
dotenv_path: Union[str, _PathLike],
key_to_unset: str,
quote_mode: str = "always",
encoding: Optional[str] = "utf-8",
) -> Tuple[Optional[bool], str]:
"""
Removes a given key from the given .... | a302d956f96ff29653c63ceee2a73bbb719258cb | 49,579 |
import os
import uuid
def generate_working_dir(working_dir_base):
"""
Creates a unique working directory to combat job multitenancy
:param working_dir_base: base working directory
:return: a unique subfolder in working_dir_base with a uuid
"""
working_dir = os.path.join(working_dir_base, str(... | 31040ee2f411542599cd5b5a1bdc788ba81bb332 | 49,580 |
def report_to_fields(report, fields=None):
"""
Take a single report and convert the KEY: value
lines into a dict of key-value pairs.
Ignore any lines that don't have a colon in them.
:param report: A list of text lines.
:param fields: If not None, then update an existing dict.
:return:
... | bb42eefc2fae7ffdb37929779caff328ddd2dbba | 49,581 |
import re
def add_http_if_no_scheme(url):
"""Add http as the default scheme if it is missing from the url."""
match = re.match(r"^\w+://", url, flags=re.I)
if not match:
parts = urlparse(url)
scheme = "http:" if parts.netloc else "http://"
url = scheme + url
return url | ea7799616c0616fda85814139b7a36264cbc9e40 | 49,582 |
def _check_half_window(half_window, allow_zero=False):
"""
Ensures the half-window is an integer and has an appropriate value.
Parameters
----------
half_window : int, optional
The half-window used for the smoothing functions. Used
to pad the left and right edges of the data to redu... | 4e40b307242f3c1137251903b227144a4deb53d6 | 49,583 |
import os
def _create_engine_kwargs():
"""Create the kwargs for the database engine.
Returns:
(Dict): "Engine arguments"
(String): "Certificate file path"
"""
kwargs = {
"client_encoding": "utf8",
"pool_size": Config.SQLALCHEMY_POOL_SIZE,
}
cert_file = "/etc/s... | 604c82c0223a31c4eacdc4cbf7f0e750434288b4 | 49,584 |
async def get_run_controller(
runId: str,
task_runner: TaskRunner = Depends(get_task_runner),
engine_store: EngineStore = Depends(get_engine_store),
run_store: RunStore = Depends(get_run_store),
) -> RunController:
"""Get a RunController for the current run.
This ensures that a run exists and i... | 10e08c4096764ee2e181083699d353edea551409 | 49,585 |
import io
import click
def get_pixel_ratio(img, img_path):
"""
Tries to read file metadata from dm file. If normal .tif images are provided
instead, prompts user for the nm/pixel ratio, which can be found using the
measurement tool in ImageJ or similar. For example, a scale bar of 100nm corresponds to... | 5d50e4b4db7620256d62f359fca8608216a54b95 | 49,586 |
def gauss_kern(size, sizey=None): # smooth test
""" Returns a normalized 2D gauss kernel array for convolutions """
size = int(size)
if not sizey:
sizey = size
else:
sizey = int(sizey)
x, y = np.mgrid[-size:size+1, -sizey:sizey+1]
g = np.exp(-(x**2/float(size)+y**2/float(sizey))... | ea0d9a4266942ae4e40d6815d6391ac4532ad808 | 49,587 |
def full_clean(string_in):
"""Call of my string cleaning functions in order"""
#print('string_in = %s' % string_in)
if string_in is None:
return string_in
elif type(string_in) == unicode:
string_in = string_in.encode('UTF-8')
elif type(string_in) not in [str, unicode]:
return... | d4325f997bcf0c71d569155d72240ae7d11661de | 49,588 |
def partitioned_variable_assign(partitioned_var, new_value):
"""Assign op for partitioned variables.
Args:
partitioned_var: A partitioned tensorflow variable
new_value: Value to be assigned to the variable var
Returns:
A tensorflow op that groups the assign ops for each of the variable slices
"""
... | f61f32ee5c948a1efe82ec329472eb841a4d8b78 | 49,589 |
from typing import Optional
from typing import Set
def process_df(
df: pd.DataFrame,
version: Optional[str] = None,
skip_databases: Optional[Set[str]] = None,
) -> DGIProcessor:
"""Get a processor that extracted INDRA Statements from DGI content based
on the given dataframe.
Parameters
--... | c63489b20073eda59cf15cb96e3fcfd5499a9efc | 49,590 |
def coerce_levels(image_numpy, levels=255, method="divide", reference_image = [], reference_norm_range = [.075, 1], mask_value=0, coerce_positive=True):
""" In volumes with huge outliers, the divide method will
likely result in many zero values. This happens in practice
quite often. TO-DO: find a b... | 9bf458c551d71a7d43841209d2e5d3aad5d6da15 | 49,591 |
from typing import List
def merge_and_count(ll: List[int], lr: List[int]) -> (int, List[int]):
"""
:param ll:
:param lr:
:return:
>>> merge_and_count([1, 2, 4], [3, 5])
(1, [1, 2, 3, 4, 5])
>>> merge_and_count([1, 2, 6], [3, 5])
(2, [1, 2, 3, 5, 6])
"""
result = []
coun... | b513ce03b317a2cc5332aa3c50abd612380b08b6 | 49,592 |
def get_ap_bboxes(img, model, dataset_name, verbose=False):
"""
Detect appearance based foreground bounding boxes on a frame by a pre-trained object detector.
Args:
img (ndarray): The frame to be detected.
model (nn.Module): The loaded detector.
dataset_name (str): The name of datase... | 41f5dcec8868cf19e10ba98a5a5ff91b375bf618 | 49,593 |
import typing
import subprocess
def syscmd(cmd: typing.Union[str, list], encoding: str=''):
"""
Runs a command on the system, waits for the command to finish, and then returns the
text output of the command. If the command produces no text output, the command's
return code will be returned instead. Op... | 4f8cb5fa97780633147e42790f984dba583ba5f4 | 49,594 |
def delete_user_entitlement(user, organization=None, detect=None):
"""Remove user from an organization.
:param user: Email ID or ID of the user.
:type user: str
"""
organization = resolve_instance(detect=detect, organization=organization)
if '@' in user:
user = resolve_identity_as_id(use... | c9b5d440f42eeb5da0746974a1b598cab72d4e03 | 49,595 |
import struct
def encode_string(input_string):
"""Encode the string value in binary using utf-8
as well as its length (valuable info when decoding
later on). Length will be encoded as an unsigned
short (max 65535).
"""
input_string_encoded = input_string.encode("utf-8")
length = len(input... | ecb26ce97cbebfe79b694e96b6e16d50069858b4 | 49,596 |
def resnet152(block, layers, pretrained=False, **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(block, layers, **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet... | b9e291a6c958b70e684d46bb63a31583d91e514b | 49,597 |
def delete_project(project_type, project_id):
"""
Delete an existing project (including all configuration, data and metadata)
GET:
- project_type: "link" or "normalize"
- project_id
"""
_check_project_type(project_type)
# TODO: replace by _init_project
if project_ty... | 917c8d885f344abc9b1edc6375badd47f6f3c3b8 | 49,598 |
import shutil
def download_file(url, filename, sourceiss3bucket=None):
"""
Download the file from `url` and save it locally under `filename`.
:rtype : bool
:param url:
:param filename:
:param sourceiss3bucket:
"""
conn = None
if sourceiss3bucket:
bucket_name = url.split('/')[3... | acf53bafc180da684d7bbd7a747d66d68aa40105 | 49,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.