content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def visualize_cut_plane(
cut_plane, ax=None, minSpeed=None, maxSpeed=None, cmap="coolwarm", levels=None, title = None
):
"""
Generate pseudocolor mesh plot of the cut_plane.
Args:
cut_plane (:py:class:`~.tools.cut_plane.CutPlane`): 2D
plane through wind plant.
ax (:py:class:... | 75,800 |
def sendMessage(client, msg, sender, recipient):
"""Send message via text.
Parameters
----------
client : obj
twilio client.
msg : str
message to send via text.
sender: str
The source phone number for SMS/MMS
formatted with a '+' and country code ... | 75,801 |
def train(train_job_params: Dict[str, Any],
output_dir: str,
return_dict: Dict[str, float] = None,
progress_dict: Dict[str, float] = None,
env_tag: str = None):
"""Train."""
del env_tag
return_dict = return_dict or {}
progress_dict = progress_dict or {}
logger_utils.sav... | 75,802 |
def get_multistage_merge_pipeline(
alias,
vcf_files,
processing_dir,
chunk_size,
bcftools_binary,
process_name,
process_command,
stage=0,
prev_stage_processes=None,
pipeline=None
):
"""
Generate Nextflow pipeline for multi-stage VCF... | 75,803 |
def tide_after_href(path):
"""Wrap href paths with 'app:/' and 'index.html' so all links point to
static files to make them work in the TideSDK app when we run python
application.py -f.
This way paths like '/view-location/123/' turn into
'app://view-location/123/index.html'
"""
if app.confi... | 75,804 |
def main(main_view: MainView):
"""
controller.tiny_ticker.main
Gathers command-line args, loads feeds into the model, and initiates the title loop.
Arguments:
mainView -- the gui view which displays feed articles
"""
tt_logger.debug('main')
urls = arguments.url
feed_manager =... | 75,805 |
def guess_game_name_from_clone_arg(clone_arg: str) -> str:
"""Guess the name of the game from the --clone argument.
:arg clone_arg: The str given by the user for the clone argument.
Usually a git link as `https://github.com/ScienceGamez/world-3.git`..
"""
if "/" in clone_arg:
# If u... | 75,806 |
def nativeIcon128(self):
"""
TOWRITE
"""
self.icon128() | 75,807 |
def midpoint_point_point_xy_numba(u, v):
""" Compute the midpoint of two points lying in the XY-plane.
Parameters
----------
u : array
XY(Z) coordinates of the first point in the XY plane.
v : array
XY(Z) coordinates of the second point in the XY plane.
Returns
-------
... | 75,808 |
def extract_training_glucose(data):
"""
Extract the input variables (x), the time (t), and the objective (y) from the data samples.
WARNING : need to be modified to include additional data, or override the function within the models
:param data:
:return:
"""
... | 75,809 |
def _build_image_with_python_client(client: docker.DockerClient, path: str,
image_tag: str, dockerfile: str) -> None:
"""Builds a Docker image by calling the Docker Python client."""
repository, tag = docker_utils.parse_repository_tag(image_tag)
if not tag:
tag = 'latest'
... | 75,810 |
def get_currencies(codes):
""" Returns a list of (code, translation) tuples for codes """
currencies = [(code, get_display(code)) for code in codes]
return currencies | 75,811 |
def load_from_module(extension_point, module_name, extension_function_name='__extend__', propagate_exceptions=False):
"""Load an ExtensionPoint from a Python module.
This imports a module and scans it for immediate sub-modules, i.e. those modules nested directly under the first
module. It imports each sub-... | 75,812 |
def is_hsts_preloaded(domain):
"""
Whether a domain is contained in Chrome's HSTS preload list.
If preload_list is None, the caches have not been initialized, so do that.
"""
if preload_list is None:
logging.error('`preload_list` has not yet been initialized!')
raise RuntimeError(
... | 75,813 |
def FOEEWMO(t, **kwargs):
"""from IFS Documentation Cycle 31,
Teten's formula for water only
after Tiedtke 1993 (cloud and large-scale precipitation scheme)
Uses the Tetens's formula
Based on Buck 1981 & Alduchov and Eskridge 1996
Args:
t: air temperature K
Returns:
es : sa... | 75,814 |
def HeadPoseImage(path: str) -> Dataset:
"""`Head Pose Image <http://crowley-coutaz.fr\
/Head%20Pose%20Image%20Database.html>`_ dataset.
The file structure should be like::
<path>
Person01/
person01100-90+0.jpg
person01100-90+0.txt
person... | 75,815 |
def partition(arr: list, start: int, end: int) -> int:
"""
Choosing last element as pivot
"""
i, j = start - 1, start
while j < end:
if arr[j] < arr[end]:
i += 1
arr[i], arr[j] = arr[j], arr[i]
j += 1
i += 1
arr[i], arr[end] = arr[end], arr[i]
re... | 75,816 |
def generate_csv(fname, fields, trait_list):
""" Generate CSV called fname with fields and trait_list """
csv = open(fname, 'w')
csv.write(','.join(map(str, fields)) + '\n')
csv.write(','.join(map(str, trait_list)) + '\n')
csv.close()
return fname | 75,817 |
def check_gae():
"""Checks if Google App Engine is present on system"""
return bool(find_gae_path()), 'Google App Engine SDK' | 75,818 |
def test_can_create_color_pairs(
rf: float, gf: float, bf: float, rb: float, gb: float, bb: float
):
"""Test that color pairs can be created."""
foreground = RGB(rf, gf, bf)
background = RGB(rb, gb, bb)
color_pair = ColorPair(foreground, background)
assert color_pair.foreground == foreground
... | 75,819 |
def default() -> dict:
"""The default hyperparameters.
It will have a version key and a list of candidate models.
Each model has its own search space inside.
"""
ret = {
'version': 1,
'models': {
'BertForTextPredictionBasic': {
'search_space': {
... | 75,820 |
def load_dataset(key):
""" Function to load datasets included in the chainladder package.
Arguments:
key: str
The name of the dataset, e.g. RAA, ABC, UKMotor, GenIns, etc.
Returns:
pandas.DataFrame of the loaded dataset.
"""
path = os.path.dirname(os.path.abspath(__fil... | 75,821 |
def get_port_options(system):
"""Lists serial ports
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of available serial ports
"""
sys_platform = system.get_sys_platform()
# For Windows Platform
if sys_platform == 'windows':
ports = ['C... | 75,822 |
def fit_phase(w, si=1, fmin=0, fmax=None, axis=-1):
"""
Performs a linear regression on the unwrapped phase of a wavelet to obtain a time-delay
:param w: wavelet (usually a cross-correlation)
:param si: sampling interval
:param fmin: sampling interval
:param fnax: sampling interval
:param ax... | 75,823 |
def count_threshold(x, threshold=10e-6):
""" count the number of above-threshold elements in an array """
return np.sum(x > threshold) | 75,824 |
def render_visible_viewport(panel, view):
# type: (sublime.View, sublime.View) -> None
"""Compute and draw a fancy scrollbar like region on the left...
... indicating the current viewport into that file or error(s) list.
"""
errors = persist.errors.get(view.buffer_id(), [])
if len(errors) > CON... | 75,825 |
def fit_lmk3d( lmk_3d, # input landmark 3d
model, # model
lmk_face_idx, lmk_b_coords, # landmark embedding
weights, # weights for the objectives
shape_num=300, expr_num=100, opt_options=None ):
... | 75,826 |
def is_alive():
"""
Checks if engine is running.
Returns:
bool: True if the engine is running and accepting commands, False otherwise
"""
## ---------------------------------------------------------------
cmd = dict()
cmd["type_"] = "is_alive"
cmd["name_"] = ""
s = s... | 75,827 |
def read_xml_no_ns(filename):
"""
read in the file or data, populating a lxml._elementTree object
stripping out namespaces
:param filename: filename representing a xml file or a string of xml data
:return: lxml._elementTree object or None
"""
parsed_xml = read_xml(filename)
if parsed_xm... | 75,828 |
def keep_type(value):
"""
Keep hook returned value type
:param value: Value to be returned
:return: Any
"""
return value | 75,829 |
def printwarning(text):
"""
Color and key word warning for print
"""
if (
read_config_level("SYSTEM", "messagelevel", "info") == "info"
or read_config_level("SYSTEM", "messagelevel", "info")
== "debug"
or read_config_level("SYSTEM", "messagelevel", "info")
== "war... | 75,830 |
def r2_score(y_true: np.array, y_score: np.array) -> float:
"""
Calculate the coefficient of determination (R^2) for a ground-truth prediction vector pair.
Args:
y_true (array-like): An N x 1 array of ground truth values.
y_score (array-like): An N x 1 array of predicted values.
Return... | 75,831 |
def test_fortify_python_available_valid(check_output_mock, fortify_tool_plugin):
"""Test that python_available is True if the relevant line is found."""
check_output_mock.side_effect = sideeffect_python_found
with tempfile.NamedTemporaryFile() as tmp_file:
assert fortify_tool_plugin._fortify_python_... | 75,832 |
def varType(row):
"""Variants should be decomposed, and normalized
using vt before applying this function"""
c1 = len(row['REF']) == len(row['ALT'])
c2 = ',' in row['REF']
c3 = ',' in row['ALT']
if c2 or c3:
return 'other'
if c1:
return 'snp'
else:
return 'indel' | 75,833 |
def shekel(x):
"""
Shekel: The modified fifth De Jong function, Equation (21) of [2]
minimum is f(x)=0.0 at x(-32,-32)
"""
A = [-32., -16., 0., 16., 32.]
a1 = A * 5
a2 = reduce(lambda x1,x2: x1+x2, [[c] * 5 for c in A])
x1,x2 = x
r = 0.0
for i in range(25):
r += 1.0/ (... | 75,834 |
def desitarget_nside():
"""Default HEALPix Nside for all target selection algorithms."""
nside = 64
return nside | 75,835 |
def get_best_hands_brute_force(board, hands):
""" get the index of the best holdem hand given a board
:param board: ([str]) list of 5 cards
:param hands: ([set(str)]) list of sets of 4 cards
:return: ([[int]]) indices of `hands` that makes the strongest holdem hand,
--> this is a list because i... | 75,836 |
def logsig_fn(phi,X):
"""
sigmoid function
static nonlinearity from Rabinowitz et al 2011
"""
a=phi[0] # baseline
b=phi[1] # asymptote
c=phi[2] # inflection point
d=phi[3] # slope
Y=a+b/(1+np.exp(-(X-c)/d))
return(Y) | 75,837 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up Abode light devices."""
bridge = hass.data[DOMAIN][entry.entry_id]
if not isinstance(bridge, Bridge):
_LOGGER.error(f"Invalid bridge. Got {bridge} for {entry.entry_id}")
devices = await bridge.get_devices()
lights = f... | 75,838 |
def get_table_9():
"""表 9 通風の利用に関する区分݈の通風の利用における相当換気回数 NV_l
Args:
Returns:
list: 表 9 通風の利用に関する区分݈の通風の利用における相当換気回数 NV_l
"""
table_9 = (0.0, 5.0, 20.0)
return table_9 | 75,839 |
def find_nodes(graph, query, data=False):
""" Iterator over all nodes matching the data query.
"""
return ((v, graph.nodes[v]) if data else v
for v in graph if query(graph.nodes[v])) | 75,840 |
def test_flag_jumps_for_one_column(timeseries_dataframe):
"""
Test provided strict behaves as expected for a single column.
"""
df = timeseries_dataframe
orig_cols = df.columns
expected = [0, 1, 1, 1, 1, 1, 1, 1, 1, 1]
# Exercise
df = df.flag_jumps(scale=dict(col1="absolute"), strict=Tr... | 75,841 |
def _SigninUIState(oobe):
"""Returns the signin ui state of the oobe. HIDDEN: 0, GAIA_SIGNIN: 1,
ACCOUNT_PICKER: 2, WRONG_HWID_WARNING: 3, MANAGED_USER_CREATION_FLOW: 4.
These values are in chrome/browser/resources/chromeos/login/display_manager.js
"""
return oobe.EvaluateJavaScript('''
loginHeader = docu... | 75,842 |
def script_overview():
"""
Endpoint serving the overview script
"""
return send_from_directory(
os.path.join(ui_config.CODE_DIR, 'js'),
'overview.js',
mimetype='application/javascript'
) | 75,843 |
def make_image(url, title=None, description=None):
"""Creates an image node
Args:
url (string): url to assign to image node
title (string, optional): assign a title to node on creation. Defaults to None.
description (string, optional): set image description on creation. Defaults to ... | 75,844 |
def get_plat_name():
"""获取所有平台ID与平台名的映射"""
plat_info = {}
res = bk.cc.get_plat_id()
for plat in res:
plat_id = int(plat['plat_id'])
plat_info[plat_id] = plat['plat_name']
return plat_info | 75,845 |
def cluster_staypoints(staypoints,
method='dbscan',
epsilon=100,
num_samples=1,
distance_matrix_metric=None,
agg_level='user'):
"""Clusters staypoints to get locations.
Parameters
---------... | 75,846 |
def word_count(df, new_col_name, col_with_lyrics):
"""
Count the number of words in a dataframe lyrics column, given a column name, process it, and save as new_col_name
Parameters
----------
df : dataframe
new_col_name : name of new column
col_with_lyric: column with lyrics
... | 75,847 |
def prepare_target(data, close_index=3, classes=6):
"""
Hello (=
uniform classes
"""
# TODO
# while const
classes = 6
data = np.array(data)
new_target = data[1:, close_index] / data[:-1, close_index]
new_target = np.insert(new_target, obj=0, values=[1.0])
n, bins = ... | 75,848 |
def create_fpl_storage_bucket():
"""Definition of a simple Cloud Storage bucket.
Documentation available here: https://cloud.google.com/storage/docs/reference/libraries
"""
storage_client = storage.Client()
try:
fpl_bucket = storage_client.create_bucket(main.FPL_BUCKET_NAME)
bucket_... | 75,849 |
def ccd_to_list(file_path: str) -> list:
"""Converts a .ccd file into a dict"""
file = open(file_path, 'r')
lines = file.readlines()
file.close()
data = []
for index, line in enumerate(lines):
try:
if line.startswith(' '):
data.append(float(line.split(' ')[... | 75,850 |
def add(a,b):
""" This function adds two numbers """
return a+b | 75,851 |
def reflective_pyramid(count=7):
"""
Draws a reflective pyramid
>>> reflective_pyramid(3)
*
***
*
>>> reflective_pyramid(5)
*
***
*****
***
*
"""
pyramid_list = []
base_matrix_list = [index*" " + "*"*(num) for index, num in enumerate(range(count, ... | 75,852 |
def get_SSH_forcing(boundary, date):
"""A function that returns the ssh forcing for the month of the date and
boundary indicated.
:arg str boundary: A string naming the boundary. e.g 'north' or 'west'
:arg str date: A string indicating the date of interest. e.g. '01-Dec-2006'.
The... | 75,853 |
def explain_instruction(bv, addr):
""" Callback for the menu item that passes the information to the GUI """
init_plugin(bv)
# Get the relevant information for this address
func = get_function_at(bv, addr)
instruction = inst_in_func(func, addr)
lifted_il_list = find_lifted_il(func, addr)
ll... | 75,854 |
def test_t_to_z():
"""Smoke test for transforms.t_to_z."""
t_arr = np.random.random(100)
z_arr = transforms.t_to_z(t_arr, dof=20)
assert z_arr.shape == t_arr.shape
t_arr2 = transforms.z_to_t(z_arr, dof=20)
assert np.allclose(t_arr, t_arr2) | 75,855 |
def draw_trial_im(t, epoch, label, n_avg=1, ch_names=None, cls_name=('non-target', 'target'), title='', **kwargs):
"""
Plot epochs trial by trial in an image.
:param t: tuple (start, end, samplerate)
:param epoch: (epochs, channels, time)
:param label:
:param n_avg:
:param ch_names:
:par... | 75,856 |
def _convert_imxyzs_to_npidxs(imxyzs, rows=13824, cols=7680, pixel_size=0.012):
"""
image space linear transform
pixel_size = sensor_width/image_cols = 92.16/7680 = sensor_height/image_rows = 165.8885/13824 # unit: mm/px
"""
col_zoomin, row_zoomin = 1/pixel_size, -1/pixel_size
xs, ys = imxyzs.T... | 75,857 |
def create_env(nzo=None, extra_env_fields={}):
""" Modify the environment for pp-scripts with extra information
OSX: Return copy of environment without PYTHONPATH and PYTHONHOME
other: return None
"""
env = os.environ.copy()
# Are we adding things?
if nzo:
# Add basic info
... | 75,858 |
def generate_dendrite_mac(shared_secret: str, username: str, password: str, admin: bool) -> str:
"""
Generate a MAC for using in registering users with Dendrite.
"""
# From: https://github.com/matrix-org/dendrite/blob/master/clientapi/routing/register.go
mac = hmac.new(
key=shared_secret.encod... | 75,859 |
def save_to_png(image_array, output_file_path, min_val=None, max_val=None):
"""
image_array is the image and it should be a 2D numpy array with values in the range [0,255].
min_val and max_val are normalization parameters (the minimum and maximum value of a pixel).
"""
if image_array.ndim != 2:
... | 75,860 |
def create_snake_environment4eat(level_filename):
""" Create a new Snake environment from the config file. """
with open(level_filename) as cfg:
env_config = json.load(cfg)
return EnvironmentAttackRandomPoison(config=env_config, verbose=1) | 75,861 |
def Search(request):
"""Course search view handler."""
search_context = views_impl.Search(request)
template_name = 'search_results.html'
context = template.RequestContext(request, search_context)
return shortcuts.render_to_response(template_name, context_instance=context) | 75,862 |
def _function_entry_stack_ops(op, to_pop):
"""Computes a set of stack operations for the entry to a FunctionCallOp.
The function calling convention is
- Push the arguments to the formal parameters
- Pop any now-dead arguments so they're not on the stack during the call
- Jump to the beginning of the function... | 75,863 |
def flash(light, color, p_on, p_off):
"""
flashes color for [on] seconds, then off for [off] seconds, repeating.
"""
def ret(ticks, elapsed_time):
if isinstance(p_on, Parameter):
on = p_on.get()
else:
on = p_on
if isinstance(p_off, Parameter):
... | 75,864 |
def get_revision() -> str:
"""return the git revision of current directory as a human-readable string.
:raises OSError: Couldn't get revision from git.
"""
try:
job = subprocess.run([GIT_PATH, 'log', '-1', '--pretty=oneline'],
stdout=subprocess.PIPE, stderr=subproce... | 75,865 |
def solver_problem2(init_state, day):
"""
input initial state, day and output fish
a more efficiet way that only record a fish library with {timer: fish number}
"""
fish_lib = {timer: init_state.count(timer) for timer in set(init_state)}
for _ in range(day):
fish_lib = update_fish(fish_l... | 75,866 |
def print_nodes_name(graph):
"""
input:
-------
graph: (tf.Graph() or tf.GraphDef()) graph in which prints only the nodes' name
return:
-------
None
"""
if isinstance(graph, graph_pb2.GraphDef):
for n in graph.node:
logger.info(n.name)
return [n.na... | 75,867 |
def _tvos_dynamic_framework_impl(ctx):
"""Experimental implementation of tvos_dynamic_framework."""
# This rule should only have one swift_library dependency. This means len(ctx.attr.deps) should be 2
# because of the swift_runtime_linkopts dep that comes with the swift_libray
swiftdeps = [x for x in c... | 75,868 |
def order_nested_object(nested_object):
"""
Simply recursively order the item. To be used for standardizing objects for JSON dumps
"""
if isinstance(nested_object, list):
if len(nested_object) > 0 and isinstance(nested_object[0], dict):
# Lists of dicts aren't handled by python's sor... | 75,869 |
def options(subparser):
"""
Defines the options for the 'messer encryption' commands. Arguments that call the set_defaults method, will call a
function with the specified name and pass the parsed args to it. Anything that the method returns is assigned to
the property 'command'.
:param subparser: A... | 75,870 |
def flipvertcircregion2file(
ExistingBMPfile: str,
NewBMPfile: str,
x: int, y: int, r: int):
"""Does a vertical flip of a
circular region
Args:
ExistingBMPfile: Whole path to
existing file
NewBMPfile : New file to
... | 75,871 |
def step_impl(context, url):
"""
Given a base URL of a transformer
"""
context.reasoner_api_url = url | 75,872 |
def add_header(r):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
# clear browser cache
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Ca... | 75,873 |
def id_feat_meas_mz_rt(cursor, mz, rt, ccs, tol_mz, tol_rt, tol_ccs, esi_mode, norm='l2'):
"""
id_feat_meas_mz_rt
description:
identifies a feature on the basis of measured m/z and retention time
parameters:
cursor (sqlite3.Cursor) -- cursor for querying lipids.db
mz (float) -- m/z t... | 75,874 |
def generate_guid():
""" Generate a GUID
"""
return uuid.uuid4().hex | 75,875 |
def RecordInstallMetadata(device, apk_package, metadata_path):
"""Records the metadata from the device for apk_package."""
metadata = device.GetInstallMetadata(apk_package, refresh=True)
if not metadata:
raise Exception('APK install failed unexpectedly.')
build_utils.WriteJson(metadata, metadata_path) | 75,876 |
def test_x5u_vulnerability(requests_mock):
"""
Test x5u_vulnerability method in vulnerabilities.py
"""
with pytest.raises(InvalidJWT):
x5u_vulnerability("", url="http://test.com")
with pytest.raises(InvalidJWT):
x5u_vulnerability(jwt_bruteforce, url="http://test.com")
status_co... | 75,877 |
def test_triux():
"""Test TRIUX system support."""
raw = read_crop(tri_fname, (0, 0.999))
_assert_mag_coil_type(raw.info, FIFF.FIFFV_COIL_VV_MAG_T1)
assert_allclose(raw.info['chs'][2]['cal'], 1.33e-10, rtol=1e-6)
# standard
with use_coil_def(elekta_def_fname):
sss_py = maxwell_filter(raw... | 75,878 |
def get_data_ch7():
"""Get the data set used in Chapter 7"""
data = np.genfromtxt('../data/airfoil_self_noise.dat', delimiter='\t')
data = (data - data.mean(axis=0)) / data.std(axis=0)
return nd.array(data[:, :-1]), nd.array(data[:, -1]) | 75,879 |
def add_to_metadata_list_manual(instr_name, param_name):
"""
Args:
intr_name (str): name of instrument which param belongs to
param_name (str): name of param
"""
metadata_list = get_metadata_list()
inst_param_tuple = (instr_name, param_name)
if inst_param_tuple not in metadata_li... | 75,880 |
def verify_import_tree(depth: int = 1, track_others: bool = False, timeit: bool = False) -> bool:
"""Locates imports that violate cirq's submodule dependencies by
instrumenting python import machinery then importing cirq.
Logs when each submodule (up to the given depth) begins and ends executing
during... | 75,881 |
def is_iterable(obj) -> bool:
"""
Test if argument is iterable.
"""
return isiterable(obj) | 75,882 |
def concat_name(name: str, *comp_names):
"""Add comp_name to name, e.g. ('dist', 'a2', 'a1')-->'a1__a2___dist'."""
comp_name = concat_comps(*comp_names)
if comp_name:
return f'{comp_name}{SPLITTER}{name}'
return name | 75,883 |
def demedian_parcellate_func_combine_hemis(lh_func, rh_func, lh_parcel_path, rh_parcel_path):
"""
#Function that takes functional data in the form <num_verts, num_timepoints> for
#both the left and right hemisphere, and averages the functional time series across
#all vertices defined in a given par... | 75,884 |
def get_pdf_upload_to():
"""
This function returns the absolute path to the folder for uploading PDFs
2019-10-22
:return: the absolute path to the folder for uploading PDFs
"""
pdf_upload_to = getattr(settings, 'OCR_PDF_UPLOAD_TO', ocr_default_settings.PDF_UPLOAD_TO)
if not os.path.isabs(pdf... | 75,885 |
def _cmpPair2(a, b):
"""Auxiliary comparision for sorting lists of pairs. Sorting on the second member of the pair."""
(x, y), (z, w) = a, b
if y < w:
return -1
elif y > w:
return 1
elif x < z:
return -1
elif x > z:
return 1
else:
return 0 | 75,886 |
def linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1):
""" Create a schedule with a learning rate that decreases linearly after
linearly increasing during a warmup period.
"""
def lr_lambda(current_step):
if current_step < num_warmup_steps:
r... | 75,887 |
def chooseStatic(schedule, staticDict, priorityQueue, modulo=24):
"""
given a scheudule and a priority queue,
it takes the next highest priority item and checks for conflicts and the event is added to the schedule only if there's no confict
if the duration of the event is less than the time... | 75,888 |
def prepare_corsika_from_blacklist(path, oldEnding='', newEnding='nomissing'):
"""Takes the path of the corsika files (there should be only corsika files in a single directory)
and removes unuseable and too short keys and writes new hdf5 files"""
oldCorsika = [h5.File(file, 'r') for file in sorted(glob.glob... | 75,889 |
def toExport8F8(op):
"""Converts number to exportable 8.8 signed fixed point number."""
return int(round(op * 256.0)) | 75,890 |
def mkminim(grid, baseuri=None):
"""
Generate minim graph from supplied grid
Returns (status,mgr) where mgr is RDF graph containing minim description,
or None.
"""
# Decode the grid
try:
(d,(r,c)) = checklist_template.checklist.match(grid, 0, 0)
except Exception, e:
prin... | 75,891 |
def update_service_permissions(service, service_obj=None, namespace=None):
"""Update the key permissions for the named client in Ceph"""
if not service_obj:
service_obj = get_service_groups(service=service, namespace=namespace)
permissions = pool_permission_list_for_service(service_obj)
call = [... | 75,892 |
def get_serializables_from_comp_xml(comp_xml):
"""
Returns list containing all serialized types found from
component xml and its imported files... NOTE: Must add
check for serial types found outside imported serial files
"""
serial_imports = comp_xml.get_serializable_type_files()
# Imports ... | 75,893 |
async def test_dispatching_selection():
""" Test that routing works in agent. """
dispatcher = Dispatcher()
called_event = asyncio.Event()
async def route_gets_called(_msg, **kwargs):
kwargs['event'].set()
async def route_not_called(_msg, **_kwargs):
print('this should not be call... | 75,894 |
def LogRegressNomalize(value):
"""Uses log regress to normalize (-inf, inf) to [0, 1]."""
value_exp = math.exp(value)
return value_exp / (value_exp + 1) | 75,895 |
def test_prob_wires_and_hermitian(hermitian):
"""Test that we can cannot give simultaneously wires and a hermitian."""
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def circuit():
qml.PauliX(wires=0)
return qml.probs(op=qml.Hermitian(hermitian, wires=0), wires=1)
with... | 75,896 |
def run_test_get_bigger_size():
""" Tests the get_bigger_size method of the Blob class. """
print()
print('-----------------------------------------------------------')
print('Testing the get_bigger_size method of the Blob class.')
print('---------------------------------------------------... | 75,897 |
def guess(intcos, geom, Z, connectivity=False, guessType="SIMPLE"):
""" Generates diagonal empirical Hessians in a.u. such as
Schlegel, Theor. Chim. Acta, 66, 333 (1984) and
Fischer and Almlof, J. Phys. Chem., 96, 9770 (1992).
"""
dim = len(intcos)
H = np.zeros((dim, dim), float)
for i... | 75,898 |
def get_cmap(n, name='Set1'):
"""
Source: https://stackoverflow.com/questions/14720331/how-to-generate-random-colors-in-matplotlib
Colormaps: https://matplotlib.org/tutorials/colors/colormaps.html
:param n: Number of classes.
:param name: The color map to be selected from.
:return: a function th... | 75,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.