content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def list_sum(*argv, **kwargs):
"""
Summarise items in provided list
Arguments:
- argv: list of item for summarise
Options:
- type: list item type (int if omitted)
Note: All types provided by this lib supported
Returns sum number in 'type' format
"""
_type_name = kwar... | d047abe3eb99ac7c468dd8b3b1bc42ee7b98e134 | 20,800 |
import os
def locate_file(start_path, file_name):
""" locate filename and return file path.
searching will be recursive upward until current working directory.
Args:
start_path (str): start locating path, maybe file path or directory path
Returns:
str: located file path. None if ... | d0af58dccd5a56e1dd7c530d9310770de2b2f208 | 20,801 |
def image_upload(request):
"""
If it's a post, then upload the image or store it locally based on config. Otherwise, return
the html of the upload.html template.
"""
if request.method == 'POST':
image_file = request.FILES['image_file']
image_type = request.POST['image_type']
... | 1d5f0f111dfd9f1b7b1f29ebb8d9fb27fb210a5f | 20,802 |
def werbo_c(topics, word_embedding_model, weight=0.9, topk=10):
"""
computes Word embedding based RBO - centroid
Parameters
----------
topics: a list of lists of words
word_embedding_model: word embedding space in gensim word2vec format
weight: p (float), default 1.0: Weight of each agreeme... | 447e3c6037196de56673a62b8841279e6f17d739 | 20,803 |
def G_t(t, G, tau, Ge = 0.0):
"""this function returns the relaxation modulus in time"""
G_rel = np.zeros(np.size(t))
if np.size(G) == 1: #the model is the SLS
for i in range(np.size(t)):
G_rel[i] = Ge + G*np.exp(-t[i]/tau)
else: #the model has more than one arm
for i in ran... | b44cb0b49e2423ee3c5aade0c625407d54889044 | 20,804 |
def iou_set(set1, set2):
"""Calculate iou_set """
union = set1.union(set2)
return len(set1.intersection(set2)) / len(union) if union else 0 | f0087b640e8b9a87167d7e2b645aca3c565e09c1 | 20,805 |
import time
def time_measured(fkt):
"""
Decorator to measure execution time of a function
It prints out the measured time
Parameters
----------
fkt : function
function that shall be measured
Returns
-------
None
"""
def fkt_wrapper(*args, **kwargs):
t1 =... | 43fe9fa24fdd27f15e988f5997424dd91f7d92c9 | 20,806 |
def test_find_codon(find_codon):
"""
A function to test another function that looks for a codon within
a coding sequence.
"""
synapto_nuc = ("ATGGAGAACAACGAAGCCCCCTCCCCCTCGGGATCCAACAACAACGAGAACAACAATGCAGCCCAGAAGA"
"AGCTGCAGCAGACCCAAGCCAAGGTGGACGAGGTGGTCGGGATTATGCGTGTGAACGTGGAGAAGGTCCT"
"GGAG... | 1e8906441d7812fbaefd7688a1c02876210ba8b8 | 20,807 |
def add_keys3(a, A, b, B):
"""
aA + bB
:param a:
:param A:
:param b:
:param B:
:return:
"""
return tcry.xmr_add_keys3_vartime_r(a, A, b, B) | e1f8205b93b2f944da271a8e4097c9466831ad6b | 20,808 |
def cause_state(value):
"""
Usage::
{{ value|cause_state}}
"""
try:
if isinstance(value, (str, unicode)):
value = eval(value)
if Bushfire.CAUSE_STATE_POSSIBLE==value:
return Bushfire.CAUSE_STATE_CHOICES[Bushfire.CAUSE_STATE_POSSIBLE-1][1]
return ... | 8e905921b1e7e1b498f42e70a134d21f2a146f2b | 20,809 |
def ReadRawSAData(DataDirectory, fname_prefix):
"""
This function reads in the raw SA data to a pandas dataframe
Args:
DataDirectory: the data directory
fname_prefix: the file name prefix
Returns:
pandas dataframe with the raw SA data
Author: FJC
"""
# get the... | d28d91131de82c0049a046231a41eb34d9f3b185 | 20,810 |
from typing import List
def not_valid_score(scores: List[int]):
"""Checks if the set of estimations is ambiguous (all scores are different)."""
return True if len(np.unique(scores)) == len(scores) else False | 9077c93a6bdfe79d0fa5277f04adb8ba58053ba9 | 20,811 |
import sys
import logging
def train(
train_op,
logdir,
log_every_n_steps=1,
graph=None,
master='',
is_chief=True,
global_step=None,
number_of_steps=None,
init_op=_USE_DEFAULT,
init_feed_dict=None,
init_fn=None,
summary_op=_USE_DEFAULT,
save_summaries_secs=600,
s... | 6458cc09a08aa57dc2de6679b2df9c7d725ad91b | 20,812 |
import numpy
def biom_to_pandas(biom_otu):
"""
Convert data from biom to SparseDataFrame (pandas) for easy access
:param biom_otu: Table
:rtype: DataFrame
"""
tmp_m = biom_otu.matrix_data
df = [SparseSeries(tmp_m[i].toarray().ravel()) for i in numpy.arange(tmp_m.shape[0])]
return (Spar... | ce865ce669dd36e60b83be00f998732abc37d6f7 | 20,813 |
import base64
import mimetypes
import time
import os
import uuid
import json
def __request(logger, cache, method, url, headers, body, keep_alive):
"""Returns file content for client request"""
if method == "HEAD" or method == "GET":
if url.startswith("/private/"):
base64_auth = base64.b64... | 1ba9113a413ac441d33629cdaf24a7d2a8d72629 | 20,814 |
def is_classmethod(method: t.Callable):
"""
A python method is a wrapper around a function that also
holds a reference to the class it is a method of.
When bound, it also holds a reference to the instance.
@see https://stackoverflow.com/questions/12935241/python-call-instance-method-using-func
... | 6600c9a16df0dc62304a02c2bb333af07f8709f8 | 20,815 |
def masked_accuracy(y_true, y_pred):
"""An accuracy function that masks based on targets (value: 0.5)
Args:
y_true: The true training labels
y_pred: The predicted labels
Returns:
float: the masked accuracy
"""
a = kb.sum(kb.cast(kb.equal(y_true, kb.r... | 0d6007eafdf849ad495458d56b4e68a0031d35fa | 20,816 |
def get_shap_interaction_values(x_df, explainer):
"""
Compute the shap interaction values for a given dataframe.
Also checks if the explainer is a TreeExplainer.
Parameters
----------
x_df : pd.DataFrame
DataFrame for which will be computed the interaction values using the explainer.
... | 9b84e0a262ba0d74eb2f24406ac6f41dfbab1625 | 20,817 |
from typing import Optional
from typing import Union
def plot_roc(
y_true: np.ndarray,
y_probas: np.ndarray,
labels: Optional[dict] = None,
classes_to_plot: Optional[list] = None,
plot_micro: Optional[bool] = False,
plot_macro: Optional[bool] = False,
title: str = "ROC Curve",
ax: Opti... | e1d92e9a06c3e1d677102f16401e054a7897f1b0 | 20,818 |
import sys
import os
import psutil
def get_cpu_info(host_info={}):
"""populate host_info with cpu information"""
if sys.platform == 'darwin':
host_info["host_cpu_model"] = \
popen(["sysctl", "-n", "machdep.cpu.brand_string"])
host_info["host_cpu_cores"] = \
popen(["sys... | 9ffb26bdef8fd638cabfa68a585f84b9f29c720b | 20,819 |
def _harmonize_input(data):
"""Harmonize different types of inputs by turning all inputs into dicts."""
if isinstance(data, (pd.DataFrame, pd.Series)) or callable(data):
data = {0: data}
elif isinstance(data, dict):
pass
else:
raise ValueError(
"Moments must be pand... | ad09d4bbf9b120825cd12b06e8a404b51ab2d23e | 20,820 |
def herd_closest_to_cluster(
x: np.ndarray,
y: np.ndarray,
t: np.ndarray,
features: np.ndarray,
nb_per_class: np.ndarray
) -> np.ndarray:
"""Herd the samples whose features is the closest to their class mean.
:param x: Input data (images, paths, etc.)
:param y: Labels of the data.
:... | 56512598efa343a974b8694e5d157e85b2179283 | 20,821 |
from typing import List
def generate_reference_config(config_entries: List[ConfigEntry]) -> {}:
"""
Generates a dictionary containing the expected config tree filled with default and example values
:return: a dictionary containing the expected config tree
"""
return config_entries_to_dict(config_e... | c00da6c96935845d4fb388251e6c5bff718cbe59 | 20,822 |
def reshape_tensor2list(tensor, n_steps, n_input):
"""Reshape tensor [?, n_steps, n_input] to lists of n_steps items with [?, n_input]
"""
# Prepare data shape to match `rnn` function requirements
# Current data input shape (batch_size, n_steps, n_input)
# Required shape: 'n_steps' tensors list of shape (batc... | dd42869bbc6d1e97a518cd133725c66408702afa | 20,823 |
import argparse
import textwrap
import sys
import os
def parse_arguments() -> dict:
"""Parse sys.argv arguments.
Args:
None
Returns:
A dictionary of arguments.
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textw... | 620aff41ab365e1f65e2eb7a80ad0ab16efea912 | 20,824 |
def squeeze(xray_obj, dimensions, dimension=None):
"""Squeeze the dimensions of an xray object."""
if dimension is None:
dimension = [d for d, s in dimensions.iteritems() if s == 1]
else:
if isinstance(dimension, basestring):
dimension = [dimension]
if any(dimensions[k] >... | abddfe5594600d39dcaece2c0be930d97c5aea2b | 20,825 |
def server_db(request, cp_server, api_server):
"""Enable database access for unit test vectors."""
db = database.get_connection(read_only=False, integrity_check=False)
api_server.db = db # inject into api_server
cursor = db.cursor()
cursor.execute('''BEGIN''')
util_test.reset_current_block_inde... | 40edd06d3aade01b70366cfe9f700772a1f9f2d7 | 20,826 |
import six
import click
def click_exception(exc, error_format):
"""
Return a ClickException object with the message from an input exception
in a desired error message format.
Parameters:
exc (exception or string):
The exception or the message.
error_format (string):
The ... | 8ebbaf6fc42ac5ef989c0afaac770418aca3b9b1 | 20,827 |
from typing import Optional
import json
import asyncio
import time
import re
def build(program_code: str, data: Data = frozendict(), random_seed: Optional[int] = None) -> Model:
"""Build (compile) a Stan program.
Arguments:
program_code: Stan program code describing a Stan model.
data: A Pyth... | c00f3af45b4f4d65b056653fff865246bf0ddd22 | 20,828 |
def _exec_with_broadcasting(func, *args, **keywords):
"""Main function to broadcast together the shapes of the input arguments
and return results with the broadcasted shape."""
# Identify arguments needing broadcasting
arg_ranks = []
arg_indices = []
for k in range(len(args)) + keywords.keys()... | 920cdaa1aae4eeb61467e4ca53647a030181a6a4 | 20,829 |
def compose_paths(path_0, path_1):
"""
The binary representation of a path is a 1 (which means "stop"), followed by the
path as binary digits, where 0 is "left" and 1 is "right".
Look at the diagram at the top for these examples.
Example: 9 = 0b1001, so right, left, left
Example: 10 = 0b1010, ... | cffb984c5bacf16691648e0910988495149087ad | 20,830 |
def combine(img1, img2, out_path, write=True):
"""combine(img1, img2, out_path, write=True)
Combines the data of two PyifxImages, ImageVolumes, or ImageLists to form new PyifxImages.
:type img1: pyifx.misc.PyifxImage, pyifx.misc.ImageVolume, list
:param img1: The first image to be added to the combination.
... | ccdee10b6d90ea9c1274f30d3c90bbe0f9e041ce | 20,831 |
import math
def invert_index(i, window, step):
"""Convert truncated squareform index back into row, col, and slice index
Task indexing for LD pruning is based on several optimizations that utilize a
cyclic, truncated squareform pattern for pairwise comparisons (between rows). This pattern
is primari... | 1acb4ef02a7158e584af5231a120f0a81af33bc4 | 20,832 |
def group_masses(ip, dm: float = 0.25):
"""
Groups masses in an isotope pattern looking for differences in m/z greater than the specified delta.
expects
:param ip: a paired list of [[mz values],[intensity values]]
:param dm: Delta for looking +/- within
:return: blocks grouped by central mass
... | 918fc4f20fee7c2955218e3c435f9e672dc55f7d | 20,833 |
def save_user_labels(*args):
"""
save_user_labels(func_ea, user_labels)
Save user defined labels into the database.
@param func_ea: the entry address of the function (C++: ea_t)
@param user_labels: collection of user defined labels (C++: const
user_labels_t *)
"""
return _ida_he... | a4a1a9ba4e37cd7f6e79efed5d9070bcdcfa8c5f | 20,834 |
def add_play():
"""Adds a new play"""
if 'Logged in as: ' + flask_login.current_user.get_id():
play_json = request.json
if request.json is None and request.data:
play_json = request.data
if play_json:
try:
# insert the created by information in pla... | 7e3e71bb007805a9c379b18c9ce1cce737ed30c9 | 20,835 |
import os
def get_compliment(file_list, file):
"""Returns a file path from the provided list that has the same name as the
file passed as the second arugment.
:param file_list: A list of paths with the same filetype.
:type file_list: list
:param file: A single path with an opposite filetype.
... | 9841207dc2ead05a1fde42baeea72e05323fb6ea | 20,836 |
def load_string_list(file_path, is_utf8=False):
"""
Load string list from mitok file
"""
try:
with open(file_path, encoding='latin-1') as f:
if f is None:
return None
l = []
for item in f:
item = item.strip()
if ... | 600c2678fdcdf6d5fa4894dd406f74c1ae4e5a96 | 20,837 |
def flash_dev(
disk=None, image_path=None, copy_method="default", port=None, program_cycle_s=4
):
"""Flash a firmware image to a device.
Args:
disk: Switch -d <disk>.
image_path: Switch -f <image_path>.
copy_method: Switch -c <copy_method> (default: shell).
port: Switch -p <... | 6ee569903f3d713fff620e122b4592ca0ed42cde | 20,838 |
def _get_bucket_and_object(gcs_blob_path):
"""Extract bucket and object name from a GCS blob path.
Args:
gcs_blob_path: path to a GCS blob
Returns:
The bucket and object name of the GCS blob
Raises:
ValueError: If gcs_blob_path parsing fails.
"""
if not gcs_blob_path.startswith(_GCS_PATH_PREF... | affda5501fbbc932c716d830226dec1c56271294 | 20,839 |
def dq_data(request):
"""Main home method and view."""
try:
cases = []
sdate, edate = None, None
sts = {0: 'Pending', 1: 'Open', 2: 'Closed'}
# Conditions
qa = request.GET.get('q_aspect')
va = request.GET.get('variance')
age = request.GET.get('age')
... | f1270dc0ae1b2a589d3995fe6bc0a9bb2199d5ed | 20,840 |
from typing import Protocol
def create_round_model(
protocol: Protocol,
ber: float,
n_tags: int) -> 'RoundModel':
"""
Factory function for creating round model.
This routine is cached, so calling it multiple time won't add much
overhead.
Parameters
----------
prot... | 2df6387abd189e5364559bb93547c789cf57f8fa | 20,841 |
def local_maxima(a_list):
"""
Takes a NoteList object.
Returns a list of tuples of the form returned by note_onsets().
Each of these (int: bar #, float: beat #) tuples will represent the onset
of a note that is a local maximum in the melody in a_list.
"""
return local_extremities(a_list, ma... | c239d91c341ee6a22cf621b13fb1cdafbe8b7b54 | 20,842 |
def get_fitted_model(data: pd.DataFrame, dataframe: pd.DataFrame) -> CTGAN:
""" The function get_fitted_model uses a CTGAN Checkpoint (see chapter about checkpoints),
to load a trained CTGAN model if one is available with the desired hyperparameters, or
train a new one if none is available. The function the... | c95c8b913f6411e0d0003ae5c2e126305306082b | 20,843 |
import math
def point_based_matching(point_pairs):
"""
This function is based on the paper "Robot Pose Estimation in Unknown Environments by Matching 2D Range Scans"
by F. Lu and E. Milios.
:param point_pairs: the matched point pairs [((x1, y1), (x1', y1')), ..., ((xi, yi), (xi', yi')), ...]
:ret... | 2d691bbf04d14e3e5b0f9273a7501d934bd0eef4 | 20,844 |
def kb_ids2known_facts(kb_ids):
"""Creates list of all known facts from kb dict"""
facts = set()
for struct in kb_ids:
arrays = kb_ids[struct][0]
num_facts = len(arrays[0])
for i in range(num_facts):
fact = [x[i] for x in arrays]
facts.add(tuple(fact))
re... | 8dd7f86c8b983f4dffa79a8229c4700a4182c710 | 20,845 |
import os
import re
def get_filepath(url, illustration, save_path='.', add_user_folder=False, add_rank=False):
"""return (filename,filepath)"""
if add_user_folder:
user_id = illustration.user_id
user_name = illustration.user_name
current_path = get_default_save_path()
cur_dirs... | 3502f0ecab6adffa9b4cb252d61961ce09f80961 | 20,846 |
def PUtilAvgT (inUV, outUV, err, scratch=False, timeAvg=1.0):
""" Average A UV data set in Time
returns Averaged UV data object
inUV = Python UV object to copy
Any selection editing and calibration applied before average.
outUV = Predefined UV data if scratch is False, ignored if
... | a1e5931a9d0e7340394e3a6227aa1a3f31e624ab | 20,847 |
def get_table_from_alter_table(line, alter_expr):
"""
Parse the content and return full qualified schema.table from the line if
schema provided, else return the table name.
Fact: if schema name or table name contains any special chars, each should be
double quoted already in dump file.
"""
... | af2bb25f240b2f9b1a171e4b7e2983000ca0d545 | 20,848 |
import os
def read_and_setup_bs(request):
"""
This routine reads the parameter files, sets up
the lattice and calculates or reads in the bandstructure
Parameters
----------
test_number : int
The test number, e.g. the folder under the tests
folder.
Returns
-------
bs... | 604b846ac430ea0494b3e5bfd4813936b898cca1 | 20,849 |
def bind_port(socket, ip, port):
""" Binds the specified ZMQ socket. If the port is zero, a random port is
chosen. Returns the port that was bound.
"""
connection = 'tcp://%s' % ip
if port <= 0:
port = socket.bind_to_random_port(connection)
else:
connection += ':%i' % port
... | 5613bae6726e2f006706b104463917e48d7ab7ca | 20,850 |
def update_target_graph(actor_tvars, target_tvars, tau):
""" Updates the variables of the target graph using the variable values from the actor, following the DDQN update
equation. """
op_holder = list()
# .assign() is performed on target graph variables with discounted actor graph variable values
f... | 15f0d192ff150c0a39495b0dec53f18a8ae01664 | 20,851 |
from typing import Callable
from re import T
def safe(function: Callable[..., T]) -> Callable[..., Result[T, Exception]]:
"""Wraps a function that may raise an exception.
e.g.:
@safe
def bad() -> int:
raise Exception("oops")
"""
def wrapped(*args, **kwargs) -> Result[T, ... | f33ce73ef9eed48e0585037f655075d78f9f6a09 | 20,852 |
def strtime(millsec, form="%i:%02i:%06.3f"):
"""
Time formating function
Args:
millsec(int): Number of milliseconds to format
Returns:
(string)Formated string
"""
fc = form.count("%")
days, milliseconds = divmod(millsec, 86400000)
hours, milliseconds = divmod(millsec, 3... | 9a1cff92086491941d8b27857169bf7744da8324 | 20,853 |
def parallel_categories():
"""Parallel Categories Plot."""
mean_neighborhood_sfo = sfo_data.groupby(["neighborhood"]).mean()
mean_sale_price_sfo = mean_neighborhood_sfo.sort_values("sale_price_sqr_foot", ascending=False)
sfo = mean_sale_price_sfo.head(10)
a = sfo.reset_index()
parallel_categorie... | fc03f4902f62a2e123e33012d58c58b4d7e55ddc | 20,854 |
def hessian_filter(img: Image, scales: list, dimension: int = 0,
scaled_to_eval=False, normalized=False, parallel=False) -> Image:
"""Applies a (multi-scale) hessian-like filtering operation on a 3D stack.
Transforms an image to an input image where each pixel represents an object-ness measu... | 1cae3d727c12c7cdcf1e4e0985a1fe843b7b8e4b | 20,855 |
def close_project(id_, **kwargs):
"""Close a project
:param id_: The ID of the project object to be updated
:type id_: str
:rtype: ProjectSerializer
"""
proj = get_project_object(id_)
check_project_permission(proj, kwargs["token_info"])
if proj.owner != kwargs["user"]:
raise con... | 7607e9627bc9a8eddc629e0deb4a4d1c1cd3fac9 | 20,856 |
import re
import os
import sys
def inspect_download_url(input_path, args, facts):
"""Process a direct download URL
Gather information required to create a recipe.
Args:
input_path: The path or URL that Recipe Robot was asked to use
to create recipes.
args: The command line ar... | 9d0b0ff3ca3c713af6886f9d59673f8a949b7696 | 20,857 |
def min_cycle_ratio(G: nx.Graph, dist):
"""[summary] todo: parameterize cost and time
Arguments:
G ([type]): [description]
Returns:
[type]: [description]
"""
mu = 'cost'
sigma = 'time'
set_default(G, mu, 1)
set_default(G, sigma, 1)
T = type(dist[next(iter(G))])
... | 37c992ed3ba9eea69165c5d66c7b83ea7550466f | 20,858 |
import string
def int2base(x, base):
"""
Method to convert an int to a base
Source: http://stackoverflow.com/questions/2267362
"""
digs = string.digits + string.ascii_uppercase
if x < 0: sign = -1
elif x == 0: return digs[0]
else:
sign = 1
x *= sign
digits = []... | f9277608cddea0d5590d294621afdb3b7af0fb34 | 20,859 |
def geometric(X):
"""
If x1,x2,...xn ~iid~ GEO(p) then the MLE is 1 / X-bar
Parameters
----------
X : array_like
Returns:
----------
geo_mle : MLE calculation for p-hat for GEO(p)
References
----------
[1] Casella, G., Berger, R. L., "Statistical Infe... | 014072a4c63f9f3d3fe067367b65689a21aa3799 | 20,860 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Run train or eval scripts for Gated2Depth')
parser.add_argument("--base_dir", help="Path to dataset", required=True)
parser.add_argument("--train_files_path", help="Path to file with train fi... | afb3f6d55b87c917225811f3716b9ecf1fcb494e | 20,861 |
def calc_dH(
e_per_atom,
stoich=None,
num_H_atoms=0,
):
"""
The original method is located in:
F:\Dropbox\01_norskov\00_git_repos\PROJ_IrOx_Active_Learning_OER\data\proj_data_irox.py
Based on a E_DFT/atom of -7.047516 for rutile-IrO2
See the following dir for derivation:
PR... | 1d6a6d3ed0581662d718fa0342fca76408d0a2d8 | 20,862 |
def _make_asset_build_reqs(asset):
"""
Prepare requirements and inputs lists and display it
:params str asset: name of the asset
"""
def _format_reqs(req_list):
"""
:param list[dict] req_list:
:return list[str]:
"""
templ = "\t{} ({})"
return [templ.... | 53b586aa00e596854ffd6292da9209c144701126 | 20,863 |
def gsl_eigen_herm_alloc(*args, **kwargs):
"""gsl_eigen_herm_alloc(size_t const n) -> gsl_eigen_herm_workspace"""
return _gslwrap.gsl_eigen_herm_alloc(*args, **kwargs) | 24884e2da582d28ad87ffba91ea9218b5f6f44f6 | 20,864 |
def cosine_similarity(array1, array2):
"""
Calcula la similitud coseno entre dos arrays
"""
# -sum(l2_norm(y_true) * l2_norm(y_pred))
return -dot(array1, array2)/(norm(array1)*norm(array2)) | 975dd0e25b70c93eff3c49ecc83def2bab2f84dd | 20,865 |
def DEW_T(Y, P, all_params):
"""
Y = list of mollar fractions of vapor like [0.2 ,0.8] or [0.1 0.2 0.7]
Sumation of X list must be 1.0
P = Pressure in kPa
all_params = list of parameters for Antonie equations
example for all params:
all_params = [[A1, B1, C1],
... | 3185d9b65d8c29c3df7f28e317e8a0d349db0ce5 | 20,866 |
def plugin_last():
"""This function should sort after other plug-in functions"""
return "last" | d2d6c00bc8d987363bd4db0013950d9b3f524c2f | 20,867 |
def init_seg_table(metadata, tablename, segid_colname=cn.seg_id, chunked=True):
""" Specifies a table for tracking info about a segment. """
columns = [Column("id", BigInteger, primary_key=True),
Column(cn.seg_id, Integer, index=True),
Column(cn.size, Integer),
# Cen... | f82a5285506d87d0d977661fcd45a336dc185c00 | 20,868 |
def extract_shebang_command(handle):
"""
Extract the shebang_ command line from an executable script.
:param handle: A file-like object (assumed to contain an executable).
:returns: The command in the shebang_ line (a string).
The seek position is expected to be at the start of the file and will b... | 27174f96f2da3167cf7a7e28c4a2f1cec72c773c | 20,869 |
import re
def split_abstracts(ftm_df):
"""
Split the mail abstract (item content) into different mails.
This is required to find the 'novel' email, and the rest of the threat. We
create a new row for each email in the threat, but it keeps the ID of the
'novel email'. We add two boolean flags for ... | 5725dda53a53e049fbcc7b42ac4fd3a51ec6c38a | 20,870 |
def get_weight_from_alias(blend_shape, alias):
"""
Given a blend shape node and an aliased weight attribute, return the index in .weight to the
alias.
"""
# aliasAttr lets us get the alias from an attribute, but it doesn't let us get the attribute
# from the alias.
existing_indexes = blend_s... | 56c870c32ee2ec05af1580fac985e09ffd5e129c | 20,871 |
from typing import List
from typing import Tuple
from typing import Any
def __check_dependences_and_predecessors(pet: PETGraphX, out_dep_edges: List[Tuple[Any, Any, Any]],
parent_task: CUNode, cur_cu: CUNode):
"""Checks if only dependences to self, parent omittable node or... | 1abdb9604fec48073b536fb7cf1e45a29dfea095 | 20,872 |
import json
def clone_master_track(obj, stdata, stindex, stduration):
"""
ghetto-clone ('deep copy') an object using JSON
populate subtrack info from CUE sheet
"""
newsong = json.loads(json.dumps(obj))
newsong['subsong'] = {'index': stindex, 'start_time': stdata['index'][1][0], 'duration': std... | 6721a87abfc88d9dd75f597ff24caf5857be594a | 20,873 |
def create_graph(num_islands, bridge_config):
"""
Helper function to create graph using adjacency list implementation
"""
adjacency_list = [list() for _ in range(num_islands + 1)]
for config in bridge_config:
source = config[0]
destination = config[1]
cost = config[2]
... | b961f5ee2955f4b8de640152981a7cede8ca80b0 | 20,874 |
def distinct_extractors(count=True, active=True):
""" Tool to count unique number of predictors for each Dataset/Task """
active_datasets = ms.Dataset.query.filter_by(active=active)
superset = set([v for (v, ) in ms.Predictor.query.filter_by(active=True).filter(
ms.Predictor.dataset_id.in_(
... | 232c10cdb69f5499d927473a6ee6d99c940870c5 | 20,875 |
def get_timepoint( data, tp=0 ):
"""Returns the timepoint (3D data volume, lowest is 0) from 4D input.
You can save memory by using [1]:
nifti.dataobj[..., tp]
instead: see get_nifti_timepoint()
Works with loop_and_save().
Call directly, or with niftify().
Ref:
[1]: http:/... | f5a718e5d9f60d1b389839fc0c637bee32b500bf | 20,876 |
def method_from_name(klass, method_name: str):
"""
Given an imported class, return the given method pointer.
:param klass: An imported class containing the method.
:param method_name: The method name to find.
:return: The method pointer
"""
try:
return getattr(klass, method_name)
... | 97274754bd89ede62ee5940fca6c4763efdbb95c | 20,877 |
def get_querypage(site: Site, page: str, limit: int = 500):
"""
:type site Site
:type page str
:type limit int
:rtype: list[str]
"""
# http://poznan.wikia.com/api.php?action=query&list=querypage&qppage=Nonportableinfoboxes
# http://poznan.wikia.com/api.php?action=query&list=querypage&qpp... | e4d05e4fb82697867261cc680a8497b8f80c97d4 | 20,878 |
import re
def parse_value(string: str) -> str:
"""Check if value is a normal string or an arrow function
Args:
string (str): Value
Returns:
str: Value if it's normal string else Function Content
"""
content, success = re.subn(r'^\(\s*\)\s*=>\s*{(.*)}$', r'\1', string)
if not ... | ead42d7f300c68b6978699473de8506794bb1ab4 | 20,879 |
def uniqify(seq, idfun=None):
"""Return only unique values in a sequence"""
# order preserving
if idfun is None:
def idfun(x):
return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
if marker in seen:
continue
seen[marker] =... | aaa6de6f3e28b0de9d23b921196591bea97a67d1 | 20,880 |
def inside(Sv, r, r0, r1):
"""
Mask data inside a given range.
Args:
Sv (float): 2D array with data to be masked.
r (float): 1D array with range data.
r0 (int): Upper range limit.
r1 (int): Lower range limit.
Returns:
bool... | 8a953b30a3dbd1bda2ce8f37475088705492e0f2 | 20,881 |
import os
def file_exists(fpath: str):
"""Checks if file exists by the given path
:param str fpath:
A path to validate for being a file
:returns:
True, if fpath is a file
False, if fpath doesn't exists or isn't a file
"""
return os.path.isfile(fpath) | 7bc85a461d6928acddd15b3be1fa8fca028b015b | 20,882 |
from resistics.common import fs_to_string
from typing import Optional
def get_solution_name(
fs: float, tf_name: str, tf_var: str, postfix: Optional[str] = None
) -> str:
"""Get the name of a solution file"""
solution_name = f"{fs_to_string(fs)}_{tf_name.lower()}"
if tf_var != "":
tf_var = tf... | bbf11abaad0878462c10d8ab95af13edd900982c | 20,883 |
import re
def escape(message: str) -> str:
"""Escape tags which might be interpreted by the theme tokenizer.
Should be used when passing text from external sources to `theme.echo`.
"""
return re.sub(
rf"<(/?{TAG_RE})>",
r"\<\1>",
message,
) | daf91638c8e763489d2fa529e9f1b2ebfda48cfa | 20,884 |
async def normalize_message(app: FastAPI, message: Message) -> Message:
"""
Given a TRAPI message, updates the message to include a
normalized qgraph, kgraph, and results
"""
try:
merged_qgraph = await normalize_qgraph(app, message.query_graph)
merged_kgraph, node_id_map, edge_id_map... | a6e0d3d4ab0590cfbdf643ec25c7bb23c7aaa8c4 | 20,885 |
def ec_elgamal_encrypt(msg, pk, symmalg):
"""
Computes a random b, derives a key from b*g and ab*g, then encrypts it using symmalg.
Input:
msg Plaintext message string.
pk Public key: a tuple (EC, ECPt, ECPt), that is (ec, generator g, a*g)
symmalg A callable th... | bc2447377f45a756e325fbed47bc28c17f4a5707 | 20,886 |
def plot_confusion_matrix(cm, classes,
normalize=False,
cmap=plt.cm.YlGnBu):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
np.set_printoptions(precision=2)
fig, ax = plt.s... | 6dcd9dc8d832f28035e25025705a4d13600087d0 | 20,887 |
from pylab import linspace
def meshgrid(params):
"""Returns meshgrid X that can be used for 1D plotting.
params is what is returned by finess.params.util.read_params."""
assert(params['finess', 'ndims'] == 1)
mx = params['grid', 'mx']
xlow = params['grid', 'xlow']
xhigh = params['grid', 'x... | 3320d8e1eab5b202152f1d90610e2f0d24adda1c | 20,888 |
def _pbe_p12(params, passphrase, hash_alg, cipher, key_size):
"""PKCS#12 cipher selection function for password-based encryption
This function implements the PKCS#12 algorithm for password-based
encryption. It returns a cipher object which can be used to encrypt
or decrypt data based on the sp... | 711376c5f653bd0888b3c35e6885942cad0c4268 | 20,889 |
def add_settings_routes(app):
""" Create routes related to settings """
@app.route('/v1/rule_settings/', methods=['GET'])
@requires_login
@use_kwargs({
'agency_code': webargs_fields.String(required=True),
'file': webargs_fields.String(validate=webargs_validate.
... | 6a199d67e40232e72dc4dcafa42a155f2257b687 | 20,890 |
def delete_by_date_paste(date):
"""
Deletes the paste entries older than a certain date. Note that it will delete any document/index type entered into
it for elasticsearch, the paste restriction is due to postgreql
:return: True once
"""
# Create a connection to the database (seemd to want it i... | aeb346d89f58d7894b36f633b90c608f635522f1 | 20,891 |
import os
def is_venv():
"""Check whether if this workspace is a virtualenv.
"""
dir_path = os.path.dirname(SRC)
is_venv_flag = True
if SYS_NAME == "Windows":
executable_list = ["activate", "pip.exe", "python.exe"]
elif SYS_NAME in ["Darwin", "Linux"]:
executable_list = ["acti... | a26a73e8253e27a644448d05985b7ae7d4111792 | 20,892 |
def convert(origDict, initialSpecies):
"""
Convert the original dictionary with species labels as keys
into a new dictionary with species objects as keys,
using the given dictionary of species.
"""
new_dict = {}
for label, value in origDict.items():
new_dict[initialSpecies[label]] =... | 5143f31acd1efdf1790e68bade3a1f8d8977bcde | 20,893 |
def Vector(point, direction, simple=None):
"""
Easy to use Vector type constructor. If three arguments are passed,
the first two are the x components of the point and the third is
the direction component of the Vector.
"""
if simple is not None:
point = Point(point, direction)
di... | 58407760ee540fa88dbc49100a5216522bd5de94 | 20,894 |
def createGrid(nx, ny):
"""
Create a grid position array.
"""
direction = 0
positions = []
if (nx > 1) or (ny > 1):
half_x = int(nx/2)
half_y = int(ny/2)
for i in range(-half_y, half_y+1):
for j in range(-half_x, half_x+1):
if not ((i==0) and (... | fe74af508e1bc7185d21f9c86b4eab64a66a52f5 | 20,895 |
from typing import Optional
from typing import Sequence
def get_private_network(filters: Optional[Sequence[pulumi.InputType['GetPrivateNetworkFilterArgs']]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetPrivateNetworkResult:
"""
Get information about a Vultr priva... | 37b409eb5f0fc5a6ddf7110ee26bfec44e56ee17 | 20,896 |
import types
import pandas
def sdc_pandas_series_operator_le(self, other):
"""
Pandas Series operator :attr:`pandas.Series.le` implementation
.. only:: developer
**Test**: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op7*
python -m sdc.runtests -k sdc.tests.te... | 101e2cf36208f76acebd06be56b1222f1e07b41e | 20,897 |
import numpy
def getArrFromFile(path = fromPath):
"""
读取原始csv文件,返回numpy数组
:param
path: 原始csv文件路径 string类型 default:fromPath
:return:
X: 由原始文件生成的数组 二维numpy数组类型
"""
X = numpy.genfromtxt(path,dtype=float,delimiter=',')[1:,:-2]
return X | 8c5c053391b305354ed398311fad6fdd988c153d | 20,898 |
import torch
def erode(binary_image, erosion=1):
"""
Sets 1s at boundaries of binary_image to 0
"""
batch_array = binary_image.data.cpu().numpy()
return torch.tensor(
np.stack([
binary_erosion(
array,
iterations=erosion,
border_va... | 60cea284d90e891e7f234174c673bd2a3a3f49dc | 20,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.