content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_paramvals_percentile(table, percentile, chi2_arr):
"""
Isolates 68th percentile lowest chi^2 values and takes random 1000 sample
Parameters
----------
table: pandas dataframe
Mcmc chain dataframe
pctl: int
Percentile to use
chi2_arr: array
Array of chi^2 va... | 16,300 |
def get_text_from_span(s, (start, end)):
"""
Return the text from a given indices of text (list of words)
"""
return " ".join(s[start: end]) | 16,301 |
def __timestamp():
"""Generate timestamp data for pyc header."""
today = time.time()
ret = struct.pack(b'=L', int(today))
return ret | 16,302 |
def reverse_index(alist, value):
"""Finding the index of last occurence of an element"""
return len(alist) - alist[-1::-1].index(value) -1 | 16,303 |
def check_subset(set_a, set_b, fail_action, *args, **kwargs):
"""
"""
for x in set_a:
if x not in set_b:
fail_action(x, *args, **kwargs) | 16,304 |
def generate_twist(loops, non_interacting=False):
"""Generate initial configuration to start braid moves where the active end has crossed outside the loops and they have an initial twist.
Format: ' โ โ โโ'
'โโโโโโโ'
'โโ โ โ '
'โโโโ โ '
' โโโ โ '
'โโโโ... | 16,305 |
def get_pathway_id_names_dict():
"""
Given a pathway ID get its name
:return: pathway_id_names_dict
"""
# Fixme: This is not analysis specfic (I think, KmcL) I believe any analysis should do
# A fix is for this is probably wise.
analysis = Analysis.objects.get(name='Tissue Compari... | 16,306 |
def IsShuttingDown(_shutting_down=_shutting_down):
"""
Whether the interpreter is currently shutting down.
For use in finalizers, __del__ methods, and similar; it is advised
to early bind this function rather than look it up when calling it,
since at shutdown module globals may be cleared.
"""
... | 16,307 |
def ellipse_center(a):
"""
Parameters
----------
a : fitted_ellipse_obj
"""
b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]
num = b*b-a*c
x0=(c*d-b*f)/num
y0=(a*f-b*d)/num
return np.array([x0,y0]) | 16,308 |
def test_task_cl_bump():
"""Test task_cl_bump."""
result = task_cl_bump()
actions = result['actions']
assert len(actions) == 4
assert isinstance(actions[1][0], type(_move_cl))
assert 'poetry run cz bump --annotated-tag' in str(actions[2])
assert actions[3] == 'git push origin --tags --no-ve... | 16,309 |
def callDiffLoops(
tl,
cl,
td,
cd,
output,
cut=0,
mcut=-1,
cpu=1,
pcut=1e-2,
igp=False,
noPCorr=False,
fdrcut=0.05,
juicebox=False,
washU=False,
customize=False,
cacut=0.0,
cmcut=0.0,
... | 16,310 |
def _to_average_temp(name, temperature_map):
"""
Converts the list of temperatures associated to a label to a list of average temperatures.
If the sensor does not exist, it will return _default_temperature. If the high or critical temperature thresholds
are invalid, it will use the values from _default_... | 16,311 |
def segments_decode(aseg):
"""
Decode segments.
Parameters
----------
aseg : numpy.ndarra of uint32
Returns
-------
segments : list of list of int
"""
max = 2 ** 32 - 1
segments = []
l = []
for x in list(aseg):
if x == max:
segments.append(l)
... | 16,312 |
def generate_sbm_network(input_file: "yaml configuration file") -> None:
"""
This function generates a simulated network, using the block model matrix given as input and saves both the network and the cluster nodes.
All parameters must be specified in a yaml file.
This function allows to create network ... | 16,313 |
def cvGetReal3D(*args):
"""cvGetReal3D(CvArr arr, int idx0, int idx1, int idx2) -> double"""
return _cv.cvGetReal3D(*args) | 16,314 |
def parse_root_firefox(root, root_folder):
"""
Function to parse the root of the firefox bookmark tree
"""
# create bookmark menu folder
bookmarks = Folder(title="Bookmarks Menu", parent_id=root_folder.id)
bookmarks.insert()
for node in root:
# skip node if not <DT>
if node.n... | 16,315 |
def request_cluster(argv):
"""
only request cluster on GCE, and output all configuration information
:param argv: sys.argv
:return: None
"""
if len(argv) < 7:
print_help()
exit(1)
cluster_name = argv[2]
ambari_agent_vm_num = int(argv[3])
docker_num = int(argv[4])
... | 16,316 |
def get_wf_double_FF_opt(
molecule,
pcm_dielectric,
linked=False,
qchem_input_params=None,
name="douple_FF_opt",
db_file=">>db_file<<",
**kwargs,
):
"""
Firework 1 : write QChem input for an FF optimization,
run FF_opt QCJob,
parse directory and inse... | 16,317 |
def return_stack():
"""
Create the stack of the obtained exception
:return: string stacktrace.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
return lines[0] + lines[1] | 16,318 |
def get_element_action_names(element):
"""Get a list of all the actions the specified accessibility object can perform.
Args:
element: The AXUIElementRef representing the accessibility object
Returns: an array of actions the accessibility object can perform
(empty if the accessibility objec... | 16,319 |
def merge_task_entity_yamls(
task_config_path: str, entity_config_path: str, merged_path: str
):
"""
Merge task yaml file and entity yaml file into a task-entity yaml
file.
:param task_config_path: the path to the task yaml file
:param entity_config_path: the path to the entity yaml file
:pa... | 16,320 |
def accuracy_on_imagenet_c(data_loaders, model, args, writer, num_iteration):
"""Computes model accuracy and mCE on ImageNet-C"""
print("Performance on ImageNet-C:")
model.eval()
ce_alexnet = get_ce_alexnet()
with torch.no_grad():
top1_in_c = AverageMeter('Acc_IN_C@1', ':6.2f')
to... | 16,321 |
def ParseFile(fname):
"""Parse a micrcode.dat file and return the component parts
Args:
fname: Filename to parse
Returns:
3-Tuple:
date: String containing date from the file's header
license_text: List of text lines for the license file
microcodes... | 16,322 |
def run_server():
"""Runs the Tornado Server and begins Kafka consumption"""
if topic_check.topic_exists("TURNSTILE_SUMMARY") is False:
logger.fatal(
"Ensure that the KSQL Command has run successfully before running the web server!"
)
exit(1)
if topic_check.topic_exists("... | 16,323 |
def create_mesh_node(world, node, mesh_ids, parent=None):
""" Creates a node of type Mesh.
"""
with underworlds.Context("edit-tool") as ctx:
target_world = ctx.worlds[world]
new_node = Mesh()
new_node.properties["mesh_ids"] = mesh_ids
new_node.name = node
new_nod... | 16,324 |
def cal_q_vel(guidance_v):
"""
ๆๆถไฝฟ็จ้ป่ฎคๅ่้ๅบฆ่ฟ่กไผๅ๏ผ็ญ่ฐ่ฏๆ็ๅไฝฟ็จ็ฒ็ณ้ๅบฆๆฅไผๅ
:return:
"""
q_vel = numpy.zeros((1, n_t + 1))
if flag_obs == 0:
q_vel[0][0] = -ref_v
q_vel[0][n_t] = ref_v
if flag_obs == 1:
for i in range(n_t + 1):
if i < 1:
q_vel[0][i] = -guidance_v[0][i]
elif i >= n_t:
q_vel[0][i] = guidan... | 16,325 |
def tf_decode(
ref_pts,
ref_theta,
bin_x,
res_x_norm,
bin_z,
res_z_norm,
bin_theta,
res_theta_norm,
res_y,
res_size_norm,
mean_sizes,
Ss,
DELTAs,
R,
DELTA_THETA,
):
"""Turns bin-based box3d format into an box_3d
Input:
ref_pts: (B,p,3) [x,y,z]... | 16,326 |
def _histogram_discretize(target, num_bins=gin.REQUIRED):
"""Discretization based on histograms."""
discretized = np.zeros_like(target)
for i in range(target.shape[0]):
discretized[i, :] = np.digitize(target[i, :], np.histogram(
target[i, :], num_bins)[1][:-1])
return discretized | 16,327 |
def apply_acl(instance, content):
"""Apply ACLs."""
any_acl_applied = False
if not isinstance(instance, roleable.Roleable):
return any_acl_applied
instance_acl_dict = {(l.ac_role_id, p.id): l
for p, l in instance.access_control_list}
person_ids = set()
for role_id, data in content... | 16,328 |
def serialize(results):
"""Serialize a ``QueryDict`` into json."""
serialized = {}
for result in results:
serialized.update(result.to_dict())
return json.dumps(serialized, indent=4) | 16,329 |
def allowed_once (cave, visited):
"""Only allows small caves to be visited once. Returns False if `cave`
is small and already in `visited`.
"""
return big(cave) or (small(cave) and cave not in visited) | 16,330 |
def isna(obj: Literal["CAT0"]):
"""
usage.dask: 2
"""
... | 16,331 |
def _serialize_examstruct(exam):
""" Serialize the exam structure for, eg. cache.
The dates, especially, need work before JSON
"""
assert isinstance(exam, dict)
date_fmt = '%Y-%m-%d %H:%M:%S'
assert isinstance(exam['start'], datetime.datetime)
assert isinstance(exam['end'], datetime.date... | 16,332 |
def _analysis_test_impl(ctx):
"""Implementation function for analysis_test. """
_ignore = [ctx]
return [AnalysisTestResultInfo(
success = True,
message = "All targets succeeded analysis",
)] | 16,333 |
def main(args):
"""
Main function for the script
:param args: parsed command line arguments
:return: None
"""
from config import cfg as opt
opt.merge_from_file(args.config)
opt.freeze()
print("Creating generator object ...")
# create the generator object
gen = Generator(re... | 16,334 |
def filename_to_scienceurl(filename, suffix=None, source="irsa", verbose=False, check_suffix=True):
"""
"""
_, filefracday, paddedfield, filtercode, ccd_, imgtypecode, qid_, *suffix_ = os.path.basename(filename).split("_")
suffix_ = "_".join(suffix_)
year,month, day, fracday = filefrac_to_year... | 16,335 |
def CD_Joint(CD_J_AS = None,
Ypred = None,
beta = None,
zeta = None,
active_set = None,
lam = None,
P = None,
P_interaction = None,
Y = None,
B = None,
B_interaction = None,
S =... | 16,336 |
def testAllCallbacksSmokeTest(
args_count: int, type_checker: TypeCheckerFixture
) -> None:
"""
Parametrized test to do basic checking over all Callbacks (except Callback0).
We generate functions with too much arguments, too few, and correct number, and check
that the errors are as expected.
T... | 16,337 |
def transform_unnamed_cols_range(df: pd.DataFrame, columns_range: range,
new_column_name_prefix: str, inplace=False) -> object:
"""
This function transforms a range of columns based assuming the presence of following schema in dataframe:
|base_column_name|Unnamed_n|Unnamed_... | 16,338 |
def shingles(tokens, n):
"""
Return n-sized shingles from a list of tokens.
>>> assert list(shingles([1, 2, 3, 4], 2)) == [(1, 2), (2, 3), (3, 4)]
"""
return zip(*[tokens[i:-n + i + 1 or None] for i in range(n)]) | 16,339 |
def load_json(filename):
"""Load JSON file as dict."""
with open(join(dirname(__file__), filename), "rb") as fp:
return json.load(fp) | 16,340 |
def getLayerList(layer_list, criterionFn):
"""Returns a list of all of the layers in the stack that match the given criterion function, including substacks."""
matching_layer = []
for layer in layer_list:
if criterionFn(layer):
matching_layer.append(layer)
if hasattr(layer, 'laye... | 16,341 |
def getBiLinearMap(edge0, edge1, edge2, edge3):
"""Get the UV coordinates on a square defined from spacing on the edges"""
if len(edge0) != len(edge1):
raise ValueError("getBiLinearMap: The len of edge0 and edge1 are not the same")
if len(edge2) != len(edge3):
raise ValueError("getBiLinearM... | 16,342 |
def _parse_args():
"""parse arguments"""
parser = argparse.ArgumentParser(description='train and export wdsr on modelarts')
# train output path
parser.add_argument('--train_url', type=str, default='', help='where training log and ckpts saved')
# dataset dir
parser.add_argument('--data_url', type... | 16,343 |
def listkeys():
""" Show stored keys
"""
stm = shared_steem_instance()
t = PrettyTable(["Available Key"])
t.align = "l"
for key in stm.wallet.getPublicKeys():
t.add_row([key])
print(t) | 16,344 |
def missing_frame_features(files, pipeline: PipelineContext):
"""Get file paths with missing frame-level features."""
frame_features = pipeline.repr_storage.frame_level
for i, file_path in enumerate(files):
if not frame_features.exists(pipeline.reprkey(file_path)):
yield file_path | 16,345 |
def _parse_orientation(response: HtmlResponse):
"""Parse Orientation.
Returns None if not available or is unknown.
"""
value = response.css('th:contains("Ausrichtung") + td ::text').get()
if value:
if value == "unbekannt" or value == "verschieden":
return None
fk_value =... | 16,346 |
def binaryread(file, vartype, shape=(1,), charlen=16):
"""
Uses numpy to read from binary file. This was found to be faster than the
struct approach and is used as the default.
"""
# read a string variable of length charlen
if vartype == str:
result = file.read(charlen * 1)
el... | 16,347 |
def subsample_data(neuron_data, sample_size = 10000):
"""
Acquires a subsample of the Neuron dataset.
This function samples a set of neurons without replacement.
Params
-----------
Returns
-----------
rand_ix (array-like):
Array containing the chosen indices
sample_neu... | 16,348 |
def appGet(*args, **kwargs):
"""
.. deprecated:: 0.42.0
Use :func:`app_get()` instead.
"""
print("dxpy.appGet is deprecated; please use app_get instead.", file=sys.stderr)
return app_get(*args, **kwargs) | 16,349 |
def connect_db():
"""Connects to the specific database."""
mongo = MongoClient(DATABASE_URL,replicaset=MONGO_REPLICASET)
#if COLLECTION_NAME in mongo[DATABASE_NAME].collection_names():
collection = mongo[DATABASE_NAME][COLLECTION_NAME]
#else:
# mongo[DATABASE_NAME].create_collection(COLLECTIO... | 16,350 |
def save_params(network, epoch_i, base_save_path="./checkpoints"):
"""
Save current params of the network.
Args:
network: the lagrangian network.
epoch_i: the current training epoch.
base_save_path: base save path for saving the parameters.
"""
save_path = Path(base_save_pat... | 16,351 |
def transient(func):
"""
decorator to make a function execution transient.
meaning that before starting the execution of the function, a new session with a
new transaction will be started, and after the completion of that function, the
new transaction will be rolled back without the consideration o... | 16,352 |
def make_mapping(environ, start_response):
"""
Establishing a mapping, storing the provided URI
as a field on a tiddler in the PRIVATEER bag.
Accepted data is either a json dictory with a uri
key or a POST CGI form with a uri query paramter.
Respond with a location header containing the uri
... | 16,353 |
def test_aws_binary_file(host):
"""
Tests if aws binary is a file type.
"""
assert host.file(PACKAGE_BINARY).is_file | 16,354 |
def create_space_magnitude_region(region, magnitudes):
"""Simple wrapper to create space-magnitude region """
if not (isinstance(region, CartesianGrid2D) or isinstance(region, QuadtreeGrid2D)) :
raise TypeError("region must be CartesianGrid2D")
# bind to region class
if magnitudes is None:
... | 16,355 |
def autocorrelation_plot(series, label, lower_lim=1, n_samples=None, ax=None, **kwds):
"""Autocorrelation plot for time series.
Parameters:
-----------
series: Time series
ax: Matplotlib axis object, optional
kwds : keywords
Options to pass to matplotlib plotting method
Returns:
... | 16,356 |
def process_input_using_awk(inputf, outputf):
"""
Square the value read from inputf and save in outputf
:param inputf: file to read number from
:param outputf: file to save squere to
:return: void
"""
cmd = "sleep 5;\n awk '{print $1*$1}' " + \
("{} > {};\n").format(inputf, outputf... | 16,357 |
def get_productivity(coin_endowments):
"""Returns the total coin inside the simulated economy.
Args:
coin_endowments (ndarray): The array of coin endowments for each of the
agents in the simulated economy.
Returns:
Total coin endowment (float).
"""
return np.sum(coin_en... | 16,358 |
def prefix_attrs(source, keys, prefix):
"""Rename some of the keys of a dictionary by adding a prefix.
Parameters
----------
source : dict
Source dictionary, for example data attributes.
keys : sequence
Names of keys to prefix.
prefix : str
Prefix to prepend to keys.
Retu... | 16,359 |
def add_polygon_to_image(image: np.ndarray, object: dict) -> np.ndarray:
""" Add the polynom of the given object to the image.
Since using CV, order is (B,G,R)
Parameters
----------
img : np.ndarray
Opencv image
object : dict
Dictionary of the polynom with meta infos.
Retu... | 16,360 |
def add(coefficient_1, value_1, coefficient_2, value_2):
"""Provides an addition algebra for various types, including scalars and
histogram objects.
Incoming values are not modified.
Args:
coefficient_1: The first coefficient, a scalar
value_1: The first value, a histogram or scalar
... | 16,361 |
def kotlin_object_type_summary(lldb_val, internal_dict = {}):
"""Hook that is run by lldb to display a Kotlin object."""
start = time.monotonic()
log(lambda: f"kotlin_object_type_summary({lldb_val.unsigned:#x}: {lldb_val.GetTypeName()})")
fallback = lldb_val.GetValue()
if lldb_val.GetTypeName() != "... | 16,362 |
def parse_arguments(root_dir):
""" Will parse the command line arguments arnd return the arg object.
"""
# Create top level parser. TODO: add description, usage, etc
parser = argparse.ArgumentParser(prog="aware.py",
description="Probabilistic demultiplexer for Illumina bcl files. Works "
... | 16,363 |
def _grep_first_pair_of_parentheses(s):
"""
Return the first matching pair of parentheses in a code string.
INPUT:
A string
OUTPUT:
A substring of the input, namely the part between the first
(outmost) matching pair of parentheses (including the
parentheses).
Parentheses between... | 16,364 |
def login():
"""
"""
url = "http://127.0.0.1:5001/rest/login"
data = {"username": "kivanc", "password": "1234"}
r = requests.post(url, json=data)
output = r.json()
return output["access_token"] | 16,365 |
def get_all_ops(ifshortcut=True, ifse=True, strides=[1, 2, 2, 2, 1, 2, 1]):
"""Get all possible ops of current search space
Args:
ifshortcut: bool, shortcut or not
ifse: bool, se or not
strides: list, list of strides for bottlenecks
Returns:
op_params: list, a list of all pos... | 16,366 |
def evaluation_per_relation(triples: dict, model: EvaluationModel, batch_size: int = 4):
"""
:param triples: It should be a dict in form (Relation id):[(s_1,p_1,o_1)...(s_n,p_n,o_n)]
"""
# Evaluate per relation and store scores/evaluation measures
score_per_rel = dict()
for k in tqdm.tqdm(trip... | 16,367 |
def apply_executor(executor, path, parameters):
"""Non-interactively run a given executor."""
args = executor["input_arguments"] if "input_arguments" in executor else {}
final_parameters = set_parameters(args, parameters)
launcher = convert_launcher(executor["executor"]["name"])
command = executor... | 16,368 |
def check_upload():
"""
ๅคๆญไปๅคฉ็ไปฃ็ ๆฏๅฆไธไผ
:return:
"""
ctime = datetime.date.today() # ๅฝๅๆฅๆ
data = db_helper.fetchone('select id from record where ctime = %s and user_id = %s',
(ctime, session['user_info']['id']))
return data | 16,369 |
def get_package_object():
"""Gets a sample package for the submission in Dev Center."""
package = {
# The file name is relative to the root of the uploaded ZIP file.
"fileName" : "bin/super_dev_ctr_api_sim.appxupload",
# If you haven't begun to upload the file yet, set this value to "Pen... | 16,370 |
def check_for_cmd():
""" Returns tuple of [Type] [Data] where type is the shuffle type and data
will contain either random shuffle parameters or the top deck order required """
try:
with open(CMD_FILE, 'r+') as f:
data = f.readline()
f.truncate(0)
# DEBUGGIN TODO REM... | 16,371 |
def _set_quantity(request, force_delete=False):
"""Set the quantity for a specific cartitem.
Checks to make sure the item is actually in the user's cart.
"""
cart = Cart.objects.from_request(request, create=False)
if isinstance(cart, NullCart):
return (False, None, None, _("No cart to update... | 16,372 |
def load_typos_file(file_name, char_vocab = {}, filter_OOA_chars = False):
"""
Loads typos from a given file.
Optionally, filters all entries that contain out-of-alphabet characters.
"""
basename, ext = os.path.splitext(file_name)
replacement_rules = list()
if ext == ".tsv":
typos... | 16,373 |
def load_config(config_file="config.yaml"):
"""Load config file to initialize fragment factories.
A config file is a Python file, loaded as a module.
Example config file:
# config.yaml
name: My LDF server
maintainer: chuck Norris <me@gmail.com>
datasets:
-
name: DBpedia-2016-04... | 16,374 |
def run_s3_test():
"""run_s3_test
Run the S3 verification test
"""
access_key = os.getenv(
'S3_ACCESS_KEY',
'trexaccesskey')
secret_key = os.getenv(
'S3_SECRET_KEY',
'trex123321')
region_name = os.getenv(
'S3_REGION_NAME'
'us-east-1')
service_... | 16,375 |
def test_2():
""" Test the backlog
"""
ann = lox.Announcement(backlog=0)
x_in = [1, 2, 3, 4, 5]
foo_soln, bar_soln = [], []
foo_q = ann.subscribe()
def foo():
x = foo_q.get()
foo_soln.append(x**2)
def bar():
x = bar_q.get()
bar_soln.append(x**3)
t... | 16,376 |
def execute_actor(actor_id,
worker_id,
execution_id,
image,
msg,
user=None,
d={},
privileged=False,
mounts=[],
leave_container=False,
fifo_h... | 16,377 |
def add_library(command):
"""
tests if the add library command is running properly
"""
from src.praxxis.library import list_library
namespace = app.main(command)
assert namespace.command == 'al' or namespace.command == "addlibrary"
assert namespace.path == "test" | 16,378 |
def find_start_end(grid):
"""
Finds the source and destination block indexes from the list.
Args
grid: <list> the world grid blocks represented as a list of blocks (see Tutorial.pdf)
Returns
start: <int> source block index in the list
end: <int> destination bl... | 16,379 |
def find_method_signature(klass, method: str) -> Optional[inspect.Signature]:
"""Look through a class' ancestors and fill out the methods signature.
A class method has a signature. But it might now always be complete. When a parameter is not
annotated, we might want to look through the ancestors and determ... | 16,380 |
def format_long_calc_line(line: LongCalcLine) -> LongCalcLine:
"""
Return line with .latex attribute formatted with line breaks suitable
for positioning within the "\aligned" latex environment.
"""
latex_code = line.latex
long_latex = latex_code.replace("=", "\\\\&=") # Change all...
long_l... | 16,381 |
def run(data_fn, prop_missing=0., max_num_feature=-1,
feature_selection='random', k=10, data_dir='_data', out_dir='_out'):
"""Run RIDDLE classification interpretation pipeline.
Arguments:
data_fn: string
data file filename
prop_missing: float
proportion of featur... | 16,382 |
def h_lgn(t, mu, sigma, normalize=False):
""" Log-normal density
Args:
t: input argument (array)
mu: mean parameter (-infty,infty)
sigma: std parameter > 0
normalize: trapz integral normalization over t
Returns:
function values
"""
y = np.ze... | 16,383 |
def align_background(data, align='auto'):
"""
Determine the Qz value associated with the background measurement.
The *align* flag determines which background points are matched
to the sample points. It can be 'sample' if background is
measured using an offset from the sample angle, or 'detector'
... | 16,384 |
def another_function_requiring_decoration():
"""Hey you! Decorate me!"""
print(
"I am the function which needs some decoration to remove my foul smell"
) | 16,385 |
def get_bounds_from_config(b, state, base_units):
"""
Method to take a 3- or 4-tuple state definition config argument and return
tuples for the bounds and default value of the Var object.
Expects the form (lower, default, upper, units) where units is optional
Args:
b - StateBlock on which ... | 16,386 |
def notify_user_activation(user, request=None):
"""Send mail for user activation"""
security = query_utility(ISecurityManager)
settings = INotificationSettings(security)
if not settings.enable_notifications: # pylint: disable=assignment-from-no-return
LOGGER.info("Security notifications disable... | 16,387 |
def read_train_data():
"""
train_data.shape = (73257, 32, 32, 3)
train_label.shape = (73257,)
extra_data.shape = (531131, 32, 32, 3)
extra_label.shape = (531131,)
data.shape = (604388, 32, 32, 3)
labels.shape = (604388,)
"""
train_data, train_label = read_images(full_data_dir+'train... | 16,388 |
def laguerreFunction(n, alpha, t, normalized=True):
"""Evaluate Laguerre function using scipy.special"""
if normalized:
Z = np.exp( .5*sps.gammaln(n+1) - .5*sps.gammaln(n+alpha+1) )
else:
Z = 1
return Z * np.sqrt(mu(alpha,t)) * sps.eval_genlaguerre(n, alpha, t) | 16,389 |
def dispatch_scan(asset_id, user_id, policy):
"""Main method for periodic scan task dispatching."""
asset = AssetInstance.objects.get(id=asset_id)
str_asset_id = str(asset.id)
str_user_id = str(user_id)
scheduled = PeriodicTask.objects.filter(name__contains='ps-'+str(asset.id))
if policy.repeat ... | 16,390 |
def end(s):
"""Select the mobile or weight hanging at the end of a side."""
assert is_side(s), "must call end on a side"
return branches(s)[0] | 16,391 |
def main():
"""
The main function (runs the GUI and the Crawler).
"""
enable_js_preference() # fix javascript to be enabled on chrome browser
g = GuiMenu() # build GuiMenu object
fb_urls = g.fb_urls # facebook urls to crawl
fb_mobile_urls = g.fb_mobile_urls # facebook urls to crawl in mo... | 16,392 |
def bam_to_fasta(source_bam, dest_fasta, sam_flag=4,
debug=False, intermediate_sam=True):
"""
Convert a .bam file to a .fasta using samtools and the specified
samtools flag.
:param source_bam: file path to .bam file to extract reads from
:param dest_fasta: file path to save resulti... | 16,393 |
def get_ca_pos_from_atoms(df, atoms):
"""Look up alpha carbon positions of provided atoms."""
ca = df[df['atom_name'] == 'CA'].reset_index()
nb = ca.reindex(atoms)
nb = nb.reset_index().set_index('index')
return nb | 16,394 |
def split_inline_box(context, box, position_x, max_x, skip_stack, containing_block, containing_page, absolute_boxes,
fixed_boxes, line_placeholders, waiting_floats, line_children):
"""Same behavior as split_inline_level."""
# In some cases (shrink-to-fit result being the preferred width)
... | 16,395 |
def LoadComponent(self,filename): # real signature unknown; restored from __doc__
"""
LoadComponent(self: object,filename: str) -> object
LoadComponent(self: object,stream: Stream) -> object
LoadComponent(self: object,xmlReader: XmlReader) -> object
LoadComponent(self: object,filename: TextReader) -> objec... | 16,396 |
def split_bits(word : int, amounts : list):
"""
takes in a word and a list of bit amounts and returns
the bits in the word split up. See the doctests for concrete examples
>>> [bin(x) for x in split_bits(0b1001111010000001, [16])]
['0b1001111010000001']
>>> [bin(x) for x in split_bits(... | 16,397 |
def rasterio_to_gdir(gdir, input_file, output_file_name,
resampling='cubic'):
"""Reprojects a file that rasterio can read into the glacier directory.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
the glacier directory
input_file : str
path to th... | 16,398 |
def global_tracer(ot_tracer):
"""A function similar to one OpenTracing users would write to initialize
their OpenTracing tracer.
"""
set_global_tracer(ot_tracer)
return ot_tracer | 16,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.