content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def number_from_string(s):
"""
Parse and return number from string.
Return float only if number is not an int. Assume number can be parsed from
string.
"""
try:
return int(s)
except ValueError:
return float(s) | 50cc7defe7c60b536d184aaf91c2831ab63043e1 | 15,900 |
def ennAvgPool(inplanes,
kernel_size=1,
stride=None,
padding=0,
ceil_mode=False):
"""enn Average Pooling."""
in_type = build_enn_divide_feature(inplanes)
return enn.PointwiseAvgPool(
in_type,
kernel_size,
stride=stride,
... | ea48e911a48237dd7ba19f0515ca4cb2e02f2fa3 | 15,901 |
def acceptable(*args, acceptables):
"""
If the characters in StringVars passed as arguments are in acceptables return True, else returns False
"""
for arg in args:
for char in arg:
if char.lower() not in acceptables:
return False
return True | 607cc752fb61e8a9348bfdd889afcbb8a8ee5189 | 15,902 |
from typing import Optional
from typing import List
from typing import Union
import warnings
def get_confusion_matrix(
ground_truth: np.ndarray,
predictions: np.ndarray,
labels: Optional[List[Union[str, float]]] = None) -> np.ndarray:
"""
Computes a confusion matrix based on prediction... | e6e45bd987345c1fc773fc1d0eccf752b8ee637c | 15,903 |
def atom_explicit_hydrogen_valences(gra):
""" explicit hydrogen valences, by atom
"""
return dict_.transform_values(atom_explicit_hydrogen_keys(gra), len) | 2f37bfd890c0f15014b17c6bd32981231104055f | 15,904 |
def get_average(pixels):
"""
Given a list of pixels, finds the average red, blue, and green values
Input:
pixels (List[Pixel]): list of pixels to be averaged
Returns:
rgb (List[int]): list of average red, green, blue values across pixels respectively
Assumes you are returning in th... | 9cd694505f8d445732bc178b5d645ff273b298d1 | 15,905 |
def _leading_space_count(line):
"""Return number of leading spaces in line."""
i = 0
while i < len(line) and line[i] == ' ':
i += 1
return i | b28daa2845618df5030a79129bb7cec1167b149a | 15,906 |
def _get_marker_indices(marker, line):
""" method to find the start and end parameter markers
on a template file line. Used by write_to_template()
"""
indices = [i for i, ltr in enumerate(line) if ltr == marker]
start = indices[0:-1:2]
end = [i + 1 for i in indices[1::2]]
assert len(start)... | 4e68f6629fd94920ddc6290c75d92e8de7b467bb | 15,907 |
import os
def get_number_of_images(dir):
"""
Returns number of files in given directory
Input:
dir - full path of directory
Output:
number of files in directory
"""
return len([name for name in os.listdir(dir) if os.path.isfile(os.path.join(dir, name))]) | a964764466aea735558a8ccc832bd0a00616883e | 15,908 |
def get_wrapper_depth(wrapper):
"""Return depth of wrapper function.
.. versionadded:: 3.0
"""
return wrapper.__wrapped__.__wrappers__ + (1 - wrapper.__depth__) | c1c31c45a059c4ee56b39322e966d30b742ef86e | 15,909 |
def apiTest():
"""Tests the API connection to lmessage. Returns true if it is connected."""
try:
result = api.add(2, 3)
except:
return False
return result == 5 | 5d63720e78fe5e1bcecd2b1792a0f9bf6345595d | 15,910 |
from scipy import stats as dists
def get_distribution(dist_name):
"""Fetches a scipy distribution class by name"""
if dist_name not in dists.__all__:
return None
cls = getattr(dists, dist_name)
return cls | bebdb2578dd191b1d0ee1aea96e88d6be4bc144c | 15,911 |
def ece(y_probs, y_preds, y_true, balanced=False, bins="fd", **bin_args):
"""Compute the expected calibration error (ECE).
Parameters:
y_probs (np.array): predicted class probabilities
y_preds (np.array): predicted class labels
y_true (np.array): true class labels
Returns:
exp_ce (float): ... | 073d1190d71808de03002322679bb29d75a31258 | 15,912 |
def _call_or_get(value, menu=None, choice=None, string=None, obj=None, caller=None):
"""
Call the value, if appropriate, or just return it.
Args:
value (any): the value to obtain. It might be a callable (see note).
Keyword Args:
menu (BuildingMenu, optional): the building menu to pass... | b5ebf790913bbdaab980ae7f050a96748f1fd3e6 | 15,913 |
import re
def is_shared_object(s):
"""
Return True if s looks like a shared object file.
Example: librt.so.1
"""
so = re.compile('^[\w_\-]+\.so\.[0-9]+\.*.[0-9]*$', re.IGNORECASE).match
return so(s) | f6d2f5f589c468613004d06c7d213f899f31b7c4 | 15,914 |
def get_name(properties, lang):
"""Return the Place name from the properties field of the elastic response
Here 'name' corresponds to the POI name in the language of the user request (i.e. 'name:{lang}' field).
If lang is None or if name:lang is not in the properties
Then name receives the local name v... | 82bd6b0fe7e35dae39767b899b56b24ff91f01cb | 15,915 |
def get_task(name):
"""Return the chosen task."""
tasks_json = load_json('tasks.json')
return tasks_json[name] | 44e39dd9757247212e8e9923fd3f7756fd3b0b9a | 15,916 |
def aws_credentials(request: pytest.fixture, aws_utils: pytest.fixture, profile_name: str):
"""
Fixture for setting up temporary AWS credentials from assume role.
:param request: _pytest.fixtures.SubRequest class that handles getting
a pytest fixture from a pytest function/fixture.
:param aws_u... | 13d1549b74b597cf3b00f98a5012c4bae111eeeb | 15,917 |
def mean_predictions(predicted):
"""
Calculate the mean of predictions that overlaps. This is donne mostly to be able to plot what the model is doing.
-------------------------------------------------------
Args:
predicted : numpy array
Numpy array with shape (Number points to predic... | 7ee19312ad17b97b27fe74a35df43ea4fa1ec709 | 15,918 |
import os
import errno
def update_diskspace(dmfilestat, cached=None):
"""Update diskspace field in dmfilestat object"""
try:
# search both results directory and raw data directory
search_dirs = [
dmfilestat.result.get_report_dir(),
dmfilestat.result.experiment.expDir,
... | a3b54b0612ac05ee92735aed5641f8b25bb22c2d | 15,919 |
def find_best_classifier(data, possible_classifiers, target_classifier):
"""Given a list of points, a list of possible Classifiers to use as tests,
and a Classifier for determining the true classification of each point,
finds and returns the classifier with the lowest disorder. Breaks ties by
preferrin... | 7c3dc1f8fc0933f238b372fcd3bf3133c2958398 | 15,920 |
def get_product_type_name(stac_item):
""" Create a ProductType name from a STAC Items metadata
"""
properties = stac_item['properties']
assets = stac_item['assets']
parts = []
platform = properties.get('platform') or properties.get('eo:platform')
instruments = properties.get('instruments'... | fc7351c513eae63233b32b86fe6e5098a1571c8a | 15,921 |
def get_show_default():
""" gets the defaults """
return SHOW_DEFAULT | 88f6b202ae16155b8ec87eb566535703e33033b7 | 15,922 |
import torch
def sample_langevin_v2(x, model, stepsize, n_steps, noise_scale=None, intermediate_samples=False,
clip_x=None, clip_grad=None, reject_boundary=False, noise_anneal=None,
spherical=False, mh=False, temperature=None, norm=False, cut=True):
"""Langevin Monte Carlo
... | a3dd79facb089afbeafc4e9845cf1324de75226b | 15,923 |
def fpoly(x, m):
"""Compute the first `m` simple polynomials.
Parameters
----------
x : array-like
Compute the simple polynomials at these abscissa values.
m : :class:`int`
The number of simple polynomials to compute. For example, if
:math:`m = 3`, :math:`x^0`, :math:`x^1` ... | 335c73bf4008be1331d8f030266f5f89d072ed2c | 15,924 |
import logging
def get_custom_logger(context):
""" Customizable template for creating a logger.
What would work is to have the format and date format passed
"""
# Initialize Custom Logging
# Timestamps with logging assist debugging algorithms
# With long execution times
manifest = cont... | 01b0d584fc81c3948fcdd3d0294c949cbd8b633f | 15,925 |
import os
def get_torch_core_binaries(module):
"""Return required files from the torch folders.
Notes:
So far only tested for Windows. Requirements for other platforms
are unknown.
"""
binaries = []
torch_dir = module.getCompileTimeDirectory()
extras = os.path.join(torch_dir, ... | df1aa86f75fa444707ed3499b30f2806389d914c | 15,926 |
def _function_fullname(f):
"""Return the full name of the callable `f`, including also its module name."""
function, _ = getfunc(f) # get the raw function also for OOP methods
if not function.__module__: # At least macros defined in the REPL have `__module__=None`.
return function.__qualname__
... | eb6fd829081a4606c7be4520a15d627960360b8f | 15,927 |
def dists2centroids_numpy(a):
"""
:param a: dist ndarray, shape = (*, h, w, 4=(t, r, b, l))
:return a: Box ndarray, shape is (*, h, w, 4=(cx, cy, w, h))
"""
return corners2centroids_numpy(dists2corners_numpy(a)) | a85122d871179a9d0fb7fa9b844caa448398184c | 15,928 |
import math
def heatmap(data_df, figsize=None, cmap="Blues", heatmap_kw=None, gridspec_kw=None):
""" Plot a residue matrix as a color-encoded matrix.
Parameters
----------
data_df : :class:`pandas.DataFrame`
A residue matrix produced with :func:`~luna.analysis.residues.generate_residue_matrix... | 99ba802f82f9425fa3946253be78730b6216d9c9 | 15,929 |
import torch
def combined_loss(x, reconstructed_x, mean, log_var, args):
"""
MSE loss for reconstruction, KLD loss as per VAE.
Also want to output dimension (element) wise RCL and KLD
"""
# First, binary data
loss1 = torch.nn.BCEWithLogitsLoss(size_average=False)
loss1_per_element = torch.... | 162b2706f9643f66ebb0c3b000ea025d411029e2 | 15,930 |
def isfloat(string: str) -> bool:
"""
This function receives a string and returns if it is a float or not.
:param str string: The string to check.
:return: A boolean representing if the string is a float.
:rtype: bool
"""
try:
float(string)
return True
except (ValueErro... | ac6d8fcbbcf6b8cb442c50895576f417618a7429 | 15,931 |
import re
def parse_path_kvs(file_path):
"""
Find all key-value pairs in a file path;
the pattern is *_KEY=VALUE_*.
"""
parser = re.compile("(?<=[/_])[a-z0-9]+=[a-zA-Z0-9]+[.]?[0-9]*(?=[_/.])")
kvs = parser.findall(file_path)
kvs = [kv.split("=") for kv in kvs]
return {kv[0]: to_... | 65d3711752808299272383f4b1328336ba9c463c | 15,932 |
def user_count_by_type(utype: str) -> int:
"""Returns the total number of users that match a given type"""
return get_count('users', 'type', (utype.lower(),)) | 232c4cc40ba31b4fb60f40708f2a38ae73096aea | 15,933 |
import re
def node_label(label, number_of_ports, debug=None):
""" generate the HTML-like label
<TABLE ALIGN="CENTER"><TR><TD COLSPAN="2">name</TD></TR>
<TR>
<TD PORT="odd">odd</TD>
<TD PORT="even">even</TD>
</TR>
singleport:
<TR>
<TD PORT="port">port</TD>
</TR>
... | 07b5a5dab593e1e105d840989b5b053551610e25 | 15,934 |
def grouperElements(liste, function=len):
"""
fonctions qui groupe selon la fonction qu'on lui donne.
Ainsi pour le kalaba comme pour les graphèmes, nous aurons
besoin de la longueur,
"""
lexique=[]
data=sorted(liste, key=function)
for k,g in groupby(data, function):
lexique.append(list(g))
return lexique | e75e8e379378ac1207ae0ee9521f630c04cff2f7 | 15,935 |
def SensorLocation_Cast(*args):
"""
Cast(BaseObject o) -> SensorLocation
SensorLocation_Cast(Seiscomp::Core::BaseObjectPtr o) -> SensorLocation
"""
return _DataModel.SensorLocation_Cast(*args) | 85a5a6f711c0c5d77f0b93b2e6f819bdfd466ce1 | 15,936 |
def fatorial(num=1, show=False):
"""
-> Calcula o fatorial de um número.
:param num: Fatorial a ser calculado
:param show: (opicional) Mostra a conta
:return: Fatorial de num.
"""
print('-=' * 20)
fat = 1
for i in range(num, 0, -1):
fat *= i
if show:
resp = f'{str... | 80ca60d2ba64a7089f3747a13c109de0bc7c159c | 15,937 |
import os
import yaml
def read_rudder_config(path=None):
"""Reads the servo configuration from config.yml and returns a matching servo."""
if path is None:
path = os.path.dirname(os.path.abspath(__file__))
with open(path + "/config.yml", "r") as yml:
conf = yaml.full_load(yml)
rudd... | 079d1172c9109f174ac8f48927a0ff03a0466806 | 15,938 |
def linear_trend(series=None, coeffs=None, index=None, x=None, median=False):
"""Get a series of points representing a linear trend through `series`
First computes the lienar regression, the evaluates at each
dates of `series.index`
Args:
series (pandas.Series): data with DatetimeIndex as the ... | 6bd09089ffd828fd3d408c0c2b03c3facfcfbd6b | 15,939 |
def snapshot_metadata_get(context, snapshot_id):
"""Get all metadata for a snapshot."""
return IMPL.snapshot_metadata_get(context, snapshot_id) | 8dda987916cb772d6498cd295056ef2b5465c00d | 15,940 |
def graph_from_tensors(g, is_real=True):
"""
"""
loop_edges = list(nx.selfloop_edges(g))
if len(loop_edges) > 0:
g.remove_edges_from(loop_edges)
if is_real:
subgraph = (g.subgraph(c) for c in nx.connected_components(g))
g = max(subgraph, key=len)
g = nx.convert_node_... | 7f43531f7cbf9221a6b00a56a24325b58f60ea84 | 15,941 |
def hook(t):
"""Calculate the progress from download callbacks (For progress bar)"""
def inner(bytes_amount):
t.update(bytes_amount) # Update progress bar
return inner | d8228b9dec203aaa32d268dea8feef52e8db6137 | 15,942 |
def delete(event, context):
"""
Delete a cfn stack using an assumed role
"""
stack_id = event["PhysicalResourceId"]
if '[$LATEST]' in stack_id:
# No stack was created, so exiting
return stack_id, {}
cfn_client = get_client("cloudformation", event, context)
cfn_client.delete_s... | 555682546aa6f1bbbc133538003b51f02e744d70 | 15,943 |
from typing import Match
import six
def _rec_compare(lhs,
rhs,
ignore,
only,
key,
report_mode,
value_cmp_func,
_regex_adapter=RegexAdapter):
"""
Recursive deep comparison implementation
"... | b7d26ed038152ee98a7b50821f3485cdc66a29d4 | 15,944 |
def exists_job_onqueue(queuename, when, hour):
"""
Check if a job is present on queue
"""
scheduler = Scheduler(connection=Redis())
jobs = scheduler.get_jobs()
for job in jobs:
if 'reset_stats_queue' in job.func_name:
args = job.args
if queuename == args[0] an... | 165bb3da4746267d789d39ee30ebd9b098ea7c1e | 15,945 |
def q_inv_batch_of_sequences(seq):
"""
:param seq: (n_batch x n_frames x 32 x 4)
:return:
"""
n_batch = seq.size(0)
n_frames = seq.size(1)
n_joints = seq.size(2)
seq = seq.reshape((n_batch * n_frames * n_joints, 4))
seq = qinv(seq)
seq = seq.reshape((n_batch, n_frames, n_joints, ... | 9c2035a1864e47e99ac074815199217867da0c96 | 15,946 |
def msa_job_space_demand(job_space_demand):
"""
Job space demand aggregated to the MSA.
"""
df = job_space_demand.local
return df.fillna(0).sum(axis=1).to_frame('msa') | 044fe6e814c2773629b8f648b789ba99bbdf0108 | 15,947 |
def get_pdf_cdf_3(corr, bins_pdf, bins_cdf, add_point=True, cdf_bool=True,
checknan=False):
"""
corr is a 3d array, the first dimension are the iterations, the second
dimension is usually the cells
the function gives back the pdf and the cdf
add_point option duplicated the last po... | 0c6983bf6c3f77aebb7a9c667c54a560ed4a3cf0 | 15,948 |
import logging
import requests
import time
def create_app():
""" Application factory to create the app and be passed to workers """
app = Flask(__name__)
logging.basicConfig(
filename='./logs/flask.log',
level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(message)s',
... | 18f1de42aa395cddef482371e8115d01d3384888 | 15,949 |
import os
def create_win_jupyter_console(folders):
"""
create a batch file to start jupyter
@param folders see @see fn create_win_batches
@return operations (list of what was done)
"""
text = ['@echo off',
'set CURRENT2=%~dp0',
'call "%CURRENT2... | 14e2e3843dea3d83da2f5c2917277e4703578419 | 15,950 |
def incidence_matrix(
H, order=None, sparse=True, index=False, weight=lambda node, edge, H: 1
):
"""
A function to generate a weighted incidence matrix from a Hypergraph object,
where the rows correspond to nodes and the columns correspond to edges.
Parameters
----------
H: Hypergraph objec... | efbac24664f30a1cd424843042d7e203a0e96c37 | 15,951 |
def initial_landing_distance(interest_area, fixation_sequence):
"""
Given an interest area and fixation sequence, return the initial landing
distance on that interest area. The initial landing distance is the pixel
distance between the first fixation to land in an interest area and the
left edge of ... | b3512ea7cb149667e09c56541340122ec1dddcb1 | 15,952 |
import gzip
import pickle
def load_object(filename):
"""
Load saved object from file
:param filename: The file to load
:return: the loaded object
"""
with gzip.GzipFile(filename, 'rb') as f:
return pickle.load(f) | f7e15216c371e1ab05169d40ca4df15611fa7978 | 15,953 |
from typing import Dict
from typing import Tuple
def list_events_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]:
"""Lists all events and return outputs in Demisto's format
Args:
client: Client object with request
args: Usually demisto.args()
Returns:
Outputs
""... | b4e3916ee8d65a47e2128453fd042d998184ea7b | 15,954 |
import os
def get_or_generate_vocab_inner(data_dir, vocab_filename, vocab_size,
generator, max_subtoken_length=None,
reserved_tokens=None):
"""Inner implementation for vocab generators.
Args:
data_dir: The base directory where data and vocab fil... | 6bb1faef913ebc3915487827576c2984fe614d84 | 15,955 |
def response_map(fetch_map):
"""Create an expected FETCH response map from the given request map.
Most of the keys returned in a FETCH response are unmodified from the
request. The exceptions are BODY.PEEK and BODY partial range. A BODY.PEEK
request is answered without the .PEEK suffix. A partial range (e.g.
BODY... | 42d992662e5bba62046c2fc1a50f0f8275798ef8 | 15,956 |
def RigidTendonMuscle_getClassName():
"""RigidTendonMuscle_getClassName() -> std::string const &"""
return _actuators.RigidTendonMuscle_getClassName() | 8c6bd6604350e6e2a30ee48c018307bc68dea76f | 15,957 |
import json
import time
import uuid
def submit():
"""Receives the new paste and stores it in the database."""
if request.method == 'POST':
form = request.get_json(force=True)
pasteText = json.dumps(form['pasteText'])
nonce = json.dumps(form['nonce'])
burnAfterRead = json.dumps... | 3f88b665b226c81785b0ecafe3389bb15dcbeaa4 | 15,958 |
def money_recall_at_k(recommended_list, bought_list, prices_recommended, prices_bought, k=5):
""" Доля дохода по релевантным рекомендованным объектам
:param recommended_list - список id рекомендаций
:param bought_list - список id покупок
:param prices_recommended - список цен для рекомендаций
:param... | edeb6c56c5ce6a2af0321aee350c5f129737cab0 | 15,959 |
import networkx
def get_clustering_fips( collection_of_fips, adj = None ):
"""
Finds the *separate* clusters of counties or territorial units that are clustered together. This is used to identify possibly *different* clusters of counties that may be separate from each other. If one does not supply an adjacenc... | acdd6daa9b0b5d200d98271a4c989e5a5912a684 | 15,960 |
def stop_after(space_number):
""" Decorator that determines when to stop tab-completion
Decorator that tells command specific complete function
(ex. "complete_use") when to stop tab-completion.
Decorator counts number of spaces (' ') in line in order
to determine when to stop.
ex. "use explo... | f0ca0bb0f33c938f6a1de619f70b204e92b20974 | 15,961 |
def find_cut_line(img_closed_original): # 对于正反面粘连情况的处理,求取最小点作为中线
"""
根据规则,强行将粘连的区域切分
:param img_closed_original: 二值化图片
:return: 处理后的二值化图片
"""
img_closed = img_closed_original.copy()
img_closed = img_closed // 250
#print(img_closed.shape)
width_sum = img_closed.sum(axis=1) # 沿宽度方向求和... | 28e5e64e15cb349df186752c669ae16d01e21549 | 15,962 |
def _search(progtext, qs=None):
""" Perform memoized url fetch, display progtext. """
loadmsg = "Searching for '%s'" % (progtext)
wdata = pafy.call_gdata('search', qs)
def iter_songs():
wdata2 = wdata
while True:
for song in get_tracks_from_json(wdata2):
yiel... | 55310c4ad05b597b48e32dde810eff9db51d66c0 | 15,963 |
import numpy
def img_to_vector(img_fn, label=0):
"""Read the first 32 characters of the first 32 rows of an image file.
@return <ndarray>: a 1x(1024+1) numpy array with data and label, while the
label is defaults to 0.
"""
img = ""
for line in open(img_fn).readlines()[:32]:... | f1d7161a0bc4d6ffebc6ee1b32eafb28c4d75f7f | 15,964 |
import appdirs
def get_config():
"""Return a user configuration object."""
config_filename = appdirs.user_config_dir(_SCRIPT_NAME, _COMPANY) + ".ini"
config = _MyConfigParser()
config.optionxform = str
config.read(config_filename)
config.set_filename(config_filename)
return config | 192ea496f80d77f241ec6deb6a4aa4b1ef7d17cf | 15,965 |
import asyncio
import websockets
def launch_matchcomms_server() -> MatchcommsServerThread:
"""
Launches a background process that handles match communications.
"""
host = 'localhost'
port = find_free_port() # deliberately not using a fixed port to prevent hardcoding fragility.
event_loop = a... | 4c23c599a61f029972ae3e54ceb3066a4ce9f207 | 15,966 |
def acq_randmaxvar():
"""Initialise a RandMaxVar fixture.
Returns
-------
RandMaxVar
Acquisition method.
"""
gp, prior = _get_dependencies_acq_fn()
# Initialising the acquisition method.
method_acq = RandMaxVar(model=gp, prior=prior)
return method_acq | 5f306d104032abc993ab7726e08453d5c18f2526 | 15,967 |
import json
def from_config(func):
"""Run a function from a JSON configuration file."""
def decorator(filename):
with open(filename, 'r') as file_in:
config = json.load(file_in)
return func(**config)
return decorator | 4342a5f6fab8f8274b9dfb762be3255672f4f332 | 15,968 |
def update_user(user, domain, password=None):
""" create/update user record. if password is None, the user is
removed. Password should already be SHA512-CRYPT'd """
passwdf = PASSWDFILE % {"domain": domain}
passwdb = KeyValueFile.open_file(passwdf, separator=":", lineformat=USERLINE+"\n")
passw... | 6e65be52fe0fb737c5189da295694bf482be9f5d | 15,969 |
def puzzle_pieces(n):
"""Return a dictionary holding all 1, 3, and 7 k primes."""
kprimes = defaultdict(list)
kprimes = {key : [] for key in [7, 3, 1]}
upper = 0
for k in sorted(kprimes.keys(), reverse=True):
if k == 7:
kprimes[k].extend(count_Kprimes(k, 2, n))
if not... | 4ad36f316a2dfa39aca9c2b574781f9199fb13ef | 15,970 |
import warnings
def periodogram_snr(periodogram,periods,index_to_evaluate,duration,per_type,
freq_window_epsilon=3.,rms_window_bin_size=100):
"""
Calculate the periodogram SNR of the best period
Assumes fixed frequency spacing for periods
periodogram - the periodogram values
... | 6b1f84d03796dc839cdb87b94bce69a8eef4f60e | 15,971 |
def derivative_overview(storage_service_id, storage_location_id=None):
"""Return a summary of derivatives across AIPs with a mapping
created between the original format and the preservation copy.
"""
report = {}
aips = AIP.query.filter_by(storage_service_id=storage_service_id)
if storage_locatio... | ab688e89c9bc9cec408e022a487d824a229a80a9 | 15,972 |
import tarfile
def fetch_packages(vendor_dir, packages):
"""
Fetches all packages from github.
"""
for package in packages:
tar_filename = format_tar_path(vendor_dir, package)
vendor_owner_dir = ensure_vendor_owner_dir(vendor_dir, package['owner'])
url = format_tarball_url(pack... | 4589ce242ab8221a34ea87ce020f53a7874e73cb | 15,973 |
def execute_search(search_term, sort_by, **kwargs):
"""
Simple search API to query Elasticsearch
"""
# Get the Elasticsearch client
client = get_client()
# Perform the search
ons_index = get_index()
# Init SearchEngine
s = SearchEngine(using=client, index=ons_index)
# Define t... | 48ec250c6deceaca850230e4be2e0e282f5838e4 | 15,974 |
def last_char_to_aou(word):
"""Intended for abbreviations, returns "a" or "ä" based on vowel harmony
for the last char."""
assert isinstance(word, str)
ch = last_char_to_vowel(word)
if ch in "aou":
return "a"
return "ä" | 3a37e97e19e1ca90ccf26d81756db57445f68a26 | 15,975 |
def times_vector(mat, vec):
"""Returns the symmetric block-concatenated matrix multiplied by a vector.
Specifically, each value in the vector is multiplied by a row of the full
matrix. That is, the vector is broadcast and multiplied element-wise. Note
this would be the transpose of full_mat * vec if full_mat r... | 5b90ebd293535810c7ad8e1ad681033997e8c1c8 | 15,976 |
import pathlib
def ensure_path(path:[str, pathlib.Path]):
"""
Check if the input path is a string or Path object, and return a path object.
:param path: String or Path object with a path to a resource.
:return: Path object instance
"""
return path if isinstance(path, pathlib.Path) else pathlib... | 40cd2e1271f7f74adbf0928f769ca1a3d89acd50 | 15,977 |
def examine_mode(mode):
"""
Returns a numerical index corresponding to a mode
:param str mode: the subset user wishes to examine
:return: the numerical index
"""
if mode == 'test':
idx_set = 2
elif mode == 'valid':
idx_set = 1
elif mode == 'train':
idx_set = 0
... | 4fee6f018cacff4c760cb92ef250cad21b497697 | 15,978 |
from pathlib import Path
import subprocess
def main():
"""Validates individual trigger files within the raidboss Cactbot module.
Current validation only checks that the trigger file successfully compiles.
Returns:
An exit status code of 0 or 1 if the tests passed successfully or failed, respecti... | e14d0638fb0078225e4c20336ad40989895da1d0 | 15,979 |
def create_pinata(profile_name: str) -> Pinata:
"""
Get or create a Pinata SDK instance with the given profile name.
If the profile does not exist, you will be prompted to create one,
which means you will be prompted for your API key and secret. After
that, they will be stored securely using ``keyri... | a1b88b8bb5b85a73a8bce01860398a9cbf2d1491 | 15,980 |
def create_tfid_weighted_vec(tokens, w2v, n_dim, tfidf):
"""
Create train, test vecs using the tf-idf weighting method
Parameters
----------
tokens : np.array
data (tokenized) where each line corresponds to a document
w2v : gensim.Word2Vec
word2vec model
n_dim : in... | 8503932c2b268ff81752fb22e8640ce9413ad2e5 | 15,981 |
def miniimagenet(folder, shots, ways, shuffle=True, test_shots=None,
seed=None, **kwargs):
"""Helper function to create a meta-dataset for the Mini-Imagenet dataset.
Parameters
----------
folder : string
Root directory where the dataset folder `miniimagenet` exists.
shots ... | a9be1fff33b8e5163d6a5af4bd48dc71dcb88864 | 15,982 |
def process_account_request(request, order_id, receipt_code):
"""
Process payment via online account like PayPal, Amazon ...etc
"""
order = get_object_or_404(Order, id=order_id, receipt_code=receipt_code)
if request.method == "POST":
gateway_name = request.POST["gateway_name"]
gatewa... | be5bdb027034e2f2791968755e41bbac762d1dda | 15,983 |
def add_classification_categories(json_object, classes_file):
"""
Reads the name of classes from the file *classes_file* and adds them to
the JSON object *json_object*. The function assumes that the first line
corresponds to output no. 0, i.e. we use 0-based indexing.
Modifies json_object in-place.... | ef92902210f275238271c21e20f8f0eec90253b0 | 15,984 |
import copy
def create_compound_states(reference_thermodynamic_state,
top,
protocol,
region=None,
restraint=False):
"""
Return alchemically modified thermodynamic states.
Parameters
----------
... | 9ef5c14628237f3754e8522d11aa6bcbe399e1b3 | 15,985 |
def initialize_binary_MERA_random(phys_dim, chi, dtype=tf.float64):
"""
initialize a binary MERA network of bond dimension `chi`
isometries and disentanglers are initialized with random unitaries (not haar random)
Args:
phys_dim (int): Hilbert space dimension of the bottom layer
c... | f0ba62a5c8605bf4e8967b5626cae9cd81992697 | 15,986 |
def tts_init():
"""
Initialize choosen TTS.
Returns: tts (TextToSpeech)
"""
if (TTS_NAME == "IBM"):
return IBM_initialization()
elif (TTS_NAME == "pytts"):
return pytts_initialization()
else:
print("ERROR - WRONG TTS") | 4de36b27298d015b808cbc4973daf02354780787 | 15,987 |
def string_dumper(dumper, value, _tag=u'tag:yaml.org,2002:str'):
"""
Ensure that all scalars are dumped as UTF-8 unicode, folded and quoted in
the sanest and most readable way.
"""
if not isinstance(value, basestring):
value = repr(value)
if isinstance(value, str):
value = value... | 081e0adaa45072f2b75c9eb1374ce2009bf4fd1d | 15,988 |
import math
def to_hours_from_seconds(value):
"""From seconds to rounded hours"""
return Decimal(math.ceil((value / Decimal(60)) / Decimal(60))) | 2ceb1f74690d26f0d0d8f60ffdc012b801dd6be3 | 15,989 |
def extract_named_geoms(sde_floodplains = None, where_clause = None,
clipping_geom_obj = None):
"""
Clips SDE flood delineations to the boundary of FEMA floodplain changes, and
then saves the geometry and DRAINAGE name to a list of dictionaries.
:param sde_floodplains: {st... | d56b5caf8a11358db4fc43f51b8a29840698fd3a | 15,990 |
import argparse
def parser_train():
"""
Parse input arguments (train.py).
"""
parser = argparse.ArgumentParser(description='Standard + Adversarial Training.')
parser.add_argument('--augment', type=str2bool, default=True, help='Augment training set.')
parser.add_argument('--batch-size', type=i... | a12d4c392b8883c1bf195cb6e1fc9333b8a9fc1b | 15,991 |
from typing import Sequence
from typing import List
from typing import Any
def convert_examples_to_features(examples: Sequence[InputExampleTC],
labels: List[str],
tokenizer: Any,
max_length: int = 512,
... | f051cb9fd68aaf08da15e99f978a6bdc24fea5d3 | 15,992 |
import os
def build_image(local_conda_channel, conda_env_file, container_tool, container_build_args=""):
"""
Build a container image from the Dockerfile in RUNTIME_IMAGE_PATH.
Returns a result code and the name of the new image.
"""
variant = os.path.splitext(conda_env_file)[0].replace(utils.CONDA... | 73ce85ac078e902e6054605351d0e7b4aba7b10d | 15,993 |
def update_setup_cfg(setupcfg: ConfigUpdater, opts: ScaffoldOpts):
"""Update `pyscaffold` in setupcfg and ensure some values are there as expected"""
if "options" not in setupcfg:
template = templates.setup_cfg(opts)
new_section = ConfigUpdater().read_string(template)["options"]
setupcfg... | b08b0faa0645151b24d8eb40b2920e63caf764e9 | 15,994 |
def testable_renderable() -> CXRenderable:
"""
Provides a generic CXRenderable useful for testin the base class.
"""
chart: CanvasXpress = CanvasXpress(
render_to="canvasId",
data=CXDictData(
{
"y": {
"vars": ["Gene1"],
... | 3e37096e51e081da8c3fa43f973248252c0276dd | 15,995 |
def secondSolution( fixed, c1, c2, c3 ):
"""
If given four tangent circles, calculate the other one that is tangent
to the last three.
@param fixed: The fixed circle touches the other three, but not
the one to be calculated.
@param c1, c2, c3: Three circles to which the other tangent circle
... | 1a6aca3e5d6a26f77b1fbc432ff26fba441e02f7 | 15,996 |
def collect3d(v1a,ga,v2a,use_nonan=True):
"""
set desired line properties
"""
v1a = np.real(v1a)
ga = np.real(ga)
v2a = np.real(v2a)
# remove nans for linewidth stuff later.
ga_nonan = ga[~np.isnan(ga)*(~np.isnan(v1a))*(~np.isnan(v2a))]
v1a_nonan = v1a[~np.isnan(ga)*(~np.is... | de53fcb859c8c95b1b95a4ad2ffea102a090e94e | 15,997 |
import os
def _DevNull():
"""On Windows, sometimes the inherited stdin handle from the parent process
fails. Workaround this by passing null to stdin to the subprocesses commands.
This function can be used to create the null file handler.
"""
return open(os.devnull, 'r') | dc815c172fd45dee4b0ed47cbd9497ce7e643972 | 15,998 |
import urllib
import requests
def get_job_priorities(rest_url):
"""This retrieves priorities of all active jobs"""
url = urllib.parse.urljoin(rest_url, "/jobs/priorities")
resp = requests.get(url)
return resp.json() | 020e825d531394798c041f32683bccfea19684c9 | 15,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.