content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def step_euler(last, dt, drift, volatility, noise):
"""Approximate SDE in one time step with Euler scheme"""
return last + drift * dt + np.dot(volatility, noise) | 5,338,100 |
def retrieve_downloads(config_bundle, cache_dir, show_progress, disable_ssl_verification=False):
"""
Retrieve downloads into the downloads cache.
config_bundle is the config.ConfigBundle to retrieve downloads for.
cache_dir is the pathlib.Path to the downloads cache.
show_progress is a boolean indi... | 5,338,101 |
def KK_RC66_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
... | 5,338,102 |
def plot_comparsion():
"""
Quick function to plot a comparison of two simulation runs. Hard coding the file names for now...
"""
sgridlow = read_and_reshape_data("sgrid_1e-8.out")
sgridhigh = read_and_reshape_data("sgrid_1e-5.out")
fig, ax = plt.subplots(figsize=(12, 12))
ax.semilogy(sgrid... | 5,338,103 |
def similar_in_manner(manner_1: UnmarkableManner) -> List[Manner]:
"""
If the value is a wildcard value, return
all possible manner of articualtion values, otherwise
return the single corresponding manner of articulation value.
"""
if isinstance(manner_1, MarkedManner):
return manner_1.manner
return manner_sta... | 5,338,104 |
def wikify(value):
"""Converts value to wikipedia "style" of URLS, removes non-word characters
and converts spaces to hyphens and leaves case of value.
"""
value = re.sub(r'[^\w\s-]', '', value).strip()
return re.sub(r'[-\s]+', '_', value) | 5,338,105 |
def predict(x, y, parameters):
"""
X -- data set of examples you would like to label
parameters -- parameters of the trained model
p -- predictions for the given dataset X
"""
# X的数量
m = x.shape[1]
# 数据集X的对应的prediction的维度
p = np.zeros((1, m))
# 前向传播
probas, caches = L_mod... | 5,338,106 |
def test_simple_conv_encoder_next_size(
simple_conv_encoder_image_classification):
"""
Args:
simple_conv_encoder_image_classification (@pytest.fixture): SimpleConvEncoder
Asserts: True if result is a tuple of adequate values.
"""
dim_x = 32
dim_y = 32
k = 4
s = 2
p... | 5,338,107 |
def assert_array_almost_equal(
x: numpy.ndarray, y: numpy.ndarray, decimal: int, err_msg: Literal["size=51"]
):
"""
usage.scipy: 8
"""
... | 5,338,108 |
def build_model(name, num_classes, loss='softmax', pretrained=True,
use_gpu=True, dropout_prob=0.0, feature_dim=512, fpn=True, fpn_dim=256,
gap_as_conv=False, input_size=(256, 128), IN_first=False):
"""A function wrapper for building a model.
"""
avai_models = list(__model_fa... | 5,338,109 |
def policy_absent(name):
"""
Ensure that the named policy is not present
:param name: The name of the policy to be deleted
:returns: The result of the state execution
:rtype: dict
"""
current_policy = __salt__['mdl_vault.get_policy'](name)
ret = {'name': name,
'comment': '',
... | 5,338,110 |
def _tolist(arg):
"""
Assure that *arg* is a list, e.g. if string or None are given.
Parameters
----------
arg :
Argument to make list
Returns
-------
list
list(arg)
Examples
--------
>>> _tolist('string')
['string']
>>> _tolist([1,2,3])
[1, 2, ... | 5,338,111 |
def calc_Qhs_sys(bpr, tsd):
"""
it calculates final loads
"""
# GET SYSTEMS EFFICIENCIES
# GET SYSTEMS EFFICIENCIES
energy_source = bpr.supply['source_hs']
scale_technology = bpr.supply['scale_hs']
efficiency_average_year = bpr.supply['eff_hs']
if scale_technology == "BUILDING":
... | 5,338,112 |
def wait_net_service(server, port, timeout=None):
""" Wait for network service to appear
@param timeout: in seconds, if None or 0 wait forever
@return: True of False, if timeout is None may return only True or
throw unhandled network exception
"""
import socket
s = sock... | 5,338,113 |
def latex_nucleus(nucleus):
"""Creates a isotope symbol string for processing by LaTeX.
Parameters
----------
nucleus : str
Of the form `'<mass><sym>'`, where `'<mass>'` is the nuceleus'
mass number and `'<sym>'` is its chemical symbol. I.e. for
lead-207, `nucleus` would be `'20... | 5,338,114 |
def ConvertToFloat(line, colnam_list):
"""
Convert some columns (in colnam_list) to float, and round by 3 decimal.
:param line: a dictionary from DictReader.
:param colnam_list: float columns
:return: a new dictionary
"""
for name in colnam_list:
line[name] = round(float(line[name])... | 5,338,115 |
def rnn_step(x, prev_h, Wx, Wh, b):
"""
Run the forward pass for a single timestep of a vanilla RNN that uses a tanh
activation function.
The input data has dimension D, the hidden state has dimension H, and we use
a minibatch size of N.
Inputs:
- x: Input data for this timestep, of shape ... | 5,338,116 |
def 世界(链接, 简称=无): #py:World
"""
用来切换到一个指定的世界。
如果当前的世界和参数里所指定的世界不一致,那么引用此函数将使当前的世界切换为指定
的世界,其后的指令将会被忽略。
如果当前的世界和参数里所指定的世界一致,那么此函数将会被忽略,其后的指令将会被执
行。
如果指定的世界没有出现在世界菜单里,那么引用此函数将添加其至菜单。
参数:
链接:有两种选择——出现在世界菜单里的名称,或者在某个网站上的世界的链接。
简称:(可选参数)出现在世界菜单里的名称
例子:
>>> ... | 5,338,117 |
def transform_application_assigned_users(json_app_data: str) -> List[str]:
"""
Transform application users data for graph consumption
:param json_app_data: raw json application data
:return: individual user id
"""
users: List[str] = []
app_data = json.loads(json_app_data)
for user in ap... | 5,338,118 |
def testapp(app):
"""Create Webtest app."""
return TestApp(app) | 5,338,119 |
def to_y_channel(img):
"""Change to Y channel of YCbCr.
Args:
img (ndarray): Images with range [0, 255].
Returns:
(ndarray): Images with range [0, 255] (float type) without round.
"""
img = img.astype(np.float32) / 255.
if img.ndim == 3 and img.shape[2] == 3:
img = bgr2... | 5,338,120 |
def get_user_signatures(user_id):
"""
Given a user ID, returns the user's signatures.
:param user_id: The user's ID.
:type user_id: string
:return: list of signature data for this user.
:rtype: [dict]
"""
user = get_user_instance()
try:
user.load(user_id)
except DoesNotE... | 5,338,121 |
def post_vehicle_action():
""" Add vehicle
:return:
"""
output = JsonOutput()
try:
if not request.is_json:
raise TypeError('Payload is not json')
payload = request.json
usecases.SetVehicleUsecase(db=db, vehicle=payload).execute()
output.add(status=200, res... | 5,338,122 |
def get_day_suffix(day):
"""
Returns the suffix of the day, such as in 1st, 2nd, ...
"""
if day in (1, 21, 31):
return 'st'
elif day in (2, 12, 22):
return 'nd'
elif day in (3, 23):
return 'rd'
else:
return 'th' | 5,338,123 |
def retain_images(image_dir,xml_file, annotation=''):
"""Deprecated"""
image_in_boxes_dict=return_image_in_boxes_dict(image_dir,xml_file, annotation)
return [img for img in image_in_boxes_dict if image_in_boxes_dict[img]] | 5,338,124 |
def compute_owa(
metrics: List[Tuple[float, float]],
datasets: Dict[K, DatasetSplit],
metadata: List[MetaData],
) -> float:
"""
Computes the OWA metric from the M4 competition, using a weighted average of the relative
MASE and sMAPE metrics depending on the size of the datasets.
Args:
... | 5,338,125 |
def do_tns(catalog):
"""Load TNS metadata."""
session = requests.Session()
task_str = catalog.get_current_task_str()
tns_url = 'https://wis-tns.weizmann.ac.il/'
search_url = ('https://wis-tns.weizmann.ac.il/'+
'search?&discovered_period_value=30&discovered_period_units=years'+
... | 5,338,126 |
def test_local_to_global_coords(
local_box: BoundingBox, embedding_box: BoundingBox, expected_embedded_box: BoundingBox
) -> None:
"""
Testing func: local_to_global_coords returns BoundingBox with global coords correctly
"""
# Act
embedded_box = local_to_global_coords(local_box, embedding_box)... | 5,338,127 |
def parse(cell, config):
"""Extract connection info and result variable from SQL
Please don't add any more syntax requiring
special parsing.
Instead, add @arguments to SqlMagic.execute.
We're grandfathering the
connection string and `<<` operator in.
"""
result = {"connect... | 5,338,128 |
def createResource(url, user, pWd, resourceName, resourceJson):
"""
create a new resource based on the provided JSON
returns rc=200 (valid) & other rc's from the put
resourceDef (json)
"""
# create a new resource
apiURL = url + "/access/1/catalog/resources/"
header = {"content-... | 5,338,129 |
def generate_invalid_sequence():
"""Generates an invalid sequence of length 10"""
return ''.join(np.random.choice(list(string.ascii_uppercase + string.digits), size=10)) | 5,338,130 |
def transform_bcs_profile(T, axis, Nc):
""" Translates the profile to body cs and then transforms it for rotation.
"""
from input_surface import circle
profile = circle(Nc, radius = 1, flag = 0)
Pb_new = np.zeros((Nc, 3), dtype = float)
ind_p = np.arange(0, 3*Nc, step = 3, dtype = int)
... | 5,338,131 |
def count_configuration(config, root=True, num_samples_per_dist=1):
"""Recursively count configuration."""
count = 1
if isinstance(config, dict):
for _, v in sorted(config.items()):
count *= count_configuration(
v, root=False, num_samples_per_dist=num_samples_per_dist)
elif callable(config):... | 5,338,132 |
def test_file_getters(config_struct):
"""Test get_* functions with no installed extensions."""
installed_jsons = maninex.get_existing_jsons(config_struct.json_dir)
installed_folders = maninex.get_existing_folders(config_struct.ext_dir)
assert len(installed_jsons) == 0
assert len(installed_folders) =... | 5,338,133 |
def transition(state_table):
"""Decorator used to set up methods which cause transitions between states.
The decorator is applied to methods of the context (state machine) class.
Invoking the method may cause a transition to another state. To define
what the transitions are, the nextStates method of t... | 5,338,134 |
def isfinite(x: Union[ivy.Array, ivy.NativeArray], f: ivy.Framework = None)\
-> Union[ivy.Array, ivy.NativeArray]:
"""
Tests each element x_i of the input array x to determine if finite (i.e., not NaN and not equal to positive
or negative infinity).
:param x: Input array.
:type x: array
... | 5,338,135 |
def form_overwrite_file(
PATH: Path, QUESTION: Optional[str] = None, DEFAULT_NO: bool = True
) -> bool:
"""Yes/no form to ask whether file should be overwritten if already existing."""
if QUESTION is None:
QUESTION = "Overwrite {PATH}?"
save = True
if PATH.is_file():
save = form_yes... | 5,338,136 |
def dist(integer):
"""
Return the distance from center.
"""
if integer == 1:
return 0
c = which_layer(integer)
rows = layer_rows(c)
l = len(rows[0])
mid = (l / 2) - 1
for r in rows:
if integer in r:
list_pos = r.index(integer)
return c + abs(mid - list_pos) - 1 | 5,338,137 |
def get_market_fundamental_by_ticker(date: str, market: str="KOSPI", prev=False) -> DataFrame:
"""특정 일자의 전종목 PER/PBR/배당수익률 조회
Args:
date (str ): 조회 일자 (YYMMDD)
market (str, optional): 조회 시장 (KOSPI/KOSDAQ/KONEX/ALL)
prev (bool, optional): 조회 일자가 휴일일 경우 이전 영업일 혹은 이후 영업일 선택
... | 5,338,138 |
def cite():
"""Print the reference"""
cite_data = """
=========== MLA ===========
Bosch, J., Marxer, R., Gomez, E., "Evaluation and Combination of
Pitch Estimation Methods for Melody Extraction in Symphonic
Classical Music", Journal of New Music Research (2016)
========== Bibtex ==========
@article{bosch2016... | 5,338,139 |
def get_all(request):
""" Gets all tags in the db with counts of use """
tags = []
for tag in Tag.objects.all():
tag_data = {
'name': tag.name,
'count': tag.facebookimage_set.distinct().count()
}
if tag_data['count'] > 0:
tags.append(tag_... | 5,338,140 |
def test_unsupported_operators():
"""Verify unsupported operators
"""
def unsupported_operator(op, func):
"""Verify error messages on unsupported operators
"""
# Indicate what we're testing in the nose printout
sys.stderr.write(f'\b\b\b\b\b\b: {op} ... ')
a = uut.Fix... | 5,338,141 |
def quadratic_crop(x, bbox, alpha=1.0):
"""bbox is xmin, ymin, xmax, ymax"""
im_h, im_w = x.shape[:2]
bbox = np.array(bbox, dtype=np.float32)
bbox = np.clip(bbox, 0, max(im_h, im_w))
center = 0.5 * (bbox[0] + bbox[2]), 0.5 * (bbox[1] + bbox[3])
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
... | 5,338,142 |
def cdlbreakaway(
client,
symbol,
timeframe="6m",
opencol="open",
highcol="high",
lowcol="low",
closecol="close",
):
"""This will return a dataframe of breakaway for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
symbol (string): T... | 5,338,143 |
def depends_on(*args):
"""Caches a `Model` parameter based on its dependencies.
Example
-------
>>> @property
>>> @depends_on('x', 'y')
>>> def param(self):
>>> return self.x * self.y
Parameters
----------
args : list of str
List of parameters t... | 5,338,144 |
def l96(x, t, f):
""""This describes the derivative for the non-linear Lorenz 96 Model of arbitrary dimension n.
This will take the state vector x and return the equation for dxdt"""
# shift minus and plus indices
x_m_2 = np.concatenate([x[-2:], x[:-2]])
x_m_1 = np.concatenate([x[-1:], x[:-1]])
... | 5,338,145 |
def translation(im0, im1, filter_pcorr=0, odds=1, constraints=None,
reports=None):
"""
Return translation vector to register images.
It tells how to translate the im1 to get im0.
Args:
im0 (2D numpy array): The first (template) image
im1 (2D numpy array): The second (sub... | 5,338,146 |
def CalculateConjointTriad(proteinsequence):
"""
Calculate the conjoint triad features from protein sequence.
Useage:
res = CalculateConjointTriad(protein)
Input: protein is a pure protein sequence.
Output is a dict form containing all 343 conjoint triad features.
"""
res = {}
pr... | 5,338,147 |
def shutdown(forza: Forza, threadPool: ThreadPoolExecutor, listener: Listener):
"""shutdown/clean up resources
Args:
forza (Forza): forza
threadPool (ThreadPoolExecutor): thread pool
listener (Listener): keyboard listener
"""
forza.isRunning = False
threadPool.shutdown(wait=... | 5,338,148 |
def _create(
*,
cls: Type[THparams],
data: Dict[str, JSON],
parsed_args: Dict[str, str],
cli_args: Optional[List[str]],
prefix: List[str],
argparse_name_registry: ArgparseNameRegistry,
argparsers: List[argparse.ArgumentParser],
) -> THparams:
"""Helper method to recursively create an... | 5,338,149 |
def extract_url(url):
"""Creates a short version of the URL to work with. Also returns None if its not a valid adress.
Args:
url (str): The long version of the URL to shorten
Returns:
str: The short version of the URL
"""
if url.find("www.amazon.de") != -1:
index = ... | 5,338,150 |
def match_name(own: str, other: str) -> bool:
"""
compares 2 medic names (respects missing middle names, or abbrev. name parts)
Args:
own: the first name
other: the last name
Returns: True if both names match
"""
# the simplest case, both name match completely
if own is Non... | 5,338,151 |
def price_setting():
""" Sets prices """
purchasing_price = float(input("enter purchasing price: "))
new_supplier = str(input("First time user(Y/N)?: ")).lower()
if new_supplier not in ['n', 'y']:
return True, {"errorMsg": f"{new_supplier} not a valid response"}, None
if new_supplier =... | 5,338,152 |
def d4_grid():
"""Test functionality of routing when D4 is specified.
The elevation field in this test looks like::
1 2 3 4 5 6 7
1 2 3 0 5 0 7
1 2 3 4 0 0 7
1 2 3 0 5 6 7
1 2 0 0 0 6 7
1 2 3 0 5 6 7
1 ... | 5,338,153 |
def pass_complex_ins(mqc):
"""
The number of PASS complex insertions.
Source: count_variants.py (bcftools view)
"""
k = inspect.currentframe().f_code.co_name
try:
d = next(iter(mqc["multiqc_npm_count_variants"].values()))
v = d["pass_complex_ins"]
v = int(v)
except ... | 5,338,154 |
def get_jwt():
"""
Get authorization token and validate its signature against the public key
from /.well-known/jwks endpoint
"""
expected_errors = {
KeyError: WRONG_PAYLOAD_STRUCTURE,
AssertionError: JWK_HOST_MISSING,
InvalidSignatureError: WRONG_KEY,
DecodeError: WR... | 5,338,155 |
def devlocation()->str:
"""
:return: 'local' or 'github
"""
return os.getenv('DEVLOCATION') or 'local' | 5,338,156 |
def test_base_widget_1():
""" Assert widget is None """
from pypom_form.widgets import BaseWidget
widget = BaseWidget()
assert widget.field is None | 5,338,157 |
def wrap_refresh(change):
"""Query the databroker with user supplied text."""
try:
query = eval("dict({})".format(db_search_widget.value))
headers = db(**query)
except NameError:
headers = []
db_search_widget.value += " -- is an invalid search"
scan_id_dict = get_scan_id... | 5,338,158 |
def convert_categorical(df, col_old, conversion, col_new=None):
"""Convet categories"""
if col_new is None:
col_new = col_old
orig_values = df[col_old].values
good_rows = np.isin(orig_values, list(conversion))
df = df.iloc[good_rows]
orig_values = df[col_old].values
cat_values = np.z... | 5,338,159 |
def _get_pipeline_configs(force=False):
"""
Connects to Shotgun and retrieves information about all projects
and all pipeline configurations in Shotgun. Adds this to the disk cache.
If a cache already exists, this is used instead of talking to Shotgun.
To force a re-cache, set the force flag to Tru... | 5,338,160 |
def downgrade():
"""Migrations for the downgrade."""
op.execute("UPDATE db_dbnode SET type = 'code.Code.' WHERE type = 'data.code.Code.';") | 5,338,161 |
def parse_cmdline(argv):
"""
Returns the parsed argument list and return code.
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
if argv is None:
argv = sys.argv[1:]
# initialize the parser object:
parser = argparse.ArgumentParser(description='Make combine output fr... | 5,338,162 |
def info(parentwindow, message, buttons, *,
title=None, defaultbutton=None):
"""Display an information message."""
return _message('info', parentwindow, message, title, buttons,
defaultbutton) | 5,338,163 |
def add_user(args):
"""
Process arguments and ask user for other needed parameters in order
to add info to DB
:param args: returned object from argparse.parse_args
:return: exit code (0 on success, 1 on failure)
"""
logger = fsurfer.log.get_logger()
if args.username is None:
us... | 5,338,164 |
def wait_for_active_cluster_commands(active_command):
"""
Wait until Cloudera Manager finishes running cluster active_command
:param active_command: Descriptive of what should be running - this just waits if any task is detected running
:return:
"""
view = 'summary'
wait_status = '[*'
do... | 5,338,165 |
def gru(xs, lengths, init_hidden, params):
"""RNN with GRU. Based on https://github.com/google/jax/pull/2298"""
def apply_fun_single(state, inputs):
i, x = inputs
inp_update = jnp.matmul(x, params["update_in"])
hidden_update = jnp.dot(state, params["update_weight"])
update_gate ... | 5,338,166 |
def get_strings_in_flattened_sequence(p):
"""
Traverses nested sequence and for each element, returns first string encountered
"""
if p is None:
return []
#
# string is returned as list of single string
#
if isinstance(p, path_str_type):
return [p]
#
# Get all... | 5,338,167 |
def convert():
"""Convert conda packages to other platforms."""
os_name = {
'darwin': 'osx',
'win32': 'win',
'linux': 'linux'
}[sys.platform]
dirname = '{}-{}'.format(os_name, platform.architecture()[0][:2])
files = glob.glob('build/{}/*.tar.bz2'.format(dirname))
for fil... | 5,338,168 |
def kansuji2arabic(string, sep=False):
"""漢数字をアラビア数字に変換"""
def _transvalue(sj, re_obj=re_kunit, transdic=TRANSUNIT):
unit = 1
result = 0
for piece in reversed(re_obj.findall(sj)):
if piece in transdic:
if unit > 1:
result += unit
... | 5,338,169 |
def get_image(member_status=None, most_recent=None, name=None, owner=None, properties=None, region=None, size_max=None, size_min=None, sort_direction=None, sort_key=None, tag=None, visibility=None):
"""
Use this data source to get the ID of an available OpenStack image.
"""
__args__ = dict()
__args... | 5,338,170 |
def sort_course_dicts(courses):
""" Sorts course dictionaries
@courses: iterable object containing dictionaries representing courses.
Each course must have a course_number and abbreviation key
@return: returns a new list containing the given courses, in naturally sorted order.
"""
det... | 5,338,171 |
def read_folder(filepath):
"""
Reads multiple image files from a folder and returns the resulting stack.
To find the images in the right order, a regex is used which will search
for files with the following pattern:
[prefix]_p[Nr][suffix]. The start number doesn't need to be 0.
The files are sor... | 5,338,172 |
def zenodo_fetch_resource_helper(zenodo_project, resource_id, is_record=False, is_file=False):
"""
Takes a Zenodo deposition/record and builds a Zenodo PresQT resource.
Parameters
----------
zenodo_project : dict
The requested Zenodo project.
is_record : boolean
Flag for if the ... | 5,338,173 |
def add_role_menu(request):
"""菜单授权"""
menu_nums = request.POST.get("node_id_json")
role_id = request.POST.get("role_id")
role_obj = auth_db.Role.objects.get(id=role_id)
menu_nums = json.loads(menu_nums)
role_obj.menu.clear()
for i in menu_nums:
menu_obj = auth_db.Menus.objects.g... | 5,338,174 |
def repo_path():
"""
little function to help resolve location of doctest_files back in repository
:return: the absolute path to the root of the repository.
"""
return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 5,338,175 |
def setup():
"""Setup a brand new pilot config for a new index.
NOTE: Paths with tilde '~' DO NOT WORK. These cause problems for resolving
paths that look like /~/foo/bar, which sometimes translate as ~/foo/bar
instead. These are disabled to prevent that from happening.
"""
PROJECT_QUERIES = {
... | 5,338,176 |
def oauth_url(auth_base, country, language):
"""Construct the URL for users to log in (in a browser) to start an
authenticated session.
"""
url = urljoin(auth_base, 'login/sign_in')
query = urlencode({
'country': country,
'language': language,
'svcCode': SVC_CODE,
'a... | 5,338,177 |
def teammsg(self: Client, message: str) -> str:
"""Sends a team message."""
return self.run('teammsg', message) | 5,338,178 |
def config_section(section):
"""
This configures a specific section of the configuration file
"""
# get a handle on the configuration reader
config_reader = get_config_reader()
# Find the group that this section belongs to.
# When we're in a namespaced section, we'll be in the group that th... | 5,338,179 |
def h_html_footnote(e, doc):
"""Handle footnotes with bigfoot"""
if not isinstance(e, pf.Note) or doc.format != "html":
return None
htmlref = rf'<sup id="fnref:{doc.footnotecounter}"><a href="#fn:{doc.footnotecounter}" rel="footnote">{doc.footnotecounter}</a></sup>'
htmlcontent_before = rf'<li c... | 5,338,180 |
def plot_image(image):
"""
:param image: the image to be plotted in a 3-D matrix format
:return: None
"""
plt.imshow(image)
plt.show() | 5,338,181 |
def segment(x,u1,u2):
""" given a figure x, create a new figure spanning the specified interval in the original figure
"""
if not (isgoodnum(u1) and isgoodnum(u2)) or close(u1,u2) or u1<0 or u2 < 0 or u1 > 1 or u2 > 1:
raise ValueError('bad parameter arguments passed to segment: '+str(u1)+', '+str(u... | 5,338,182 |
def worker():
"""Print usage of GPU
"""
if SHOW_GPU_USAGE_TIME == 0:
return
while True:
process = psutil.Process(os.getpid())
print("\n Gen RAM Free:" + humanize.naturalsize(psutil.virtual_memory().available),
"I Proc size:" + humanize.naturalsize(process.memory_inf... | 5,338,183 |
def compress_files(file_names):
"""
Given a list of files, compress all of them into a single file.
Keeps the existing directory structure in tact.
"""
archive_file_name = 'archive.zip'
print(f'{len(file_names)} files found. Compressing the files...')
cwd = os.getcwd()
with ZipFile(archi... | 5,338,184 |
def box_from_anchor_and_target(anchors, regressed_targets):
"""
Get bounding box from anchor and target through transformation provided in the paper.
:param anchors: Nx4 anchor boxes
:param regressed_targets: Nx4 regression targets
:return:
"""
boxes_v = anchors[:, 2] * regressed_targets[:,... | 5,338,185 |
def block_device_mapping_update(context, bdm_id, values, legacy=True):
"""Update an entry of block device mapping."""
return IMPL.block_device_mapping_update(context, bdm_id, values, legacy) | 5,338,186 |
async def run():
"""
Bot setup
"""
async with aiohttp.ClientSession() as session:
token = env_file.get()
bot.add_cog(DevCommands(bot))
bot.add_cog(GeneralCommands(bot, session))
bot.add_cog(LinksCommands(bot))
if 'DBL_TOKEN' in token:
bot.add_cog(TopGG... | 5,338,187 |
def append_expression_of_remove_child(*, child: DisplayObject) -> None:
"""
Append expression of remove_child (removeElement).
Parameters
----------
child : DisplayObject
Child object to remove.
"""
import apysc as ap
with ap.DebugInfo(
callable_=append_ex... | 5,338,188 |
def test_check_versions_negative_binary_not_found():
"""Test check_versions - negative case, binary not found."""
with mock.patch("shutil.which", return_value=None):
with pytest.raises(
AEAException,
match="'go' is required by the libp2p connection, but it is not installed, or it... | 5,338,189 |
def consumer(address,callback,message_type):
"""
Creates a consumer binding to the given address pull messages.
The callback is invoked for every reply received.
Args:
- address: the address to bind the PULL socket to.
- callback: the callback to invoke for every message. Mu... | 5,338,190 |
def _parse_continuous_records(prepared_page, section_dict):
"""Handle parsing a continuous list of records."""
# import pdb; pdb.set_trace()
columns = 6
start = prepared_page.index('Date and time')
for i, column in enumerate(prepared_page[start:start + columns]):
column_index = start + i
... | 5,338,191 |
def power_law_at_2500(x, amp, slope, z):
""" Power law model anchored at 2500 AA
This model is defined for a spectral dispersion axis in Angstroem.
:param x: Dispersion of the power law
:type x: np.ndarray
:param amp: Amplitude of the power law (at 2500 A)
:type amp: float
:param slope: Sl... | 5,338,192 |
def map2alm(
maps,
lmax=None,
mmax=None,
iter=3,
pol=True,
use_weights=False,
datapath=None,
gal_cut=0,
use_pixel_weights=False,
):
"""Computes the alm of a Healpix map. The input maps must all be
in ring ordering.
Parameters
----------
maps : array-like, shape (... | 5,338,193 |
def credits():
"""
Credits Page
"""
return render_template("credits.html") | 5,338,194 |
def register_view(request):
"""Register a new user."""
if request.method == "POST":
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# Create a new User object but don't save it yet.
new_user = user_form.save(commit=False)
# Set the chos... | 5,338,195 |
def show_available_models():
"""Displays available models
"""
print(list(__model_factory.keys())) | 5,338,196 |
def deleteone(indextodelete, openfile=open):
"""
Delete a task from the todofile
"""
index_existant = False
with openfile(todofilefromconfig(), "r") as todofile:
lines = todofile.readlines()
with openfile(todofilefromconfig(), "w") as todofile:
for line in lines:
# if... | 5,338,197 |
def handle_pdf_build(pdf_job_dict: Dict[str, Any], tx_payload, redis_connection) -> str:
"""
A job dict is now setup and remembered in REDIS
so that we can match it when we get a future callback.
The project.json (in the folder above the CDN one) is also updated, e.g., with new commits.
The jo... | 5,338,198 |
def test_missing_file_raises_access_denied(basic_auth_db: BasicAuthDb, basic_auth_db_path: Path):
"""
In the default setup the sys-admin may not have created a blank db file.
Correct behaviour here is to behave as if the file exists and is empty.
We want an AuthenticationFailedException NOT any OSError ... | 5,338,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.