content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from pathlib import Path
import scipy
from datetime import datetime
def fit_sir(times, T_real, gamma, population, store, pathtoloc, tfmt='%Y-%m-%d', method_solver='DOP853', verbose=True, \
b_scale=1):
"""
Fit the dynamics of the SIR starting from real data contained in `pathtocssegi`.
The initial co... | 7a7da41fc178c805cc334e5a0060a2f9cc5f29d3 | 3,641,600 |
from typing import Dict
from typing import OrderedDict
def panelist_debuts_by_year(database_connection: mysql.connector.connect
) -> Dict:
"""Returns an OrderedDict of show years with a list of panelists'
debut information"""
show_years = retrieve_show_years(database_connection... | 40ba0cd67991b7c83b33e77522065b8bb75232c1 | 3,641,601 |
def _stirring_conditions_html(stirring: reaction_pb2.StirringConditions) -> str:
"""Generates an HTML-ready description of stirring conditions.
Args:
stirring: StirringConditions message.
Returns:
String description of the stirring conditions.
"""
if stirring.type == stirring.NONE:... | 0f03c67602163da3b732dfdcb0d367c6a0806c0d | 3,641,602 |
def load_action_plugins():
"""
Return a list of all registered action plugins
"""
logger.debug("Loading action plugins")
plugins = get_plugins(action, ActionPlugin)
if len(plugins) > 0:
logger.info("Discovered {n} action plugins:".format(n=len(plugins)))
for ap in plugins:
... | 55588021e933392136cb0d7f9dff7224716cce34 | 3,641,603 |
import io
import os
def read_file_in_root_directory(*names, **kwargs):
"""Read a file."""
return io.open(
os.path.join(os.path.dirname(__file__), *names),
encoding=kwargs.get('encoding', 'utf-8')
).read().strip() | 0fdf6d445a0cd152e66988d59d29a04e5f0a1651 | 3,641,604 |
def set_effective_property_value_for_node(
nodeId: dom.NodeId, propertyName: str, value: str
) -> dict:
"""Find a rule with the given active property for the given node and set the new value for this
property
Parameters
----------
nodeId: dom.NodeId
The element id for which to set p... | 36cf035bd878ac4c4936cebbacc115273807b892 | 3,641,605 |
def classroom_page(request,unique_id):
"""
Classroom Setting Page.
"""
classroom = get_object_or_404(Classroom,unique_id=unique_id)
pending_members = classroom.pending_members.all()
admins = classroom.special_permissions.all()
members = admins | classroom.members.all()
is_admin = classr... | fc37979a44da63fb0dc174799523f3a77fefb1e4 | 3,641,606 |
def concat_hists(hist_array: np.array):
"""Concatenate multiple histograms in an array by adding them up with error prop."""
hist_final = hist_array[0]
for hist in hist_array[1:]:
hist_final.addhist(hist)
return hist_final | e659ceb97f38620f561920ddab6339ecb901ee55 | 3,641,607 |
def renorm_flux_lightcurve(flux, fluxerr, mu):
""" Normalise flux light curves with distance modulus."""
d = 10 ** (mu/5 + 1)
dsquared = d**2
norm = 1e18
# print('d**2', dsquared/norm)
fluxout = flux * dsquared / norm
fluxerrout = fluxerr * dsquared / norm
return fluxout, fluxerrout | 97f2606d54b106d2051983dfc29d942112e7a1e3 | 3,641,608 |
import argparse
from pathlib import Path
import sys
from io import StringIO
def retrieve(args: argparse.Namespace, file_handler: DataFilesHandler, homepath: Path) -> str:
"""Find an expression by name."""
name = NAME_MULTIPLEXOR.join(args.REGULAR_EXPRESSION_NAME)
try:
return file_handler.get_patt... | acb2fd8c624eff05fd1181974afa46585dec275e | 3,641,609 |
def find_focus(stack):
"""
Parameters
----------
stack: (nd-array) Image stack of dimension (Z, ...) to find focus
Returns
-------
focus_idx: (int) Index corresponding to the focal plane of the stack
"""
def brenner_gradient(im):
assert len(im.shape) == 2, 'Input ima... | 234cecb9c43f9427cd8c5d1e9b2ae24c14239835 | 3,641,610 |
def get_amr_line(input_f):
"""Read the amr file. AMRs are separated by a blank line."""
cur_amr=[]
has_content=False
for line in input_f:
if line[0]=="(" and len(cur_amr)!=0:
cur_amr=[]
if line.strip()=="":
if not has_content:
continue
else:
... | 5b0c980a8c68143d8fdeb413185ee445b11cd30b | 3,641,611 |
def getHwAddrForIp(ip):
"""
Returns the MAC address for the first interface that matches the given IP
Returns None if not found
"""
for i in netifaces.interfaces():
addrs = netifaces.ifaddresses(i)
try:
if_mac = addrs[netifaces.AF_LINK][0]['addr']
if_ip = addrs[netifaces.AF_INET][0]['addr']
except Inde... | efbeb494ed0a3fb135e87a66a170a94f4ca78231 | 3,641,612 |
def rbf_multiquadric(r, epsilon=1.0, beta=2.5):
"""
multiquadric
"""
return np.sqrt((epsilon*r)**2 + 1.0) | 068ab09a609a47e631d91f90634fe4a5810e0fd1 | 3,641,613 |
def is_valid_sudoku(board):
"""
Checks if an input sudoku board is valid
Algorithm:
For all non-empty squares on board, if value at that square is a number,
check if the that value exists in that square's row, column,
and minor square.
If it is, return False.
"""
cols = [set(... | 001a02a47acbaa192215d985f3d743c42a9fb42b | 3,641,614 |
def lab_to_nwb_dict(lab_key):
"""
Generate a dictionary containing all relevant lab and institution info
:param lab_key: Key specifying one entry in element_lab.lab.Lab
:return: dictionary with NWB parameters
"""
lab_info = (lab.Lab & lab_key).fetch1()
return dict(
institution=lab_in... | dcde08b3421d56003d23ca19747430c6d95bf431 | 3,641,615 |
from typing import Set
from re import A
def length(self: Set[A]) -> int:
"""
Returns the length (number of elements) of the set. `size` is an alias for length.
Returns:
The length of the set
"""
return len(self) | cab214f7b06fc8ae604286cd40d6d558d05b7175 | 3,641,616 |
import time
def timestamp(tdigits=8):
"""Return a unique timestamp string for the session. useful for ensuring
unique function identifiers, etc.
"""
return str(time.clock()).replace(".", "").replace("-", "")[: tdigits + 1] | b209795f67735ada82238e5fa47f5132efa61384 | 3,641,617 |
from typing import List
from typing import Optional
def hierarchical_mutation(original_individual: Individual, strength: float, **kwargs) -> List[Optional[Individual]]:
# TODO: Double Check
"""Choose a node in the graph_manager, choose a parameter inside the node, mutate it.
Each parameter has probability... | a726478230b1cd37a0065f08c42b3dd125db9357 | 3,641,618 |
def is_wrapped_exposed_object(obj):
"""
Return True if ``obj`` is a Lua (lupa) wrapper for a BaseExposedObject
instance
"""
if not hasattr(obj, 'is_object') or not callable(obj.is_object):
return False
return bool(obj.is_object()) | 117a43f9dcc886dc88a77c2ace016b89e43b3c4c | 3,641,619 |
def no_transform(image):
"""Pass through the original image without transformation.
Returns a tuple with None to maintain compatability with processes that
evaluate the transform.
"""
return (image, None) | 25b45a5c77d3c2864ebc7a046e0f47b2fafb067b | 3,641,620 |
def build_menu(buttons, n_cols, header_buttons=None, footer_buttons=None):
"""Builds a menu with the given style using the provided buttons
:return:
list of buttons
"""
menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
if header_buttons:
menu.insert(0, [header_b... | f068ef9222b7e16cf19d901961f0315b2d6aebe3 | 3,641,621 |
def dbbox2result(dbboxes, labels, num_classes):
"""
Convert detection results to a list of numpy arrays.
:param dbboxes: (Tensor): shape (n, 9)
:param labels: (Tensor): shape (n, )
:param num_classes: (int), class number, including background class
:return: list (ndarray): dbbox results of each... | 945ba8c82837d51446eb8d3123497facafb0d503 | 3,641,622 |
def SSderivative(ds):
"""
Given a time-step ds, and an single input time history u, this SS model
returns the output y=[u,du/ds], where du/dt is computed with second order
accuracy.
"""
A = np.array([[0]])
Bm1 = np.array([0.5 / ds])
B0 = np.array([[-2 / ds]])
B1 = np.array([[1.5 / d... | c255937fd1f727932d5b09fc70c586e7bdb10bf1 | 3,641,623 |
def clean_post(value):
"""Remove unwanted elements in post content"""
doc = lxml.html.fragment_fromstring(value)
doc.tag = 'div' # replaces <li>
doc.attrib.clear()
# remove comment owner info
for e in doc.xpath('//div[@class="weblog_keywords"]'):
e.drop_tree()
return lxml.html.tost... | c7670d5632760b577aa7ac9dae24de15bf164c67 | 3,641,624 |
def get_houdini_version(as_string=True):
"""
Returns version of the executed Houdini
:param as_string: bool, Whether to return the stiring version or not
:return: variant, int or str
"""
if as_string:
return hou.applicationVersionString()
else:
return hou.applicationVersion(... | efcc18a89552f8dd1c4807be2042b51db2c2fb61 | 3,641,625 |
import socket
def check_port_open(port: int) -> bool:
"""
Проверка на свободный порт port
Является частью логики port_validation
"""
try:
sock = socket.socket()
sock.bind(("", port))
sock.close()
print(f"Порт {port} свободен")
return True
except OSError... | 76ba3ddd03bf1672b8b4ce5fd048561c3a9e78e8 | 3,641,626 |
from datetime import datetime
def convert_date_to_tick_tick_format(datetime_obj, tz: str):
"""
Parses ISO 8601 Format to Tick Tick Date Format
It first converts the datetime object to UTC time based off the passed time zone, and then
returns a string with the TickTick required date format.
!!! i... | 9f8efc2136b75310649d31328d4359d2030aff97 | 3,641,627 |
def measurement(resp, p):
"""model measurement effects in the filters by translating the response at
each location and stimulus (first 3 axes of resp) toward the filterwise mean
(4th axis) according to proportion p. p=1 means that all filters reduce
to their respective means; p=0 does nothing; p<0 is po... | 99d24b3b790c0aa1d2873ca5521144a1e326b661 | 3,641,628 |
def irpf(salario,base=12.5,prorrateo=0):
"""Entra el salario y la base, opcionalmente un parametro para prorratear
Si no se da el valor de la bas3e por defecto es 12.5"""
if type(salario)==float and type(base)==float:
if prorrateo==True:
return (salario*(1+2/12))*(base/100)
elif ... | b549e78f2cbd3227cc99d4ce7277a90058696895 | 3,641,629 |
def get2p3dSlaterCondonUop(Fdd=(9, 0, 8, 0, 6), Fpp=(20, 0, 8), Fpd=(10, 0, 8), Gpd=(0, 3, 0, 2)):
"""
Return a 2p-3d U operator containing a sum of
different Slater-Condon proccesses.
Parameters
----------
Fdd : tuple
Fpp : tuple
Fpd : tuple
Gpd : tuple
"""
# Calculate F_d... | 6ae077b1913bf40f93adcdbbbbc882baa9d56eea | 3,641,630 |
from typing import AnyStr
import pickle
def read_meta_fs(filename: AnyStr):
"""
Read meta data from disk.
"""
settings.Path(filename).mkdir(parents=True, exist_ok=True)
filepath = settings.pj(filename, "meta.pkl")
with open(filepath, "rb") as fh:
return pickle.load(fh) | 8fdf4c74d34c623cd1ac7d15f32f891685f1d863 | 3,641,631 |
def compile(model, ptr, vtr, num_y_per_branch=1):
"""Create a list with ground truth, loss functions and loss weights.
"""
yholder_tr = []
losses = []
loss_weights = []
num_blocks = int(len(model.output) / (num_y_per_branch + 1))
printcn(OKBLUE,
'Compiling model with %d outputs ... | 24af75f3b5bc6ba06d88f81023c2c7011f1d6922 | 3,641,632 |
import html
def strip_clean(input_text):
"""Strip out undesired tags.
This removes tags like <script>, but leaves characters like & unescaped.
The goal is to store the raw text in the database with the XSS nastiness.
By doing this, the content in the database is raw
and Django can continue to ass... | 83e2bd3cb5c2645dd4ea611fd0e0577d118b8326 | 3,641,633 |
def setup(mu=MU, sigma=SIGMA, beta=BETA, tau=TAU,
draw_probability=DRAW_PROBABILITY, backend=None, env=None):
"""Setups the global environment.
:param env: the specific :class:`TrueSkill` object to be the global
environment. It is optional.
>>> Rating()
trueskill.Rating(mu=2... | ce797c9994e477bc618f8f52cc63babcc61b78fd | 3,641,634 |
def _bytepad(x, length):
"""Zero pad byte string as defined in NIST SP 800-185"""
to_pad = _left_encode(length) + x
# Note: this implementation works with byte aligned strings,
# hence no additional bit padding is needed at this point.
npad = (length - len(to_pad) % length) % length
return to... | b02304fbb0e4bc42a80bc3fdc246c4fc9d55c816 | 3,641,635 |
import argparse
def str2bool(val):
"""enable default constant true arguments"""
# https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
if isinstance(val, bool):
return val
elif val.lower() == 'true':
return True
elif val.lower() == 'false':
retu... | ca229cd53674c6e9a8f37c60909826bf50c6accb | 3,641,636 |
def get_scalefactor(metadata):
"""Add scaling factors to the metadata dictionary
:param metadata: dictionary with CZI or OME-TIFF metadata
:type metadata: dict
:return: dictionary with additional keys for scling factors
:rtype: dict
"""
# set default scale factore to 1
scalefactors = {... | 0619d5fa8f24008ddf4364a965268755c07d09c3 | 3,641,637 |
def alignmentEntropy(align, statistic='absolute', removeGaps=False, k=1, logFunc=np.log):
"""Calculates the entropy in bits of each site (or kmer) in a sequence alignment.
Also can compute:
- "uniqueness" which I define to be the fraction of unique sequences
- "uniquenum" which is the number of... | ea06ae01cd1aa69cfc7dd19c72caafc5478fda38 | 3,641,638 |
def NodeToString(xml_node):
"""Returns an XML string.
Args:
xml_node: xml.dom.Node object
Returns:
String containing XML
"""
return xml_node.toxml() | 043072bbb40f33947febedf967679e3e39931834 | 3,641,639 |
def difference(data, interval):
""" difference dataset
parameters:
data: dataset to be differenced
interval: the interval between the two elements to be differenced.
return:
dataset: with the length = len(data) - interval
"""
return [data[i] - data[i ... | 611f4ad36935000ae7dc16f76aef7cbb494b36ac | 3,641,640 |
def merge_dictionaries(dict1, dict2):
""" Merges two dictionaries handling embedded lists and
dictionaries.
In a case of simple type, values from dict1 are preserved.
Args:
dict1, dict2 dictionaries to merge
Return merged dictionaries
"""
for k2, v2 in dict2.items():
if k2 no... | 8d46ce04496be2b5ba0e66788aed1a4e5ec1c85c | 3,641,641 |
def build(model_def, model_name, optimizer, loss_name, custom_objects=None):
"""build keras model instance in FastEstimator
Args:
model_def (function): function definition of tf.keras model or path of model file(h5)
model_name (str, list, tuple): model name(s)
optimizer (str, optimizer,... | 28cf56036b00790cf3e6350cc2741d93dd047e3a | 3,641,642 |
import wave
def check_audio_file(audio_file):
"""
Check if the audio file contents and format match the needs of the speech service. Currently we only support
16 KHz, 16 bit, MONO, PCM audio format. All others will be rejected.
:param audio_file: file to check
:return: audio duration, if file matc... | a6807cddefa7440b2f1cb11b2b3b309579f372e0 | 3,641,643 |
def uniform(name):
"""
Calls the findUniform function from util.py to return the uniform bounds for the given molecule.
Input: name of molecule
Output: array of length [2] with the upper and lower bounds for the uniform prior
"""
prior = findUniform(name, 'd_h')
return prior | e01b8c5056d199a8e0048e148170d5fc4c5c28a1 | 3,641,644 |
def merge_two_dicts(x, y):
"""Merges two dicts, returning a new copy."""
z = x.copy()
z.update(y)
return z | 9126ada395d9d7f3da5a45b7d46c5b440b5cf23d | 3,641,645 |
def num_utterances(dataset: ds.DatasetSplit):
"""Returns the total number of utterances in the dataset."""
return sum([len(interaction) for interaction in dataset.examples]) | 0927b96666f2f409c9fb0ec3c63576632810b6dc | 3,641,646 |
def __virtual__():
"""
Only return if requests and boto are installed.
"""
if HAS_LIBS:
return __virtualname__
else:
return False | 633ec9294e7585a6d5fc8a1dba2b436a20a4ab7a | 3,641,647 |
def register():
"""Register user"""
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
username = request.form.get("username")
email = request.form.get("email")
password = request.form.get("password")
# Logs user into database
... | 1c37ad0eac8f6a2230106cfd9e3754d6053956ff | 3,641,648 |
def _csd_multitaper(X, sfreq, n_times, window_fun, eigvals, freq_mask, n_fft,
adaptive):
"""Compute cross spectral density (CSD) using multitaper module.
Computes the CSD for a single epoch of data.
Parameters
----------
X : ndarray, shape (n_channels, n_times)
The time... | e936cb89ed18df8da25737be6fdfb31822c8db6f | 3,641,649 |
def _build_tmp_access_args(method, ip, ttl, port, direction, comment):
"""
Builds the cmd args for temporary access/deny opts.
"""
opt = _get_opt(method)
args = "{0} {1} {2}".format(opt, ip, ttl)
if port:
args += " -p {0}".format(port)
if direction:
args += " -d {0}".format(d... | 17a00e10af84519edb1a5dd8d89be614cb548ea1 | 3,641,650 |
def add_two_values(value1, value2):
""" Adds two integers
Arguments:
value1: first integer value e.g. 10
value2: second integer value e.g. 2
"""
return value1 + value2 | 10f71fcbde9d859f094724c94568eee55a7b989a | 3,641,651 |
import pandas
def combine_nearby_breakends(events, distance=5000):
"""
1d clustering, prioritizing assembled breakpoint coords
"""
breakends = []
positions = get_positions(events)
for (chrom, orientation), cur_events in positions.groupby(["chrom", "orientation"]):
cur_events = cur_e... | dad6867e7dfa406f8785b131fb2c93694fe60f0d | 3,641,652 |
def get_mongo_database(connection, database_name):
""" Access the database
Args:
connection (MongoClient): Mongo connection to the database
database_name (str): database to be accessed
Returns:
Database: the Database object
"""
try:
return connection.get_database(da... | 9299cbe0b697dec2e548fb5e26e2013214007575 | 3,641,653 |
from typing import Dict
from typing import Callable
def make_mappings() -> Dict[str, Callable[[], None]]:
"""サンプル名と実行する関数のマッピングを生成します"""
# noinspection PyDictCreation
m = {}
extlib.regist_modules(m)
return m | 598decb0b3197b1c64c982354de1fea9fdb3ce3d | 3,641,654 |
def S(state):
"""Stringify state
"""
if state == State.IDLE: return "IDLE"
if state == State.TAKING_OFF: return "TAKING_OFF"
if state == State.HOVERING: return "HOVERING"
if state == State.WAITING_ON_ASSIGNMENT: return "WAITING_ON_ASSIGNMENT"
if state == State.FLYING: return "FLYING"
if ... | 58c6005dcf8549225c233cc1af486fca9578111d | 3,641,655 |
import os
import logging
def eval_classif_cross_val_roc(clf_name, classif, features, labels,
cross_val, path_out=None, nb_steps=100):
""" compute mean ROC curve on cross-validation schema
http://scikit-learn.org/0.15/auto_examples/plot_roc_crossval.html
:param str clf_name... | b7196e024082015601f71cb9faaeb0c84444e419 | 3,641,656 |
def trace_get_watched_net(trace, i):
"""
trace_get_watched_net(Int_trace trace, unsigned int i) -> Int_net
Parameters
----------
trace: Int_trace
i: unsigned int
"""
return _api.trace_get_watched_net(trace, i) | f7140cbfcc27d511b3212ba7adf97f0b6c91582b | 3,641,657 |
from typing import Optional
from typing import OrderedDict
def dist_batch_tasks_for_all_layer_mdl_vs_adapted_mdl(
mdl: nn.Module,
spt_x: Tensor, spt_y: Tensor, qry_x: Tensor, qry_y: Tensor,
layer_names: list[str],
inner_opt: DifferentiableOptimizer,
fo: bool,
nb_inner_t... | 72830d75e195b8363936d78a8c249b9f6bbd7125 | 3,641,658 |
from typing import Callable
from typing import List
import numbers
def adjust_payload(tree: FilterableIntervalTree,
a_node: FilterableIntervalTreeNode,
adjustment_interval: Interval,
adjustments: dict,
filter_vector_generator: Callable[[dict]... | fa93deede3e7fee950834e5e02bc79bb98e68f03 | 3,641,659 |
from typing import Tuple
import os
def _read_cropped() -> Tuple[np.ndarray, np.ndarray]:
"""Reads the cropped data and labels.
"""
print('\nReading cropped images.')
path_cropped = os.path.join(DATA_FOLDER, FOLDER_CROPPED)
result = _recursive_read_cropped(path_cropped)
print('Done reading crop... | 798a60b13c49903672c65c9fd631141061a0873f | 3,641,660 |
def get_max(data, **kwargs):
"""
Assuming the dataset is loaded as type `np.array`, and has shape
(num_samples, num_features).
:param data: Provided dataset, assume each row is a data sample and \
each column is one feature.
:type `np.ndarray`
:param kwargs: Dictionary of differential priv... | 03697d2a2bc6afe3c1d576bd9f8766c97e86626d | 3,641,661 |
def find_u_from_v(matrix, v, singular_value):
"""
Finds the u column vector of the U matrix in the SVD UΣV^T.
Parameters
----------
matrix : numpy.ndarray
Matrix for which the SVD is calculated
v : numpy.ndarray
A column vector of V matrix, it is the eigenvector of the Gramian ... | ef2871c86bf7ddc4c42446a54230068282ad85df | 3,641,662 |
import torch
def transform(dataset, perm_idx, model, view):
"""
for view1 utterance, simply encode using view1 encoder
for view 2 utterances:
- encode each utterance, using view 1 encoder, to get utterance embeddings
- take average of utterance embeddings to form view 2 embedding
"""
model... | 484adb7d53f80366b591ef45551b245dce00acca | 3,641,663 |
from typing import List
def double(items: List[str]) -> List[str]:
"""
Returns a new list that is the input list, repeated twice.
"""
return items + items | 9e4b6b9e84a80a9f5cbd512ca820274bb8cad924 | 3,641,664 |
def system_from_problem(problem: Problem) -> System:
"""Extracts the "system" part of a problem.
Args:
problem: Problem description
Returns:
A :class:`System` object containing a copy of the relevant parts of the problem.
"""
return System(
id=problem.id,
name=proble... | 42c0db09d00043ba61ae164bb58a0ecb48599027 | 3,641,665 |
def get_service_endpoints(ksc, service_type, region_name):
"""Get endpoints for a given service type from the Keystone catalog.
:param ksc: An instance of a Keystone client.
:type ksc: :class: `keystoneclient.v3.client.Client`
:param str service_type: An endpoint service type to use.
:param str reg... | c962ad44e4d73a102f9c09803f94c68cee2aeb51 | 3,641,666 |
def get_task_for_node(node_id):
""" Get a new task or previously assigned task for node """
# get ACTIVE task that was previously assigned to this node
query = Task.query.filter_by(node_id=node_id).filter_by(status=TaskStatus.ACTIVE)
task = query.first()
if task:
return task
node = Nod... | 5a01869f40f5c0840dfdc2ed1e3417c694f51aca | 3,641,667 |
from xpedite.profiler.profileInfo import loadProfileInfo
import os
def loadProfileInfo(profileInfoPath, remote=None):
"""
Load profile information from a profileInfo.py file, set a default application information
file, and set the profile information's host if the application is running remotely
@param remot... | 95f25683174e157fa8031276d96f9bbef41706df | 3,641,668 |
import subprocess
def open_process(verbose, args, outputs):
""" Run the given arguments as a subprocess. Time out after TIMEOUT
seconds and report failures or stdout. """
report_output(outputs["stdout"],
verbose, "Writing", args)
proc = None
if outputs["stderr"] is not None:
... | 47b32c34d422d7809ee3d885632467f4c7aacb89 | 3,641,669 |
def cik_list():
"""Get CIK list and use it as a fixture."""
return UsStockList() | ec845471860dcf4ce9dcf0e82e2effda21bcbf0b | 3,641,670 |
def get_eval_config(hidden_dim,
max_input_length=None,
num_input_timesteps=None,
model_temporal_relations=True,
node_position_dim=1,
num_input_propagation_steps=None,
token_vocab_size=None,
... | 90ff743a372a2db3eb52927bf8c6d996a11137cb | 3,641,671 |
def classNew(u_id):
"""
Allow an ADMIN to create a new class (ADMIN ONLY)
Returns: none
"""
myDb, myCursor = dbConnect()
data = request.get_json()
createNewClass(myCursor, myDb, data)
dbDisconnect(myCursor, myDb)
return dumps({}) | 29532ea5c979b725b46c1dd775c1f093006b1a43 | 3,641,672 |
import types
import functools
def copy_func(f):
"""Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)."""
g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__,
argdefs=f.__defaults__,
closure=f.__closure__)
g = functools.up... | d661876d8568c5f33ae07682c874edd8d71dd7c9 | 3,641,673 |
from typing import List
def augment(img_list: list, hflip: bool = True, rot: bool = True) -> List[np.ndarray]:
"""
Augments the image inorder to add robustness to the model
@param img_list: The List of images
@param hflip: If True, add horizontal flip
@param rot: If True, add 90 degrees rotation
... | 3d953ba2c9ce869ec612644d9a5370690c930e22 | 3,641,674 |
def _neurovault_collections(parts, query):
"""Mocks the Neurovault API behind the `/api/collections/` path.
parts: the parts of the URL path after "collections"
ie [], ["<somecollectionid>"], or ["<somecollectionid>", "images"]
query: the parsed query string, e.g. {"offset": "15", "limit": "5"}
... | 5ee1e6b9b59fb12e76c38c20cde65c18c3fd201a | 3,641,675 |
def display_states():
""" Display the states"""
storage_states = storage.all(State)
return render_template('7-states_list.html', states=storage_states) | b9dc5c739546fee0abce077df1bba38587062f1a | 3,641,676 |
def recompress_folder(folders, path, extension):
"""Recompress folder"""
dest = runez.SYS_INFO.platform_id.composed_basename("cpython", path.name, extension=extension)
dest = folders.dist / dest
runez.compress(path, dest, logger=print)
return dest | 5cadc1a0b32509630cd3fa5af9fd758899e4bf94 | 3,641,677 |
import pathlib
def guessMimetype(filename):
"""Return the mime-type for `filename`."""
path = pathlib.Path(filename) if not isinstance(filename, pathlib.Path) else filename
with path.open("rb") as signature:
# Since filetype only reads 262 of file many mp3s starting with null bytes will not find... | 84f6b2f80b341f330e3f6b9e65b4863d055f8796 | 3,641,678 |
import json
import sys
def collectMessages():
""" A generic stimulus invocation """
global rmlEngine
try:
stimuli = []
rawRequest = request.POST.dict
for rawKey in rawRequest.keys():
keyVal = rawKey
jsonPayload = json.loads(keyVal)
try:
... | 55c3cb0444f4cfe4a1bfa4631f3e2351f63e9394 | 3,641,679 |
def filter_ptr_checks(props):
"""This function will filter out extra pointer checks.
Our support to primitives and overflow pointer checks is unstable and
can result in lots of spurious failures. By default, we filter them out.
"""
def not_extra_check(prop):
return extract_property_... | e5964637c3f1a27521f5305673c9e5af3189e15d | 3,641,680 |
import time
def makeKeylistObj(keylist_fname, includePrivate=False):
"""Return a new unsigned keylist object for the keys described in
'mirror_fname'.
"""
keys = []
def Key(obj): keys.append(obj)
preload = {'Key': Key}
r = readConfigFile(keylist_fname, (), (), preload)
klist = []
... | 13e79fbb9ac8ad207cc2533532c6be6bb0372beb | 3,641,681 |
def getwpinfo(id,wps):
"""Help function to create description of WP inputs."""
try:
wpmin = max([w for w in wps if 'loose' in w.lower()],key=lambda x: len(x)) # get loose WP with most 'V's
wpmax = max([w for w in wps if 'tight' in w.lower()],key=lambda x: len(x)) # get tight WP with most 'V's
info = f"... | 0dcf6c205a1988227e23a77e169a9114f1fdf2cc | 3,641,682 |
def build_word_dg(target_word, model, depth, model_vocab=None, boost_counter=None, topn=5):
""" Accept a target_word and builds a directed graph based on
the results returned by model.similar_by_word. Weights are initialized
to 1. Starts from the target_word and gets similarity results for it's children
... | ffd32cef2b44fd9e9cd554cd618091dfe8e5377f | 3,641,683 |
import sys
def train(network, num_epochs, train_fn, train_batches, test_fn=None,
validation_batches=None, threads=None, early_stop=np.inf,
early_stop_acc=False, save_epoch_params=False, callbacks=None,
acc_func=onehot_acc, train_acc=False):
"""
Train a neural network by updating ... | 8b5860883b04b9856b8794813aae3493a0389588 | 3,641,684 |
def sample_normal_gamma(mu, lmbd, alpha, beta):
""" https://en.wikipedia.org/wiki/Normal-gamma_distribution
"""
tau = np.random.gamma(alpha, beta)
mu = np.random.normal(mu, 1.0 / np.sqrt(lmbd * tau))
return mu, tau | 0f11ce95cfb772aeb023b61300bdb03d827cab37 | 3,641,685 |
from typing import Iterable
from typing import Callable
from typing import Type
from typing import Optional
from typing import List
from typing import Set
async def _common_discover_entities(
current_entity_platform: EntityPlatform,
config_entry: ConfigEntry,
source_objects: Iterable[TObject],... | 6ead5fa56712bf4186969f47a40c70cfea51b5da | 3,641,686 |
def _dice(terms):
"""
Returns the elements of iterable *terms* in tuples of every possible length
and range, without changing the order. This is useful when parsing a list of
undelimited terms, which may span multiple tokens. For example:
>>> _dice(["a", "b", "c"])
[('a', 'b', 'c'), ('a', 'b'),... | bb8f567d82405864c0bf81b2ee9f3cb89b875d11 | 3,641,687 |
from datetime import datetime
def parse_date(val, format):
"""
Attempts to parse the given string date according to the
provided format, raising InvalidDateError in case of problems.
@param str val (e.g. 2014-08-12)
@param str format (e.g. %Y-%m-%d)
@return datetime.date
"""
try:
... | 4686bf46d12310ee7ac4aa1986df55b598909a06 | 3,641,688 |
def get_capture_dimensions(capture):
"""Get the dimensions of a capture"""
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
return width, height | 9a13253c1ca5c44b7a1ef4440989b1af9abcb776 | 3,641,689 |
import os
def run_system_optimization(des_vars, subsystems, scalers, loop_number):
"""Method to run the top-level system optimization based on the disciplinary surrogate models.
:param des_vars: definition of design variables
:type des_vars: dict
:param subsystems: definition of the disciplinary surr... | faa46f94f6c866c5f1ec20827ce78ef7e13dfe95 | 3,641,690 |
def analyze_lines(msarc, trcdict, slit, pixcen, order=2, function='legendre', maskval=-999999.9):
"""
.. todo::
This needs a docstring!
"""
# Analyze each spectral line
aduse = trcdict["aduse"]
arcdet = trcdict["arcdet"]
xtfits = trcdict["xtfit"]
ytfits = trcdict["ytfit"]
wma... | 6e14c21545736d37ed6b231e5fc0e62293317b38 | 3,641,691 |
def ad_modify_user_pwd_by_mail(user_mail_addr, old_password, new_password):
"""
通过mail修改某个用户的密码
:param user_mail_addr:
:return:
"""
conn = __ad_connect()
user_dn = ad_get_user_dn_by_mail(user_mail_addr)
result = conn.extend.microsoft.modify_password(user="%s" % user_dn, new_password="%s"... | 7cc5c654517ad3f175e06500310f0bbfec516ad1 | 3,641,692 |
def markup_record(record_text, record_nr, modifiers, targets, output_dict):
""" Takes current Patient record, applies context algorithm,
and appends result to output_dict
"""
# Is used to collect multiple sentence markups. So records can be complete
context = pyConText.ConTextDocument()
# Split... | 2eee4560a411bcd7ef364b6ed9b37cc2870cd3b5 | 3,641,693 |
import inspect
def get_file_name(file_name):
"""
Returns a Testsuite name
"""
testsuite_stack = next(iter(list(filter(lambda x: file_name in x.filename.lower(), inspect.stack()))), None)
if testsuite_stack:
if '/' in testsuite_stack.filename:
split_character = '/'
els... | 97172600d785339501f5e58e8aca6581a0a690e0 | 3,641,694 |
import torch
def track_edge_matrix_by_spt(batch_track_bbox, batch_track_frames, history_window_size=50):
"""
:param batch_track_bbox: B, M, T, 4 (x, y, w, h)
:return:
"""
B, M, T, _ = batch_track_bbox.size()
batch_track_xy = batch_track_bbox[:, :, :, :2]
batch_track_wh = batch_track_bbox[:... | 5303f401d925c26a1c18546ba371a2119a41ec3d | 3,641,695 |
def _file(space, fname, flags=0, w_ctx=None):
""" file - Reads entire file into an array
'FILE_USE_INCLUDE_PATH': 1,
'FILE_IGNORE_NEW_LINES': 2,
'FILE_SKIP_EMPTY_LINES': 4,
'FILE_NO_DEFAULT_CONTEXT': 16,
"""
if not is_in_basedir(space, 'file', fname):
space.ec.warn("... | d8a04244c90f3f730c297a8dbaa1372acd61993b | 3,641,696 |
def prepare_features(tx_nan, degree, mean_nan=None, mean=None, std=None):
"""Clean and prepare for learning. Mean imputing, missing value indicator, standardize."""
# Get column means, if necessary
if mean_nan is None: mean_nan = np.nanmean(tx_nan,axis=0)
# Replace NaNs
tx_val = np.where(np.isnan(... | 2f9fd73cd04b40a85556573a62a083a0ffaa725c | 3,641,697 |
def _write_matt2(model, name, mids, nmaterials, op2, op2_ascii, endian):
"""writes the MATT2"""
#Record - MATT2(803,8,102)
#Word Name Type Description
#1 MID I Material identification number
#2 TID(15) I TABLEMi entry identification numbers
#17 UNDEF None
key = (803, 8, 102)
nfields = 17... | 607b94a6c1e3daf4b482acbb1df1ce967f1bce3b | 3,641,698 |
def all_subclasses(cls):
"""Returns all known (imported) subclasses of a class."""
return cls.__subclasses__() + [g for s in cls.__subclasses__()
for g in all_subclasses(s)] | 8b9a2ecd654b997b5001820d6b85e442af9cee3b | 3,641,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.