content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import ast
def tok_to_number(m: ast.Module, tok: Token) -> ast.Number:
"""Converts a numerical token into a number AST node."""
if tok.kind == TokenKind.CHARACTER:
number_kind = ast.NumberKind.CHARACTER
value = tok.value
elif tok.kind == TokenKind.KEYWORD:
assert tok.value in (Keyword.TRUE, Keyword.... | 553d231f9287046ff96d9877e1e0fdfa1ab52ffe | 66,400 |
from typing import Dict
import tqdm
def build_embeddings(embedding_size_y: int, word_indexes: Dict[str, int]) -> np.array:
"""
build embeddings to be used with basic models
"""
logger.info('build glove embeddings')
embeddings_indexes: Dict[str, np.array] = {}
# open glove 840 file
with op... | 42aeb1bd0ea652f96b9768d70d28f70291fff400 | 66,401 |
def dx_filter_coe(ver=0):
"""
差分算子discrete filter
用于correlate而非convolve
"""
##ver-1
if ver == 1:
l = sqrt(2)-1
a = zeros([3,3])
a[1,0] = -l/2
a[1,2] = l/2
a[[0,2],0] = -(1-l)/4
a[[0,2],2] = (1-l)/4
elif ver == 2:
a = zeros([3,3])
... | 6587e295c7124601c0a1364038f0d0f8eaf21141 | 66,402 |
async def api_count():
""" Aggregate api count at third minute of every hour """
task_result = await api_count_task()
return task_result | 350eab2124f0021d9478a1e58692d92c1a4b6dfe | 66,403 |
from typing import Set
def list_all_programs() -> Set[str]:
"""
List all programs registered by QCEngine.
"""
return set(programs.keys()) | 938bc95aa548d2fd722ad0f3298a15ab2accfb9c | 66,404 |
def get_runtime(job):
"""Returns the runtime in milliseconds or None if job is still running"""
if job.metadata.get("finished_time") is not None:
finished_time = job.metadata.get("finished_time")
else:
return None
start_time = job.metadata.get("scrapystats")["start_time"]
return floa... | 710d9d135ae7097bb85b0c3e8ea88d142da593e2 | 66,405 |
def apply(input):
"""
Calculates the dot product of two matricies using keras, with a tensorflow-gpu backend.
Returns the product as the output.
"""
input = InputObject(input)
z = K.dot(input.A, input.B)
# Here you need to use K.eval() instead of z.eval() because this uses the backend sessi... | 60f72e9afa59bebbfd590c5d965eadd4e0180fb4 | 66,406 |
import os
def deletereport(filename):
"""Function to return user reports"""
if not session.get("logged_in"):
return render_template("login.html")
username = session["username"]
file_delete = "profiles/%s/reports/%s" % (username,filename)
os.remove(file_delete)
files_list = os.listdir('... | 97b8b3b6b68db82d02a7ee6411ccfd43757409b7 | 66,407 |
def get_repos():
"""
Gets a list of repositories on the strands account
Return list of dictionaries
"""
return get_list('https://api.github.com/orgs/strands-project/repos')
# r = requests.get('https://api.github.com/orgs/strands-project/repos',auth=auth)
# if(r.ok):
# repos = json.lo... | 547fa9742cf986bfe103eac8cb7235a6c58247cc | 66,408 |
def get_video_duration(video_file):
"""Get video duration in seconds"""
return float(FFProbe(video_file).video[0].duration) | 75d5ac2a2f3b73880317c52f2f26cf797f832ce6 | 66,409 |
def classStatus(classes):
"""Determines the class status of the student based on credits.
:param dict classes:
The class information. Format:
classes = {className: {"grade": grade, "credits",
numCredits}}
:return:
The status of the student.
:rtype: str
"""
... | e629701553780665820c5532bd42797332c52ed0 | 66,410 |
def IsCorrectFuzzyNumberValue(value):
"""
All operations in fuzzy logic are executed with numbers in interval [0, 1].
"""
if IsNumber(value):
return (0. <= value) and (value <= 1.)
else:
print('{} not a real number in [0, 1], type = {}'.format(str(value), type(value)))
retur... | 40d39b5884daef46eafe2136d1a4b1ebbd38099e | 66,411 |
import requests
import regex
def get_available_airspaces():
"""
Gets and returns all available airspaces and their sizes from openaip
"""
try:
directory = requests.get(_airspace_url, timeout=5)
if directory.status_code == 404:
return _airspace_cache
airspaces = rege... | f464e853c47ed617c2f64b41b4a9f60a100b24b2 | 66,412 |
import torch
def bmtm(mat1, mat2):
"""batch matrix transpose matrix product"""
return torch.einsum("bji, bjk -> bik", mat1, mat2) | 9c00e371f4180da67b09be8e2cf35c3bab0785e3 | 66,413 |
def getdatasetnames():
""" retrieve the shortnames of all the datasets """
qset = Datasets.objects.all().values_list('datasetname', flat=True).order_by('id')
lst = list(qset)
return lst | 44359deff375c2c4525c3898ff7140c92bdfc4cc | 66,414 |
def get_residue_ranges(numbers):
"""Given a list of integers, creates a list of ranges with the consecutive numbers found in the list.
Parameters
----------
numbers: list
A list of integers
Returns
------
list
A list with the ranges of consecutive numbers found in the list
... | 0f263ee265574e64bec655ec2b5f35fdef2cf8af | 66,415 |
import re
def get_geometry_from_file_pdb(file_name, read_multiple=False):
"""
Reads a Conquest formatted file and the geometry of all structures in it
:param file_name: file name
:param read_multiple: read multiple files if available
:return: list of Geometry objects
"""
file_txt = open(f... | 61866d353e6d43a7f78e1a72316d916b258b4a8e | 66,416 |
import locale
import logging
def run():
"""Run atomic-reactor."""
locale.setlocale(locale.LC_ALL, '')
logging.captureWarnings(True)
setup_introspection_signal_handler()
args = parser.parse_args()
task = args.pop("func")
task_args = _process_global_args(args)
return task(task_args) | ad75d3cdf2e26d435c0768914130e01a7fcf1fed | 66,417 |
def instance_get_host(instance):
"""
Retrieve the host the instance is located on
"""
return instance['OS-EXT-SRV-ATTR:host'] | 0fef8cdf9e2ba7ac26e8a1ef2b2a1786cbe73d9d | 66,418 |
def get_ozone_conc(lat, lon, timestamp):
"""
Returns the ozone contents in matm-cm for the given latitude/longitude
and timestamp (provided as either a datetime object or a string in any
sensible format - I strongly recommend using an ISO 8601 format of
yyyy-mm-dd) according to van Heuklon's Ozone m... | 014b858fa7a8e4e594a10c44a004d46c6b7f575f | 66,419 |
def wavedecn(data, wavelet, mode='symmetric', level=None, axes=None):
"""
Multilevel nD Discrete Wavelet Transform.
Parameters
----------
data : ndarray
nD input data
wavelet : Wavelet object or name string, or tuple of wavelets
Wavelet to use. This can also be a tuple containi... | 88a77363c19839453aea7aae8402de18dfff7ea4 | 66,420 |
def instance_type_purge(context, name):
""" Removes specific instance_type from DB
Usually instance_type_destroy should be used
"""
session = get_session()
instance_type_ref = session.query(models.InstanceTypes).\
filter_by(name=name)
records = instance_... | 124d630b43b484d19532863e6ea786fc35a7c5e9 | 66,421 |
from datetime import datetime
def get_bbox_and_stat(scan_lst,
labels_lst,
obstacle_lst,
pipeline,
write_path=None,
OBB=False,
write_seg_id=False,
detailed=False,
... | 3823ebb670711ecd4f9194e400ef8a1d69f2269c | 66,422 |
from typing import Optional
def ceiling(node: NodeInput, name: Optional[str] = None) -> Node:
"""Return node which applies ceiling to the input node element-wise.
@param node: The node providing data to ceiling operation.
@param name: Optional name for output node.
@return The node performing element... | 0f258acc15fa47c053ed120c4502474540ca9d89 | 66,423 |
import random
def random_combination_with_replacement(iterable, r):
"""Random selection from itertools.combination_with_replacement(iterable, r)."""
pool = tuple(iterable)
n = len(pool)
indices = sorted(random.choices(range(n), k=r))
return tuple(pool[i] for i in indices) | ead7962804e63edaed82b39d10ee276022cd131f | 66,424 |
def cartesian_smoothing(ijk,data,sigma):
"""
Smoothing data on a(n uncomplete) cartesian grid
Parameters
----------
ijk : array od shape(nvox,3) list of the positions
it is typically returned by (array(np.where())).T
data :array of shape (ijk.shape[0],d) where d is the datas dimension
da... | d6510d9ef22106b10b2d8b20e2936a1ac1ea2566 | 66,425 |
import csv
def loadcsv(filename):
"""
Reads an input CSV file.
Args:
filename (str): input file path.
Returns:
List containing all rows from the CSV file without headers.
"""
with open(filename, "r", encoding="utf-8") as f:
return list(filter(None, list(csv.reader(f)... | 442d0fdf7bcc160e98c83d7c848ec9477cf757fe | 66,426 |
from typing import Dict
import re
def apply_list_replace(input_str: str, replacements: Dict[str, str]) -> str:
"""
Apply a series of replacement on the input.
:param input_str: the string to be modified
:param replacements: a Dict regex -> replacement. Each item will be passed to re.sub()
:re... | 287e1a7763e7f56719adf566358c62156bcf668c | 66,427 |
def get_subject_name_from_ics_event_category(full_subject_name: str) -> str:
"""This function gets subject name from the categories in ics event
Args:
full_subject_name (str): Full subject name with format XXX_YYY_ZZZ
Return:
subject_name (str): Subject name
"""
full_subject_name_l... | 89af99b51d3cbe5193b5d22576963f27e43837e5 | 66,428 |
def line_search_wolfe2(f, myfprime, xk, pk, gfk=None, old_fval=None,
old_old_fval=None, args=(), c1=1e-4, c2=0.9, amax=None,
extra_condition=None, maxiter=10):
"""Find alpha that satisfies strong Wolfe conditions.
Parameters
----------
f : callable f(x,*arg... | 581484562c476ef096c753af449c6d0d338b5cda | 66,429 |
def rgb(duration=250, brightness=100, sleep=3000):
"""
Color changes from red to green to blue.
:param int duration: The duration to fade to next color, in milliseconds.
:param int brightness: The brightness of the transition.
:param int sleep: The time to sleep between colors, in milliseconds
... | 6392ade61c59ca1c41ae3b53c0e4516ef9c1d57b | 66,430 |
def overlappingDates(date_set1, date_set2):
"""
date_set1: (tuple) a tuple with the start date and end date
date_set2: (tuple) a tuple with the start date and end date
"""
# find recent date
if date_set1[0] > date_set2[0]:
start_date = date_set1[0]
else:
start_date = date_set... | 01e0a6f28b8e8780a1d347f5a8864887965d4a56 | 66,431 |
def use_middleware_script(container_type):
"""
Should the pilot use a script for the stage-in/out?
Check the container_type (from queuedata) if 'middleware' is set to 'container' or 'bash'.
:param container_type: container type (string).
:return: Boolean (True if middleware should be containerised)... | 74f93a0952bdd81e8b3c604e17082f86bb3ff93b | 66,432 |
def _rewrite_collection_links(document):
"""Rewrite Eve HATEOAS-style "_links" to JSON-LD for a collection.
Also rewrites links for items in the collection."""
links = document.get('_links')
assert links is not None, 'internal error'
# Eve generates RFC 5988 link relations ("next", "prev", etc.)
... | 99b218cce99e10772ed502288574553a19f55685 | 66,433 |
import os
import logging
from sys import flags
def run(flags_obj, datasets_override=None, strategy_override=None):
"""Run MNIST model training and eval loop using native Keras APIs.
Args:
flags_obj: An object containing parsed flag values.
datasets_override: A pair of `tf.data.Dataset` objects to train t... | 72a7996bbede940c4562dfd235903df4c2e4a8f6 | 66,434 |
def remove_events(all_time,
all_flux,
events,
width_factor=1.0,
include_empty_segments=True):
"""Removes events from a light curve.
This function accepts either a single-segment or piecewise-defined light
curve (e.g. one that is split by qua... | 9b2900d70cab8e68c4cf394ccbfb69cd8b44c526 | 66,435 |
def convolutional_model(input_shape):
"""
Implements the forward propagation for the model:
CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> DENSE
Note that for simplicity and grading purposes, you'll hard-code some values
such as the stride and kernel (filter) sizes.
N... | b904087a6645309247f19fcc45ba67402f3affd6 | 66,436 |
def softmax_column(Z):
"""Softmax function."""
exp_values = np.exp(Z)
return exp_values / np.sum(exp_values, axis=0, keepdims=True) | ed7aba6a94da589f9cd9aa32541fa6522e2f41ba | 66,437 |
from typing import Tuple
import traceback
def detect_active_window() -> Tuple[str, str]:
"""Get class and title of active window.
Identify the OS and display server and pick the method accordingly.
Returns:
Tuple[str, str]: [description]
"""
wm_class = window_title = ""
try:
... | acf57c56745d3d12d9464bba63f182810e7ecce7 | 66,438 |
def strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ("y", "ye... | f6fbce54f7fe4bea906cc51d398d95cf2dd699e8 | 66,439 |
import warnings
def is_domain_malicious(subject: str, **kwargs) -> bool:
"""
Checks if the given domain is malicious.
.. warning::
This method may be removed in the future.
It is still available for convenience.
Please consider the following alternative example:
::
... | a525e881b00c61d4896ef07b6a8bb1a17ea023a5 | 66,440 |
from typing import Union
def serialize_attribute_value(value: Union[str, int, float, bool, None]):
"""
Serialize a value to be stored in a Magento attribute.
"""
if isinstance(value, bool):
return "1" if value else "0"
elif value is None:
return ""
return str(value) | a9d5b4f6d507672b594eb1c88d4d86c9bfc6bc11 | 66,441 |
def _str_decode(my_string):
"""Parse the string for objects and indexes and return a list.
Args:
my_string: A string object
Returns:
List of strings with strings resresenting mrsimulator objects and indexes.
Example:
>>> string = 'sys_0_site_0_isotropic_chemical_shift'
... | ea06f61a1f8b4b013a1e00f25e9de72721977e5b | 66,442 |
import torch
def get_activation(activation):
"""Given a string returns a `torch.nn.modules.activation`."""
if not isinstance(activation, str):
return activation
mapper = {
"leaky_relu": nn.LeakyReLU(),
"relu": nn.ReLU(),
"selu": nn.SELU(),
"tanh": nn.Tanh(),
... | b96544a56ff73d1ad03944f97e24859069ea000b | 66,443 |
def hidden_value(context=None, id='', value=''):
"""Generates a hidden input with the given id and value."""
return _return_or_write(context, '<input type="hidden" id="' + id + '" value="' + value + '">') | 8c5f96e8cc2c17d90ad55f673c0ccc654faafd86 | 66,444 |
def xcache_activation_command(jobid):
"""
Return the xcache service activation command.
:param jobid: PanDA job id to guarantee that xcache process is unique (int).
:return: xcache command (string).
"""
# a successful startup will set ALRB_XCACHE_PROXY and ALRB_XCACHE_PROXY_REMOTE
# so any... | 86050072785185cdcc7adcf59eafe930a6d30105 | 66,445 |
from operator import index
def times_householder_vector(A, H, j):
"""
Computes A * v_j where v_j is the j'th Householder vector in H.
Parameters
----------
A: k x M matrix to multiply by v_j.
H: M x k matrix of Householder reflectors.
j: The column of H from which to extract v_j.
Ret... | a649317b3252badfca61563bfd605804d1216b71 | 66,446 |
def mk_uni_port_num(intf_id, onu_id):
"""
Create a unique virtual UNI port number based up on PON and ONU ID
:param intf_id:
:param onu_id: (int) ONU ID (0..max)
:return: (int) UNI Port number
"""
return intf_id << 11 | onu_id << 4 | 3d348b9d6dc40f54d6f3667a8a5310a3d52b3d5d | 66,447 |
def CalculateNormalizedMoreauBrotoAutoAvFlexibility(ProteinSequence):
"""
####################################################################################
Calculte the NormalizedMoreauBorto Autocorrelation descriptors based on
AvFlexibility.
Usage:
result=CalculateNormalizedMoreauBrotoAutoAvFlexibility... | b32d741c01839feed9f76f3aca75c7c794a415fb | 66,448 |
import pickle
import pprint
def litmus_main(args):
"""
Prepare predictive model
"""
assert(args.load_state or args.scores_file)
if args.load_state:
# Load trained model + metadata
with open(args.load_state, "rb") as pkl_f:
model, featurizer, langs_list, langs_pivot... | c1bd857b71d4d2bedfa1049da5f15c236bd109db | 66,449 |
def token_to_eth_output(token_amount_to_sell: int) -> "Wei":
""" Constant Price Model implementation with fee. """
input_amount_with_fee = token_amount_to_sell * FEE_MODIFIER
numerator = input_amount_with_fee * ETH_RESERVE
denominator = TOKEN_RESERVE * 1000 + input_amount_with_fee
return Wei(numerat... | e3b88df5165282cf0e608d62864ce5122236fc1a | 66,450 |
def complex_to_real(X):
"""
WRITEME
Parameters
----------
X : list of complex vectors
Notes
-----
This function assumes X as 2D
"""
new_X = []
for i in range(len(X)):
x = X[i]
new_x = np.concatenate([np.real(x), np.imag(x)])
new_X.append(new_x)
ret... | 33394d089776487e8944b140789624f15fd0df70 | 66,451 |
import json
def read_json_single(json_file, allMandatoryExposureKeys):
"""Reads json manifest file.
"""
if miscutils.fwdebug_check(3, 'FMUTILS_DEBUG'):
miscutils.fwdebug_print("reading file %s" % json_file)
allExposures = []
my_header = {}
numseq = {}
all_exposures = dict()
w... | a43b1990c259f8345b50da0e75decd8cdaa75af1 | 66,452 |
def num_particles(fs):
"""Mean-field occupation."""
return np.sum(n * fs[n] * fs[n] for n in range(len(fs))) | 91abf67da32b81b36b6d3e9468b87f4516c58538 | 66,453 |
from pathlib import Path
def find_files(base_root: Path):
"""
Search the given base directory for the actual dataset root.
This makes it a little easier for the dataset manager
:param base_root:
:return:
"""
# These are folders we expect within the dataset folder structure. If we hit them,... | d54ab18fb1bc7b49a7bf486b11d020a5d17e3cdb | 66,454 |
def mean_abs_percentage_error(y_true, y_pred):
"""
This function calculates MAPE
:param y_true: list of real numbers, true values
:param y_pred: list of real numbers, predicted values
:return: mean absolute percentage error
"""
# initialize error at 0
error = 0
# loop over all sample... | 7f08e717600e2d1301e951765524b95d3240368d | 66,455 |
def cpuprofile(func):
"""Decorator - profile cpu usage
"""
def wrapper(*args, **kwargs):
if PROFILE:
profiler = Profiler()
profiler.start()
func(*args, **kwargs)
if PROFILE:
profiler.stop()
print(profiler.output_text(unicode=False, colo... | aba4a5703484bbd7e69066336a91df9c8b89492d | 66,456 |
def asdict(inst, recurse=True, filter=None, dict_factory=dict):
"""
Return the ``attrs`` attribute values of *i* as a dict. Optionally recurse
into other ``attrs``-decorated classes.
:param inst: Instance of a ``attrs``-decorated class.
:param bool recurse: Recurse into classes that are also
... | f79aaaf4cf34fb21521c2d1e35186dfbe63fc67d | 66,457 |
def summult(list1, list2):
"""
Multiplies elements in list1 and list2, element by element, and
returns the sum of all resulting multiplications. Must provide equal
length lists.
Usage: lsummult(list1,list2)
"""
if len(list1) != len(list2):
raise ValueError("Lists not equal length in summult.")
s... | 2b1c4543867998c8edf372c2388df13ce07df910 | 66,458 |
import logging
def insert_into_staging_table(**kwargs):
"""
reads teh temp file and inserts into postgres using
python for better error handling.
"""
# connect to db
connection_id = "postgres_default" # this is the name in airflow variables
dbhook = PostgresHook(postgres_conn_id=connectio... | 162231f1e18c437865dc017e28efbaf480886519 | 66,459 |
def nwchem_psivar_list():
"""Return a dict with keys of most NWChem methods and values of dicts
with the PSI Variables returned by those methods. Used by cbs()
wrapper to avoid unnecessary computations in compound methods.
Result is appended to ``VARH``.
"""
VARH = {}
VARH['nwc-scf'... | a2baf3e98c10363722e162a7d82a86bc57ea397a | 66,460 |
import argparse
def create_parser():
"""
Creates the argparse parser with all the arguments.
"""
parser = argparse.ArgumentParser(
description='CLI for testing packet movement through pipelined,\
using RYU REST API & Scapy',
formatter_class=argparse.ArgumentDefault... | a1a846ecc1d141a218995404116f7d47446191ef | 66,461 |
def CRPS_compute(CRPS):
"""Compute the averaged values from the given CRPS object.
Parameters
----------
CRPS : dict
A CRPS object created with CRPS_init.
Returns
-------
out : float
The computed CRPS.
"""
return 1.0*CRPS["CRPS_sum"] / CRPS["n"] | 378dee32c7a9c7a88784438c228f21ae3b6f24f3 | 66,462 |
def cim_to_glm_name(prefix, cim_name):
"""Helper to manage the fact that we need to prefix our object names
to make them match what's in the GridLAB-D model.
Also, if the given name is NOT surrounded by quotes, it will be.
It would appear that all the 'name' attributes in the GridLAB-D
models from ... | aedf44eccff2237b99458a59f2de3b1f2775c80b | 66,463 |
import argparse
from typing import Optional
def commit_changes(args: argparse.Namespace, working_repo: git.Repo) -> Optional[git.objects.commit.Commit]:
"""Add local changes and commit them, if any."""
working_repo.index.add('*')
if working_repo.head.is_valid() and not working_repo.index.diff(working_repo... | 2618f1a683a1f61999c3ca2db27b8d219dadef00 | 66,464 |
import os
from urllib import request as url
def getPDBFile(path):
"""
Obtain a PDB file. First check the path given on the command
line - if that file is not available, obtain the file from the
PDB webserver at http://www.rcsb.org/pdb/ .
Parameters
path: Name of PDB ... | 44d70aa7330be8256a89d0e1183111bcf59f3e91 | 66,465 |
import html
def side_navbar(links):
"""A navigation bar for switching between dashboards."""
return html.Nav(
html.Ul(links, className="moj-side-navigation__list", id="navigation-items"),
className="moj-side-navigation",
role="navigation",
) | 93f6e2036f09b4f4dcfc44cfd3956d3c62eb5e82 | 66,466 |
def tz_syntax(string):
""" returns 'good' and clean reply if reply to adjust the current time zone is fine """
signs = ['+','-']
cond = all(len(s) <= 2 for s in string[1:].replace(',','.').split('.'))
if string[0] in signs and cond == True or string == '0':
return 'good', string.replace(',','.').strip()
else:
... | b727cc1459999410c91adc8dce5683e2fb583db3 | 66,467 |
def GPR_MODEL(Params,Lambda_Inv,Xtrain,Ytrain,alpha_,Xtest):
""" Implementation of a GP mean (mu) predictor
mu = Ktrans \dot alpha_
inputs:
* Params, Lambda_Inv: Trained kernel parameters.
* alpha_: Precomputed product of (Kself+\sigma*I)^{-1} \dot Ytrain.
... | 56a94ab52f4f335e70cf4f952aeacf784c332ce1 | 66,468 |
def dispatch_to_container(containers, current_highlight, key):
"""Dispatch the key to container and handle highlighting.
If the LEFT or RIGHT key is pressed, we switch the highlighting
to the next container.
"""
if key in [KEY_RIGHT]:
next_true = False
UpdateHeuristics.force_unupda... | d4e2782fe190e43bb306ffcd1fd615c020653e37 | 66,469 |
def make_cct_embedded(image_db=None, bbox_db=None):
"""
Takes in path to the COCO Camera Trap format jsons for images (species labels) and/or
bboxes (animal/human/vehicle) labels and embed the class names and annotations into the image entries.
Since IndexedJsonDb() can take either a path or a loaded j... | 53863e200e444b01ee70b697995baadb2a270840 | 66,470 |
def generate_typedef(typedef: Typedef, typenames: TypeNameMap, readlevel: UserLevel, writelevel: UserLevel, ul: UserLevel, use_async: bool) -> str:
"""Generates a Python class for a system model typedef.
Args:
typedef (Typedef): A DeCoP typedef.
typenames (TypeNameMap): A list of type name subs... | 38617088edbdb5dcde0d0f5e0c743b4b4da635c6 | 66,471 |
def parse_html_table(table):
"""
Parse table and filter out rows having child elements ('div') having a class attribute 'pCellBodyR' containing data
"""
trs = table.find_all('tr')
print(len(trs))
my_table = []
for tr in trs:
testRow = etree.HTML(str(tr))
# Catch row containi... | 336676bc0af2542d4777f3d4769a18e76165fd14 | 66,472 |
def cm2inch(*tupl):
"""Converts inches into mm for figures.
"""
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl) | f787126814b60e2215fc92cb78f0bc8d8400c601 | 66,473 |
def batchnorm_forward(x, gamma, beta, bn_param):
"""
Forward pass for batch normalization.
During training the sample mean and (uncorrected) sample variance are
computed from minibatch statistics and used to normalize the incoming data.
During training we also keep an exponentially decaying running... | 866b54c722abe446a1dbc8eacbbbd9a46fc530d5 | 66,474 |
def form_or_dict_value(context, dict, key_name):
"""Outputs the value of the dict[key_name] unless request.POST contains the data
for the item which then overrides the dictionary's value.
This both fixes problems with normal django templating which will not retrieve
any keys starting with an underscore and it... | 74c6a05e9d12ffdb25ba045dc32de4d0df08a0c5 | 66,475 |
from matplotlib.mlab import griddata
def grid(x, y, z, resX=500, resY=500):
"""
Converts 3 column data to matplotlib grid
"""
#from scipy.interpolate import griddata
xi = np.linspace(min(x), max(x), resX)
yi = np.linspace(min(y), max(y), resY)
# mlab version
Z = griddata(x, y, z, xi,... | 116e3cfbd72abccd3c02a9a4bd93778c7ce190f2 | 66,476 |
def edge(u :int, v :int, g :Graph) -> tuple:
"""
Retrieve the edge from a vertex u to vertex v.
Args:
u: The source of the edge.
v: The target of the edge.
g: The Graph.
Returns:
(e, True) if it exists a single edge from u to v,
(None, False) otherwise.
"""
... | 48bb2453b039008d4ec7d758af0e047166ca2679 | 66,477 |
def fun_dfun(obj, space, d):
"""
Computes the posterior predictive and posterior predictive gradients of the
provided GPyOpt object.
Parameters
----------
obj: GPyOpt object
The GPyOpt object with a surrogate probabilistic model.
space: GPyOpt space
A GPyOpt object that cont... | 14c39d96dc810d8078ff2dd602fc6216214e8d3f | 66,478 |
from operator import matmul
def get_hidden_at(known_T, known_A, known_B, LAYER, x, prior=True):
"""
Get the hidden value for an input using the known transform and known A.
This function IS NOT CHEATING.
"""
if prior:
which_activation = [y for x in known_T.get_hidden_layers(x) for y in x]
... | aa901c156b457442ae812074e775961f87b62d5c | 66,479 |
def get_bases():
"""Returns an ordered queryset of Airstrips which are bases"""
return Airstrip.objects.filter(is_base=True).order_by('ident') | 89bb8e090b034dfe3291a71d242e3acc8078abd0 | 66,480 |
def fidelity_promo(order):
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0 | 62d8010a59a26a86c190b231568eb5b164380ada | 66,481 |
import scipy
def get_normalized_dispersion(mat_mean, mat_var, nbins=20):
""" Calculates the normalized dispersion. The dispersion is calculated for each feature
and then normalized to see how its dispersion compares to samples that had a
similar mean value.
"""
# See equation in https://a... | e7ad0883d13044e0627e84851a8cfb04a197982e | 66,482 |
def deflection(xyz1, xyz2, xyz3):
"""
Calculate deflection angle(alpha)
"""
v1 = xyz1 - xyz2
v2 = xyz3 - xyz2
alpha = np.arccos(np.dot(v1, v2) / (np.sqrt(v1[0]**2 + v1[1]**2 + v1[2]**2) * (
np.sqrt(v2[0]**2 + v2[1]**2 + v2[2]**2)))) * 180 / np.pi
return alpha | bee601e353529a56a11ebc73a788dc063aade4e7 | 66,483 |
def wave_filter(x, wavelet = 'haar', maxsize = 2**14, minsize = 2**1):
"""
Filter a time series by applying a orthogonal wavelet transform
and removing all scales with more than maxsize coeffs, or less than minsize coeffs
"""
WT = pywt.wavedec(x, wavelet=wavelet)
sizes = [len(x) for x in WT]
... | 446d1031b266db97c20c34565bdfda642b814eac | 66,484 |
def parse_lines(parameters):
"""
Separates the parameters from their tied/fixed/special
characters.
Parameters
----------
parameters : list
A list of rows (each a tuple) containing the line parameters from an
f26 file.
Returns
-------
lines : `astropy.table.Table`
... | 26046c9e732640ebc687f42440cf2b28869e68c0 | 66,485 |
def sliver_overall_score_for_one_couple(score):
"""
Computes overall score:
"""
score_list = list(score.values())
overall_score = np.average(np.array(score_list))
return overall_score | e64b10c8180e21ab718b52c4fd1dc60144e504b2 | 66,486 |
def partition_opm_license_list(df):
"""This function partitions the OPM Granted Licenses list by license type, storing the result in a Python dictionary.
Parameters
----------
df (DataFrame): OPM Granted Licenses list
Returns
-------
license_list_dict (dict): OPM Granted Licenses list part... | 4f9bab49385e23732e5e56e3f0dbf8762eb05438 | 66,487 |
import os
import codecs
def homepage(request):
"""The view of the homepage, generated from a Markdown file.
The content is taken from a Markdown file, which is always located at `home.md` of the `cantus-staticpages` repository.
"""
markdown_file = '../cantus-staticpages/content/home.m... | c88b7508b8f1ca1cc956466151b6e65441189252 | 66,488 |
import json
async def processing_request(web, request, token, post=False):
"""Функция "processing_request" - обрабатывает текущий запрос на Веб-сервер от клиента."""
route_path = request.path
headers = request.headers
query_args = request.rel_url.query
if route_path is not None or route_path != '... | 061463aae84add2c52561ef4ab2eb38a050b15ed | 66,489 |
def ShowTaskIPC(cmd_args=None):
""" Routine to print IPC summary of given task
Usage: showtaskipc <address of task>
"""
if not cmd_args:
print "No arguments passed"
print ShowTaskIPC.__doc__
return False
tval = kern.GetValueFromAddress(cmd_args[0], 'task *')
if not ... | c3eaf43c5f0184231465df6efc188fb49bbdeda7 | 66,490 |
def retrive_var(scopes):
"""
Retrieves variables from different scopes in the graph
:param scopes: the scopes to search in
:return: list of variables
"""
var = []
for scope in scopes:
var += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,
scope=sc... | dc7a209e81598e1869ce9862342f68b99562c9eb | 66,491 |
def intToIp(ip, version):
"""Transform an integer string into an IP address."""
# just to be sure and hoping for Python 2.2
ip = int(ip)
if ip < 0:
raise ValueError("IPs can't be negative: %d" % (ip))
ret = ""
if version == 4:
if ip > MAX_IPV4_ADDRESS:
raise ValueE... | e5709eae93546b18630582caa8a056555867817b | 66,492 |
from typing import Tuple
def _find_model_temperature_range(model_type: str) -> Tuple[float, float]:
"""Returns temperature range around 0C for given model type."""
if "gdas1" in model_type.lower():
return -8, 6
return -4, 3 | bebfc0b440b2c13640047dc1ecb8b94d765f63f9 | 66,493 |
import requests
def vagrantup_check(os_name: str, version: str) -> bool:
"""
Checks whether an OS is on version :version on the vagrantup box.
Returns:
(bool): is OS updated?
"""
# Fetch url & parse HTML
r = requests.get(VAGRANTUP_BOX_URL)
document = lxml.html.fromstring(r.text)
... | 7802fbcc614da4539558f6c47178fb0e075613d9 | 66,494 |
import sqlite3
def get_data_from_db():
"""Returns a list of article strings and their
corresponding labels as two arrays.
Connects to the article sqlite db, who's path
is specified at the top of the program with
ARTICLE_TEXT_DB_PATH.
Labels are the "right-score" of the article.
... | eab20135ebddf22e349ba15d601fe220f03ea6c2 | 66,495 |
def getClampDeviceNames(protoDH):
"""
get the Clamp devices used in the current protocol
:param protoDH: handle to current protocol
:return clampDeviceNames: The names of the clamp devices used in this protocol, or None if no devices
"""
if protoDH.name()[-8:] == 'DS_Store': ## OS X filesystem ... | 0df7ffbebe7262eba7c9d8396015a2e396ebe304 | 66,496 |
def _get_event_result(query):
"""
Perform the get_event query and return the serialized results. This is
its own function to enable caching to work.
Returns: (string, found)
"""
db = get_db()
event = db['events'].find_one(
query,
{'_id': 0, 'coordinates': 0, 'categorymainsub'... | a362ed569995f26b451fd0ebc1a1a4c975acb396 | 66,497 |
def logs():
"""
Copy over logs
"""
stack_uuid = request.args['uuid']
to_dir = request.args['dir']
return docker.copy_logs(stack_uuid, to_dir) | a08fb83b0f2cbcfa2cc8ab0fd88a3e5b0186e477 | 66,498 |
def image_distortion_loss(y, y_hat):
""" MSE (per image pair) """
return tf.reduce_mean(tf.math.pow(y - y_hat, 2), axis=[1, 2, 3]) | 56ae39c7a5beb1ba3b65cfdd58269bb03e8e40b5 | 66,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.