content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_azpro():
"""Test module azpro.py by downloading
azpro.csv and testing shape of
extracted data has 3589 rows and 6 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = azpro(test_path)
try:
assert x_train.shape == (3589, 6)
except:
shutil.rmtree(test_path)
raise() | 62,000 |
def _type(array: Array) -> Type | None:
"""Get the type object associated with an array.
Parameters
----------
array : dask_awkward.Array
The collection.
Returns
-------
Type
The awkward type object of the array; if the array does not
contain metadata ``None`` is re... | 62,001 |
def dcgan_discriminator(x, flags, scope=None, reuse=None, return_acts=False):
"""DCGAN-style discriminator network."""
nonlinearity = nonlinearity_fn(flags.nonlinearity_d, True)
ds_fs = flags.downsample_conv_filt_size
x_fs = flags.extra_conv_filt_size
acts = []
with tf.variable_scope(scope, reuse=reuse):
... | 62,002 |
def reconstruct_cfcoeffcients(output_dict, atomtype=None):
"""
Reconstruct the CFCoefficient list from the output dictionary
of the FleurCFCoeffWorkChain
:param output_dict: output dictionary node or the corresponding
dictionary
:param atomtype: int of the atomtype to recons... | 62,003 |
def raise_winerror(winerr=None, msg=None):
"""
Raises :py:exc:`OSError` (formerly :py:exc:`WindowsError`) using the given
Windows Error number. If the error number is not given,
:py:func:`ctypes.GetLastError` is called.
Does nothing if *winerr*, or by default, the result of
:py:func:`cty... | 62,004 |
def test_map_args_size():
"""
Feature: Check the size of inputs of map.
Description: The size of inputs of map must be greater than 1.
Expectation: The size of inputs of map must be greater than 1.
"""
class MapNet(Cell):
def __init__(self):
super().__init__()
sel... | 62,005 |
def get_int_forms(ref_group, isomorphisms):
"""Return a list of integer forms ('permutations') for a list of isomorphisms,
i.e., mappings, based on a reference group."""
return [get_integer_form([iso[elem] for elem in ref_group.elements])
for iso in isomorphisms] | 62,006 |
def header_string(key_length=0, number_of_seconds=2):
""" return a header string for the output file """
header_string = '#'
header_string += ' ' * (key_length+8)
header_string += ' 1 2 3 ' * number_of_seconds + '\n'
header_string += '#'
header_string += ' ' * ... | 62,007 |
def send_message(gmess, address):
"""
Envia un mensaje usando un request y retorna la respuesta como
un grafo RDF
"""
msg = gmess.serialize(format='xml')
r = requests.get(address, params={'content': msg})
# Procesa la respuesta y la retorna como resultado como grafo
gr = Graph()
gr.... | 62,008 |
def test_gpx_to_dataframe(converter):
"""
Tests if the gpx_converter.Converter.gpx_to_dataframe function is working:
Parameters
----------
converter: gpx_converter.Converter
The converter that is used to test this function
"""
result = converter.gpx_to_dataframe()
assert result ... | 62,009 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
config.include('pyramid_chameleon')
log.info('Starting RaspiServer...')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('hom... | 62,010 |
def describe_replication_subnet_groups(Filters=None, MaxRecords=None, Marker=None):
"""
Returns information about the replication subnet groups.
See also: AWS API Documentation
Exceptions
Examples
Returns information about the replication subnet groups.
Expected Output:
:exampl... | 62,011 |
def sparse_average_precision_at_k(y_true: csr_matrix, y_scores: csr_matrix, k: int = 5) -> float:
"""
Computes the average precision at k for sparse binary matrices.
:param y_true: grounded truth in binary format (n_samples, n_labels)
:param y_scores: predictions in representation that can be ranked (e.... | 62,012 |
def load_checkpoint(checkpoint, name, basepath="", use_student_settings=False):
""" Restores Checkpoint
Args:
checkpoint: tf.train.Checkpoint object to restore.
name: name of the checkpoint to restore.
basepath: base directory where checkpoint is located.
student: boolean to indi... | 62,013 |
def do_monitor(args):
""" Handle "monitor" mode.
"""
# If we aren't running in monitor mode, then we are done.
if not args.monitor:
return
# This is the main retry loop.
while True:
# Fork the process.
logger.info('Forking child process.')
pid = os.fork()
# If we are the child, leave this function an... | 62,014 |
def plotpi(benchmark, predicted, target_addr, title, filename, ylim = None, label1=None, label2=None, ylabel=None, legendloc = None):
"""
input:
benchmark -- list[paths]
predicted -- list[paths]
"""
fig = plt.figure()
if title:
plt.title(title)
if ylim:
plt.ylim(y... | 62,015 |
def test_paragraph_series_m_ha_ol_nl_i2_ha_t():
"""
Test case: Ordered list newline indent of 2 atx heading text
was: test_list_blocks_256gxa
"""
# Arrange
source_markdown = """1.
# foo
"""
expected_tokens = [
"[olist(1,1):.:1:3:]",
"[BLANK(1,3):]",
"[end-o... | 62,016 |
def calc_contour_normals_2d(pts,seg):
"""calc 2d normals of contour pts
assume the pts are clockwise around the object
(row,col)
"""
pset = set([tuple(x) for x in pts])
normals = empty((len(pts),2),int)
j=0
for i in xrange(len(seg)):
p1,p2,p3 = [array(seg[x]) for x in (i... | 62,017 |
def build_model(X_train, X_test, y_train, y_test):
"""Build and evaluate a model. Also returns the test-set predictions."""
count_vect = sktext.CountVectorizer()
X_train_counts = count_vect.fit_transform(X_train)
tfidf_transformer = sktext.TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_tra... | 62,018 |
def int_to_comma_hex(n: int, blength: Optional[int] = None) -> str:
"""
int_to_comma_hex
Translates an integer in its corresponding hex string
:type n: ``int``
:param n: Input integer
:type blength: ``Optional[int]``
:param blength: Add padding to reach length
:return: Translated hex ... | 62,019 |
def load_sqlalchemy_response_from_json(filename):
""" Load a sqlalchemy response from a json file """
with open(filename, 'r', encoding="utf-8") as tmp:
data = json.load(tmp)
return load_sqlalchemy_response_from_object(data) | 62,020 |
def get_peaks(runs, signal_type, version='xenonnt_v7', output_folder='/project2/lgrandi/yuanlq/xenonnt/', **kargs):
"""wrapper around get_array to get peaks of a certain source. Now supporting KrS1A, KrS1B, Ar37.
Args:
runs (str or 1darray): runs to extract certain signal. Assumed all type of runs if p... | 62,021 |
def imshow(image, ax=None, title=None):
"""
Print the given image
"""
if ax is None:
fig, ax = plt.subplots()
# PyTorch tensors assume the color channel is the first dimension
# but matplotlib assumes is the third dimension
image = image.transpose((1, 2, 0))
# Undo... | 62,022 |
def svn_wc_diff_callbacks3_invoke_dir_opened(*args):
"""
svn_wc_diff_callbacks3_invoke_dir_opened(svn_wc_diff_callbacks3_t _obj, svn_wc_adm_access_t adm_access,
svn_boolean_t tree_conflicted, char path,
svn_revnum_t rev, void diff_baton) -> svn_error_t
"""
return apply(_wc.svn_wc_diff_call... | 62,023 |
def get_reset_password():
"""Get the user name and email address to reset the password.
:returns: the html form for resetting password
:rtype: str
"""
return template('get_reset_code.html') | 62,024 |
def update_config(original, update):
"""
Recursively update a dict.
Parameters must be specified in original to be overwritten
"""
for basekey, baseval in original.items():
if isinstance(baseval, dict):
for key, val in baseval.items():
if key in update:
... | 62,025 |
def test_mech_snapshot_list_not_created(mock_locate, mock_load_mechfile,
mechfile_one_entry):
"""Test 'mech snapshot list' when vm is not created."""
mock_load_mechfile.return_value = mechfile_one_entry
runner = CliRunner()
result = runner.invoke(cli, ['snapshot',... | 62,026 |
def select_polynomial_degree(n_samples: int = 100, noise: float = 5):
"""
Simulate data from a polynomial model and use cross-validation to select
the best fitting degree
Parameters
----------
n_samples: int, default=100
Number of samples to generate
noise: float, default = 5
... | 62,027 |
def test_list_date_time_max_length_2_nistxml_sv_iv_list_date_time_max_length_3_3(mode, save_output, output_format):
"""
Type list/dateTime is restricted by facet maxLength with value 7.
"""
assert_bindings(
schema="nistData/list/dateTime/Schema+Instance/NISTSchema-SV-IV-list-dateTime-maxLength-3... | 62,028 |
def send_markdown_email(
subject='',
sender=None,
to=None,
cc=None,
bcc=None,
markdown_content=''
):
"""Sends an email w/ text and HTML produced from Markdown
"""
sender = sender or htk_setting('HTK_DEFAULT_EMAIL_SENDER', HTK_DEFAULT_EMAIL_SENDER)
to = to or htk_setting('HTK_DEF... | 62,029 |
def buildNamesPaths(dataRoot, resultsRoot, size, tissue, cellList, runFolder, shortFolderName):
"""Construct paths and stem names for files"""
dataPathList = []
resultsPathList = []
nameList = [] # more concise name for file
for cell in cellList:
# input data paths
currDataPath = os... | 62,030 |
def get_request_id():
"""
获取request_id
"""
try:
return get_request().request_id
except AttributeError:
return "" | 62,031 |
def create_message(to, subject, message_text):
"""Create a message for an email and return a dictionary
object with its "raw" field containing a base64url encoded
string
{'raw': str}
Example for MIMEText object
>>> message = email.mime.text.MIMEText("Hello world")
>>> message['to'] = 'worl... | 62,032 |
def resetconfig(configbase):
"""
Reset configuration in indicated directory
"""
dip_config = (
{ "dipbase": None
, "dipdir": None
})
writeconfig(configbase, dip_config)
return | 62,033 |
def adcm_api_credentials() -> dict:
"""ADCM credentials for use in tests"""
return {"user": "admin", "password": "admin"} | 62,034 |
def unfill_isogeny_matrix(M):
"""
Reverses the action of ``fill_isogeny_matrix``.
INPUT:
- ``M`` -- a square symmetric matrix of integers.
OUTPUT:
(matrix) a square symmetric matrix obtained from ``M`` by
replacing non-prime entries with `0`.
EXAMPLES::
sage: M = Matrix([[0... | 62,035 |
def test_db_watt_conversion_reversible():
"""
Tests that converting from db to watt and back results in the
original db value.
"""
db = 10
assert watt_to_dbm(dbm_to_watt(db)) == approx(db) | 62,036 |
def __on_draw__(event):
"""Auto-wraps all text objects in a figure at draw-time"""
import matplotlib as mpl
fig = event.canvas.figure
# Cycle through all artists in all the axes in the figure
for ax in fig.axes:
for artist in ax.get_children():
# If it's a text artist, wrap it..... | 62,037 |
def expanded_filename():
"""Return the full absolute path to the STACK_TRACE_FILENAME with any environment
variables ($VAR) and users (~user) expanded."""
return os.path.abspath(
os.path.expanduser(
os.path.expandvars(
os.getenv(ENV_STACK_TRACE_FILENAME, DEFAULT_STACK_TRACE_FILENAME)))) | 62,038 |
def _from_csr_ss(csr: _CSR, rsp, rep):
"""
Convert a subset of a Numba CSR to an MKL sparse matrix handle.
"""
_sp = ffi.from_buffer(csr.rowptrs)
_cols = ffi.from_buffer(csr.colinds)
_vals = ffi.from_buffer(csr.values)
return _lk_mkl_spsubset(rsp, rep, csr.ncols, _sp, _cols, _vals) | 62,039 |
def dc(cls: type):
"""Pydantic dataclass decorator with custom configuration and auto update forward references"""
cls = pydantic.dataclasses.dataclass(config=Config)(cls)
cls.__pydantic_model__.update_forward_refs()
return cls | 62,040 |
def populateNetworksId(bam, bam_configuration, bamConfig):
""" Populate the network IDs based on the list of networks defined in iotipallocation.conf to facilitate getNextAvailableIP API call to BAM """
# Get list of Id for the networks
networksId = {}
for location, network in bamConfig['netloc'].items... | 62,041 |
def register_game_events(window):
"""
Function used to register all prepared methods inside window property of GameWindow object.
:param window: GameWindow object
"""
@window.window.event
def on_draw():
on_draw_factory(window)()
@window.window.event
def on_mouse_motion(x, y, dx,... | 62,042 |
def get_contour_data(model, pipeline, n_points=1000):
"""Create the data used to show the boundary of the decision function."""
x0s = np.linspace(X_AXIS[0], X_AXIS[1], n_points)
x1s = np.linspace(Y_AXIS[0], Y_AXIS[1], n_points)
x0, x1 = np.meshgrid(x0s, x1s)
X = np.c_[x0.ravel(), x1.ravel()]
... | 62,043 |
def parse_args():
""" parse_args """
parser = ArgumentParser(description="resnet50 example")
parser.add_argument("--model", type=str, default="resnet50",
help="the network architecture for training or testing")
parser.add_argument("--phase", type=str, default="test",
... | 62,044 |
def http_check_closest_invalid_no_lang(session: requests.Session):
"""HTTP GET /city/v1/closest returns 400"""
res = session.get(URL_PREFIX + "/city/v1/closest")
assert_error_reply(res, 400) | 62,045 |
def test__synchronized_on_instance__class__no_parentheses() -> None:
"""Test `@synchronized_on_instance` with no parentheses."""
# pylint: disable=missing-function-docstring
@synchronized_on_instance
class _Class:
def method(self, variables: Dict[str, Union[int, bool]]) -> str:
loc... | 62,046 |
def get_stacktrace(testcase, stack_attribute='crash_stacktrace'):
"""Returns the stacktrace for a test case.
This may require a blobstore read.
"""
result = getattr(testcase, stack_attribute)
if not result or not result.startswith(data_types.BLOBSTORE_STACK_PREFIX):
return result
# For App Engine, we ... | 62,047 |
async def test_extract_frame_no_integration(caplog):
"""Test extracting the current frame without integration context."""
with patch(
"homeassistant.helpers.frame.extract_stack",
return_value=[
Mock(
filename="/home/paulus/homeassistant/core.py",
linen... | 62,048 |
def test_ap_hs20_eap_fast_gtc(dev, apdev):
"""Hotspot 2.0 connection with FAST/EAP-GTC"""
check_eap_capa(dev[0], "FAST")
eap_test(dev[0], apdev[0], "43[3:6]", "FAST", "user") | 62,049 |
def edit_blogpost(request,blogpost_id):
"""编辑已有条目"""
blogpost = BlogPost.objects.get(id = blogpost_id)
title = blogpost.title
#确认请求的主题属于当前登陆的用户,使用函数check_blog_owner
check_blog_owner(request,title)
if request.method !='POST':
#初次请求,使用当前条目填充表单
form = BlogPostForm(instance = blogpost)
else:
#POST提交的数据,对数据进行处理
... | 62,050 |
def get_points_simple(**kwargs):
"""Load a DataFrame of points with the most typical query
Parameters
----------
**kwargs
Optional arguments that are passed to get_credentials()
Returns
-------
points_df : pandas DataFrame
DataFrame of all points
"""
import warnings... | 62,051 |
def run_text_query(cand_provider,
top_qty,
query_text,
query_id=FAKE_QUERY_ID, field_name=TEXT_FIELD_NAME):
"""Run a text query.
:param cand_provider: a candidate provider object
:param top_qty: a number of top-scored entries to return
:param que... | 62,052 |
def init():
"""Initialises the internal font cache.
It does not need to be called explicitly.
"""
global __FONTCACHE
if __FONTCACHE is not None:
return
__FONTCACHE = {}
if sys.platform in ("win32", "cli"):
_cache_fonts_win32()
elif sys.platform == "darwin":
_cach... | 62,053 |
def download(symbol_source, data_source, output_dir, start, end):
"""Download historical price data."""
try:
azul.get_price_data(symbol_source, data_source, output_dir, start, end)
except Exception as e:
log.error(e)
raise | 62,054 |
def all_scatter_plots(data):
"""
Generate scatter plots for all hard-coded variable pairs
Arguments:
data: pandas dataframe
Returns: scripts, divs
scripts: list of scripts, each as returned by scatter_plot()
divs: list of divs, each as returned by scatter_plot()
"""
# ... | 62,055 |
def make_predictions(*, input_data, save_as: str) -> dict:
"""Predict probability of device failure for the test data
Parameters
----------
input_data : _type_
A csv file containing the test data
save_as : str, optional
name to save the file as, by default None
Returns
----... | 62,056 |
def analyze_mds(mds, files):
"""
Return dictionary with names of package`s type
===================ARGUMENTS==================
mds - list of mds
files - list of files that situated in cwd
"""
builtin = check_builtin(mds)
local = parse_local(mds, files)
outside = parse_outside(mds, lo... | 62,057 |
def test_control_func():
""" test_control_func """
res = scalar_add(3, 4)
assert res == 7
res = scalar_add_if(3, 4)
assert res == 27
res = scalar_mul_while(2)
assert res == 256 | 62,058 |
def init_serializer(serializer=None, **kwargs):
"""Initialize a serializer from a name, class, or instance"""
serializer = serializer or 'pickle'
# Backwards=compatibility with 0.6; will be removed in 0.8
if serializer == 'safe_pickle' or (serializer == 'pickle' and 'secret_key' in kwargs):
seri... | 62,059 |
def load_json_dataset(path):
"""Load json file and store fields separately."""
# Read dataset
data = []
with open(path, encoding='utf-8') as f:
dataset = json.load(f)
# Iterate and write question-answer pairs
for article in dataset['data']:
doc_truth = [utils.normalize(article['t... | 62,060 |
def create_single_mnist(samples=60000, dataset="training", noise=False):
""" Create a dataset where a single MNIST digit is located in the middle of a long image. """
# Extract images and labels from base MNIST files
images, labels = load_mnist(dataset)
new_images = []
new_labels = []
if sample... | 62,061 |
def get_policy_group(description=None,display_name=None,domain=None,id=None,opts=None):
"""
Use this data source to access information about an existing resource.
"""
__args__ = dict()
__args__['description'] = description
__args__['displayName'] = display_name
__args__['domain'] = domain
... | 62,062 |
def get_rot_from_mat(m_mat):
"""
Extracts the rotation from a given MMatrix.
Args:
m_mat
Return:
rot
"""
trans_matrix = oMa.MTransformationMatrix(m_mat)
rot = trans_matrix.rotation()
return rot | 62,063 |
def _dH_df(bss_data, freq_range=None):
"""
Median frequency derivative value of the PS representation of the BSS
components
Parameters
----------
bss_data : numpy.ndarray
Array containing source signals. It must have dimensions CxTxE, where C
is the number of components, T the n... | 62,064 |
def prev_fail_scenario_relevance(context, param1, param2):
"""
Related operations for the previous failure scenario
"""
try:
print("failed info about param", param2)
fail_info = gr.get_rerun_info(param2.strip())
if not (fail_info is None):
if isinstance(fail_info, str... | 62,065 |
def ask_support_exchanges(intent, session):
""" responds support exchanges.
"""
session_attributes = {}
reprompt_text = None
card_title = intent['name']
session_attributes = {}
should_end_session = False
speech_output = "Latest prices are updated from all major crypto currency exchanges... | 62,066 |
def Language_req(description):
"""Create a function that captures the language requirements from the job description"""
description = description.lower()
matches = re.findall(r"\benglish\sand\sgerman\b|\bgerman\sand\senglish\b\benglisch\sund\sdeutsch\b|\benglish\b|\benglisch\b|\bgerman\b|\bdeutsch\b", descr... | 62,067 |
def LogN(mu, sigma, tag=None):
"""
A Log-Normal random variate
Parameters
----------
mu : scalar
The location parameter
sigma : scalar
The scale parameter (must be positive and non-zero)
"""
assert sigma>0, 'Sigma must be positive'
return uv(rv=ss.lognorm(sigma, ... | 62,068 |
def test03(ntest, prefix='fig-v01') :
"""Test for 2-d binning of the restricted rad-phi range of entire image
"""
from time import time
import algos.graph.GlobalGraphics as gg
from PSCalib.GeometryAccess import img_from_pixel_arrays
arr, geo = data_geo(ntest)
iX, iY = geo.get_pixel_coord_i... | 62,069 |
async def worker(
processor: WatchStreamProcessor,
streams: Streams,
key: ObjectRef,
) -> None:
"""
The per-object workers consume the object's events and invoke the processors/handlers.
The processor is expected to be an async coroutine, always the one from the framework.
In fa... | 62,070 |
def matrix_hits(binary_matrix):
"""Gets the number of cells with value 1 in matrix."""
logging.info("Counting how many contacts are predicted.")
count = 0
(n1, n2) = binary_matrix.shape
for i in range(n1):
for j in range(n2):
if j > i:
count += binary_matrix[i, ... | 62,071 |
def svn_wc_create_notify_url(*args):
"""svn_wc_create_notify_url(char url, svn_wc_notify_action_t action, apr_pool_t pool) -> svn_wc_notify_t"""
return _wc.svn_wc_create_notify_url(*args) | 62,072 |
def erpnext_ebay_save_file_on_filesystem_hook(*args, **kwargs):
"""Intercept all write_file events, and mogrify images
Replaces the standard write_file event. Obtains the filename, content_type
etc. Calls the normal backup 'save_file_on_filesystem' with all arguments.
If we do not handle the attachment... | 62,073 |
def main( input_df, name, detailed=False ):
"""
Each OTU is now ordered by centrality and the AUC of each is calculated.
:param input_df: Important features and OTUs that have been passed on to be ordered
:param name: name attached to all detailed output
:param detailed: Output helper tables
:re... | 62,074 |
def cal_wordInCategory_fre(train_file):
"""
:param trian_file: 训练文件 : 分为两列 <label,doc_words>
:return:
"""
# 统计每个类别中,每个词的词频
wordInCategory_dict = {} # key:label value: dict{key:word value:count}
with open(train_file,'r',encoding='utf-8') as f:
for line in f.readlines():
... | 62,075 |
def _team_info(data, parsed_data):
"""Metadata of a players Season - Team info."""
parsed_data['team_data'] = defaultdict(lambda: None)
parsed_data['team_data']['full_name'] = data['team'].get('name')
# most team names have no id, simple hash for the id
team_id_hash = sum([ord(x) for x in parsed_da... | 62,076 |
def get_elapsed_time_ms(start_time_in_seconds: float):
"""
Returns the elapsed time in millis from the given start time.
"""
end_time = time.time()
return int((end_time - start_time_in_seconds) * 1000) | 62,077 |
def to_rgba(color):
"""
Convert from `colRGB`.
`colRGB` is a `wxPython` type which is basically `BGR`. We don't want to work with
`BGR`, so being able to simply convert `RGB` is preferable.
The algorithm is actually the same swapping in either direction, but having a clear name
makes it obviou... | 62,078 |
def days_in_month_366(month, year=0):
"""Days of the month (366 days calendar).
Parameters
----------
month : int
numerical value of the month (1 to 12).
year : int, optional
(dummy value).
Returns
-------
out : list of int
days of the month.
Notes
----... | 62,079 |
def clear_records(document_id):
"""Delete all records associated with the given document."""
q = {'term': {'document_id': document_id}}
query_delete(records_index(), q) | 62,080 |
def connectedvmware_extension_list(
client: MachineExtensionsOperations,
resource_group_name,
vm_name,
expand=None
):
"""
List all the vm extension of a given vm.
"""
return client.list(resource_group_name=resource_group_name,
name=vm_name,
... | 62,081 |
def plot_energy_from_initial_source(
energy_bins=np.linspace(0, 20e6, 50),
input_filename='initial_source.h5'):
"""makes a plot of the energy distribution of the source"""
f = h5py.File(input_filename,'r')
dset = f['source_bank']
e_values = []
for particle in dset:
e_value... | 62,082 |
def _get_date_from_yyyymmdd(original_date):
""" if date is in YYYYMMDD format, return date """
valid_date = ""
try:
valid_date = datetime.datetime.strptime(original_date, '%Y%m%d')
except ValueError:
pass
return valid_date | 62,083 |
def do_transactions(account):
"""Ask to Deposit, Withdraw, or Finish; write new account file
when finished. The account parameter is an Account object."""
# Prompt for D)eposit, W)ithdraw, or F)inish and convert to uppercase
action = input('D)eposit, W)ithdraw, or F)inish: ')
action = act... | 62,084 |
async def test_http_spec_version_is_missing_or_correct(mock_app):
"""
asgi["spec_version"] (Unicode string) – Version of the ASGI HTTP spec this server
understands; one of "2.0" or "2.1". Optional; if missing assume 2.0
https://asgi.readthedocs.io/en/latest/specs/www.html#http-connection-scope
Tes... | 62,085 |
def plot_raw_spikes_in_rows(waveforms, assignments, spacing=1, width=1, vscale=1,
subplot_adj=0.9, colors=DEFAULT_COLORS, figtitle="",
figdir="./", fname_postfix="", show=True):
"""Plot raw spikes, each spike in a separate row and each channel in a separate ... | 62,086 |
def on_open(ws):
"""
Starts a new thread that loops, taking user input and sending it to the websocket.
:param ws: websocket.WebSocketApp that sends messages to a browser_manager
"""
threading.Thread(target=_run_browser).start() | 62,087 |
def run_request(bunch, url):
"""Run and time a request with the python requests library
"""
import requests
import time
import numpy as np
try:
time.sleep(np.random.random_sample()*10)
start = time.time()
response = requests.post(url=url, json=bunch)
assert respon... | 62,088 |
def rdfile_reader(filename):
"""Generator function returning individual reactions from the specified
RD file."""
lr = LineReader(filename)
read_rdf_header(lr)
keep_reading = True
while keep_reading:
reaction, keep_reading = read_reaction(lr)
yield reaction
lr.close() | 62,089 |
def numeric_plots(df):
"""
Creating a matrix of correlation plots with the numeric features.
Parameters
----------
df: pandas.dataframe
A pandas dataframe
Returns
-------
splom: Altair chart object
The Altair object for the plots
Example
-------
... | 62,090 |
def _kv_read_checked(conf, key, default=None):
# type: (dict, str, obj) -> obj
"""Read a key as some value with a check against None and length
:param dict conf: configuration dict
:param str key: conf key
:param obj default: default to assign
:rtype: obj or None
:return: value of key
""... | 62,091 |
def authorization(request, user_name):
""" 메일로 발송된 인증 url로 요청했을 때 작동하는 views """
name = base64.b64decode(user_name.encode('utf-8')) # 인코딩되었던 email name 부분을 디코딩
email = name.decode('utf-8') + '@knu.ac.kr' # 뒤에 knu.ac.kr를 붙여서 완전한 메일 구성
user = User.objects.get(email=email)
user.is_active = True #... | 62,092 |
def info(ctx: click.Context) -> None:
"""Show information on the kong instance."""
info = get("information", lambda: information(ctx.obj["session"]))
click.echo(json_pretty(info)) | 62,093 |
def main():
"""Train model.
"""
config = load_config()
human36m = get_dataset(config)
model = get_model(config)
criterion = get_criterion(config)
optimizer = get_optimizer(config, model)
lr_scheduler = get_lr_scheduler(config, optimizer)
device = get_device(config.USE_CUDA)
# P... | 62,094 |
def registry() -> Dict[str, Dict]:
"""
Return a dictionary of problems of the form:
`{
"problem name": {
"params": ...,
},
...
}`
where `flexs.landscapes.RosettaFolding(**problem["params"])` instantiates the
rosetta folding landscape for the given set of para... | 62,095 |
def _Cfunction(name, flags, *types):
"""(INTERNAL) New ctypes function binding.
"""
if hasattr(dll, name):
p = ctypes.CFUNCTYPE(*types)
f = p((name, dll), flags)
_Cfunctions[name] = f
return f
raise NameError('no function %r' % (name,)) | 62,096 |
def update_quarter_scores(game):
"""
Utility to update quarter scores for existing games. New games handled via ncaa_loader.
"""
doc = urllib.urlopen(game.get_ncaa_xml_url()).read()
soup = BeautifulSoup(doc)
quarters = len(soup.findAll('score')[1:])/2
t2_quarters = soup.findAll('score')[1:qu... | 62,097 |
def no_alpha(rv, host, companion, limits, new_x=None, normalize=True):
"""Entangled spectrum model with entrinsic flux ratio.
Need to make sure to mulitply by the radius**2 of the respective star.
Parameters
----------
rv: float
rv offset of the companion spectrum.
host: Specturm
... | 62,098 |
def make_output(lights_to_render):
"""
Prints out the lights in the desired format. Only a helper function. Not used.
:param lights_to_render: lights that should be rendered.
:return: nothing
"""
output = ""
for light_strip in lights_to_render:
for light in light_strip:
o... | 62,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.