content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def hex2int(s: str):
"""Convert a hex-octets (a sequence of octets) to an integer"""
return int(s, 16) | 5,339,300 |
def add_gender_data(candidates, wd_session, gdata):
"""Add gender data (P21) for Wikidata items if humans (P31:Q5)"""
qids = '|'.join([c['pageprops']['wikibase_item'] for c in candidates if c.get('pageprops', {}).get('wikibase_item')])
GENDER_QUERY_BASE = {
'action': 'wbgetentities',
'props'... | 5,339,301 |
def into_two(lhs, ctx):
"""Element I
(num) -> push a spaces
(str) -> equivlaent to `qp`
(lst) -> split a list into two halves
"""
ts = vy_type(lhs, simple=True)
return {
NUMBER_TYPE: lambda: " " * int(lhs),
str: lambda: quotify(lhs, ctx) + lhs,
list: lambda: [
... | 5,339,302 |
def get_subgroup_df_row_generator(csv_path, subgroup_path):
"""
Loads benchmark subgroup dataframe containing "file" (str), "gender" (int), "race" (int), "expression_id" (int)
:param csv_path: path to sub-group .csv file.
:return: DataFrame for sub-group.
"""
col_names = ["file", "gender", "race... | 5,339,303 |
def closelog(log, runspyder=True):
"""
Close the log machinery used by the main counting routines by removing the
handlers
.. rubric :: Parameters
log : logging object
The log object
runspyder : bool. Default=True
If ``runspyder=True``, remove the extra handler for stdout added... | 5,339,304 |
def find_renter_choice(par,sol,t,i_beta,i_ht_lag,i_p,a_lag,
inv_v,inv_mu,v,mu,p,valid,do_mu=True):
""" find renter choice - used in both solution and simulation """
v_agg = np.zeros(2)
p_agg = np.zeros(2)
# a. x
iota_lag = -1
i_h_lag = -1
LTV_lag = np.nan
_m... | 5,339,305 |
def main():
""" EgoisticLily クライアントモジュール
:return:
"""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-p', '--port', help='server port number', default='50055')
args = arg_parser.parse_args()
port_str = '[::]:' + args.port
with grpc.insecure_channel(port_str) as channel... | 5,339,306 |
def met_zhengkl_gh(p, rx, cond_source, n, r):
"""
Zheng 2000 test implemented with Gauss Hermite quadrature.
"""
X, Y = sample_xy(rx, cond_source, n, r)
rate = (cond_source.dx() + cond_source.dy()) * 4./5
# start timing
with util.ContextTimer() as t:
# the test
zheng_gh = cgo... | 5,339,307 |
def get_domains(admin_managed: Optional[bool] = None,
include_unverified: Optional[bool] = None,
only_default: Optional[bool] = None,
only_initial: Optional[bool] = None,
only_root: Optional[bool] = None,
supports_services: Optional[Sequenc... | 5,339,308 |
def get_writer(Writer=None, fast_writer=True, **kwargs):
"""
Initialize a table writer allowing for common customizations. Most of the
default behavior for various parameters is determined by the Writer class.
Parameters
----------
Writer : ``Writer``
Writer class (DEPRECATED). Default... | 5,339,309 |
def find_last_service(obj):
"""Identify last service event for instrument"""
return Service.objects.filter(equipment=obj).order_by('-date').first() | 5,339,310 |
def swap_tree(tree):
""" Swaps the left and right branches of a tree. """
if tree is None:
return
tree.left, tree.right = tree.right, tree.left
swap_tree(tree.left)
swap_tree(tree.right) | 5,339,311 |
def SectionsMenu(base_title=_("Sections"), section_items_key="all", ignore_options=True):
"""
displays the menu for all sections
:return:
"""
items = get_all_items("sections")
return dig_tree(SubFolderObjectContainer(title2=_("Sections"), no_cache=True, no_history=True), items, None,
... | 5,339,312 |
def perform_save_or_create_role(is_professor, created_user, req_main, is_creating):
"""Performs update or create Student or Professor for user"""
response_verb = 'created' if is_creating else 'updated'
if is_professor is True:
professor_data = None
if 'professor' in req_main.keys():
... | 5,339,313 |
def ecg_rsp(ecg_rate, sampling_rate=1000, method="vangent2019"):
"""Extract ECG Derived Respiration (EDR).
This implementation is far from being complete, as the information in the related papers
prevents me from getting a full understanding of the procedure. Help is required!
Parameters
---------... | 5,339,314 |
def bootstrap(request):
"""Concatenates bootstrap.js files from all installed Hue apps."""
# Has some None's for apps that don't have bootsraps.
all_bootstraps = [(app, app.get_bootstrap_file()) for app in appmanager.DESKTOP_APPS if request.user.has_hue_permission(action="access", app=app.name)]
# Iterator ov... | 5,339,315 |
def get_selection(selection):
"""Return a valid model selection."""
if not isinstance(selection, str) and not isinstance(selection, list):
raise TypeError('The selection setting must be a string or a list.')
if isinstance(selection, str):
if selection.lower() == 'all' or selection == '':
... | 5,339,316 |
def getAllImageFilesInHierarchy(path):
"""
Returns a list of file paths relative to 'path' for all images under the given directory,
recursively looking in subdirectories
"""
return [f for f in scan_tree(path)] | 5,339,317 |
def list_package(connection, args):
"""List information about package contents"""
package = sap.adt.Package(connection, args.name)
for pkg, subpackages, objects in sap.adt.package.walk(package):
basedir = '/'.join(pkg)
if basedir:
basedir += '/'
if not args.recursive:
... | 5,339,318 |
def calc_hebrew_bias(probs):
"""
:param probs: list of negative log likelihoods for a Hebrew corpus
:return: gender bias in corpus
"""
bias = 0
for idx in range(0, len(probs), 16):
bias -= probs[idx + 1] + probs[idx + 5] + probs[idx + 9] + probs[idx + 13]
bias += probs[idx + 2] +... | 5,339,319 |
def load_wiki(size = 128, validate = True):
"""
Return malaya pretrained wikipedia ELMO size N.
Parameters
----------
size: int, (default=128)
validate: bool, (default=True)
Returns
-------
dictionary: dictionary of dictionary, reverse dictionary and vectors
"""
if not isin... | 5,339,320 |
def check_sentence(rc, s, annotations, is_foreign=False, ignore_warnings=False):
""" Check whether a given single sentence gets the
specified annotations when checked """
def check_sent(sent):
assert sent is not None
if sent.tree is None and not is_foreign:
# If the sentence... | 5,339,321 |
def generate_pibindex_rois_fs(aparc_aseg):
""" given an aparc aseg in pet space:
generate wm, gm and pibindex rois
make sure they are non-overlapping
return 3 rois"""
wm = mask_from_aseg(aparc_aseg, wm_aseg())
gm = mask_from_aseg(aparc_aseg, gm_aseg())
pibi = mask_from_aseg(aparc_aseg, pibi... | 5,339,322 |
def get_log_name(GLASNOST_ROOT, start_time, client_ip, mlab_server):
"""Helper method that given a test key, finds the logfile"""
log_glob = "%s/%s.measurement-lab.org/%s_%s_*" % (start_time.strftime('%Y/%m/%d'), mlab_server, start_time.strftime('%Y-%m-%dT%H:%M:%S'), client_ip)
if start_time < dateti... | 5,339,323 |
def generate_mpc_imitate(dataset, data_params, nn_params, train_params):
"""
Will be used for imitative control of the model predictive controller.
Could try adding noise to the sampled acitons...
"""
class ImitativePolicy(nn.Module):
def __init__(self, nn_params):
super(Imitat... | 5,339,324 |
def rescale(img, mask, factor):
"""Rescale image and mask."""
logging.info('Scaling: %s', array_info(img))
info = img.info
img = ndimage.interpolation.zoom(img, factor + (1,), order=0)
info['spacing'] = [s/f for s, f in zip(info['spacing'], factor)]
mask = rescale_mask(mask, factor)
assert i... | 5,339,325 |
def get_data_all(path):
"""
Get all data of Nest and reorder them.
:param path: the path of the Nest folder
:return:
"""
nb = count_number_of_label(path+ 'labels.csv')
data_pop = {}
for i in range(nb):
label, type = get_label_and_type(path + 'labels.csv', i)
field, data =... | 5,339,326 |
def from_tfrecord_parse(
record,
pre_process_func=None,
jpeg_encoded=False):
"""
This function is made to work with the prepare_data.TFRecordWriter class.
It parses a single tf.Example records.
Arguments:
record : the tf.Example record with the features of
... | 5,339,327 |
def load_shapes_coords(annotation_path):
"""
> TODO: Ensure and correct the clockwise order of the coords of a QUAD
"""
quads_coords = pd.read_csv(annotation_path, header=None)
quads_coords = quads_coords.iloc[:,:-1].values # [n_box, 8]
quads_coords = quads_coords.reshape(-1, 4, 2)
if... | 5,339,328 |
def _GenerateAggregatorReduction(emitter, registers, aggregators,
output_address, multiplicative_sum_offset,
additive_sum_offset):
"""Reduce 4 lane sum aggregators to 1 value and store the sums."""
emitter.EmitNewline()
emitter.EmitComment('Aggrega... | 5,339,329 |
def caller_path(steps=1, names=None):
"""Return the path to the file of the current frames' caller."""
frame = sys._getframe(steps + 1)
try:
path = os.path.dirname(frame.f_code.co_filename)
finally:
del frame
if not path:
path = os.getcwd()
if names is not None:
... | 5,339,330 |
def reader_json_totals(list_filenames):
"""
This reads the json files with totals and returns them as a list of dicts.
It will verify that the name of the file starts with totals.json to read it.
This way, we can just send to the function all the files in the directory and it will take care
of selec... | 5,339,331 |
def test_cdf(dist, grid):
"""
Validate cumulative distribution function.
"""
cdf = dist.cdf
for x, y in grid:
assert_allclose(cdf(x), y, atol=1e-3, err_msg=f'{dist} CDF, x={x}') | 5,339,332 |
def main(argv=None):
"""
"""
if argv == None:
argv = sys.argv[1:]
try:
ancestor1_file = argv[0]
ancestor2_file = argv[1]
except IndexError:
err = "Incorrect number of arguments!\n\n%s\n\n" % __usage__
raise CompareAncestorError(err)
out = compareAncesto... | 5,339,333 |
def list_scripts(zap_helper):
"""List scripts currently loaded into ZAP."""
scripts = zap_helper.zap.script.list_scripts
output = []
for s in scripts:
if 'enabled' not in s:
s['enabled'] = 'N/A'
output.append([s['name'], s['type'], s['engine'], s['enabled']])
click.echo... | 5,339,334 |
def support_message(bot, update):
"""
Receives a message from the user.
If the message is a reply to the user, the bot speaks with the user
sending the message content. If the message is a request from the user,
the bot forwards the message to the support group.
"""
if updat... | 5,339,335 |
def is_hitachi(dicom_input):
"""
Use this function to detect if a dicom series is a hitachi dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
... | 5,339,336 |
def index_of_first_signal(evt_index, d, qsets, MAXT3):
""" Check the evt_index of the last signal triplet (MC truth).
Args:
Returns:
"""
first_index = -1
k = 0
for tset in qsets:
for ind in tset: # Pick first of alternatives and break
#[HERE ADD THE OPTION TO CHOOSE ... | 5,339,337 |
def before_scenario(request, feature, scenario):
"""Create scenario report for the item."""
request.node.__scenario_report__ = ScenarioReport(scenario=scenario, node=request.node) | 5,339,338 |
def readcrd(filename, REAL):
"""
It reads the crd file, file that contains the charges information.
Arguments
----------
filename : name of the file that contains the surface information.
REAL : data type.
Returns
-------
pos : (Nqx3) array, positions of the charges.
q... | 5,339,339 |
def load_and_initialize_hub_module(module_path, signature='default'):
"""Loads graph of a TF-Hub module and initializes it into a session.
Args:
module_path: string Path to TF-Hub module.
signature: string Signature to use when creating the apply graph.
Return:
graph: tf.Graph Graph of the module.
... | 5,339,340 |
def get_mention_token_dist(m1, m2):
""" Returns distance in tokens between two mentions """
succ = m1.tokens[0].doc_index < m2.tokens[0].doc_index
first = m1 if succ else m2
second = m2 if succ else m1
return max(0, second.tokens[0].doc_index - first.tokens[-1].doc_index) | 5,339,341 |
def shlcar3x3(x,y,z, ps):
"""
This subroutine returns the shielding field for the earth's dipole, represented by
2x3x3=18 "cartesian" harmonics, tilted with respect to the z=0 plane (nb#4, p.74)
:param x,y,z: GSM coordinates in Re (1 Re = 6371.2 km)
:param ps: geo-dipole tilt angle in radius.
... | 5,339,342 |
def raan2ltan(date, raan, type="mean"):
"""Conversion to True Local Time at Ascending Node (LTAN)
Args:
date (Date) : Date of the conversion
raan (float) : RAAN in radians, in EME2000
type (str) : either "mean" or "true"
Return:
float : LTAN in hours
"""
if type == ... | 5,339,343 |
def _extract_bbox_annotation(prediction, b, obj_i):
"""Constructs COCO format bounding box annotation."""
height = prediction['eval_height'][b]
width = prediction['eval_width'][b]
bbox = _denormalize_to_coco_bbox(
prediction['groundtruth_boxes'][b][obj_i, :], height, width)
if 'groundtruth_area' in pred... | 5,339,344 |
def main(argv):
"""
Script main method, which loads two machine learning models, performing stance detection and subsequent veracity
determination for a dataset of branches using these models, and printing the results.
See project README for more in-depth description of command-line interfaces.
:p... | 5,339,345 |
def value_and_entropy(emax, F, bw, grid_size=1000):
"""
Compute the value function and entropy levels for a θ path
increasing until it reaches the specified target entropy value.
Parameters
==========
emax: scalar
The target entropy value
F: array_like
The policy function t... | 5,339,346 |
def browse_directory():
"""
Browse the local file system starting at the given path and provide the following information:
- project_name_unique: If the given project name is not yet registered in the projects list
- project_path_prefix: The given path with a final separator, e.g. /data/
- project_d... | 5,339,347 |
def test_laplace_obs_derivatives():
"""
The AdjointDoubleLayer kernel should be equal to the stress from the displacement from
the SingleLayer kernel. The same should be true of the Hypersingula kernel with
respect to the DoubleLayer kernel.
"""
t = sp.var("t")
line = refine_surfaces(
... | 5,339,348 |
def _biorthogonal_window_loopy(analysis_window, shift):
"""
This version of the synthesis calculation is as close as possible to the
Matlab implementation in terms of variable names.
The results are equal.
The implementation follows equation A.92 in
Krueger, A. Modellbasierte Merkmalsverbesser... | 5,339,349 |
def bool_exprs():
"""
Generate all boolean expressions:
- Boolean operators: and([Var]), or([Var]), xor([Var]) (CPMpy class 'Operator', is_bool())
- Boolean equality: Var == Var (CPMpy class 'Comparison')
"""
if SOLVER_CLASS is None:
return
names... | 5,339,350 |
def depthwise(data, N, H, W, CI, k_ch, KH, KW, PAD_H, PAD_W, SH, SW, block_size, use_bias=False):
"""
Depthwise 5-D convolutions,every channel has its filter-kernel
Args:
data (list):a list,the size is 3 if use_bias else the size is 2;
data[0] tvm.tensor.Tensor of type float16 ,shape ... | 5,339,351 |
def init_full_x_new_cli(init_full_x):
"""Change commandline call"""
name = "full_x"
branch = "full_x_new_cli"
orion.core.cli.main(
(
"hunt --init-only -n {branch} --branch-from {name} --cli-change-type noeffect "
"--enable-evc "
"./black_box_new.py -x~uniform(... | 5,339,352 |
async def get_last_recipe_json():
""" Doc Str """
with open(DEBUG_DIR.joinpath("last_recipe.json"), "r") as f:
return json.loads(f.read()) | 5,339,353 |
def FindDescendantComponents(config, component_def):
"""Return a list of all nested components under the given component."""
path_plus_delim = component_def.path.lower() + '>'
return [cd for cd in config.component_defs
if cd.path.lower().startswith(path_plus_delim)] | 5,339,354 |
def overlapbatch(args):
"""
%prog overlapbatch ctgfasta poolfasta
Fish out the sequences in `poolfasta` that overlap with `ctgfasta`.
Mix and combine using `minimus2`.
"""
p = OptionParser(overlap.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_h... | 5,339,355 |
def queue_job(script, submit=True):
"""Queue a pipeline script given as a string."""
import os
with tempfile.NamedTemporaryFile("w+") as fh:
fh.write(script)
fh.flush()
# TODO: do this in a better way
if submit:
cmd = "caput-pipeline queue %s"
else:
... | 5,339,356 |
def _get_source(loader, fullname):
"""
This method is here as a replacement for SourceLoader.get_source. That
method returns unicode, but we prefer bytes.
"""
path = loader.get_filename(fullname)
try:
return loader.get_data(path)
except OSError:
raise ImportError('source not ... | 5,339,357 |
def get_source_files(sf: Path) -> list:
"""
Search for files ending in .FLAC/.flac and add them to a list.
Args:
sf (str/pathlib.Path): Folder location to search for files.
Returns:
list: List of file locations found to match .FLAC/.fladc.
"""
return re_file_search.get_list(sf,... | 5,339,358 |
def extract_features(clip):
"""
Feature extraction from an audio clip
Args:
clip ():
Returns: A list of feature vectors
"""
sr, clip_array = wav_read(io.BytesIO(clip))
if clip_array.ndim > 1:
clip_array = clip_array[:, 0]
segments = frame_breaker.get_frames(clip_array, ... | 5,339,359 |
def summarize(vocab, write_to_file=True):
"""
>>> summarize({'var', '{', '/regexp/'}, write_to_file=False)
The size of vocabulary is 5
"""
# Add /*start*/ and /*end*/ tokens to the count.
size = len(vocab) + 2
if size < 128:
size = t.green(str(size))
elif 128 <= size < 256:
... | 5,339,360 |
def warn(msg, file=sys.stderr):
"""Log warning message ``msg`` to stderr."""
msg = 'WARNING: %s' %msg
if six.PY2:
msg = msg.encode('utf-8')
print(msg, file=file) | 5,339,361 |
def _attribute_tester(message, attribute_name: str, attribute_type: str, num_different_values=2, num_edges_of_interest=1):
"""
Tests attributes of a message
message: returned from _do_arax_query
attribute_name: the attribute name to test (eg. 'jaccard_index')
attribute_type: the attribute type (eg. ... | 5,339,362 |
def comparison_func(target: TwoQubitWeylDecomposition,
basis: TwoQubitBasisDecomposer,
base_fid: float,
comp_method: str):
"""
Decompose traces for arbitrary angle rotations.
This assumes that the tq angles go from highest to lowest.
... | 5,339,363 |
def values_graph(my_path, calced, my_experimental, graph_name):
"""X axis -> residue numbers, Y axis -> values
"calced" is a dict containing values for residues (as keys)
"experimental" is a list containing STR record objects"""
experimental = copy.deepcopy(my_experimental)
exp_line, calc_lin... | 5,339,364 |
def create_bs4_obj(connection):
"""Creates a beautiful Soup object"""
soup = BeautifulSoup(connection, 'html.parser')
return soup | 5,339,365 |
def __create_dataframe_from_cassandra(query,con):
"""
Function to query into Cassandra and Create Pandas DataFrame
Parameter
---------
query : String - Cassandra Query
con : cassandra connection object
Return
------
df : pd.DataFrame - DataFrame created using the ... | 5,339,366 |
def get_onehot_attributes(attr_dict, attr2idx, split):
"""get the labels in onehot format
Args:
attr_dict (dict: the dictory contains image_id and its top 5 attributes
attr2idx (dict): the dictory contains corresponding index of attributes
split (str): the split of the dataset (train, v... | 5,339,367 |
def create_worker_snapshot(compute, project, zone, worker):
"""Creates a snapshot for the worker if it does not already exists."""
try:
compute.snapshots().get(project=project, snapshot=f"{worker}-worker-boot").execute()
print("snaphost is already present won\'t be created")
return
except googleapicl... | 5,339,368 |
def test_re_b37_re_b37_v(mode, save_output, output_format):
"""
TEST :branch : base='string', pattern='abc*', value='abc',
type='valid', RULE='2,3,4'
"""
assert_bindings(
schema="msData/regex/reB37.xsd",
instance="msData/regex/reB37.xml",
class_name="Doc",
version="1.... | 5,339,369 |
def generate_activity_histogram(messages, filename):
"""
Save a graph to filename of the times messages were sent.
"""
times = range(24)
fig, ax = plt.subplots()
ax.hist([message.time.hour for message in messages], times, density=True)
ax.set_xlabel("Time")
ax.set_xlim(min(times), max(ti... | 5,339,370 |
async def post(
url: str,
content: bytes,
*,
headers: List[Tuple[bytes, bytes]] = None,
loop: Optional[AbstractEventLoop] = None,
cafile: Optional[str] = None,
capath: Optional[str] = None,
cadata: Optional[str] = None,
ssl_context: Optional[ssl.SS... | 5,339,371 |
def parse_config_file(path):
"""Parse TOML config file and return dictionary"""
try:
with open(path, 'r') as f:
return toml.loads(f.read())
except:
open(path,'a').close()
return {} | 5,339,372 |
def DPP2607_Write_CcaC7r1Coefficient(ccac7r1):
"""
Writes: CCA C7R1 Coefficient.
DPP2607_Write_CcaC7r1Coefficient(DWORD CCAC7R1).
:type ccac7r1: int
:rtype: None
"""
log(DEBUG, 'DPP2607_Write_CcaC7r1Coefficient(%r)', ccac7r1)
payload = [0x71]
payload.extend(list(bytearray(struct.pack... | 5,339,373 |
def _write_labelbuddy_part(
all_docs: Iterator[Tuple[pd.Series, pd.Series, pd.DataFrame]],
part_nb: int,
part_size: Optional[int],
output_dir: Path,
) -> None:
"""Write labelbuddy documents to jsonl file.
Writes at most `part_size` documents (or all documents if `part_size` is
`None`) taken... | 5,339,374 |
def wordnet_pos(tag):
"""
Transforms nltk part-of-speech tag strings to wordnet part-of-speech tag string.
:param tag: nltk part-of-speech tag string
:type: str
:return: the corresponding wordnet tag
:type: wordnet part-of-speech tag string
"""
return getattr(nltk_wordnet_pos_dict, tag[0... | 5,339,375 |
def plot_featurelist_learning_curve(df, data_subset='allBacktests', metric= None):
"""
Plot the featurelist length and error metric to generate a learning curve
df: Pandas df
Contains information on feature lists, and accuracy for iterations on a model. output of test_feature_selection()
data_s... | 5,339,376 |
def call_telegram_api(function: str, data: dict):
"""Make a raw call to Telegram API."""
return requests.post(
f'https://api.telegram.org/bot{TELEGRAM_TOKEN}/{function}', data=data) | 5,339,377 |
def test_POMDP(POMDP, policy, test_data, status):
"""simulation"""
# Basic settings
p = POMDP
ind_iter = 0
horizon = len(test_data)
state = status
action = p.actions[0]
belief = p.init_belief
reward = 0
state_set = [state]
action_set = []
observation_set = ["null"]
al... | 5,339,378 |
def set_testcase_with_impacts(testcase, impacts):
"""Set testcase's impact-related fields given impacts."""
testcase.impact_stable_version = impacts.stable.version
testcase.impact_stable_version_likely = impacts.stable.likely
testcase.impact_beta_version = impacts.beta.version
testcase.impact_beta_version_lik... | 5,339,379 |
def compute_bkr_collection(myCollection,percentile=10,make_images=False,image_name=''):
""" Computes a synthetic background value for a given collection, based on
the lowest values at each point for each image. it treats row (long axis of laser line)
and wavenumber seperately.
Notes:
-Does... | 5,339,380 |
def inverse_cell_center(structure):
"""
make an inversion against the cell center
:param structure: an instance of pymatflow.structure.crystal.Crystal()
"""
# first transfer to fractional coordinate and inverse against [0.5, 0.5, 0.5]
structure.natom = len(structure.atoms)
frac = structure.g... | 5,339,381 |
def courses_to_take(input):
"""
Time complexity: O(n) (we process each course only once)
Space complexity: O(n) (array to store the result)
"""
# Normalize the dependencies, using a set to track the
# dependencies more efficiently
course_with_deps = {}
to_take = []
for course, deps in input.items():
... | 5,339,382 |
def _merge_GlyphOrders(font, lst, values_lst=None, default=None):
"""Takes font and list of glyph lists (must be sorted by glyph id), and returns
two things:
- Combined glyph list,
- If values_lst is None, return input glyph lists, but padded with None when a glyph
was missing in a list. Otherwise, return value... | 5,339,383 |
def complete_multipart_upload(bucket, key, credentials, uploadId, parts):
"""
Complete multipart upload.
Raise exception if something wrong happens; otherwise success
Args:
bucket(str): bucket name
key(str): object key or `GUID/filename`
credentials(dict): aws credentials
... | 5,339,384 |
def sig_for_ops(opname):
"""sig_for_ops(opname : str) -> List[str]
Returns signatures for operator special functions (__add__ etc.)"""
# we have to do this by hand, because they are hand-bound in Python
assert opname.endswith('__') and opname.startswith('__'), "Unexpected op {}".format(opname)
n... | 5,339,385 |
def substr(source, start_index, count):
"""
substr(source, start_index, count) -> list object
Return a subset of a string `source`, starting at `start_index` and
of length `count`
"""
pass | 5,339,386 |
def add_qos(tenant_id, qos_name, qos_desc):
"""Adds a qos to tenant association."""
LOG.debug(_("add_qos() called"))
session = db.get_session()
try:
qos = (session.query(network_models_v2.QoS).
filter_by(tenant_id=tenant_id).
filter_by(qos_name=qos_name).one())
... | 5,339,387 |
def lstm2(hidden_nodes, steps_in=5, steps_out=1, features=1):
"""
A custom LSTM model.
:param hidden_nodes: number of hidden nodes
:param steps_in: number of (look back) time steps for each sample input
:param steps_out: number of (look front) time steps for each sample output
:param features: ... | 5,339,388 |
def build_carousel_scroller(items):
"""
Usage:
item_layout = widgets.Layout(height='120px', min_width='40px')
items = [pn.Row(a_widget, layout=item_layout, margin=0, background='black') for a_widget in single_pf_output_panels]
# items = [widgets.Button(layout=item_layout, description=st... | 5,339,389 |
def smolsolve(x, xBound, f0, t, K_A, source, Nt):
""" solve Smoluchowski equations
Input: x, initial condition, time, kernel, # timestep
Output: solution f(t,x)
"""
dx = xBound[1] - xBound[0]
Nx = x.size
dt = t / Nt
g = x * f0
for t in range(Nt):
JL = 0*x
fsrc = 0*x
# source term for f
... | 5,339,390 |
def on_stickerpack_removed(bot, user_id, stickerpack_name):
"""Called whenever a stickerpack of a user gets removed"""
bot.send_message(user_id, "The sticker pack %s has been removed, sorry for the inconvenience" % stickerpack_name)
with storage.session_scope() as session:
storage.remove_every_pack_... | 5,339,391 |
def base_round(x, base):
"""
This function takes in a value 'x' and rounds it to the nearest multiple
of the value 'base'.
Parameters
----------
x : int
Value to be rounded
base : int
Tase for x to be rounded to
Returns
-------
int
The ro... | 5,339,392 |
def numbers_basics():
"""
Here we will be seeing different numbers data type in Python.
:return: none
"""
log_debug(2 + 2)
log_debug(2 * 4)
log_debug(14 / 3)
log_debug(14 % 3)
log_debug(2 ** 3)
# BODMAS rule is applied
log_debug(2 + 10 * 10)
# The below code will not gi... | 5,339,393 |
def _update_schema_1_to_2(table_metadata, table_path):
"""
Given a `table_metadata` of version 1, update it to version 2.
:param table_metadata: Table Metadata
:param table_path: [String, ...]
:return: Table Metadata
"""
table_metadata['path'] = tuple(table_path)
table_metadata['schema... | 5,339,394 |
def train_cnn_7layer(data, file_name, params, num_epochs=10, batch_size=256, train_temp=1, init=None, lr=0.01, decay=1e-5, momentum=0.9, activation="relu", optimizer_name="sgd"):
"""
Train a 7-layer cnn network for MNIST and CIFAR (same as the cnn model in Clever)
mnist: 32 32 64 64 200 200
cifar: 64 6... | 5,339,395 |
def validate():
"""
Goes over all season, make sure they are all there, and they should have length 52, except last one
"""
input_file = processedDatafileName
clusters_file = 'data/SeasonClustersFinal'
seasonDic = {}
allSeasons = {}
for line in open(cluster... | 5,339,396 |
def get_registry(): # noqa: E501
"""Get registry information
Get information about the registry # noqa: E501
:rtype: Registry
"""
try:
res = Registry(
name="Challenge Registry",
description="A great challenge registry",
user_count=DbUser.objects.count(... | 5,339,397 |
def test_deformation_grid():
""" Test deformation grid, there is only so much that we can do ...
"""
im0, c0, dfield1, weight1, dfield2, weight2, pp1, pp2, pp3 = get_data_small_deform()
gridsampling = 6
# Create identity deform
d1 = DeformationGridBackward(im0, gridsampling)
assert... | 5,339,398 |
def get_fraction_vaccinated(model, trajectories, area=None, include_recovered=True):
"""Get fraction of individuals that are vaccinated or immune (by area) by
state.
Parameters
----------
model : amici.model
Amici model which should be evaluated.
trajectories : pd.DataFrame
Tra... | 5,339,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.