content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_extension_manager():
"""Return the extension manager used by Review Board.
The same instance will be returned every time.
Returns:
ExtensionManager:
The extension manager used by Review Board.
"""
global _extension_manager
if not _extension_manager:
_extension_... | 2f31e8d74dbef8e96ef862798daad4aab5bc0196 | 44,326 |
def get_title(dbname, page_id, replicas_port, user, password):
"""
Get title of the page with id as `page_id`.
:param dbname: Which database the module corresponds to.
:param page_id: The Id of the page whose page title is to be fetched.
:param replicas_port: port for connecting to meta table throu... | 9354cd4046b413ab1c5d0a7a1c81c6c04709048e | 44,327 |
from typing import Optional
def resolve_url_param(param: UrlParam, context: Optional[Context] = None) -> ResolvedUrlParam:
"""
Resolve a URL parameter.
Args:
param: A URL parameter, which is one of the items below.
- A URL parameter value.
- A list of URL parameter values.... | ae7c1c273307adbf403ec217ec9f443b0c6ff879 | 44,329 |
def fifo(jobs,num_frames):
""" Frame list
Each item in this list will be a tuple as follows:
Tuple[0] - represents the number of the page frame sequentially, 1,2,3, etc..
Tuple[1] - reresents the job current in this frame
Tuple[2] - represents the moment that job arrived (starting with 0 for first m... | 6fabcbab27cc3270e72eabbda79166b1b4393239 | 44,330 |
def CMYKratio_to_CIE(cmykr):
"""Converts CMYK color space (ratio representation) to CIE"""
rgb = CMYKratio_to_RGB(cmykr)
return RGB_to_CIE(rgb) | 58464be2c201ce33a849a2278e79cc8df1d346cf | 44,332 |
def laptops_list(request):
"""View a list of LNL's laptops"""
laptops = Laptop.objects.filter(retired=False)
return render(request, 'laptops/laptops_list.html', {"laptops": laptops}) | e6ea36883787783c4d09c3bbe40442f357825862 | 44,333 |
def get_bcl(signal_markers: pd.DataFrame):
"""Function to return estimates of the cycle length for a recording
For a given train of signal markers (either QRS start, AT, or other), will estimate the cycle length as the
difference between successive markers, with an estimate made that the last cycle length ... | b41828fbf758a7b595ddb97d5859dcfa12cc0934 | 44,334 |
def exponential_head_correction(r, V, cutoff):
"""Use an exponential function to smoothly force V to a finite value at V(0)
Parameters
----------
r : np.ndarray
Separation values
V : np.ndarray
Potential at each of the separation values
cutoff : int
The last real value o... | eae10963883e5c9c7ae45cf0430fcfcb020797bf | 44,335 |
def fa_to_en(string):
"""Convert Persian digits to EN
Usage::
>>> from persiantools import digits
>>> converted = digits.fa_to_en("۰۱۲۳۴۵۶۷۸۹")
:param string: A string, will be converted
:rtype: str
"""
digits_map = {
"۰": "0",
"۱": "1",
... | 3687dae8663d855200f2f79b81cb85d23ecabf74 | 44,336 |
def plugin_get(request, plugin_id, fields):
"""Get plugin info."""
plugin = iotronicclient(request).plugin.get(plugin_id, fields)
return plugin | c949b9ea1e2c21f5afc2633a8a6a8b73a70e52d5 | 44,337 |
import six
def _bytes_list_feature(values):
"""
:param values:
:return:
"""
def _norm2bytes(value):
return value.encode() if isinstance(value, str) and six.PY3 else value
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[_norm2bytes(values)])) | e9e0272ce582d174b0795fa901c254fc1c3f6b8c | 44,338 |
def quicklook_region(request, region_id=10000002, type_id=34):
"""
Generates system level overview for a specific type.
Defaults to tritanium & the forge.
"""
# Get the item type
type_object = InvType.objects.get(id=type_id)
# Get list of materials to build
materials = InvTypeMaterial.... | ede0e36a305eed2ea233a995dda7f719a275a262 | 44,339 |
def delete_event_subscription( context, id ):
"""
Deletes an event subscription
Args:
context: The Redfish client object with an open session
id: The identifier for the subscription
Returns:
The response of the DELETE
"""
# Get the current subscriptions
subscriptio... | e47b8e09b8daaa5f33598ccda6d5e1279de1f592 | 44,340 |
def preprocess_data(data_frame, label_columns_list, data_file_name):
"""
start preprocessing the data
"""
print '\npreprocessing..'
print Style.RESET_ALL
for col in label_columns_list:
data_frame[col] = data_frame[col].apply(lambda arr: arr.strip(""))
data_frame[col] = data_frame... | 51e2ecd45b392a2cd12cae4f47f7dc16560a97a0 | 44,341 |
def get_prayer(id):
"""Returns specific prayer from id."""
return Prayer.query.get(id) | 95e4425e28d9c9e2b028dc5b144eaacc69289cbb | 44,342 |
def docstring_parameters_section(obj):
"""
Return the parameters section of a docstring
"""
return docstring_section_lines(obj.__doc__, 'parameters') | afb01bd0c18ecc3d8d7294bda7dd00c09b831465 | 44,343 |
def split_string_by_bytes(s: str, bytes_count: int) -> list[bytes]:
"""A function that splits a string into N-byte particles"""
s = s.encode()
return [s[i : i + bytes_count] for i in range(0, len(s), bytes_count)] | 58a2dcdda7cab6832eecd15200af2c7d10dbd367 | 44,344 |
import collections
def score_urls(*args, \
search_terms=config.search_terms, **kwargs):
"""
Returns urls ordered by search relevance
"""
def search_key(tokens, default=0):
score, _, _ = search_terms.replace_terms(tokens)
return -(score or default)
tags = collections.Counter... | 0c8aeaae6b43b923d85a36968799234c28297163 | 44,345 |
import logging
def recipe(recipe_file, ctype=container_type.DOCKER, single_stage=False,
userarg=None):
"""Recipe builder"""
# Make user arguments available
USERARG = {} # pylint: disable=unused-variable
if userarg:
USERARG = userarg # alias
# Consider just 2 stages for the tim... | b0f77150404ada6120e6ae2c5f6a155c043996d2 | 44,346 |
def get_collective_group_size(group_name: str = "default") -> int:
"""Return the size of the collective group with the given name.
Args:
group_name: the name of the group to query
Returns:
The world size of the collective group, -1 if the group does
not exist or the process doe... | 1ab6e69f7f8d2f4c11c3d93a5e8d94422f22d462 | 44,347 |
def collision(object1, object2):
"""detect collision between two objects using circles
Tests for collision between two objects by testing whether two circles
centered on the objects overlap. Objects must have a
a "radius" attribute, which is used to create the circle.
Args:
object1: First ... | e42bcce7a111fa7f8de2c10b16a91c0d49992ddb | 44,348 |
import pandas as pd
import numpy as np
def rm_standard_dev(var,window,ravelmodeltime,numOfEns):
"""
Smoothed standard deviation
"""
print('\n\n-----------STARTED: Rolling std!\n\n')
if var.ndim == 3:
rollingstd = np.empty((var.shape))
for i in range(var.shape[1]):
... | 5eacda1f79e1f4fe00c3cb8d32222f75f9eb3562 | 44,350 |
def compute_purity(cluster_assignments, class_assignments):
"""Computes the purity between cluster and class assignments.
Compare to https://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-clustering-1.html
Args:
cluster_assignments (list): List of cluster assignments for every point.
... | ee6c8e84c7833125fdaa2581acb90cbe92610514 | 44,351 |
def add(a,b):
"""
Return the addition of the arguments
>>> add(1,2)
3
>>> add('a','b')
'ab'
>>> add(1, '2')
Traceback (most recent call last):
File "test.py", line 43, in <module>
add(1, '2')
TypeError: unsupported operand type(s) for +: 'int' and 'str'
"""
retu... | ecf8728670525cb1f8c6c558021fc468ef4c8780 | 44,352 |
def ida_star(root, goal, heuristic):
""" Based on https://en.wikipedia.org/wiki/Iterative_deepening_A* """
bound = heuristic(root, goal)
path = StackSet([root])
while True:
t = search(path, 0, bound, goal, heuristic)
if t == 'FOUND':
return (path, bound)
... | a02cd44d8145fb342ce791f41c9e3db1583b3b06 | 44,354 |
def getLiterature(movieID, indexF, dataF):
"""Return literature information for a movie."""
return _parseColonList(movieID, indexF, dataF, 'MOVI: ', _lit) | a7ce5a50fd0dda6d3a8228ca1605e49527bbd6a9 | 44,356 |
def find_key_symptom(tariffs, cause_reduction, cause, endorsements,
rules=None):
"""Find the key endorsed symptom for a cause
Args:
tariffs (dict): processed tariff matrix
cause_reduction (dict): mapping from cause46 to cause34
cause (int): cause number at the cause... | e8805fd29bf09cd3e0269ae4203f4fd7912f5c72 | 44,357 |
def all_gather(x, replication_factor, name):
""" Gather the data on all replicas to all other replicas. Each replica will
have the exact same output.
Args:
x: The tensor to gather
replication_factor: The replication factor of the model.
name: Optional op name.
Returns:
A tensor o... | 22d039fb1e921ef0bee39e93255aee09dee87a02 | 44,358 |
def generate_legend_file(split_names, legend_file_name, out_dir,
hdfs_client=None):
"""
generate legend file for each all the splits
"""
legend_file = '{0}/{1}'.format(out_dir, legend_file_name)
if hdfs_client is None:
with open(legend_file, 'a+') as f:
... | c10acf8c7ad6402082f09fe011336070a1d54cc7 | 44,359 |
import socket
def get_ip4_from_socket() -> str:
"""Get the public IPv4 of this system by inspecting a socket connection.
Warning: This returns a local IP address when running behind a NAT, e.g. on Docker.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect((IP4_SOCKET_E... | 4952ca64362b8fb4c2515d06cc23785bf60fd28e | 44,360 |
import csv
import re
def _get_parse(str_src, ns_args):
"""Return {'tree':, 'rulerrow':, 'alignments':} parse
from text and ArgParse options
"""
if ns_args.sourceformat != None:
e_fmt = ns_args.sourceformat
if e_fmt == FMT_CSV:
try:
o_dialect = csv.Sniff... | 3eda4ef949d574a5707e3a00c02860050a9a8866 | 44,361 |
def transform(tokens):
"""
Accumulate tokens in lines.
Add token (and white spaces) to a line until it overflow 80 chars.
"""
lines = []
current_line = []
for t in tokens:
if sum([len(x) + 1 for x in current_line]) + len(t) > 80:
lines.append(current_line)
cu... | c30af21db61b2b00848b0263552461f9682a6d08 | 44,362 |
def get_input(calc_params_crystal, elements, bs_repo, label):
"""
Generates a test input
"""
calc_params_crystal['title'] = label
return write_input(calc_params_crystal, [bs_repo[el] for el in elements]) | f3c91caa0322006085edad0262545799cadf11b5 | 44,363 |
import json
def ocr_loader(json_path):
"""Helper function to load ocr data from json file
Args:
json_path (string):
Path to the json file with OCR output data
Returns:
string:
OCR text output
"""
json_path = json_path.replace('\\', '/')
with open(json_... | 7e182b184b305bffc97dadf59b139a1aa53250b1 | 44,364 |
def precision_posterior_prior(samples, mean, variance,
a_prior=5, b_prior=6):
""" This using the solution of Question 3 from Exercise 3
Parameters
----------
samples : array [n_samples,]
the samples from data distribution (i.e. X ~ Normal(mu, sigma^2))
mean : a scalar
th... | 1c462fc9db7a096a3c532ac1f75fd6945675ecc6 | 44,365 |
import re
def tokenize_only(text):
"""
first tokenize by sentence, then by word to ensure that punctuation is caught as it's own token
filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation)
Args:
text:
Returns:
"""
tokens = [
word.lower()
... | f4863258976dece4075b83a540a16beb11f23bdb | 44,366 |
def locations_list():
"""Returns a dictionary of ASNs as keys, list of associated locations, router hostnames, and \
router display names as keys. Used by Flask to populate the /routers/<asn> route, which is \
ingested by a JS Ajax call to populate the list of locations associated with the selected \
ne... | d71aa6634247788bfcd041a8b9b14204a12ae82c | 44,367 |
def check_min_area( prob_mask, frame, min_area = p.min_area, type = 2,
check_area = p.check_area, **kwargs):
"""Finds contours in image and optinally checks if area bigger than `min_area`
Parameters
------------
prob_mask : ndarray
2D probability map output of `prob_mas... | bd821438bd6a9a785c0108a988068dc635978d2f | 44,368 |
def video(request, id=None):
"""
*/entry/videos/<id>*, */entry/videos/new*
The entry interface's edit/add/delete video view. This view creates
the edit page for a given video, or the "new video" page if it
is not passed an ID. It also accepts POST requests to create or edit
videos.
If call... | 651f4e18a73267af26ce558feecc0b8041c0ac38 | 44,369 |
def country(get_response):
"""Detect the user's country and assign it to `request.country`."""
def _country_middleware(request):
client_ip = get_client_ip(request)
if client_ip:
request.country = get_country_by_ip(client_ip)
if not request.country:
request.countr... | 340fde4c5b2000ec688af6f5024200ada264c8cc | 44,370 |
def extract_clips_with_consecutive_frames(path, num_clips, num_frames_per_clip):
"""
Args:
path: path of a video
num_clips: expected numbers of splitted clips
num_frames_per_clip: number of frames in a single clip, pretrained model only supports 16 frames
Returns:
A list of r... | 87d285d6b30bdfa075eebfec6fc21bf7cc66508b | 44,371 |
import time
def solve_classical(args):
""" Classical Model Solver """
t_init = time()
# Create the model and load the spectra.
data = map(oracle.specutils.Spectrum.load, args.spectra_filenames)
model = oracle.models.StellarSpectrum(args.config_filename, data)
# Sort the spectra from blue to... | 5e93199eb8bd168dce7c232fa6077456787c8ae2 | 44,372 |
def layer_modelformset(extra=0):
""" Form set for film layers """
return forms.modelformset_factory(ReflectivityLayer, form=LayerForm, extra=extra,
fields=('name', 'thickness', 'sld', 'i_sld', 'roughness', 'remove', 'layer_number',
... | fe053473b09e9522d296298d5513de5dafeb3cdd | 44,373 |
import json
def setup(hass, config):
"""Set up the MQTT export component."""
pub_topic = config[DOMAIN].get("publish_topic", DEFAULT_TOPIC)
global PAYLOAD
PAYLOAD = dict(states=None, details=None)
# Add the configuration
PAYLOAD["details"] = hass.config.as_dict()
def mqtt_event_listener... | e2d02e99c70bae0c65216ea8c423bf2880da1793 | 44,374 |
from .test_broadcasting import broadcast_shapes
def two_broadcastable_shapes(draw, shapes=shapes):
"""
This will produce two shapes (shape1, shape2) such that shape2 can be
broadcast to shape1.
"""
shape1, shape2 = draw(two_mutually_broadcastable_shapes)
if broadcast_shapes(shape1, shape2) !... | 78f0a0b22db6bdaee0dc81da5197fcc88e4bed9c | 44,375 |
def observed(data):
"""Computes the observed agreement, Pr(a), between annotators."""
total = float(np.sum(data))
agreed = np.sum(data.diagonal())
percent_agreement = agreed / total
return percent_agreement | 6a7b8f5b9df47acc67f55018fd805b8d77feebf1 | 44,377 |
def number_name(item):
"""The English name for that number
>>> assert number_name(5) == 'five'
"""
return _inlection.number_to_words(item) | e71bf1b86ddf725ba5b76a0a5247869a858aa3ed | 44,378 |
def create_nmt_model(session, forward_only, model_path=None, use_best=False, FLAGS=None, buckets=None, translate=False):
"""Create translation model and initialize or load parameters in session."""
assert FLAGS is not None
assert buckets is not None
decode_input = FLAGS.decode_input
decode_file = ... | 4d0a2849eefd4fb472630e62b411989ce2f63b3e | 44,379 |
def pay_cash(amount, *args):
"""This exists so we can update the global cash counter.
:param amount: Amount to pay
:type args: bool[]
"""
paid = app_character.statblock.pay_cash(amount, *args)
return paid | a2b86cf8ff86eae587add6d8d37ef7c716dba3ae | 44,380 |
def degeneracyOrientation(G):
"""Directed version of G with <= degeneracy out-neighbors per vertex."""
D = {}
for v,d in degeneracySequence(G):
D[v] = {w for w in G[v] if w not in D}
return D | 42ecc0b31c892553e12b8dc62a9d8d47b2abf0c8 | 44,381 |
import json
def update_job_by_id(user, job_id):
"""Update a job
"""
# get If-Match header
if_match_etag = utils.check_and_get_etag(flask.request.headers)
values = clean_json_with_schema(update_job_schema, flask.request.json)
job = v1_utils.verify_existence_and_get(job_id, _TABLE)
job = d... | ca74f95a7a54a0ba81a994e4932c8c36d2083ad4 | 44,383 |
def _kalman_info_sample(J_ini, h_ini, log_Z_ini,
J_dyn_11, J_dyn_21, J_dyn_22, h_dyn_1, h_dyn_2, log_Z_dyn,
J_obs, h_obs, log_Z_obs):
"""
Information form Kalman sampling for time-varying linear dynamical system with inputs.
"""
T, D = h_obs.shape
# Run... | 8112835eb895845b369e666aeabe5a4cd355b5bf | 44,384 |
import json
import requests
def generate_pdf(layout: LabelLayout, api: str = DEFAULT_LABEL_API) -> bytes:
"""
Generate a PDF from the given *layout* using the `Lab Labels
<https://github.com/MullinsLab/Lab-Labels>`_ web service *api*.
Returns a byte string.
"""
spec = json.dumps(layout.spec()... | 31e0398fb32773a247ad5283fcd7eefd903dd224 | 44,385 |
from typing import Optional
from datetime import datetime
def get_term_start_end_from_date_for_actual_working_time(
start_date: Optional[str], end_date: Optional[str], tzinfo: Optional[datetime.tzinfo] = None
) -> tuple[Optional[str], Optional[str]]:
"""開始日と終了日から、実績作業時間を取得するAPIに渡すクエリパラメタterm_startとterm_endを返し... | cb93cb6880eb4e663df65e765fb1b338eb1d8369 | 44,386 |
def cwipc_source_netclient(address, verbose=False):
"""Return cwipc_source-like object that reads individual compressed pointclouds from a TCP-based server specified as host:port"""
source = _NetClientSource(address, verbose=verbose)
return source | e1779fd9c47d06bf851abd895d3aafbd79d685e5 | 44,387 |
def create_msa_matrix(chimerics, msa):
"""
Convert a msa from chimerics to a matrix.
Each cell has the subexon number (Index) or nan for gaps and padding.
"""
if not chimerics:
return np.empty((0, 0), dtype=object)
n_seq = len(msa)
n_col = msa.get_alignment_length()
msa_matrix =... | 99bf3d8404ed55064bc028675406a371f6795edf | 44,388 |
from typing import Union
def number_of_objectives(obj_instance: Union[_ScalarObjective, VectorObjective]) -> int:
"""Return the number of objectives in the given obj_instance.
Args:
obj_instance (Union[_ScalarObjective, VectorObjective]): An instance of one of
the objective classes
R... | 0f4dd7722ee4d68faa31ab582fb09de325ece338 | 44,389 |
def to_ps(obj, parlen=False):
"""Converts object into postscript literal
>>> to_ps(None)
'null'
>>> to_ps(123)
'123'
>>> to_ps(456.78)
'456.78'
>>> to_ps(True), to_ps(False)
('true', 'false')
>>> to_ps('foo bar baz')
'foo bar baz'
>>> to_ps('foo bar baz', parlen=True)
... | 11fa2888678970f9ab37e4827e87bbf67856898c | 44,390 |
def undistort_image(img, mtx, dist, newcameramtx=None):
"""
Use camera intrinsics to undistort raw image
:param img: Raw Image
:param mtx: Camera Intrinsics matrix
:param dist: Distortion Coefficient
:param newcameramtx: Camera Intrinsics matrix after correction
:return: Undistorted image
... | 6d88e800d24d98ada522b087b16d5187dcba571d | 44,392 |
def voigt_tau(wave, par):
""" Find the optical depth at input wavelengths
Taken from linetools.analysis.voigt
This is a stripped down routine for calculating a tau array for an
input line. Built for speed, not utility nor with much error
checking. Use wisely. And take careful note of the expected... | 372164dba3032596d591c57d9ac66491b036608d | 44,393 |
def enum_member_name(state):
"""
All enum member names have the form <EnumClassName>.<EnumMemberName>. For
our rendering we only want the member name, so we take their representation
and split it.
"""
return str(state).split('.', 1)[1] | d6fa9320c1f96209fd6d547f1a7715ade391c672 | 44,394 |
def combine_datasets(lma_data):
""" lma_data is a list of xarray datasets of the type returned by
pyxlma.lmalib.io.cf_netcdf.new_dataset or
pyxlma.lmalib.io.read.to_dataset
"""
# Get a list of all the global attributes from each dataset
attrs = [d.attrs for d in lma_data]
# Create a ... | 48087548d182b6dce4914a82675ec91686ef1454 | 44,395 |
def gene_pvalue_burden_nb(df_model):
""" Calculate burden P-values based on the transfered NB model params
"""
# PVAL_SYN, PVAL_MIS, PVAL_NONS, PVAL_SPL, PVAL_TRUNC, PVAL_NONSYN = [], [], [], [], [], []
# for i, row in df_model.iterrows():
# PVAL_SYN.append(nb_model.nb_pvalue_greater_midp(row.O... | 52544dbd8fa3ec12c4539ac2017a110fcd6c7691 | 44,396 |
from typing import Counter
import re
def seq2polyA(seq):
""" input seq
output polyA report
(1) pass or not
(2) Left or Right
(3) most common character
(4) length of polyA
(5) length of isoseq
"""
lst = []
L = seq[0:10]
R = seq[-10:]
end = L + R
... | 61517f86dc776863d3586c2013115c2e9c0afd96 | 44,397 |
def multiscale_entropy(timeseries, stat_name, scales, **kwds):
"""
Calculates multi-scale entropy for any of the entropies defined above.
Idea from Costa, Goldberger and Peng, "Multiscale Entropy Analysis of
Complex Physiologic Time Series", Phys. Rev. Lett. 89, No.6, July 2002
timeseries: pd.Series... | 78e44ef40d956d7ae145c275b365cf406acc906a | 44,398 |
def setbit(target, bit):
"""
Устанавливает бит bit в 1 в байте target
"""
return target | (1 << bit) | 55f073fb82c5a29a50b8505be6a8a3971ebaf872 | 44,399 |
def get_footprint(request):
"""Generates and render png"""
template = loader.get_template('dashboard/fits_to_png.html')
start = request.GET.get('start')
end = request.GET.get('end')
program = request.GET.get('program')
if not program:
processed_exposures = []
elif not start or not en... | be8b12b04d8fb2cd14a5f66e703d539ed07acf5c | 44,400 |
def test_game(env, agent, n_eval_episodes):
"""
Test the agent to measure rewards.
It evlautes the agent with the environment for some epidoses,
and record totol rewards.
:param env: environment to intereact with
:param agent: agent
:param n_eval_episodes: number of episodes
"""
all... | 8ed5db93ad5af4fa99910e732ee8b1c62f3a7eb0 | 44,401 |
def dict_union_combine(dict1, dict2, combine_op=op.add,
default=util_const.NoParam,
default2=util_const.NoParam):
"""
Combine of dict keys and uses dfault value when key does not exist
CAREFUL WHEN USING THIS WITH REDUCE. Use dict_stack2 instead
"""
key... | df0519411a82f416b797a87c9cd728d0b95ad419 | 44,402 |
def mixed_treatment_intervention():
"""Apply mixed strategy on all controls starting at time 0."""
return zika.Intervention(
time=0,
treated_bednet_use=0.5,
condom_use=0.5,
treatment_of_infected=0.5,
indoor_spray_use=0.5,
) | 8bac3c90cbe77dc55c24e35707cbeccbc3b09f8f | 44,404 |
def expand_agent(agent, ontology, ns_filter=None):
"""Return children agents of a given parent agent.
Parameters
----------
agent : indra.statements.Agent
An INDRA Agent whose children in the given ontology should
be returned as Agents.
ontology : indra.ontology.IndraOntology
... | 16995d99344259164a4ed33c908636f3037d4c71 | 44,405 |
def sphericalize_density_matrix(mol, dm):
"""Sphericalize the density matrix in the sense of an integral over all possible rotations.
Args:
mol (pyscf Mole): pyscf Mole object used for the computation of the density matrix.
dm (numpy ndarray): density matrix in AO-basis.
Returns:
n... | 4f8e0182aa46a2ef5cf8ec9251c11c280f3e23f9 | 44,406 |
def has_specific_team_access(user, team):
"""
To have access to a team a user must:
- Be course staff
OR
- be in the correct bubble
- be in the team if it is private
"""
return has_course_staff_privileges(user, team.course_id) or (
user_protection_status_matches_t... | 2a3246e18afefe3df0cb590dfd89d4200f87d451 | 44,407 |
import logging
def check_queue(queue_name):
"""
Args:
queue_name : queue_name of the queue
Checks queue for messages, logs queue status of messages left on que and hidden messages
returns only when queue is empty
"""
region = get_config()['provider']['region']
client = boto3.cli... | 7d6972aaf1a0cb6734dc25b503d424504fed507c | 44,408 |
def plot_trap(radius= default_radius, height= default_height, slope= default_slope, delta= default_delta, constant_population= True):
"""Generates a plot for the fish trap operating over 1 week
Args:
radius: the radius of the semi-circular trap created
height: the height of the trap
slo... | ab92b847117033d61117720f4e25c5cbbcd6706d | 44,409 |
def systematic_sample(n, prob):
""" systematic re-sampling algorithm.
Note: objects with > 1/n probability (better than average) are guaranteed to occur atleast once.
see section 2.4 of 'Comparison of Resampling Schemes for Particle Filtering' by Douc et. al for more info.
"""
assert(n == len(prob))... | b4a170327b095c2d69d808a29dc75121b99b6964 | 44,410 |
def add_organization(authn):
"""Add organization."""
try:
post_data = request.get_json()
org_name = post_data['name']
primary_admin = User.from_uuid(authn.sub)
is_public = post_data.get('is_public', True)
except NoResultFound:
raise NotFound('User does not exist')
... | 2f8fc7b47b1772649ecc61e982b2f2fffeeda500 | 44,411 |
def _f_integrand(z, cosmo):
"""
Calculate the integrand for a given redshift and cosmology. This
the integrand for integral that appears in Zhang2018, Inoue2004
and Ioka2003.
Parameters
----------
z : float
The input redshift.
cosmo : An instance of :obj:`astropy.cosmology`
... | 4e344dca4260f830839a9f20c9f8bf7ec8989330 | 44,412 |
def generate_type_handlers(model):
"""
Generates msg handlers for all messages except for dumps and requests (handled by vpp, not client).
:param model: meta-model of VPP API used for jVPP generation.
"""
type_handlers = []
for t in model.types:
if not isinstance(t, Class):
c... | b05bdb26a732900255d52c2a6f550a1802fef967 | 44,414 |
def ex9():
"""
Example 9
Breakable Activity
file name: Example9.py
Copyright Log Opt Co., Ltd.
Consider the same scenario as in Example 6.
Here, Activities can interrupt their processing and re-start after one unit of break time.
Find the optimal schedule (minimum tardiness solution) un... | eff77c2432f96a8c17b176aa9430f0610377d31e | 44,415 |
def _applySpecial_ColourMapOpts_negativeCmap(
args, overlayList, displayCtx, target):
"""Handles the :attr:`.ColourMapOpts.negativeCmap` option. See
:func:`_applyColourMap`.
"""
args.negativeCmap = _applyColourMap(
args.negativeCmap, overlayList, displayCtx)
return True | c2cbedf04402bdd183ab35c373240c32ba81d58b | 44,416 |
def concrete_head(expr, n=10):
""" Return head of computed expression """
if not expr._resources():
raise ValueError("Expression does not contain data resources")
if iscollection(expr.dshape):
head = expr.head(n + 1)
result = compute(head)
if not len(result):
ret... | b96417320441a4f3a1257aed9752a19131765bc8 | 44,417 |
def list():
"""Seznam cvičení"""
usr = getUser()
if request.params.get("activate"):
lec = Lecture.get( request.params.get("activate") )
lec.activate()
msg("Cvičení %s bylo zapnuto" % lec.name,"success")
redirect(request.path)
if request.params.get... | 28167e6e93b8d9fb720bce0a711ab480b9aced39 | 44,418 |
import torch
def load_snapshot(snapshot_file):
"""Load a training snapshot"""
print("--- Loading model from snapshot")
# Create network
norm_act = partial(InPlaceABN, activation="leaky_relu", slope=.01)
body = models.__dict__["net_wider_resnet38_a2"](norm_act=norm_act, dilation=(1, 2, 4, 4))
... | 980c291141387ba6490391f2f014802280ad5f7b | 44,419 |
def squash(x, axis=-1):
"""The Squashing Function.
The nonlinear activation function used in Capsule Network
# Arguments
x: Input Tensor.
axis: Integer axis along which the squashing function is to be applied.
# Returns
Tensor with scaled value of the input tensor
"""
s_... | 0812568db60940ffa4bdaf517f2ac54e0a7e1b06 | 44,420 |
import json
def update_user_chosen(request):
"""This view updates the team member: this is needed to see the ground truth of a specific user"""
request_body_json = json.loads(request.body)
user = request_body_json['user_chosen']
if user is not None:
request.session['team_member'] = user
... | 2c96338eb1e52d589efcc85a023697e4c9b9273f | 44,421 |
def encode(ds, is_implicit_vr, is_little_endian):
"""Encode a pydicom Dataset `ds` to bytes.
Parameters
----------
ds : pydicom.dataset.Dataset
The dataset to encode
is_implicit_vr : bool
The element encoding scheme the dataset will be encoded with.
is_little_endian : bool
... | 7765c5fb6ac649b421091081220d1035f7f427c4 | 44,422 |
import json
def tryJSON(response: Response) -> dict:
"""
Try to convert response data to JSON
"""
try:
response_data = response.json()
except json.decoder.JSONDecodeError:
raise PluginException(
cause="Received an unexpected response from Deep Security",
as... | 4fbd9e092cd983b468d4e97a3e9596c486dc653a | 44,425 |
def path_to_coords(svg_path: str, xtype: str = None) -> np.array:
"""From SVG path to numpy array of coordinates, each row being a (row, col) point"""
indices_str = [
pt.replace("M", "").replace("Z", "").replace("_", " ").split(",") for pt in svg_path.split("L")
]
if xtype == "datetime":
... | eb782543a602557129b732086e0f61272058c8d8 | 44,426 |
def insert(*data):
"""
Create an insert clause, e.g. `INSERT INTO ...`
Each value in *data* should be dictionary with key/values representing
columns/values. The format of this should be the same as in
:py:func:`.update`.
"""
return QueryBuilder().insert(*data) | 3a9645018e6f3c5773eceeba3b77be573fa5fd3d | 44,427 |
def get_default_gl_major_version():
""" Default GL major version """
return __gl_major_version__ | 16c7862da2d8172cc51180473d3be8093f9ccfcd | 44,428 |
def expandf(m, format): # noqa B002
"""Expand the string using the format replace pattern or function."""
if isinstance(format, (Replace, ReplaceTemplate)):
if not format.use_format:
raise ValueError("Replace not compiled as a format replace")
elif not isinstance(format, (compat.string... | 6fd5fee15e3e9a6cac6223564189dad352f64346 | 44,429 |
import time
def validate(val_loader, model, crf_criterion, vb_decoder):
"""
Performs one epoch's validation.
:param val_loader: DataLoader for validation data
:param model: model
:param crf_criterion: viterbi loss layer
:param vb_decoder: viterbi decoder
:return: validation F1 score
"... | fc71d1593a13f607e6ad2ce7087bb56c003b1da8 | 44,430 |
def sort_box(box):
"""
对box排序,及页面进行排版
box[index, 0] = x1
box[index, 1] = y1
box[index, 2] = x2
box[index, 3] = y2
box[index, 4] = x3
box[index, 5] = y3
box[index, 6] = x4
box[index, 7] = y4
"""
box = sorted(box,key=lambda x:sum([x[1],x... | 41946a66cda6bce0371ca11c6c95890608115ab8 | 44,432 |
def get(proj_dir, key) :
"""return settings value by key, default value if the value
doesn't exist in the project-local settings file
:param proj_dir: absolute project directory
:param key: settings key
:returns: settings value, default value for key, or None
"""
util.e... | ade8ac3bac6e8f8889be09f6166078aca6818adf | 44,433 |
from typing import Union
def pair_correlation_neighbor_list(
displacement_or_metric: Union[DisplacementFn, MetricFn],
box_size: Box,
radii: Array,
sigma: float,
species: Array=None,
dr_threshold: float=0.5):
"""Computes the pair correlation function at a mesh of distances.
The pair correl... | b13485e4a11b78948058132040badca2b2b372ca | 44,434 |
import time, random
def generate_trade_id():
"""
采取一定规则生成一个11位的交易号
"""
trade_id = str(time.time())
trade_id = trade_id[:3] + str(random.randint(1000, 10000)) + trade_id[7:10] + trade_id[11]
return trade_id | 79a25817b5eaa0e18c46f419e0373e620d5d9b6f | 44,435 |
def area(spectra, energy, a, b):
"""
This function helps to determinate area under each photopeak through,
trapeziodal method.
Where:
spectra: net count rate vector
energy: energy vector
a: lower limit
b: upper limit
"""
spec = []
spec = spectra
spec = ... | 448cbdedacbfdd9ae16f30c42b942d4dd8925525 | 44,436 |
def create_tuple_1(t0_type_info: CLTypeInfo):
"""Returns CL type information for a byte array.
:param CLTypeInfo t0_type_info: Type information pertaining to first tuple element.
"""
return CLTypeInfoForTuple1(
typeof=CLType.TUPLE_1,
t0_type_info=t0_type_info
) | 4bf3781600bf3ddb6ebf1c4d61268c4ba5ed0e27 | 44,438 |
def request_path( request ):
"""
Get the path of the request
"""
return str(request.path) | 506672b635b6196aa032c7bed5b740c5a8d70c79 | 44,439 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.