content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def translate_provider_for_icon(sync_server, project, site):
"""
Get provider for 'site'
This is used for getting icon, 'studio' should have different icon
then local sites, even the provider 'local_drive' is same
"""
if site == sync_server.DEFAULT_SITE:
return sync_server.... | 28,700 |
def save_subsystem_config(client, fd, indent=2, name=None):
"""Write current (live) configuration of SPDK subsystem to stdout.
Args:
fd: opened file descriptor where data will be saved
indent: Indent level. Value less than 0 mean compact mode.
Default is indent level 2.
"""
c... | 28,701 |
def server_delete_ip(body=None): # noqa: E501
"""delete server IP
Send by server during shutdown. # noqa: E501
:param body: port of iperf server. Ip and time could be emply
:type body: dict | bytes
:rtype: List[InlineResponse200]
"""
if connexion.request.is_json:
body = ServerAdd... | 28,702 |
def validate_environment_variables():
# type: () -> None
"""
Checks that the following are set as environment variables :
- confluence host name
- workspace
"""
global CONFLUENCE_HOST
CONFLUENCE_HOST = env.get("CONFLUENCE_HOST")
global WORKSPACE
WORKSPACE = env.get("WORK... | 28,703 |
def _UpdateDatastore(test_key, test_attributes, query_time):
"""Updates a LuciTest's disabled_test_variants, issue_keys, tags in datastore.
This function modifies LuciTest attributes as follows:
- Overwrites existing disabled_test_variants.
- Adds new issue_keys to existing issue_keys,
- Overwrites existing ... | 28,704 |
def extract_key_and_index(field):
"""Returns the key type, key name and if key is a compound list then returns the index pointed by the field
Arguments:
field: csv header field
"""
for key_type, value in KEY_TYPES.items():
regex = re.compile(value["regex"])
match = regex.match(fiel... | 28,705 |
def _normalize_heartrate_of_logfiles():
"""Normalizes heartrate of each dataframe/user by dividing by min of the movementtutorial.
Saves changes directly to globals.df_list
Note: I didn't do this on the refactoring-step on purpose, since the user might want to
do some plots, which might be ... | 28,706 |
def as_mask(indexes, length):
"""
Convert indexes into a binary mask.
Parameters:
indexes (LongTensor): positive indexes
length (int): maximal possible value of indexes
"""
mask = torch.zeros(length, dtype=torch.bool, device=indexes.device)
mask[indexes] = 1
return mask | 28,707 |
def interpolate_array(x, y, smooth_rate=500):
"""
:param x:
:param y:
:return:
"""
interp_obj = interpolate.PchipInterpolator(x, y)
new_x = np.linspace(x[0], x[-1], smooth_rate)
new_y = interp_obj(new_x)
return new_x, new_y | 28,708 |
def calculate_resource_utilization_for_slaves(
slaves: Sequence[_SlaveT], tasks: Sequence[MesosTask]
) -> ResourceUtilizationDict:
""" Given a list of slaves and a list of tasks, calculate the total available
resource available in that list of slaves, and the resources consumed by tasks
running on those... | 28,709 |
def check_pass(value):
"""
This test always passes (it is used for 'checking' things like the
workshop address, for which no sensible validation is feasible).
"""
return True | 28,710 |
def state_array_to_int(s):
"""translates a state s into an integer by interpreting the state as a
binary represenation"""
return int(state_array_to_string(s), 2) | 28,711 |
def async_task(coro, loop=asyncio.get_event_loop(), error_cb=None):
"""
Wrapper to always print exceptions for asyncio tasks.
"""
future = asyncio.ensure_future(coro)
def exception_logging_done_cb(future):
try:
e = future.exception()
except asyncio.CancelledError:
... | 28,712 |
def is_valid_charts_yaml(content):
"""
Check if 'content' contains mandatory keys
:param content: parsed YAML file as list of dictionary of key values
:return: True if dict contains mandatory values, else False
"""
# Iterate on each list cell
for chart_details in content:
# If one ... | 28,713 |
def run_watcher(pattern: str, command: str, run_on_start: bool=False) -> None:
"""
For every files that match the given glob pattern, this will,
every SLEEP_TIME, check whether any of those files changed. If
any changed, then it would run the command given.
If run_on_start is given, the bash comman... | 28,714 |
def get_trader_fcas_availability_agc_status_condition(params) -> bool:
"""Get FCAS availability AGC status condition. AGC must be enabled for regulation FCAS."""
# Check AGC status if presented with a regulating FCAS offer
if params['trade_type'] in ['L5RE', 'R5RE']:
# AGC is active='1', AGC is ina... | 28,715 |
def load_class(full_class_string):
"""
dynamically load a class from a string
"""
class_data = full_class_string.split(".")
module_path = ".".join(class_data[:-1])
class_str = class_data[-1]
module = importlib.import_module(module_path)
# Finally, we retrieve the Class
r... | 28,716 |
def request_credentials_from_console():
"""
Requests the credentials interactive and returns them in form (username, password)
"""
username = raw_input('Username: ')
password = raw_input('Password: ')
return username, password | 28,717 |
def prettify_url(url):
"""Return a URL without its schema
"""
if not url:
return url
split = url.split('//', 1)
if len(split) == 2:
schema, path = split
else:
path = url
return path.rstrip('/') | 28,718 |
def CDLMORNINGDOJISTAR(data: xr.DataArray, penetration: float = 0.3) -> xr.DataArray:
"""
Morning Doji Star (Pattern Recognition)
Inputs:
data:['open', 'high', 'low', 'close']
Parameters:
penetration: 0.3
Outputs:
double series (values are -1, 0 or 1)
"""
return multi... | 28,719 |
def panerror_to_dict(obj):
"""Serializer function for POCS custom exceptions."""
name_match = error_pattern.search(str(obj.__class__))
if name_match:
exception_name = name_match.group(1)
else:
msg = f"Unexpected obj type: {obj}, {obj.__class__}"
raise ValueError(msg)
return ... | 28,720 |
def build_class_instance(module_path: str, init_params: Optional[dict] = None):
"""
Create an object instance from absolute module_path string.
Parameters
----------
module_path: str
Full module_path that is valid for your project or some external package.
init_params: optional dict
... | 28,721 |
def check_line(group, flag, value):
""" Check each line of the initialization file
"""
# Check for admissible group/flag combinations
assert (group in STRUCTURE.keys())
assert (flag in STRUCTURE[group])
# Check the values for the flags.
try:
if (group, flag) == ('BASICS', 'periods'... | 28,722 |
def generate_experiment_file_from_videos(video_root, experiment_root, video_name):
"""
Generate experiment files from video
:param video_root: Root folder of the videos
:param experiment_root: Root folder where experiment specification would be stored in yml file
:param video_name: Name of the video... | 28,723 |
def maintainers_mapper(maintainers, package):
"""
Update package maintainers and return package.
https://docs.npmjs.com/files/package.json#people-fields-author-contributors
npm also sets a top-level "maintainers" field with your npm user info.
"""
# note this is the same code as contributors_map... | 28,724 |
def calc_original_pressure(pressure_ratio):
"""
calculates the original pressure value given the <code>AUDITORY_THRESHOLD</code>.
The results are only correct if the pressure ratio is build using the <code>AUDITORY_THRESHOLD</code>.
:param pressure_ratio: the pressure ration that shall be converted to ... | 28,725 |
def validate(conf):
""" The list of validation checks to be performed """
check_branch_commit_exists(conf)
check_ocaml_version(conf)
check_unique_keys(conf, 'run_path_tag')
check_unique_keys(conf, 'codespeed_name')
check_run_path_tag_length(conf) | 28,726 |
def normalize_field_names(fields):
"""
Map field names to a normalized form to check for collisions like 'coveredText' vs 'covered_text'
"""
return set(s.replace('_','').lower() for s in fields) | 28,727 |
def unzip(path_to_zip_file, directory_to_extract_to='.'):
"""
Helper function to unzinp a zip file
"""
zip_ref = zipfile.ZipFile(path_to_zip_file, 'r')
zip_ref.extractall(directory_to_extract_to)
zip_ref.close() | 28,728 |
def which(program): # type: (str) -> str
"""Like UNIX which, returns the first location of a program given using your system PATH
If full location to program is given, uses that first"""
dirname, progname = os.path.split(program) # type: str, str
syspath = tuple([dirname] + os.environ['PATH'].split(os.p... | 28,729 |
def powspec_disc_n(n, fs, mu, s, kp, km, vr, vt, tr):
"""Return the n'th Lorentzian and its width"""
Td = ifana.LIF().Tdp(mu, s, vr, vt) + tr
Ppp = (kp*exp(-(kp+km)*tr)+km)/(kp+km)
kpbar = (kp*(Td-tr)-log(Ppp))/Td
return 1./Td * 2*kpbar/(kpbar**2 + (2*pi*(fs - n*1./Td))**2), kpbar | 28,730 |
def list_keys(request):
"""
Tags: keys
---
Lists all added keys.
READ permission required on key.
---
"""
auth_context = auth_context_from_request(request)
return filter_list_keys(auth_context) | 28,731 |
def rounder(money_dist: list, pot: int, to_coin: int = 2) -> list:
"""
Rounds the money distribution while preserving total sum
stolen from https://stackoverflow.com/a/44740221
"""
def custom_round(x):
""" Rounds a number to be divisible by to_coin specified """
return int(to_coin *... | 28,732 |
def test_check_spoil_contrib():
"""
Construct a case where a star spoils the edge of the 8x8 (edge and then background pixel).
Note that for these mock stars, since we we are checking the status of
the first star, ASPQ1 needs to be nonzero on that star or the
check_spoil_contrib code will bail out ... | 28,733 |
def test_search_term_found_in_title(admin_client, public_resource_with_metadata):
"""
Test of direct URL querystring for a search
Test valid JSON response
Test index response
Test title match in search
"""
search_term = public_resource_with_metadata.title
djangoresponse = admin_client.ge... | 28,734 |
def find_wcscorr_row(wcstab, selections):
""" Return an array of indices from the table (NOT HDU) 'wcstab' that matches the
selections specified by the user.
The row selection criteria must be specified as a dictionary with
column name as key and value(s) representing the valid d... | 28,735 |
def activity_boxplot(DataFrame):
"""
Plots the distribution of pXC50 according to binary activity labels with a boxplot.
"""
inactives = DataFrame[DataFrame['Activity']==0]['pXC50']
actives = DataFrame[DataFrame['Activity']==1]['pXC50']
plt.figure(figsize = (10, 7.5))
mean... | 28,736 |
def populate_pair_lists(pair, blacklist, blackpairs, badpairs, newpairs, tickerlist):
"""Check pair conditions."""
# Check if pair is in tickerlist and on 3Commas blacklist
if pair in tickerlist:
if pair in blacklist:
blackpairs.append(pair)
else:
newpairs.ap... | 28,737 |
def togglePopup(
id,
view,
params,
title="",
position=None,
showCloseIcon=True,
draggable=True,
resizable=False,
modal=False,
overlayDismiss=False,
sessionId="current_session",
pageId="current_page",
viewPortBound=False,
):
"""Toggles a popup.
Will open up th... | 28,738 |
def test_create_entity_relationships():
"""
Given
- indicator domain name
- related indicators
When
- run the fetch incidents command
Then
- Validate created relationships
"""
domain_name = "test.com"
relevant_indicators = [
{
'type': 'IP',
... | 28,739 |
def process_image(image_file):
""" ๋ค์ฏ ๋จ๊ณ์ ์ด๋ฏธ์ง ์ฒ๋ฆฌ(Image precessing)๋ฅผ ํ๋๋ค.
ํ์ฌ ํจ์์์ ์์๋ฅผ ๋ณ๊ฒฝํ์ฌ ์ ์ฉํ ์ ์์ต๋๋ค.
1) Gray-scale ์ ์ฉ
2) Morph Gradient ์ ์ฉ
3) Threshold ์ ์ฉ
4) Long Line Removal ์ ์ฉ
5) Close ์ ์ฉ
6) Contour ์ถ์ถ
:param image_file: ์ด๋ฏธ์ง ์ฒ๋ฆฌ(Image precessing)๋ฅผ ์ ์ฉํ ์ด๋ฏธ์ง ํ์ผ
:return: ์ด๋ฏธ์ง ์ฒ๋ฆฌ ํ... | 28,740 |
def query_review_data(category, title_keyword, count, output_uri):
"""
Query the Amazon review dataset for top reviews from a category that contain a
keyword in their product titles. The output of the query is written as JSON
to the specified output URI.
:param category: The category to query, such... | 28,741 |
def _gftRead(url, step):
"""
Reads in a gtf file from a specific db given the url.
Some gft have a certain number of header lines that
are skipped however.
Input: url where gtf is fetched from
Input: number of lines to skip while reading in the frame
Output: gtf in a... | 28,742 |
def add() -> jsonify:
"""
Adds a new item in the server and returns the updated list to the front-end
"""
# Passed Items from Front-End
name = request.form['name']
priority = request.form['priority']
price = request.form['price'].replace(",", "") # To prevent string to float conversion
... | 28,743 |
def _get_base(**kwargs):
"""
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
"""
profile = get_container_profile(copy.deepcopy(kwargs.get("profile")))
kw_overrides = copy.deepcopy(kwargs)
... | 28,744 |
def calculate(formula, **params):
""" Calculate formula and return a dictionary of coin and amounts """
formula = Formula.get(formula)
if formula is None:
raise InvalidFormula(formula)
if not formula.expression:
return {}
return calculate_expression(formula.expression, formula, **p... | 28,745 |
def plot_learning(train_loss, eval_loss, path_to_save):
"""
Generates and saves a plot of training and development set loss curves
to file.
:param train_loss: (list) training losses
:param eval_loss: (list) dev set losses
:param path_to_save: (str) output directory
:return: void
"""
... | 28,746 |
def subcommand(args, api):
"""Execute the right airgap subcommand from args."""
if args.action == "download-scripts":
download_scripts.subcommand(args, api)
elif args.action == "upload":
upload.subcommand(args, api)
elif args.action == "download-compliance-scripts":
download_comp... | 28,747 |
def run_models():
""" run all models for comparison --- takes a while """
# feature sets and combinations to compare
# Non Deep Methods
if run_ehr_baselines:
run_outcome(outcome = "future_afib", features=features)
run_outcome(outcome = "stroke_6m", features=features)
run_outcome(... | 28,748 |
def plot_histogram(x):
"""
Visualise range distribution
:param x:
:return:
"""
x = x.flatten()
plt.hist(x)
plt.show() | 28,749 |
def pack_batch_tensor(inputs):
"""default pad_ids = 0
"""
input_max_length = max([d.size(0) for d in inputs])
# prepare batch tensor
input_ids = torch.LongTensor(len(inputs), input_max_length).zero_()
input_mask = torch.LongTensor(len(inputs), input_max_length).zero_()
for i, d in enumerate(... | 28,750 |
def schedule(dev):
""" Gets the schedule from the thermostat. """
# TODO: expose setting the schedule somehow?
for d in range(7):
dev.query_schedule(d)
for day in dev.schedule.values():
click.echo("Day %s, base temp: %s" % (day.day, day.base_temp))
current_hour = day.next_change_... | 28,751 |
def build_network(network_class=None,
dataset_dirs_args=None,
dataset_dirs_class=None,
dataset_dirs=None,
dataset_spec_args=None,
dataset_spec_class=None,
dataset_spec=None,
network_spec_args=No... | 28,752 |
def slt_workflow(slicetiming_txt="alt+z",SinkTag="func_preproc",wf_name="slicetiming_correction"):
"""
Modified version of porcupine generated slicetiming code:
`source: -`
Creates a slice time corrected functional image.
Workflow inputs:
:param func: The reoriented functional file.
... | 28,753 |
def lookup_service_root(service_root):
"""Dereference an alias to a service root.
A recognized server alias such as "staging" gets turned into the
appropriate URI. A URI gets returned as is. Any other string raises a
ValueError.
"""
if service_root == EDGE_SERVICE_ROOT:
# This will trig... | 28,754 |
def test_list_blocks_259():
"""
Test case 259: Here is an empty bullet list item:
"""
# Arrange
source_markdown = """- foo
-
- bar"""
expected_tokens = [
"[ulist(1,1):-::2:]",
"[para(1,3):]",
"[text(1,3):foo:]",
"[end-para:::True]",
"[li(2,1):2::]",
... | 28,755 |
def main():
"""
Main
"""
test_cm2_lycopene_100() | 28,756 |
def test_gitlab_fetcher(url, username, repository, git_ref, tmp_path):
"""Test creating a valid fetcher for GitLab URLs."""
mock_git_fetcher = Mock()
with patch("reana_server.fetcher.WorkflowFetcherGit", mock_git_fetcher):
parsed_url = ParsedUrl(url)
_get_gitlab_fetcher(ParsedUrl(url), tmp_p... | 28,757 |
def get_initial_configuration():
"""
Return (pos, type)
pos: (1, 1) - (9, 9)
type will be 2-letter strings like CSA format.
(e.g. "FU", "HI", etc.)
"""
warnings.warn(
"""get_initial_configuration() returns ambiguous cell state.
Use get_initial_configuration_with_dir() instead... | 28,758 |
def request_pull_to_diff_or_patch(
repo, requestid, username=None, namespace=None, diff=False
):
"""Returns the commits from the specified pull-request as patches.
:arg repo: the `pagure.lib.model.Project` object of the current pagure
project browsed
:type repo: `pagure.lib.model.Project`
:... | 28,759 |
def GL(alpha, f_name, domain_start = 0.0, domain_end = 1.0, num_points = 100):
""" Computes the GL fractional derivative of a function for an entire array
of function values.
Parameters
==========
alpha : float
The order of the differintegral to be computed.
... | 28,760 |
def check_lint(root_dir, ignore, verbose, dry_run, files_at_a_time,
max_line_len, continue_on_error):
"""Check for lint.
Unless `continue_on_error` is selected, returns `False` on the first
iteration where lint is found, or where the lint checker otherwise
returned failure.
:return:... | 28,761 |
def remove_comments(s):
"""
Examples
--------
>>> code = '''
... # comment 1
... # comment 2
... echo foo
... '''
>>> remove_comments(code)
'echo foo'
"""
return "\n".join(l for l in s.strip().split("\n") if not l.strip().startswith("#")) | 28,762 |
def generate_wsl(ws):
"""
Generates watershed line that correspond to areas of
touching objects.
"""
se = square(3)
ero = ws.copy()
ero[ero == 0] = ero.max() + 1
ero = erosion(ero, se)
ero[ws == 0] = 0
grad = dilation(ws, se) - ero
grad[ws == 0] = 0
grad[grad > 0] = 255
... | 28,763 |
def train_lstm_model(x, y,
epochs=200,
patience=10,
lstm_dim=48,
batch_size=128,
lr=1e-3):
"""
Train an LSTM to predict purchase (1) or abandon (0)
:param x: session sequences
:param y: target label... | 28,764 |
def nash_sutcliffe_efficiency(predicted, observed):
""" implements Nash-Sutcliffe Model Efficiencobserved Coefficient where predicted is modeled and observed is observed"""
if np.isnan(np.min(predicted)) or np.isnan(np.min(observed)):
return np.asarray([np.nan])
return 1 - np.sum((predicted - observed)**2) / np.su... | 28,765 |
def display_duplicates(df: Union[pd.DataFrame, pd.Series]) -> None:
"""Print a summary of the column-wise duplicates in the passed
dataframe.
"""
if isinstance(df, pd.core.series.Series):
df = pd.DataFrame(df)
dup_count = 0
print("Number of column-wise duplicates per column:")
for co... | 28,766 |
def tf_Affine_transformer(points, theta):
"""
Arguments:
points: `Matrix` [2, np] of grid points to transform
theta: `Matrix` [bs, 2, 3] with a batch of transformations
"""
with tf.name_scope('Affine_transformer'):
num_batch = tf.shape(theta)[0]
grid = tf.tile(tf.expand_d... | 28,767 |
def read_COCO_gt(filename, n_imgs=None, ret_img_sizes=False, ret_classes=False, bbox_gt=False):
"""
Function for reading COCO ground-truth files and converting them to GroundTruthInstances format.
:param filename: filename of the annotation.json file with all COCO ground-truth annotations
:param n_imgs:... | 28,768 |
def get_metrics_from_file(metric_file):
"""Gets all metric functions within a file
:param str metric_file: The name of the file to look in
:return: Tuples containing (function name, function object)
:rtype: list
"""
try:
metrics = import_module(metric_file)
metrics = get_sorted_... | 28,769 |
def mnist_model(inputs, mode):
"""Takes the MNIST inputs and mode and outputs a tensor of logits."""
# Input Layer
# Reshape X to 4-D tensor: [batch_size, width, height, channels]
# MNIST images are 28x28 pixels, and have one color channel
inputs = tf.reshape(inputs, [-1, 28, 28, 1])
data_format = 'channels... | 28,770 |
def show_local_mp4_video(file_name, width=640, height=480):
"""Renders a mp4 video on a Jupyter notebook
Args:
file_name (str): Path to file.
width (int): Video width.
height (int): Video height.
Returns:
obj: Video render as HTML object.
"""
video_encoded = base64.... | 28,771 |
def change_status(sid, rev, status, **kwargs):
"""
[INCOMPLETE]
- DISABLE OTHER REVISION OF THE SAME SIGNTURE WHEN DEPLOYING ONE
Change the status of a signature
Variables:
sid => ID of the signature
rev => Revision number of the signature
status => New state
... | 28,772 |
def trilinear_interpolation(a: np.ndarray, factor: float) -> np.ndarray:
"""Resize an three dimensional array using trilinear
interpolation.
:param a: The array to resize. The array is expected to have at
least three dimensions.
:param factor: The amount to resize the array. Given how the
... | 28,773 |
def load_data(path):
"""ๅฐๆๆ็labelไธtext่ฟ่กๅ็ฆป๏ผๅพๅฐไธคไธชlist"""
label_list = []
text_list = []
with open(path, 'r') as f:
for line in f.readlines():
data = line.strip().split('\t')
data[1] = data[1].strip().split()
label = [0 for i in range(8)]
total = 0
... | 28,774 |
def invoke(request):
"""Where the magic happens..."""
with monitor(labels=_labels, name="transform_request"):
transformed_request = _transform_request(request)
with monitor(labels=_labels, name="invoke"):
response = _model.predict(transformed_request)
with monitor(labels=_labels, name... | 28,775 |
def serializers(): #FIXME: could be much smarter
"""return a tuple of string names of serializers"""
try:
import imp
imp.find_module('cPickle')
serializers = (None, 'pickle', 'json', 'cPickle', 'dill')
except ImportError:
serializers = (None, 'pickle', 'json', 'dill')
try... | 28,776 |
def check_job(job_name):
"""Checks if transcription job has finished using its job name.
If the transcription job hasn't finished it will call itself recursively
until the job is completed.
Arguments:
job_name (str): the job name of the transcription job in AWS
Transcri... | 28,777 |
async def set_offset(bot, message):
"""```
Set the offset for the DnD ping cycle.
Usage:
* /set_offset N
```"""
new_offset = message.content[12:].strip()
try:
new_offset = int(new_offset)
except ValueError:
pass
with open(PING_CYCLE_OFFSET_FILE, 'w') as f:
... | 28,778 |
def munge_pocket_response(resp):
"""Munge Pocket Article response."""
articles = resp['list']
result = pd.DataFrame([articles[id] for id in articles])
# only munge if actual articles present
if len(result) != 0:
result['url'] = (result['resolved_url'].combine_first(result['given_url']))
... | 28,779 |
def while_t():
"""printing small 't' using while loop"""
i=0
while i<7:
j=0
while j<4:
if j==1 or i==3 and j!=3 or j==2 and i in(3,6) or j==3 and i==5:
print("*",end=" ")
else:
print(" ",end=" ")
j+=1
pr... | 28,780 |
def __abs_path(path):
"""
Creates an absolute path, based on the relative path from the configuration file
:param path: A relative path
:return: The absolute path, based on the configuration file
"""
if not os.path.isabs(path):
parent = os.path.abspath(os.path.join(config_path, os.pardir... | 28,781 |
def cgo_library(name, srcs,
toolchain=None,
go_tool=None,
copts=[],
clinkopts=[],
cdeps=[],
**kwargs):
"""Builds a cgo-enabled go library.
Args:
name: A unique name for this rule.
srcs: List of Go, C and C++ fil... | 28,782 |
async def test_track_template_error(hass, caplog):
"""Test tracking template with error."""
template_error = Template("{{ (states.switch | lunch) > 0 }}", hass)
error_calls = []
@ha.callback
def error_callback(entity_id, old_state, new_state):
error_calls.append((entity_id, old_state, new_s... | 28,783 |
def fake_data_PSBL_phot(outdir='', outroot='psbl',
raL=259.5, decL=-29.0,
t0=57000.0, u0_amp=0.8, tE=500.0,
piE_E=0.02, piE_N=0.02,
q=0.5, sep=5.0, phi=75.0, b_sff1=0.5, mag_src1=16.0,
parallax=True, ... | 28,784 |
def is_dicom(path: pathlib.Path) -> bool:
"""Check if the input is a DICOM file.
Args:
path (pathlib.Path): Path to the file to check.
Returns:
bool: True if the file is a DICOM file.
"""
path = pathlib.Path(path)
is_dcm = path.suffix.lower() == ".dcm"
is_dcm_dir = path.is... | 28,785 |
def _hessian(model: 'BinaryLogReg', data: Dataset, data_weights: Optional[jnp.ndarray]) -> jnp.ndarray:
"""Ravelled Hessian matrix of the objective function with respect to the model parameters"""
params_flat, unravel = ravel_pytree(model.params)
random_params = model.random_params
h = jax.hessian(lambd... | 28,786 |
def promax2meta(doc, target):
"""
Return meta information (Line or Area) of csv Promax geometry file.
Arguments:
doc -- csv Promax geometry file
target -- meta information to get (Line or Area)
"""
ptarget = r'' + re.escape(target) + r'\s*[=:]\s*\"?([\w-]+)\"?'
for line in open(doc):
... | 28,787 |
def axLabel(value, unit):
"""
Return axis label for given strings.
:param value: Value for axis label
:type value: int
:param unit: Unit for axis label
:type unit: str
:return: Axis label as \"<value> (<unit>)\"
:rtype: str
"""
return str(value) + " (" + str(unit) + ")" | 28,788 |
def save_notebook(filename, timeout=10):
"""
Force-saves a Jupyter notebook by displaying JavaScript.
Args:
filename (``str``): path to notebook file being saved
timeout (``int`` or ``float``): number of seconds to wait for save before timing-out
Returns
``bool``: whether the n... | 28,789 |
def test_config_start_with_api(test_microvm_with_api, vm_config_file):
"""
Test if a microvm configured from file boots successfully.
@type: functional
"""
test_microvm = test_microvm_with_api
_configure_vm_from_json(test_microvm, vm_config_file)
test_microvm.spawn()
response = test_m... | 28,790 |
def test_gen():
"""Create the test system."""
project_name = "test_grid_sinfactory"
return PFactoryGrid(project_name=project_name).gens["SM1"] | 28,791 |
def validate_api_key():
"""Validates an API key submitted via POST."""
api_key_form = ApiKeyForm()
api_key_form.organization.choices = session['orgs_list']
if api_key_form.validate_on_submit():
session['org_id'] = api_key_form.organization.data
return jsonify(True)
return json... | 28,792 |
def test_suggest_add(entities, capsys):
"""
The netixlan described in the remote-ixf doesn't exist,
but there is a relationship btw the network and ix (ie a different netixlan).
The network does not have automatic updates.
There isn't a local-ixf that matches the remote-ixf.
We suggest adding th... | 28,793 |
def plot_clickForPlane():
""" Create a Plane at location of one mouse click in the view or
onto a clicked object or
at a pre-selected point location:
Create a Plane perpendicular to the view at location of one mouse click.
- Click first on the Button then click once on the View.
- Click first on... | 28,794 |
def is_logged_in(f):
"""
is logged in decorator
"""
@wraps(f)
def wrap(*args, **kwargs):
"""
wrap from template
"""
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('Unauthorized, Please login', 'danger')
... | 28,795 |
def dataframe_from_mult_files(filenames):
"""@param filenames (List[Str]): list of filenames"""
dfs = []
for filename in filenames:
dfs.append(dataframe_from_file(filename))
return pd.concat(dfs, axis=0) | 28,796 |
def batch_euclidean_dist(x, y, min_val):
""" euclidean_dist function over batch
x and y are batches of matrices x' and y':
x' = (x'_1, | x'_2 | ... | x'_m).T
y' = (y'_1, | y'_2 | ... | y'_n).T
Where x_i and y_j are vectors. We calculate the distances between each pair x_i and y_j.
res'[i, j] ... | 28,797 |
def outgroup_reformat(newick, outgroup):
"""
Move the location of the outgroup in a newick string to be at the end of the string
Inputs:
newick --- a newick string to be reformatted
outgroup --- the outgroup
Output:
newick --- the reformatted string
"""
# Replace the outgroup and co... | 28,798 |
def get_source_token(request):
"""
Perform token validation for the presqt-source-token header.
Parameters
----------
request : HTTP request object
Returns
-------
Returns the token if the validation is successful.
Raises a custom AuthorizationException error if the validation fail... | 28,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.