content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def remove_accents(string):
"""
Removes unicode accents from a string, downgrading to the base character
"""
nfkd = unicodedata.normalize('NFKD', string)
return u"".join([c for c in nfkd if not unicodedata.combining(c)]) | 5,319,000 |
def __get_a0( # pylint: disable=invalid-name
n: int, a0: Optional[np.ndarray] = None
) -> np.ndarray:
"""
Returns initial parameters for fitting algorithm.
:param n: Number of parameters
:param a0: Initial parameters value. Optional
:return: nd.array
"""
if a0 is not None:
retu... | 5,319,001 |
def convert_yaw_to_old_viewpoint(yaw):
""" we initially had viewpoint coordinates inverted
Example:
>>> import math
>>> TAU = 2 * math.pi
>>> old_viewpoint_labels = [
>>> ('left' , 0, 0.000 * TAU,),
>>> ('frontleft' , 45, 0.125 * TAU,),
>>> ... | 5,319,002 |
def uploadimages(path_list,client,csv_list):
"""Uploads images to imgur.
Arguments:
path_list {list} -- [List of files at directory.]
client {ImgurClient} -- [ImgurClient we get from authentication.]
csv_list {list} -- [List of uploaded pictures.]
"""
#we create a dataframe to k... | 5,319,003 |
def extract_lexical_features_test(nlp, tweet_list):
"""Provides tokenization, POS and dependency parsing
Args:
nlp (spaCy model): Language processing pipeline
"""
result = []
texts = (tweet for tweet in tweet_list)
for doc in nlp.pipe(texts, batch_size=10000, n_threads=3):
setti... | 5,319,004 |
def _run_commands(cmdinfos, proc):
"""Execute the commands specified in the 'cmdinfos' dictionary."""
if proc.is_remote:
# In case of a remote host, it is much more effecient to run all commands in one go, because
# in this case only one SSH session needs to be established.
cmd = ""
... | 5,319,005 |
def get_hostname():
""" Return hostname. """
return tg.config.get('workbox.hostname') | 5,319,006 |
def geocode_location(api_key, loc):
"""Get a geocoded location from gooogle's geocoding api."""
try:
parsed_json = http.get_json(GEOCODING_URL, address=loc, key=api_key)
except IOError:
return None
return parsed_json | 5,319,007 |
def degree(f, *gens, **args):
"""
Return the degree of ``f`` in the given variable.
The degree of 0 is negative infinity.
Examples
========
>>> degree(x**2 + y*x + 1, gen=x)
2
>>> degree(x**2 + y*x + 1, gen=y)
1
>>> degree(0, x)
-inf
"""
allowed_flags(args, ['gen'... | 5,319,008 |
def getworstlda(matches):
"""find the worst tournaments in terms of 'last direct acceptance'"""
global joinedrankingsdf
#join rankings with playernames
dirname = ".."
playersDB = dirname + "/atp_players.csv"
rankings.columns = ['date', 'rank', 'id','points']
playersdf = pd.read_csv... | 5,319,009 |
def fit_model_sector(sector_corpus: Dict[DocId, Token]) -> sbmtm:
"""Fits the model taking the sector corpus data structure as an input
Args:
sector_corpus: a dict where keys are doc ids and
values are the tokenised descriptions
Returns:
The model
"""
model = sbmtm()
... | 5,319,010 |
def get_simulated_matches(path, met, sample_to_match, pop_var):
"""Selects initial conditions from cosmic data to match to star sample
Parameters
----------
path : `str`
path to cosmic data
met : `float`
metallicity of cosmic data file
sample_to_match : `DataFrame`
A d... | 5,319,011 |
def _save_traj(ts_zma, ts_dct, savefs_dct, zma_locs=(0,)):
""" save trajectory and zma stuff
"""
zrxn = ts_dct['zrxn']
_, ts_path = savefs_dct['ts_fs']
ioprinter.info_message(
'Saving the V-Matrix into the filesystem...', newline=1)
zma_fs = autofile.fs.zmatrix(ts_path)
zma_fs[-1].... | 5,319,012 |
def _get_url_ext(url: str):
"""
>>> _get_url_ext('http://example.com/blog/feed')
'feed'
>>> _get_url_ext('http://example.com/blog/feed.xml')
'xml'
>>> no_error = _get_url_ext('http://example.com')
"""
try:
url_path = urlparse(url).path.strip('/')
except ValueError:
re... | 5,319,013 |
def download(job, stop_download, publish, update_job_progress):
"""
See https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
for more information regarding the backoff behaviour (i.e. jitter).
"""
start_position_bytes = 0
if os.path.exists(job.filepath):
start_posit... | 5,319,014 |
async def flip_coin(message: types.Message):
"""Отправляет случайный стикер"""
path = await get_random_sticker_path()
async with aiofiles.open(path, 'rb') as sticker:
await message.answer_sticker(sticker)
logger.success('A sticker was sent successfully') | 5,319,015 |
def connect_server():
"""Connect to azure cosmos DB.
Connet to azure cosmos DB.
Need to insert ID, DB name, table name, and key.
Args:
None
Returns:
clt(str): an instance for connecting to azure cosmos DB server
"""
clt = client.Client(
'wss://<YOURID>... | 5,319,016 |
def test_device_cli(cli_func: Callable) -> None:
"""Test specific CLI call doesn't crash.."""
with patch.object(sys, "argv", ["--help"]), patch.object(sys, "exit"):
cli_func() | 5,319,017 |
def checkCpuTime(sleeptime=0.2):
"""Check if cpu time works correctly"""
if checkCpuTime.passed:
return True
# First test that sleeping does not consume cputime
start1 = process_time()
sleep(sleeptime)
t1 = process_time() - start1
# secondly check by comparing to cpusleep (where we ... | 5,319,018 |
def xmind_to_iwork_csv_file(xmind_file):
"""Convert XMind file to a iwork csv file"""
xmind_file = get_absolute_path(xmind_file)
logging.info('Start converting XMind file(%s) to iwork file...', xmind_file)
testcases = get_xmind_testcase_list(xmind_file)
fileheader = ["用例概要*", "用例描述", "测试步骤", "测试数据"... | 5,319,019 |
def load_ply(path):
"""
Loads a 3D mesh model from a PLY file.
:param path: A path to a PLY file.
:return: The loaded model given by a dictionary with items:
'pts' (nx3 ndarray), 'normals' (nx3 ndarray), 'colors' (nx3 ndarray),
'faces' (mx3 ndarray) - the latter three are optional.
"""
... | 5,319,020 |
def parse_range(rng, dictvars={}):
"""Parse a string with an integer range and return a list of numbers, replacing special variables in dictvars."""
parts = rng.split('-')
if len(parts) not in [1, 2]:
raise ValueError("Bad range: '%s'" % (rng,))
parts = [int(i) if i not in dictvars else dictva... | 5,319,021 |
def relpaths(basepath: _path_t, pattern: Union[str, Iterable[_path_t]]) -> List[str]:
"""Convert a list of paths to relative paths
Parameters
----------
basepath : Union[str, Path]
Path to use as the reference when calculating relative paths
pattern : Union[str, Iterable[Union[str, Path]]]
... | 5,319,022 |
def binary_backtests_returns(
backtests: pd.DataFrame,
) -> pd.DataFrame:
"""
Converts a Horizon backtest data frame into a binary backtests of directions
"""
return backtests.diff().apply(np.sign).dropna() | 5,319,023 |
def calculate_students_features_csv(entry_id, xmodule_instance_args):
"""
Compute student profile information for a course and upload the
CSV to an S3 bucket for download.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = ugettex... | 5,319,024 |
def remove_shared_nodes(vars=None):
"""
Remove shared nodes
:param vars: `nodes` as key - Node Id for the node
:type vars: dict
:param vars: `email` as key - Email address of the user
:type vars: dict
:raises Exception: If there is an issue
while removing shared... | 5,319,025 |
def colorMap(value, name="jet", vmin=None, vmax=None):
"""Map a real value in range [vmin, vmax] to a (r,g,b) color scale.
:param value: scalar value to transform into a color
:type value: float, list
:param name: color map name
:type name: str, matplotlib.colors.LinearSegmentedColormap
:return:... | 5,319,026 |
def cc_embed_data(
name,
srcs,
cc_file_output,
h_file_output,
testonly = False,
cpp_namespace = None,
strip_prefix = None,
flatten = False,
identifier = None,
**kwargs):
"""Embeds 'srcs' into a C++ module.
Generates a header like:
... | 5,319,027 |
def save_genre(row: dict):
"""Genre's control and save in data base."""
try:
result: Genres = session.query(Genres) \
.filter(Genres.name == row.get('genre_name')) \
.one()
return result
except MultipleResultsFound:
pri... | 5,319,028 |
def test_edge_detector_from_undef(circuit):
"""Test the edge detector's parameters u_rise, u_fall."""
setup = []
i = 0
for value in (False, True):
for ur in (False, True, None):
for uf in (False, True):
for r in (False, True):
dest = edzed.Input(f'... | 5,319,029 |
def specializations(examples_so_far, h):
"""Specialize the hypothesis by adding AND operations to the disjunctions"""
hypotheses = []
for i, disj in enumerate(h):
for e in examples_so_far:
for k, v in e.items():
if k in disj or k == 'GOAL':
continue
... | 5,319,030 |
def formulate_contingency(problem: LpProblem, numerical_circuit: OpfTimeCircuit, flow_f, ratings, LODF, monitor,
lodf_tolerance):
"""
:param problem:
:param numerical_circuit:
:param flow_f:
:param LODF:
:param monitor:
:return:
"""
nbr, nt = ratings.shape
... | 5,319,031 |
def max_pooling3d(inputs,
pool_size, strides,
padding='valid', data_format='channels_last',
name=None):
"""Max pooling layer for 3D inputs (e.g. volumes).
Arguments:
inputs: The tensor over which to pool. Must have rank 5.
pool_size: An integer or tuple... | 5,319,032 |
def parareal_engine(x_0, U, num_iter, coarse_model="learned"):
"""Rolls out a trajectory using Parareal
Args:
x_0: Initial state
U: Control sequence
num_iter: Number of Parareal iterations to use for prediction
coarse_model: Learned/Analytical coarse model
Returns:
X: The corresponding state seq... | 5,319,033 |
def plot_posterior_op(trace_values, ax, kde_plot, point_estimate, round_to,
alpha_level, ref_val, rope, text_size=16, **kwargs):
"""Artist to draw posterior."""
def format_as_percent(x, round_to=0):
return '{0:.{1:d}f}%'.format(100 * x, round_to)
def display_ref_val(ref_val):
... | 5,319,034 |
def get_reviews(directory_name, API_key, place_id, verbose=True):
"""Retrieve and save reviews of properties through Google Map Places Details API as json files.
Parameters
----------
directory_name: str
name of a new directory containing all the saved json files
API_key: str
key fo... | 5,319,035 |
def change_theme(file: str, theme_name: str, logfile: str) -> bool:
"""
Change Oh My ZSH Theme
"""
if get_zsh_theme(file, logfile):
current_file = read_file_log(file, logfile)
current_theme = get_zsh_theme(file, logfile)[1]
new_theme = f'ZSH_THEME="{theme_name}"'
new_file... | 5,319,036 |
def check_tensor(data):
"""Ensure that data is a numpy 4D array."""
assert isinstance(data, np.ndarray)
if data.ndim == 2:
data = data[np.newaxis,np.newaxis,...]
elif data.ndim == 3:
data = data[np.newaxis,...]
elif data.ndim == 4:
pass
else:
raise RuntimeError('... | 5,319,037 |
def _find_first_ref(ref: Ref, message_type: Type[B]) -> Optional[B]:
""" Finds and returns (if exists) the first instance of the specified message type
within the specified Ref.
"""
# Get the body message, if it exists
body = _get_ref_body(ref)
if isinstance(body, message_type):
return b... | 5,319,038 |
def remove(name):
"""remove a package repository
Use this command to remove a repository from your local index.
"""
ctx = click.get_current_context()
ctx.obj.config.remove_repository(
name=name
)
ctx.obj.write_config() | 5,319,039 |
def verify_activation_token(*, uidb64, token):
"""
:param uidb64: (str) Base 64 of user PK.
:param token: (str) Hash.
:return: (bool) True if user verified, False otherwise.
"""
user_id = force_text(urlsafe_base64_decode(uidb64))
try:
user = User.objects.get(pk=user_id)
except ... | 5,319,040 |
def test_parse():
"""Test parsing pubtator."""
parser = PubtatorGeneParser()
scraper = mock.MockPubtatorGeneScraper()
gen_df = scraper.scrape(mock.TEST_CHUNKSIZE)
parsed_df = parser.parse(next(gen_df))
assert parsed_df.shape[0] == 1 | 5,319,041 |
def to_unix_timestamp(self):
"""Check the toUnixTimestamp() function with DateTime64 extended range"""
stress = self.context.stress
for year in years_range(stress):
with Given(f"I choose datetimes in {year}"):
datetimes = select_dates_in_year(year=year, stress=stress)
timezo... | 5,319,042 |
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a min... | 5,319,043 |
async def filters_active(event):
""" For .filters command, lists all of the active filters in a chat. """
try:
from ub.modules.sql_helper.filter_sql import get_filters
except AttributeError:
await event.reply("`Running on Non-SQL mode!`")
return
transact = f"`{JAVES_NNAME}`: ** T... | 5,319,044 |
def read_protein_from_file(file_pointer):
"""The algorithm Defining Secondary Structure of Proteins (DSSP) uses information on e.g. the
position of atoms and the hydrogen bonds of the molecule to determine the secondary structure
(helices, sheets...).
"""
dict_ = {}
_dssp_dict = {'L': 0, 'H': 1,... | 5,319,045 |
def match(string, rule='IRI_reference'):
"""Convenience function for checking if `string` matches a specific rule.
Returns a match object or None::
>>> assert match('%C7X', 'pct_encoded') is None
>>> assert match('%C7', 'pct_encoded')
>>> assert match('%c7', 'pct_encoded')
"""
... | 5,319,046 |
def verify_td3(mrz: List[str]) -> bool:
"""Verify TD3 MRZ"""
if mrz[0][0] != "P":
return False
# if mrz[0][1]: # At the discretion of the issuing State or organization or "<"
# if mrz[0][2:5]: # ISSUING STATE OR ORGANIZATION
# if mrz[0][5:44]: # NAME
if calculate_check_digit(mrz[1][0:9])... | 5,319,047 |
def test_label_sample_invalid_boolean():
"""Unit test for attempting to label a sample with an invalid boolean label"""
dataset_id = create_demo_dataset()
# Fetch samples
response = client.get(f"{PREFIX}/datasets/{dataset_id}/samples")
assert response.status_code == 200
sample_id = response.j... | 5,319,048 |
def compute_pwcca(acts1, acts2, epsilon=0.):
""" Computes projection weighting for weighting CCA coefficients
Args:
acts1: 2d numpy array, shaped (neurons, num_datapoints)
acts2: 2d numpy array, shaped (neurons, num_datapoints)
Returns:
Original cca coefficient mean and weighted mean
... | 5,319,049 |
def Prepare(benchmark_spec):
"""Prepare the virtual machines to run memtier against memcached.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
"""
client = benchmark_spec.vm_groups['client']
server = benchmark_spec.vm_groups['server']
... | 5,319,050 |
def read_table(srm_file):
"""
Reads SRM compositional data from file.
For file format information, see:
http://latools.readthedocs.io/en/latest/users/configuration/srm-file.html
Parameters
----------
file : str
Path to SRM file.
Returns
-------
SRM compositions : panda... | 5,319,051 |
def walker_method(for_class=object, methods_list=None):
"""A decorator to add something to the default walker methods,
selecting on class
"""
if methods_list is None: # handle early binding of defaults
methods_list = fallback_walker_method_list
def wrap(walker):
# wrap a walker wi... | 5,319,052 |
def get_data(name_dataset='index',
verbose=True,
address="../datasets/",):
"""
This function is to load dataset from the git repository
:param name_dataset: name of dataset (str)
:param verbose:
:param address: url of dataset in the git repo
:return data: loaded dataset... | 5,319,053 |
def copy_valid_indices(
acts, # type: torch.Tensor
target, # type: List[List[int]]
act_lens, # type: List[int]
valid_indices, # type: List[int]
):
# type: (...) -> (torch.Tensor, List[List[int]], List[int])
"""Copy the CTC inputs without the erroneous samples"""
if len(valid_indices) == ... | 5,319,054 |
def linprog_verbose_callback(res):
"""
A sample callback function demonstrating the linprog callback interface.
This callback produces detailed output to sys.stdout before each iteration
and after the final iteration of the simplex algorithm.
Parameters
----------
res : A `scipy.optimize.Op... | 5,319,055 |
def is_odd(num: int) -> bool:
"""Is num odd?
:param num: number to check.
:type num: int
:returns: True if num is odd.
:rtype: bool
:raises: ``TypeError`` if num is not an int.
"""
if not isinstance(num, int):
raise TypeError("{} is not an int".format(num))
return num % 2 ==... | 5,319,056 |
def cross_entropy_loss(y_hat, y):
"""
Cross entropy loss
y_hat: predict y after softmax, shape:(M,d), M is the #of samples
y: shape(M,d)
"""
loss = np.mean(np.sum(- y * np.log(y_hat), axis=-1))
dy = y_hat - y
return loss, dy | 5,319,057 |
def string_list(resource_name, encoding='utf-8'):
"""Package resource wrapper for obtaining resource contents as list of
strings.
The function uses the 'string' method and splits the resulting string
in lines.
Params:
resource_name: Relative path to the resource in the package (from the
... | 5,319,058 |
def get_plugin_names():
""" Get the list of names of registered plugins.
"""
pluginlist = []
# Read
if os.path.isfile(regfile):
with open(regfile, 'rb') as f:
pluginlist = f.read().decode().splitlines()
# Clean
pluginlist = [line.strip() for line in pluginlist]
plugin... | 5,319,059 |
def loss(params_json, model_weights, train_csv, validation_csv, out_csv):
"""
Record aggregate losses.
"""
v = TCRVAE.of_json_file(params_json)
v.vae.load_weights(model_weights)
df = pd.DataFrame(
OrderedDict([('train', v.evaluate(v.get_data(train_csv, v.params['batch_size']))),
... | 5,319,060 |
def rpc_get_name() -> Optional[str]:
"""Retrieve the JsonRpc id name."""
global _RpcName
return _RpcName | 5,319,061 |
def _epd_platform_from_raw_spec(raw_spec):
""" Create an EPDPlatform instance from the metadata info returned by
parse_rawspec.
if no platform is defined ('platform' and 'osdist' set to None), then
None is returned.
"""
platform = raw_spec[_TAG_PLATFORM]
osdist = raw_spec[_TAG_OSDIST]
i... | 5,319,062 |
def index(request):
"""The home page for Distance Tracker."""
if request.user.is_authenticated:
today = date.today()
cur_week = today.isocalendar()[1]
cur_month = today.month
cur_year = today.year
exercises_week = Exercise.objects.filter(owner=request.user,
... | 5,319,063 |
def mod_from_file(mod_name, path):
"""Runs the Python code at path, returns a new module with the resulting globals"""
attrs = runpy.run_path(path, run_name=mod_name)
mod = imp.new_module(mod_name)
mod.__dict__.update(attrs)
return mod | 5,319,064 |
def interpolation(x0: float, y0: float, x1: float, y1: float, x: float) -> float:
"""
Performs interpolation.
Parameters
----------
x0 : float.
The coordinate of the first point on the x axis.
y0 : float.
The coordinate of the first point on the y axis.
x1 : float.
T... | 5,319,065 |
def do2ptblinding(unblindedfile, cosmfile, inifor2pt, outftag = 'bl', seed='blinded'):
"""
Given unblinded data file, computes and applies blinding factors.
Factors are computed doing [shift cosm 2pt fn]/[ref cosm 2pt fn]
where cosm parameters are taken from pregenerated
cosmfile, and the shifted c... | 5,319,066 |
def product_counter_v3(products):
"""Get count of products in descending order."""
return collections.Counter(products) | 5,319,067 |
def symlink_force(source, link_name):
"""
if symbolic link already exists, remove it first then make symlink
"""
if os.path.exists(link_name) and os.path.islink(link_name):
os.remove(link_name)
os.symlink(source, link_name) | 5,319,068 |
def remove_noise(line,minsize=8):
"""Remove small pixels from an image."""
if minsize==0: return line
bin = (line>0.5*np.amax(line))
labels,n = ndimage.label(bin)
sums = ndimage.sum(bin,labels,range(n+1))
sums = sums[labels]
good = np.minimum(bin,1-(sums>0)*(sums<minsize))
return good | 5,319,069 |
def regle_catboost_depth(depth, categorical_features_index,
X, y, affiche_boxplot=True):
"""
Voir l'influence de l'hyperparamètre ccp_alpha de ExraTreesRegressor
Parameters
----------
depth : La profondeur de l'arbre, obligatoire.
categorical_features_index : les ... | 5,319,070 |
def predict(args):
"""
predicts scores for test files
"""
assert len(args.test_files) > 0, 'No test files are provided.'
logger.info('Loading dataset and configuration...')
hc_data = HCDataset(args.config_path, args.cv, args.folds, args.train_files, args.dev_files, args.test_files)
logger.info('Restoring the mod... | 5,319,071 |
def _ParseFormatDocString(printer):
"""Parses the doc string for printer.
Args:
printer: The doc string will be parsed from this resource format printer.
Returns:
A (description, attributes) tuple:
description - The format description.
attributes - A list of (name, description) tuples, one t... | 5,319,072 |
def build_answers_xml(selector, args):
""" builds an answers xml string for a selector class using
default answers for the selector's questions. If any other attributes
were included in the call, they are appended to as part of the
work-info. """
# build an answers xml tree
answers = ET.Ele... | 5,319,073 |
def berger_table(teams):
"""Returns an iterator over possible rounds (each player plays once against each other player).
This returns the same matches as round_robin but the order in which the elements are returned is better for having
many matches concurrently (on different courts for example).
Note t... | 5,319,074 |
def give_me_the_answer(question, clever=False):
"""This gives you the answer.
Parameters
----------
question: str
the question you are asking.
clever: bool, optional
whether or not the answer should be clever or not
Returns
-------
The answer
"""
if not isinsta... | 5,319,075 |
def round_down(x: float, decimal_places: int) -> float:
"""
Round a float down to decimal_places.
Parameters
----------
x : float
decimal_places : int
Returns
-------
rounded_float : float
Examples
--------
>>> round_down(1.23456, 3)
1.234
>>> round_down(1.2345... | 5,319,076 |
def plot_scatter(x_data, y_data, xlim=None, ylim=None, xlabel=None, ylabel=None,
filename=None, log=False, loc=None,
file_size_labels=False):
""" Scatter plot of the given data """
fig = plt.figure(figsize=(6, 2.5))
# Down Sample:
x_data = x_data[::1000]
y_data = ... | 5,319,077 |
def import_from_string(val, setting_name):
"""
Attempt to import a class from a string representation.
"""
try:
parts = val.split(".")
module_path, class_name = ".".join(parts[:-1]), parts[-1]
module = importlib.import_module(module_path)
return getattr(module, class_name... | 5,319,078 |
def datatype_to_tracktype(datatype):
"""
Infer a default track type from a data type. There can
be other track types that can display a given data type.
Parameters
----------
datatype: str
A datatype identifier (e.g. 'matrix')
Returns
-------
str, str:
A track type ... | 5,319,079 |
def test_c_5__disrupted_circular_movement_due_to_dislodged_convoy():
"""
AUSTRIA: A Trieste -> Serbia
A Serbia -> Bulgaria
TURKEY: A Bulgaria -> Trieste (Convoy)
F Aegean Sea Transports Bulgaria -> Trieste
F Ionian Sea Transports Bulgaria -> Trieste
F Ad... | 5,319,080 |
def rossler(x, y, z, a, b, c):
""" Rössler System of Ordinary Differential Equations """
dx = - y - z
dy = x + a*y
dz = b + z*(x - c)
return dx, dy, dz | 5,319,081 |
def comparePlistVersion(item):
"""Gets the version string from the plist at path and compares versions.
Returns 0 if the plist isn't installed
-1 if it's older
1 if the version is the same
2 if the version is newer
Raises munkicommon.Error if there's an error in the ... | 5,319,082 |
def get_extension(filename):
"""
Extract file extension from filename using regex.
Args:
filename (str): name of file
Returns:
str: the file extension
"""
match = re.search(r"\.(?P<ext>[^.]+)$", filename)
if match:
return match.group("ext")
raise ValueError(f"No... | 5,319,083 |
def chdir(*paths):
"""Change the current working directory, restore on context exit."""
paths = [p if p is not None else '' for p in paths]
path = os.path.join(*paths)
if not path:
yield
return
oldwd = os.getcwd()
os.chdir(path)
try:
yield path
finally:
o... | 5,319,084 |
def run_async(func):
"""
Allows you to run a click command asynchronously.
"""
func = asyncio.coroutine(func)
def inner_handler(*args, **kwargs):
run(func(*args, **kwargs))
return update_wrapper(inner_handler, func) | 5,319,085 |
def test_io_1():
"""
Test DAX movie IO.
"""
movie_h = 50
movie_w = 40
movie_l = 10
data = numpy.random.randint(0, 60000, (movie_h, movie_w)).astype(numpy.uint16)
movie_name = storm_analysis.getPathOutputTest("test_dataio.dax")
# Write dax movie.
wr = datawriter.inferWriter... | 5,319,086 |
def test_plot_confidence_intervals(fake_regression_data):
"""Smoke test.
"""
res = run_model.run(fake_regression_data,
y='y',
X=['x1', 'x2', 'x3', 'x4'])
chart = plot_confidence_intervals.run(res)
chart_specs = chart.to_dict()
# Check chart width a... | 5,319,087 |
def Conv2D(input_tensor, input_shape, filter_size, num_filters, strides=1, name=None):
"""
Handy helper function for convnets.
Performs 2D convolution with a default stride of 1. The kernel has shape
filter_size x filter_size with num_filters output filters.
"""
shape = [filter_size, filter_size, input_shape, nu... | 5,319,088 |
def scale_val(val, factor, direction):
"""Scale val by factor either 'up' or 'down'."""
if direction == 'up':
return val+(val*factor)
if direction == 'down':
return val-(val*factor)
raise ValueError('direction must be "up" or "down"') | 5,319,089 |
def ttee(iterable, n=2):
"""
>>> ttee("ABC")
(('A', 'B', 'C'), ('A', 'B', 'C'))
"""
return tuple(map(tuple, tee(iterable, n))) | 5,319,090 |
def test_notify_syslog_by_url(openlog, syslog):
"""
API: Syslog URL Testing
"""
# an invalid URL
assert apprise.plugins.NotifySyslog.parse_url(object) is None
assert apprise.plugins.NotifySyslog.parse_url(42) is None
assert apprise.plugins.NotifySyslog.parse_url(None) is None
obj = app... | 5,319,091 |
def test_load_error_wrong_class():
"""Test that the load function can detect wrong __class__
"""
with pytest.raises(
LoadWrongDictClassError, match="SlotDoesntExist is not a pyleecan class"
):
load(load_file_2) | 5,319,092 |
def addattrs(field, css):
"""
在模板的form的field中,特别是input中添加各种attr
"""
attrs = {}
definition = css.split(',')
for d in definition:
if '=' not in d:
attrs['class'] = d
else:
t, v = d.split('=')
attrs[t] = v
return field.as_widget(attrs=attrs) | 5,319,093 |
def regular_periodic(freqs, amplitudes, phase, size=501):
"""Generate periodic test data sampled at regular intervals: superposition
of multiple sine waves, each with multiple harmonics.
"""
times = np.linspace(0, 2, size)
values = np.zeros(size)
for (i,j), amplitude in np.ndenumerate(amplitudes... | 5,319,094 |
def generate_excel_view(queryset, fields, filterstr=None):
"""
Generates an excel file from the given queryset with the specified fields.
fields: list [<fieldname1>, <fieldname2>, ...] or dict with {<fieldname>: formatting_function(object, fieldname)}
filterstr: a djangoql filter string which will lazy ... | 5,319,095 |
def makeDir(dirName):
"""Makes a new directory with the specified name. If the directory already
exists then raise a new exception."""
if (os.access(dirName, os.F_OK)):
raise Exception("Directory already exists: " + dirName)
return commands.getstatusoutput("mkdir " + dirName) | 5,319,096 |
def get_tag_by_name(repo: Repository, tag_name: str) -> Tag:
"""Fetches a tag by name from the given repository"""
ref = get_ref_for_tag(repo, tag_name)
try:
return repo.tag(ref.object.sha)
except github3.exceptions.NotFoundError:
raise DependencyLookupError(
f"Could not find... | 5,319,097 |
def get_geo_selected(results, datas, extras, filters=False):
"""Get specific Geography based on existing ids."""
wards = []
all_list = get_all_geo_list(filters)
datas.remove('') if '' in datas else datas
extras.remove('') if '' in extras else extras
results['wards'] = datas
area_ids = list(m... | 5,319,098 |
def notify(text, boxwidth=60):
"""Create a 'notification' styled textbox"""
return box(text, decor="*", boxwidth=boxwidth) | 5,319,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.