content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def get_weak_model(op, diff_type, nonzero2nonzero_weight, zero2zero_weight=0,
zero2nonzero_weight=math.inf, nonzero2zero_weight=math.inf, precision=0):
"""Return the weak model of the given bit-vector operation ``op``.
Given the `Operation` ``op``, return the
`WeakModel` of... | be34db3112ff7788bb96e6d6cc467d4d98d8af51 | 2,661 |
def get_temp():
"""
読み込んだ温度を返す
"""
return sensor.t | a4c7ed616af202599581cd47be87cb10ea571947 | 2,662 |
def load_clean_yield_data(yield_data_filepath):
"""
Cleans the yield data by making sure any Nan values in the columns we care about
are removed
"""
important_columns = ["Year", "State ANSI", "County ANSI", "Value"]
yield_data = pd.read_csv(yield_data_filepath).dropna(
subset=important_c... | 14c5facc947d1ff8bcc7714447e9da3b7842bcee | 2,663 |
def create_element_mapping(repnames_bedfile):
"""Create a mapping of the element names to their classes and families"""
elem_key = defaultdict(lambda : defaultdict(str))
with open(repnames_bedfile, "r") as bed:
for line in bed:
l = line.strip().split("\t")
name = l[3]
... | d3bc0491625d318b8f049c71a10571c21caf03d8 | 2,664 |
def _get_CRABI_iterators(captcha_dataframe,
train_indices,
validation_indices,
batch_size,
image_height,
image_width,
character_length,
catego... | 7e01586f359860b5d1e461e9612b164e6cf9365f | 2,665 |
import uuid
def run(request, context):
"""Creates a template.
Args:
request (orchestrate_pb2.CreateTemplateRequest): Request payload.
context: Context.
Returns:
A orchestrate_pb2.CreateTemplate with the status of the request.
"""
template = request.template
print('Orchestrate.CreateTemplate ... | 484de4399b23bbc71e35ad70b054c1a62c41952e | 2,666 |
def fit_2dgaussian(data, error=None, mask=None):
"""
Fit a 2D Gaussian to a 2D image.
Parameters
----------
data : array_like
The 2D array of the image.
error : array_like, optional
The 2D array of the 1-sigma errors of the input ``data``.
mask : array_like (bool), optiona... | 6ac3c7b7cba17baba719bd1d1fc87030f9c45dca | 2,667 |
def to_roman(number):
"""
Converts an arabic number within range from 1 to 4999 to the
corresponding roman number. Returns None on error conditions.
"""
try:
return roman.toRoman(number)
except (roman.NotIntegerError, roman.OutOfRangeError):
return None | 48fbe99caa527e711f8d0285577d96941a34b9c9 | 2,669 |
def GDAL_like(filename, fileout=""):
"""
GDAL_like
"""
BSx, BSy, Mb, Nb, M, N = 0,0, 0,0, 0,0
dataset1 = gdal.Open(filename, gdal.GA_ReadOnly)
dataset2 = None
if dataset1:
band1 = dataset1.GetRasterBand(1)
M, N = int(dataset1.RasterYSize), int(dataset1.RasterXSize)
B ... | 34d4ea83a7c7e1726aa1d5a4d89e16bbed50cdd1 | 2,670 |
def take_attendance(methodcnt):
"""global setup_bool
if (setup_bool == False or methodcnt == False):
print ("in if statement")
setup_bool = True
else:"""
print ("checking in - F.R.")
react_with_sound(attendance_final)
client.CheckIn()
return 2 | 0ecdf80e59de5d968f7adc042d6be369367f4195 | 2,671 |
def feature_selection(data, features):
"""
Choose which features to use for training.
:param data: preprocessed dataset
:param features: list of features to use
:return: data with selected features
"""
return data[features] | 6303e52a9c64acfbb5dcfd115b07b3bef2942821 | 2,672 |
def parse_docstring(docstring, line=0, filename='<string>', logger=None,
format_name=None, options=None):
# type: (str, int, Any, Optional[logging.Logger], Optional[str], Any) -> Tuple[OrderedDict[str, Arg], Optional[Arg]]
"""
Parse the passed docstring.
The OrderedDict holding pars... | 47cd0318f24ec1a26233ad6e98a398a4c9e95db6 | 2,673 |
def srCyrillicToLatin(cyrillic_text):
"""
Return a conversion of the given string from cyrillic to latin, using
'digraph' letters (this means that e.g. "nj" is encoded as one character). Unknown
letters remain unchanged.
CAVEAT: this will ONLY change letters from the cyrillic subset of Unicode.
For in... | cd4850b6c0bcf9b27aa1340dc98956c026e8f557 | 2,674 |
def from_phone(func=None):
"""来自手机的消息(给自己发的) FriendMsg"""
if func is None:
return from_phone
async def inner(ctx):
assert isinstance(ctx, FriendMsg)
if ctx.MsgType == MsgTypes.PhoneMsg:
return await func(ctx)
return None
return inner | 8e47e82e014d3d727a615e310997cd2c634ae821 | 2,675 |
import pathlib
def create_scan_message():
"""Creates a dummy message of type v3.asset.file to be used by the agent for testing purposes.
The files used is the EICAR Anti-Virus Test File.
"""
file_content = (pathlib.Path(__file__).parents[0] / 'files/malicious_dummy.com').read_bytes()
selector = 'v... | e899e705fc022046876dd2a1584e7db74c4b7105 | 2,677 |
def is_permutation_matrix( m ):
"""
Test whether a numpy array is a `permutation matrix`_.
.. _permutation_matrix: https://en.wikipedia.org/wiki/Permutation_matrix
Args:
m (mp.matrix): The matrix.
Returns:
(bool): True | False.
"""
m = np.asanyarray(m)
return (m.nd... | 7cfe48fd0cd36c4ff151ebe248c79e685ee99cc8 | 2,678 |
def create_security_role(connection, body, error_msg=None):
"""Create a new security role.
Args:
connection: MicroStrategy REST API connection object
body: JSON-formatted definition of the dataset. Generated by
`utils.formjson()`.
error_msg (string, optional): Custom Error M... | fbae3596e0cdcc430b2a7a30fc9ed594f3717ba3 | 2,679 |
def dbm_to_w(dbm):
"""Convert dBm to W."""
return 10 ** (dbm / 10.) * sc.milli | b6b782f35a3a07a2f372958363609b3b0f00a43a | 2,680 |
from operator import inv
def lml(alpha, beta, Phi, Y):
"""
4 marks
:param alpha: float
:param beta: float
:param Phi: array of shape (N, M)
:param Y: array of shape (N, 1)
:return: the log marginal likelihood, a scalar
"""
N = len(Phi)
M = len(Phi[0])
part1 = (-N*0.5)*np.l... | a6d17ed0f6c81958360687d5758cd8a35147dd56 | 2,681 |
def balance_set(X, Y, adr_labels_size, nonadr_labels_size):
"""balances the set by doing up- and down -sampling to converge into the same class size
# Arguments
X - set samples
Y - set labels
adr_labels_size - ADR_MENTION_CLASS size
nonadr_labels_size - NON_ADR_MENTION_CLASS siz... | e73468dd600a9d6f9b13a46356110d35fba8ce59 | 2,683 |
from pathlib import Path
def load_det_lcia(result_dir, method, act_code, det_lcia_dict=None):
"""Return precalculated deterministic LCIA score"""
result_dir = Path(_check_result_dir(result_dir))
method = _check_method(method)
if not det_lcia_dict:
det_lcia_dict = _get_det_lcia_dict(result_dir,... | c9ba6532f674bcbe988cdc645b7dd86a93ed27e5 | 2,684 |
def get_geometry(location, geolevel):
"""
Get geometry of a single location code/name
"""
if not utils.is_number(location) and location != "BR":
assert geolevel, "You need to specify which geographic level this location is"
location = ibgetools.ibge_encode(location, geolevel)
if loca... | da53cfe7845c7adffbcbd941dc3f0b62bdb15e2f | 2,685 |
def render_to_string(template, context={}, processors=None):
"""
A function for template rendering adding useful variables to context
automatically, according to the CONTEXT_PROCESSORS settings.
"""
if processors is None:
processors = ()
else:
processors = tuple(processors)
for processor in get_st... | 678eab60113a05fba86591ee7bb47e26ecfb0b37 | 2,686 |
def find_node_names(structure):
""" Return the names of the nodes for the structure """
# Look through all of the items in the structure for names
# Check through each of the lists and sub-lists
names=set()
for i in xrange(len(structure)):
if isinstance(structure[i],basestring):
... | 812194e2d8dbd34741e9f03a6c775bb30f551341 | 2,687 |
def handle_question():
"""Save response and redirect to next question."""
# get the response choice
choice = request.form['answer']
# add this response to the session
responses = session[RESPONSES_KEY]
responses.append(choice)
session[RESPONSES_KEY] = responses
if (len(responses) == l... | 184dc816303f48e134320f602126d381ee820b59 | 2,689 |
from typing import Callable
def makeNotePlayer(seq: Sequencer, out: PortInfo
) -> Callable[[int, bool], None]:
"""Returns a callable object that plays midi notes on a port."""
def playNote(note: int, enabled: bool) -> None:
if enabled:
seq.sendEvent(NoteOn(0, 0, note, 127), out)
... | 7cb9741944f6f71fbfd55b825c2c7e4638bfa317 | 2,690 |
import base64
def file_to_attachment(filename):
"""
Convert a file to attachment
"""
with open(filename, 'rb') as _file:
return {'_name':filename,
'content':base64.b64encode(_file.read())
} | 9b64fe8a4329eae000cd76d58450c32644a736f6 | 2,692 |
def diff_mean(rolling_window, axis=-1):
"""For M5 purposes, used on an object generated by the
rolling_window function. Returns the mean of the first
difference of a window of sales."""
return np.diff(rolling_window, axis=axis).mean(axis=axis) | 85294f16c89658eaca9562e1ff4652d5865a5a59 | 2,694 |
import numpy
def noiseFraction(truth_h5, measured_h5, tolerance):
"""
Return the fraction of measured localizations that are greater than
tolerance pixels from the nearest truth localization.
Note: This will return 0 if there are no measured localizations.
truth_h5 - A saH5Py.SAH5Py object with ... | 282e8c835906cf218e6eb1ef94cbb595419419f5 | 2,695 |
def compute_rigid_flow(depth, pose, intrinsics, reverse_pose=False):
"""Compute the rigid flow from target image plane to source image
Args:
depth: depth map of the target image [batch, height_t, width_t]
pose: target to source (or source to target if reverse_pose=True)
camera transformation matri... | 5b01bfb9768bc1f180b06f599e71c4808c945854 | 2,697 |
def get_versions(script_name):
""" 返回指定名称脚本含有的所有版本。"""
versions = repository.get(script_name, None)
if not versions:
return None
return sorted(versions, reverse=True) | 4399c5531bbf0d10f750d64ce3a63e156d62ba1b | 2,698 |
from typing import Any
def linear_search_while(lst: list, value: Any) -> int:
"""Return the index of the first occurrence of value in lst, or return
-1 if value is not in lst.
>>> linear_search([2, 5, 1, -3], 5)
1
>>> linear_search([2, 4, 2], 2)
0
>>> linear_search([2, 5, 1, -3], 4)
-1... | c90c39148b5c30fbb4f6732e322d03632ad63b39 | 2,701 |
def get_pagerduty_secret_name():
"""
Get name of the PagerDuty secret for currently used addon.
Returns:
string: name of the secret
"""
return config.DEPLOYMENT["addon_name"] + constants.MANAGED_PAGERDUTY_SECRET_SUFFIX | be731e1dcebc3f8a225e249def332abd0d8ea71b | 2,702 |
from typing import Dict
def check_docs(
doc_path: str, recurse: bool = True, max_threads: int = 10, delay: float = 0
) -> Dict[str, Dict[str, UrlResult]]:
"""
Check multiple HTML files in `doc_path`.
Parameters
----------
doc_path : str
Path
recurse: bool
If True, recurse ... | c3cc03a61f633143d03f8bfa1063242de8797bfa | 2,703 |
def timeParser(dstr):
"""
parse clock time string into array
"""
hh, mm, ss = dstr.split(':')
return np.array([hh, mm, ss]).astype(int) | 3b4f72ceaf4f2e9bd5fc93664d896537ad0f9884 | 2,706 |
import struct
def get_43_ai_core_data(input_file=None):
"""Function for getting datas from aicore: ov/cnt/total_cyc/ov_cyc/pmu_cnt/stream_id."""
result_data = []
with open(input_file, 'rb') as ai_core_file:
while True:
line_ = ai_core_file.read(128)
if line_:
... | 03c9a62a4fd2a2041489cbcb19e2e8e4788e6b0d | 2,707 |
from typing import Type
def get_configuration_class_with_attributes(
klass: Type[AlgorithmConfiguration],
) -> Type[AlgorithmConfiguration]:
"""Get AlgorithmConfiguration with set attributes.
Args:
klass: a class to be used to extract attributes from.
Returns:
a class with the attrib... | ae8ea9b30781854269eb97da6889d1a61ae29935 | 2,708 |
def get_token_symbol(token_address: str):
"""
Gets the token symbol
If not have the external method `symbol` to get the score symbol,
it will raise JSONRPCException.
"""
call = CallBuilder()\
.from_(wallet.get_address())\
.to(token_address)\
.method("symbol")\
.b... | 9c84fbcb893345f701d8ce0d24509dd595139d8c | 2,709 |
def iceil(x):
"""
Return the ceiling of the input, element-wise.
The ceil of the scalar `x` is the smallest integer `i`, such
that `i >= x`. It is often denoted as :math:`\lceil x \rceil`.
Parameters
----------
x : array_like
Input data.
Returns
-------
y : {numpy.nda... | bdc893fe00f073393240b1a861e79c9c4667abc4 | 2,710 |
from typing import Optional
import yaml
def get_repo_version(filename: str, repo: str) -> Optional[str]:
"""Return the version (i.e., rev) of a repo
Args:
filename (str): .pre-commit-config.yaml
repo (str): repo URL
Returns:
Optional[str]: the version of the repo
"""
wit... | 821653bdeb60a86fce83fb3a05609996231ec5d4 | 2,711 |
from typing import Iterator
from typing import Tuple
import torch
def plot_grad_flow(named_parameters: Iterator[Tuple[str, torch.nn.Parameter]]) -> plt.Figure:
"""
Plots the gradients flowing through different layers in the net during training.
Can be used for checking for possible gradient vanishing / ex... | cc0bd23b8cea9359e003cff7c414ce80fcbf5b1b | 2,712 |
from typing import Dict
from typing import Any
def mk_cli_context_settings(
mk_db: CliCtxDbBase.MkFnT,
) -> Dict[str, Any]:
"""Create initial click context parameters for this cli application.
This is currently used as input for autocompletion.
Example:
`@click.group(context_settings=mk_cli_... | 09f232936ef3c09a5c00edada04a31a64058aaad | 2,713 |
import requests
import ast
def get_file_action(header: 'dict[str,str]') -> str:
"""Gets action file form main repo
Args:
header (dict[str,str]): Header with auth token
Raises:
get_aciton_file_e: Raised when no aciton file was collected
Returns:
str: T... | d1c6eb349aea156e2180f5218e247e86a8a60f3c | 2,714 |
from typing import Union
from typing import Callable
import warnings
def sensor(raw_input_shape: StandardizedTensorShape, f: SensorFunction = None,
sensor_id: str = None, history: int = None) \
-> Union[Callable[[SensorFunction], SensorLambda], SensorLambda]:
"""Decorator for creating sensors f... | 0bfa60c70cc43cd0929a8db840469d8fd6ffbac7 | 2,715 |
def collection(collection, _pod=None):
"""Retrieves a collection from the pod."""
return _pod.get_collection(collection) | 6d95c9afbcdbb2fe81f71b9d4f17be50aec1aea4 | 2,717 |
def appif(cfg):
"""
Return interface belonging to application
"""
return get_interface_of_network(appnet(cfg)['name']) | e13f7cee8f4785e82bc558500d5d4938a3c728f2 | 2,718 |
def f(x):
"""
Try and have the NN approximate the
xor function.
"""
if x[0] == x[1]:
return 0.
else:
return 1. | 8111e53f0ff0dfdd75f08d845e5176bc287a65e1 | 2,719 |
import pandas
import json
def dataframe_to_list(df: pandas.DataFrame) -> list:
"""
Use caution with datetime columns, as they may not be de/serialized as desired
"""
return json.loads(df.to_json(orient="records")) | 244f76f1970364f13ddf6bb53a6280962d0ae45a | 2,720 |
def decimal_to_binary(integer,nbits=8,grouped=0):
"""Converts integer to binary string of length nbits, sign bit and
then m.s.b. on the left. Negative numbers are twos-complements, i.e.,
bitwise complement + 1."""
# Just remember that minus sign and ignore it
if integer < 0:
negative = True... | 89cef0feaad6d1c25dd67b97a0caf2212ea4a55d | 2,721 |
def line_integrals(state, uloc, vloc, kind="same"):
"""
calculate line integrals along all islands
Arguments:
kind: 'same' calculates only line integral contributions of an island with itself,
while 'full' calculates all possible pairings between all islands.
"""
vs = state.v... | 4a8b32246a9a60d9a42368d7643bc6ddea1c44d0 | 2,722 |
def _BBANDS(kwargs):
"""
布林带
技术参数
-------
使用21天,2倍
"""
df = kwargs.get('df')
limit_start = kwargs.get('limit_start')
limit_end = kwargs.get('limit_end')
ndays = 21
inds = indicators(
'BBANDS', df, timeperiod=ndays).loc[limit_start:limit_end, :]
traces = []
fo... | ee19ee06b5fb6a306f6d43285a616e61584c65a8 | 2,723 |
from typing import Optional
from typing import Iterable
from typing import Tuple
def make_colors(color: OpColor, fill_color: OpColor, colors: Optional[Iterable[OpColor]]) -> Tuple[OpColor, ...]:
"""Creates final colors tuple."""
if colors is None:
return conform_color(color), conform_color(fill_color)... | 8bba1bef72543fb4bd497ada924d23ebf2692f7c | 2,724 |
def print_qa(questions,
answers_gt,
answers_gt_original,
answers_pred,
era,
similarity=dirac,
path=''):
"""
In:
questions - list of questions
answers_gt - list of answers (after modifications like truncation)
a... | 01b44361066668462868abed00f49811e0648d11 | 2,725 |
def recast_to_supercell(z, z_min, z_max):
"""Gets the position of the particle at ``z`` within the simulation
supercell with boundaries ``z_min`` y ``z_max``. If the particle is
outside the supercell, it returns the position of its closest image.
:param z:
:param z_min:
:param z_max:
:retur... | 2d144a656a92eaf3a4d259cf5ad2eadb6cfdf970 | 2,726 |
from typing import List
from typing import Optional
import io
import csv
async def get_pedigree(
internal_family_ids: List[int] = Query(None),
response_type: ContentType = ContentType.JSON,
replace_with_participant_external_ids: bool = True,
replace_with_family_external_ids: bool = True,
include_h... | 5ecf064d82a6391d3ed025aeac2bf070710d5ebe | 2,729 |
def lang_string_set_to_xml(obj: model.LangStringSet, tag: str) -> etree.Element:
"""
serialization of objects of class LangStringSet to XML
:param obj: object of class LangStringSet
:param tag: tag name of the returned XML element (incl. namespace)
:return: serialized ElementTree object
"""
... | f49a1d73f1fd4354c245427bc1277600c67a5d99 | 2,730 |
def grasp_from_contacts(contact1,contact2):
"""Helper: if you have two contacts, this returns an AntipodalGrasp"""
d = vectorops.unit(vectorops.sub(contact2.x,contact1.x))
grasp = AntipodalGrasp(vectorops.interpolate(contact1.x,contact2.x,0.5),d)
grasp.finger_width = vectorops.distance(contact1.x,contac... | 945ff950a59b1442efc6abdce68861957b0a60a7 | 2,731 |
def boolean_dumper(dumper, value):
"""
Dump booleans as yes or no strings.
"""
value = u'yes' if value else u'no'
style = None
return dumper.represent_scalar(u'tag:yaml.org,2002:bool', value, style=style) | 40a6a270d1ad1a289947c064c7f85edb1d589bb7 | 2,734 |
def preprocess_data_4_catboost(data_df, output_path=None):
"""
preprocess data for working with gradient boosting techniques
specifically with the catboost library. since this is going to use
the preprocessing built into the catboost library there are slightly
different steps to be done
"""
... | 9bc60ca096963fe6fb8a30e19442d870694f1339 | 2,735 |
def conv_current_to_electrons_second(current):
"""
Convert a current in Amps to a number of
electrons per second.
"""
return int(current / const.electron_charge) | 76051a529c230b54a6d07f282c97b48d4ea59758 | 2,736 |
import json
def get_users():
"""
Use urllib3 to make a REST call to get list of Okta
Users for a given Okta Application
"""
request_url = f"{OKTA_URL}/apps/{OKTA_APP_ID}/users"
okta_users_request = HTTP.request(
'GET',
request_url,
headers={'Content-Type': 'application/... | b94816de46d843a3a80a53c569d52b17e142d4e9 | 2,737 |
def n_sample_per_class_train_set(df, n_samples=3, class_column="category"):
"""
returns a subset of the provided df that contains n_samples instances of each class
:param df: panda dataframe that contains hidden_reps with class labels
:param n_samples: number of samples per class
:param class_column: column w... | 107d9845b8e5efb3da09f13d11ae796fc560b874 | 2,738 |
def clip_count(cand_d, ref_ds):
"""Count the clip count for each ngram considering all references."""
count = 0
for m in cand_d.keys():
m_w = cand_d[m]
m_max = 0
for ref in ref_ds:
if m in ref:
m_max = max(m_max, ref[m])
m_w = min(m_w, m_max)
count += m_w
return count | f33ad8c5a9de8e136ea97684de3bd64779471bb6 | 2,739 |
def container_wrapper(directive, literal_node, caption, classes):
"""adapted from
https://github.com/sphinx-doc/sphinx/blob/master/sphinx/directives/code.py
"""
container_node = docutils.nodes.container(
'', literal_block=True, classes=classes) # ['literal-block-wrapper']
parsed = docutils.... | 17e9db3f494174a721cd80c179514bbc3db773c1 | 2,740 |
def get_current_and_next_quarters(request, num):
"""
Returns the current and next num uw_sws.models.Term objects in a list
for the current quarter refered in the user session. Returns the next
num -1 quarters along with the current one.
"""
term = get_current_quarter(request)
quarters = [ter... | 26f5d268148d3f0395d1d41739d51b1f06a0bd6a | 2,741 |
from typing import Tuple
from typing import Dict
def _create_metadata_from_dat_df(
csv_df: pd.DataFrame,
) -> Tuple[Dict[int, tuple], Pitch]:
"""Creates meta information from the CSV file as parsed by pd.read_csv().
Parameters
----------
csv_df: DataFrame
Containing all data from the posi... | d53e66ff343c2391058e2717dde5bbe7c11a2c44 | 2,742 |
def main():
"""
Main function used in script, primarily used as a handle
to get the output into stdout.
"""
# There are no args, but parse them just so help works
print(process_files_json(), end="")
return None | 495af3e19cdd823ee6853f516b17df0c489f34f9 | 2,743 |
def expand(doc, doc_url="param://", params=None):
"""
ASSUMING YOU ALREADY PULED THE doc FROM doc_url, YOU CAN STILL USE THE
EXPANDING FEATURE
USE mo_json_config.expand({}) TO ASSUME CURRENT WORKING DIRECTORY
:param doc: THE DATA STRUCTURE FROM JSON SOURCE
:param doc_url: THE URL THIS doc CAME... | d8a8045cb6afea089f1241dc1a47bf6c95fc3628 | 2,745 |
def get_model_creator(hparams):
"""Get the right model class depending on configuration."""
if hparams.architecture == 'peng':
model_creator = model.Model
"""vanilla lstm, seq2seq"""
return model_creator | 84c65108e6be1a723184778db564b75ea333d52f | 2,746 |
import unittest
def extra():
"""Tests faint.extra. That is, less central faint code, possibly
requiring extensions (e.g. tesseract or GraphViz dot).
"""
return unittest.defaultTestLoader.discover("py_tests/test_extra",
top_level_dir="py_tests/") | c6fc2694144e852edaef219d95bc384b5b394d7d | 2,747 |
def cmd_te_activate(abs_filename):
"""最前面に持ってくる(テキストエディタ向け)
ファイルが含まれるVisual Studioを探し出して最前面に持ってくる。
abs_filename- ファイル名の絶対パス
(Ex.) c:/project/my_app/src/main.cpp
"""
return _te_main2(cmd_activate,abs_filename) | 2a4922c89360f049c50cc2b2b81509c48d32968e | 2,748 |
def search(search_domain, fmt=None):
"""Handle redirect from form submit."""
domain = tools.parse_post_data(search_domain)
if domain is None:
return handle_invalid_domain(search_domain)
if fmt is None:
if features.enable_async_search():
return flask.redirect('/search?ed={}'... | 4be9a751fad12fae67a34b7c4bda2b2be3d7ff89 | 2,749 |
def get_graph_from_particle_positions(
particle_positions, box_lengths, cutoff_distance, store_positions=False
):
"""Returns a networkx graph of connections between neighboring particles
Args:
particle_positions (ndarray or dataframe): Shape
(`n_particles`, `n_dimensions`). Each of ... | a51ecbfd83fe08ae07f4e6952f2796eba9f79f0a | 2,750 |
import numpy as np
def cca(x,y):
""" canonical correlation analysis cca
wx, wy, r = cca(x,y) returns wx, wy two matrices which columns [:,i] correspond to the canonical weights (normalized eigenvectors) and a vector r containing the canonical correlations, all sorted in decreasing order. cca assumes... | f0d734fc927789d6ecca0685a85f727e48b334df | 2,751 |
def train_models(vae, emulator, em_lr, vae_lr, signal_train, dataset, val_dataset,
epochs, vae_lr_factor, em_lr_factor, vae_min_lr, em_min_lr, vae_lr_patience, em_lr_patience,
lr_max_factor, es_patience, es_max_factor):
"""
Function that train the models simultaneously
:par... | a3301f178aade90cb5a5b441ccf7607e2f13c776 | 2,753 |
def get_next_term(cfg):
"""
Gets the next term to be added.
Args:
cfg: Expression config
"""
term = {}
if np.random.choice(['quantity', 'number'], p=[cfg.ratio, 1 - cfg.ratio]) == 'quantity':
idx = np.random.choice(range(len(cfg.quants)))
if cfg.reuse:
term['... | edaf22a93ce1a0c51f4193c3ea022202c8bbaaef | 2,754 |
def demand_share_per_timestep_constraint_rule(backend_model, group_name, carrier, timestep, what):
"""
Enforces shares of demand of a carrier to be met by the given groups
of technologies at the given locations, in each timestep.
The share is relative to ``demand`` technologies only.
.. container::... | 65cfc120a9a7a5f26b4057a21b7a38a32a335955 | 2,755 |
def b2str(data):
"""Convert bytes into string type."""
try:
return data.decode("utf-8")
except UnicodeDecodeError:
pass
try:
return data.decode("utf-8-sig")
except UnicodeDecodeError:
pass
try:
return data.decode("ascii")
except UnicodeDecodeError:
... | 05cbe6c8072e1bf24cc9ba7f8c8447d0fa7cbf7f | 2,756 |
def plotalphaerror(alphaarr,errorarr,errorlagarr):
""" This will plot the error with respect then alpha parameter for the
constraint.
"""
sns.set_style('whitegrid')
sns.set_context('notebook')
Nlag=errorlagarr.shape[-1]
nlagplot=4.
nrows=1+int(sp.ceil(float(Nlag)/(2*nlagp... | e87c771212a3e39b1f4d7a1a74fc18c1d2e85f87 | 2,757 |
def fill_space(space, dim, size, minval, maxval, factor):
"""Fill a dim-dimensional discrete space of ℕ^{size} with
some random hyperplane with values ranging from minval to
maxval. Returns a ℕ^{size} array. Changes space in-place."""
offsets=[np.array([0]*dim)]
return ndim_diamond_square_rec(space, dim, size, of... | 7744cb465438b40019f3edae9db04143b16d19b1 | 2,758 |
def fracorder_lowshelving_eastty(w1, w2, G1, G2, rB=None):
"""
Parameters
----------
w1: float
Lower corner frequency.
w2: float
Upper corner frequency.
G1: float
Target level at lower corner frequency in dB.
G2: float
Target level at upper corner frequency in... | 379a87b024ff993c0abf0b75a482a8ab66a67546 | 2,759 |
def get_cookie_date(date):
"""
Return a date string in a format suitable for cookies (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Date)
:param date: datetime object
:return: date string in cookie format
"""
return date.strftime("%a, %d %b %Y %H:%M:%S GMT") | f2b4d6decab72cf1f25754bc7e290f62eae92156 | 2,760 |
def fill_block_with_call(newblock, callee, label_next, inputs, outputs):
"""Fill *newblock* to call *callee* with arguments listed in *inputs*.
The returned values are unwraped into variables in *outputs*.
The block would then jump to *label_next*.
"""
scope = newblock.scope
loc = newblock.loc
... | 76e9edbeca59a75d9854e6ffa2d02658da7511ab | 2,761 |
def data_context_service_interface_pointuuid_media_channel_service_interface_point_spec_mc_pool_available_spectrumupper_frequencylower_frequency_frequency_constraint_get(uuid, upper_frequency, lower_frequency): # noqa: E501
"""data_context_service_interface_pointuuid_media_channel_service_interface_point_spec_mc_p... | 412f0b48a050e9201e6d52450a04a6bef0f4a0f3 | 2,763 |
def image_to_string(filename):
"""Generate a string representation of the image at the given path, for embedding in code."""
image = pyglet.image.load(filename)
data = image.get_data('LA', 16)
s = ''
for x in data:
s += "\\x%02x" % (ord(x))
return s | 19dea26d51dd29449759c5e1a3b4c9fc098702f3 | 2,764 |
def mpf_connectome(
mc, num_sampled, max_depth, args_dict, clt_start=10, sr=0.01, mean_estimate=False
):
"""Perform mpf statistical calculations on the mouse connectome."""
args_dict["max_depth"] = max_depth
args_dict["total_samples"] = num_sampled[0]
args_dict["static_verbose"] = False
args_dic... | 6ae8ddb7c3355ddbf072a5bf97f57fe4e13b500e | 2,765 |
def valuedict(keys, value, default):
"""
Build value dictionary from a list of keys and a value.
Parameters
----------
keys: list
The list of keys
value: {dict, int, float, str, None}
A value or the already formed dictionary
default: {int, float, str}
A defa... | 44283bac3be75c3569e87a890f507f7cff4161b6 | 2,766 |
async def chunks(request):
"""A handler that sends chunks at a slow pace.
The browser will download the page over the range of 2 seconds,
but only displays it when done. This e.g. allows streaming large
files without using large amounts of memory.
"""
async def iter():
yield "<html><hea... | 590fe83c5ee53c603b973063e0e077ab87a220ae | 2,767 |
def get_zero_ranges(*args):
"""
get_zero_ranges(zranges, range) -> bool
Return set of ranges with zero initialized bytes. The returned set
includes only big zero initialized ranges (at least >1KB). Some zero
initialized byte ranges may be not included. Only zero bytes that use
the sparse storage method (S... | bd95dbb237ca0b2934e8653b1198d10d25abc553 | 2,769 |
def fista_step(L, Wd, X, alpha, last_Z):
"""
Calculates the next sparse code for the FISTA algorithm
Dimension notation:
B - Number of samples. Usually number of patches in image times batch size
K - Number of atoms in dictionary
d - Dimensionality of atoms in dictionary
... | 6e237a01e631d08efcc425068c646b792d984cdd | 2,770 |
def get_and_validate_certs_for_replacement(
default_cert_location,
default_key_location,
default_ca_location,
new_cert_location,
new_key_location,
new_ca_location):
"""Validates the new certificates for replacement.
This function validates the new specified certi... | 9a4a3b46609fc1e5e7cc525b84397b9adba86b32 | 2,771 |
def build_model(cfg):
"""
Built the whole model, defined by `cfg.model.name`.
"""
name = cfg.model.name
return META_ARCH_REGISTRY.get(name)(cfg) | b106eca0f110007cb852dce9760e5e0ee08940a8 | 2,772 |
def download_n_parse_3k(url):
"""
Gets the article's metadata
Args:
url: The article's URL
"""
article3k = Article(url)
try:
article3k.download()
article3k.parse()
except Exception:
print(f"Download or Parse:\t{url}")
return
return article3k.text | fa63fc7c03b63c5e08004d61488074be538c714b | 2,773 |
def crop_to_square(img, target_size=None):
"""
Takes numpy array img and converts it to a square by trimming
:param img: np.array representing image
:param target_size: optionally specify target size. If None, will return min(l, w) x min(l, w)
:return: np.array
"""
l, w = img.shape
img_c... | 2ad566c7d0a0c719ff207bc06d33e70208a7a03f | 2,774 |
def reboot(name, path=None):
"""
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
"""
ret = {"result": True, "changes... | 2519f9ad5434dbb9ff0a48f5280483829584ebb1 | 2,775 |
import networkx
def find(domain):
""" Finds connected domains within a domain.
A domain is defined to be a connected region of lattice
points, subject to periodic boundary conditions.
Parameters
----------
domain : :py:class:`~fieldkit.mesh.Domain`
The set of nodes to seek connected ... | 3ea2128f84104686be88d359cda3df2554013f41 | 2,776 |
def url_to_license(url):
"""Given a URL, return the license as a license/version tuple"""
(scheme, netloc, path, *remainder) = urlparse(url)
path_parts = path.split('/')
if len(path_parts) < 4:
raise LicenseException("Did not get 4 path segments, probably not a CC license URL")
license = pa... | e6ae2d67f1dbd02c0fe0885231dbac4ae112b0d3 | 2,777 |
def dsystem_dt(request):
"""Test systems for test_discrete"""
# SISO state space systems with either fixed or unspecified sampling times
sys = rss(3, 1, 1)
# MIMO state space systems with either fixed or unspecified sampling times
A = [[-3., 4., 2.], [-1., -3., 0.], [2., 5., 3.]]
B = [[1., 4.],... | faaf22165fc147955b69b1d983fbc37dafb34772 | 2,778 |
import types
def update_attributes(dsFolder: types.GirderModel, data: dict):
"""Upsert or delete attributes"""
crud.verify_dataset(dsFolder)
validated: AttributeUpdateArgs = crud.get_validated_model(AttributeUpdateArgs, **data)
attributes_dict = fromMeta(dsFolder, 'attributes', {})
for attribute_... | d58dfecf68822d4b45688ea16ec39e97e999d458 | 2,779 |
def machado_et_al_2009_matrix_protanomaly(severity):
"""Retrieve a matrix for simulating anomalous color vision.
:param cvd_type: One of "protanomaly", "deuteranomaly", or "tritanomaly".
:param severity: A value between 0 and 100.
:returns: A 3x3 CVD simulation matrix as computed by Machado et al
... | a99a07a7f447fc741ee1a4bd239bda5ed8079e6b | 2,780 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.