content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def api(default=None, api=None, **kwargs):
"""Returns the api instance in which this API function is being ran"""
return api or default | 4,600 |
def parse_json(data):
"""Parses the PupleAir JSON file, returning a Sensors protobuf."""
channel_a = []
channel_b = {}
for result in data["results"]:
if "ParentID" in result:
channel_b[result["ParentID"]] = result
else:
channel_a.append(result)
sensors = list(... | 4,601 |
def asynchronize_tornado_handler(handler_class):
"""
A helper function to turn a blocking handler into an async call
:param handler_class: a tornado RequestHandler which should be made asynchronus
:return: a class which does the same work on a threadpool
"""
class AsyncTornadoHelper(handler_cla... | 4,602 |
def check_regex(regexstring):
""" method to check that the regex works"""
if regexstring is not None:
try:
compiledregex = re.compile(regexstring, flags=re.IGNORECASE)
# result = compiledregex.match(string)
except:
raise click.BadOptionUsage("The regex didn't ... | 4,603 |
def convert_single_example(ex_index, example: InputExample,
tokenizer, label_map, dict_builder=None):
"""Converts a single `InputExample` into a single `InputFeatures`."""
# label_map = {"B": 0, "M": 1, "E": 2, "S": 3}
# tokens_raw = tokenizer.tokenize(example.text)
tokens_ra... | 4,604 |
def create_scenariolog(sdata, path, recording, logfilepath):
"""
シナリオのプレイデータを記録したXMLファイルを作成する。
"""
element = cw.data.make_element("ScenarioLog")
# Property
e_prop = cw.data.make_element("Property")
element.append(e_prop)
e = cw.data.make_element("Name", sdata.name)
e_prop.ap... | 4,605 |
async def converter_self_interaction_target(client, interaction_event):
"""
Internal converter for returning the received interaction event's target. Applicable for context application
commands.
This function is a coroutine.
Parameters
----------
client : ``Client``
The cli... | 4,606 |
def publication_pages(publication_index_page) -> List[PublicationPage]:
"""Fixture providing 10 PublicationPage objects attached to publication_index_page"""
rv = []
for _ in range(0, 10):
p = _create_publication_page(
f"Test Publication Page {_}", publication_index_page
)
... | 4,607 |
def copy_orphans(source_path, albums_paths, out_path):
""" Copies orphan files.
Method iterates over the files in the first level of source_path and detects
the files that do not exist under any level of albums_path. These are considered
orphans files and are copied to out_path. Files that have the sam... | 4,608 |
def rp_completion(
rp2_metnet,
sink,
rp2paths_compounds,
rp2paths_pathways,
cache: rrCache = None,
upper_flux_bound: float = default_upper_flux_bound,
lower_flux_bound: float = default_lower_flux_bound,
max_subpaths_filter: int = default_max_subpaths_filter,
logger: Logger = getLogge... | 4,609 |
def wrap(func, *args, unsqueeze=False):
"""
Wrap a torch function so it can be called with NumPy arrays.
Input and return types are seamlessly converted.
"""
args = list(args)
for i, arg in enumerate(args):
if type(arg) == np.ndarray:
args[i] = torch.from_numpy(arg)
... | 4,610 |
def STOCHF(data, fastk_period=5, fastd_period=3, fastd_ma_type=0):
"""
Stochastic %F
:param pd.DataFrame data: pandas DataFrame with open, high, low, close data
:param int fastk_period: period used for K fast indicator calculation
:param int fastd_period: period used for D fast indicator calculatio... | 4,611 |
def playerid_reverse_lookup(player_ids, key_type=None):
"""Retrieve a table of player information given a list of player ids
:param player_ids: list of player ids
:type player_ids: list
:param key_type: name of the key type being looked up (one of "mlbam", "retro", "bbref", or "fangraphs")
:type ke... | 4,612 |
def test_expense_categories_search(ns_connection):
"""
HOW TO JOIN account's name in advanced search
"""
categories = list(ns_connection.expense_categories.get_all())
ns_connection.client.set_search_preferences(return_search_columns=True)
advanced_categories = list(ns_connection.expense_categor... | 4,613 |
def write_yaml(data):
""" A function to write YAML file"""
with open('toyaml.yml', 'w') as f:
yaml.dump(data, f) | 4,614 |
def get_delta_z(z, rest_ghz, ghz=None):
"""
Take a measured GHz value, and calculates the restframe GHz value based on the given z of the matched galaxy
:param z:
:param ghz:
:return:
"""
# First step is to convert to nm rom rest frame GHz
set_zs = []
for key, values in transitions.... | 4,615 |
def hist_orientation(qval, dt):
"""
provided with quats, and time spent* in the direction defined by quat
produces grouped by ra, dec and roll quaternions and corresponding time, spent in quats
params: qval a set of quats stored in scipy.spatial.transfrom.Rotation class
params: dt corresponding to... | 4,616 |
def prepare_data(args: argparse.Namespace) -> None:
"""Break one or a list of videos into frames."""
url_root = args.url_root
if args.s3:
url_root = s3_setup(args.s3)
inputs = parse_input_list(args)
logger.info("processing %d video(s) ...", len(inputs))
num_videos = len(inputs)
vid... | 4,617 |
def delete_job_queue(jobQueue=None):
"""
Deletes the specified job queue. You must first disable submissions for a queue with the UpdateJobQueue operation. All jobs in the queue are terminated when you delete a job queue.
It is not necessary to disassociate compute environments from a queue before submitti... | 4,618 |
def tcpip(port=5555, debug=False):
"""
切换到tcpip模式(网络模式)
:param port: 端口(默认值5555)
:param debug: 调试开关(默认关闭)
:return: 不涉及
"""
return adb_core.execute(f'tcpip {port}', debug=debug) | 4,619 |
def proclamadelcaucacom_story(soup):
"""
Function to pull the information we want from Proclamadelcauca.com stories
:param soup: BeautifulSoup object, ready to parse
"""
hold_dict = {}
#text
try:
article_body = soup.find('div', attrs={"class": "single-entradaContent"})
mainte... | 4,620 |
def asarray_fft(x, inverse):
"""Recursive implementation of the 1D Cooley-Tukey FFT using np asarray
to prevent copying.
Parameters:
x (array): the discrete amplitudes to transform.
inverse (bool): perform the inverse fft if true.
Returns:
x (array): the amplitudes of the origin... | 4,621 |
def bootstrap(ctx):
"""Creates a systemd service file and to enable it."""
project_name = ctx.project.name
service_file = Path(ctx.paths.remote.configs) / f'{project_name}.service'
ctx.sudo(f'systemctl enable --now {service_file}') | 4,622 |
def get_long_description():
"""
Returns the long description of Wapyce.
:return: The long description of Wapyce.
:rtype: str
"""
with open(
os.path.join(BASE_DIRECTORY, 'README.md'),
'r',
encoding='utf-8'
) as readme_file:
return readme_file.read() | 4,623 |
def wrap_locale_context(func):
"""Wraps the func with the current locale."""
@jinja2.contextfilter
def _locale_filter(ctx, value, *args, **kwargs):
doc = ctx['doc']
if not kwargs.get('locale', None):
kwargs['locale'] = str(doc.locale)
return func(value, *args, **kwargs)
... | 4,624 |
def _create_node(module_path, tree_element):
"""Constructs a list of strings comprising the sections of the node module. Node module file is written.
:param module_path: full path to the library where the subnode lives
:param tree_element: Element object from the xml.etree.ElementTree package
:return:... | 4,625 |
def mu_Xe(keV=12):
"""Returns inverse 1/e penetration depth [mm-1 atm-1] of Xe given the
x-ray energy in keV. The transmission through a 3-mm thick slab of Xe at
6.17 atm (76 psi) was calculated every 100 eV over an energy range
spanning 5-17 keV using:
http://henke.lbl.gov/optical_constants/fil... | 4,626 |
def file_md5(input_file):
"""
:param input_file: Path to input file.
:type input_file: str
:return: Returns the encoded data in the inputted file in hexadecimal format.
"""
with open(input_file, 'rb') as f:
data = f.read()
return hashlib.md5(data).hexdigest() | 4,627 |
def signup(request):
"""Register a new user.
This view has multiple behaviours based on the request composition. When
some user is already signed in, the response ask the user to first sign
out. When the request has no data about the new user, then the response
carries the registration form. When t... | 4,628 |
def exit_func():
"""
this function should be called when exiting, first clear the screen, then exit
:return: exits program and clear the screen
"""
clear()
sys.exit(0) | 4,629 |
def assert_content_text_equal(act_text, exp_filepath):
"""
Compare an actual text file content and the content of an expected text
file for line-wise equality, tolerating differences in line endings
(LF vs. CRLF).
"""
with open(exp_filepath, 'r') as exp_fp:
exp_text = exp_fp.read()
a... | 4,630 |
def shuffle_rows(X):
"""
Randomly shuffles rows of a numpy matrix
"""
n, _ = X.shape
indices = list(range(n))
shuffle(indices)
X[:] = X[indices] | 4,631 |
def message_args() -> Dict[str, str]:
"""A formatted message."""
return {"subject": "Test message", "message": "This is a test message"} | 4,632 |
def to_drive_type(value):
"""Convert value to DriveType enum."""
if isinstance(value, DriveType):
return value.value
sanitized = str(value).upper().strip().replace(" ", "_")
try:
return DriveType[sanitized].value
except KeyError as err:
raise ValueError(f"Unknown drive type:... | 4,633 |
def upload_authorized_key(host, port, filepath):
"""UPLOAD (key) upload_authorized_key"""
params = {'method': 'upload_authorized_key'}
files = [('key', filepath, file_get_contents(filepath))]
return _check(https.client.https_post(host, port, '/', params, files=files)) | 4,634 |
def thermalize_cutoff(localEnergies, smoothing_window, tol):
"""Return position where system is thermalized
according to some tolerance tol, based on the derivative
of the smoothed local energies
"""
mean = np.mean(localEnergies)
smoothLocalEnergies = smoothing(localEnergies, smoothing_window)
... | 4,635 |
def annualize_metric(metric: float, holding_periods: int = 1) -> float:
"""
Annualize metric of arbitrary periodicity
:param metric: Metric to analyze
:param holding_periods:
:return: Annualized metric
"""
days_per_year = 365
trans_ratio = days_per_year / holding_periods
return (1... | 4,636 |
def parse_args():
"""Command line arguments parser."""
app = argparse.ArgumentParser()
app.add_argument("in_chain", help="Input chain file or stdin")
app.add_argument("reference_2bit", help="Reference 2bit file")
app.add_argument("query_2bit", help="Query 2bit file")
app.add_argument("output", h... | 4,637 |
def get_latest_tag():
"""
Find the value of the latest tag for the Adafruit CircuitPython library
bundle.
:return: The most recent tag value for the project.
"""
global LATEST_BUNDLE_VERSION # pylint: disable=global-statement
if LATEST_BUNDLE_VERSION == "":
LATEST_BUNDLE_VERSION = g... | 4,638 |
def detail(request, name):
"""
List all details about a single service.
"""
service = CRITsService.objects(name=name,
status__ne="unavailable").first()
if not service:
error = 'Service "%s" is unavailable. Please review error logs.' % name
return ... | 4,639 |
def read_gold_conll2003(gold_file):
"""
Reads in the gold annotation from a file in CoNLL 2003 format.
Returns:
- gold: a String list containing one sequence tag per token.
E.g. [B-Kochschritt, L-Kochschritt, U-Zutat, O]
- lines: a list list containing the original line spli... | 4,640 |
def clone_reindex(clone_ingest_config: CloneIngestConfig, **kwargs):
"""Pipeline for pulling down jsons from s3 and reindexing into elasticsearch"""
announce('Pulling down parsed snapshot files for reindexing ...')
clone_ingest_config.snapshot_manager.pull_current_snapshot_to_disk(
local_dir=clone_i... | 4,641 |
def translate_nova_exception(method):
"""Transforms a cinder exception but keeps its traceback intact."""
@functools.wraps(method)
def wrapper(self, ctx, *args, **kwargs):
try:
res = method(self, ctx, *args, **kwargs)
except (nova_exceptions.ConnectionRefused,
key... | 4,642 |
def _update_form(form):
""" """
if not form.text():
return form.setStyleSheet(error_css)
return form.setStyleSheet(success_css) | 4,643 |
def build_vocab_from_file(src_file, save_path, min_frequency=5, size=0, without_sequence_tokens=False):
"""
Generate word vocabularies from monolingual corpus.
:param src_file: Source text file.
:param save_path: Output vocabulary file.
:param min_frequency: Minimum word frequency. # for yelp and a... | 4,644 |
def create_adapter(openvino, cpu_only, force_torch, use_myriad):
"""Create the best adapter based on constraints passed as CLI arguments."""
if use_myriad:
openvino = True
if cpu_only:
raise Exception("Cannot run with both cpu-only and Myriad options")
if force_torch and openvi... | 4,645 |
def test_2():
"""
Binary and unary predicates with an overlapping variable subset.
:return:
"""
x, y = map(Variable, ['x', 'y'])
model = Model() # Instantiate a model.
enemy = model['enemy'] = Predicate(arity=2, name='enemy')
hostile = model['hostile'] = Predicate(name='hostile')
... | 4,646 |
def _make_ecg(inst, start, stop, reject_by_annotation=False, verbose=None):
"""Create ECG signal from cross channel average."""
if not any(c in inst for c in ['mag', 'grad']):
raise ValueError('Unable to generate artificial ECG channel')
for ch in ['mag', 'grad']:
if ch in inst:
... | 4,647 |
def lorentzian(freq, freq0, area, hwhm, phase, offset, drift):
"""
Lorentzian line-shape function
Parameters
----------
freq : float or float array
The frequencies for which the function is evaluated
freq0 : float
The center frequency of the function
area : float
hwhm: float
... | 4,648 |
def findTilt(root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
return findTilt_helper(root)[1] | 4,649 |
def generate_report():
"""
Get pylint analization report and write it to file
"""
files = get_files_to_check()
dir_path = create_report_dir()
file_path = create_report_file(dir_path)
config_opts = get_config_opts()
pylint_opts = '--load-plugins pylint_flask' + config_opts
pylint_stdo... | 4,650 |
def read_files(year,month,day,station):
"""
"""
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
# i have a function for this ....
rinexfile = station + cdoy + '0.' + cyy + 'o'
navfilename = 'auto' + cdoy + '0.' + cyy + 'n'
if os.path.isfile(rinexfile):
print('rinexfile exists')
... | 4,651 |
def make_trampoline(func_name):
""" Create a main function that calls another function """
mod = ir.Module('main')
main = ir.Procedure('main')
mod.add_function(main)
entry = ir.Block('entry')
main.add_block(entry)
main.entry = entry
entry.add_instruction(ir.ProcedureCall(func_name, []))
... | 4,652 |
def plot_in_flux_basic(
cur,
facility,
title):
"""Plots timeseries influx/ outflux from facility name in kg.
Parameters
----------
cur: sqlite cursor
sqlite cursor
facility: str
facility name
influx_bool: bool
if true, calculates influx,
i... | 4,653 |
def enrich(
db_path: Path = typer.Argument(
"./spotify.db", file_okay=True, dir_okay=False, writable=True
),
table: str = typer.Argument(
...,
),
uri_column: str = typer.Option(
"spotify_track_uri", help="Column name containing tracks' URIs"
),
new_name: str = typer.O... | 4,654 |
def run_and_retry(json_file: str = "latest.json", charts_file: str = "charts.svg", max_attempts: int = 10, sleep_seconds_on_error: float = 10) -> None:
"""
Calculates the current CBBI confidence value alongside all the required metrics.
Everything gets pretty printed to the current standard output and a cle... | 4,655 |
def main(global_config, **settings):
"""Return a Pyramid WSGI application."""
if not settings.get('sqlalchemy.url'):
try:
settings['sqlalchemy.url'] = os.environ['BLOG2017_DB']
except KeyError:
print('Required BLOG2017_DB not set in global os environ.')
sys.ex... | 4,656 |
def model_fields(dbo, baseuri=None):
"""Extract known fields from a BQ object, while removing any known
from C{excluded_fields}
@rtype: dict
@return fields to be rendered in XML
"""
attrs = {}
try:
dbo_fields = dbo.xmlfields
except AttributeError:
# This occurs when the ... | 4,657 |
def test_fetch_incidents(mocker):
"""Unit test
Given
- fetch incidents command
- command args
- command raw response
When
- mock the Client's token generation.
- mock the Client's get_alerts_request.
Then
- run the fetch incidents command using the Client
Validate The length ... | 4,658 |
def get_bsj(seq, bsj):
"""Return transformed sequence of given BSJ"""
return seq[bsj:] + seq[:bsj] | 4,659 |
def update_celery_task_status_socketio(task_id):
"""
This function would be called in Celery worker
https://python-socketio.readthedocs.io/en/latest/server.html#emitting-from-external-processes
"""
# connect to the redis queue as an external process
external_sio = socketio.RedisManager(
... | 4,660 |
def test_perform():
"""Test the `/perform` path."""
response = app.test_client().post(
"/perform/simple",
data=json.dumps({"colour": [0, 255, 0]}),
content_type="application/json",
)
assert response.status_code == 200
assert response.json == {"status": "OK"} | 4,661 |
def test_colormap():
"""Test colormap support for non-uniformly distributed control-points"""
with TestingCanvas(size=size, bgcolor='w') as c:
idata = np.linspace(255, 0, size[0]*size[1]).astype(np.ubyte)
data = idata.reshape((size[0], size[1]))
image = Image(cmap=Colormap(colors=['k', '... | 4,662 |
def sample(problem: Dict, N: int, calc_second_order: bool = True,
skip_values: int = 0):
"""Generates model inputs using Saltelli's extension of the Sobol' sequence.
Returns a NumPy matrix containing the model inputs using Saltelli's sampling
scheme. Saltelli's scheme extends the Sobol' sequence... | 4,663 |
def standardize(table, option):
"""
standardize
Z = (X - mean) / (standard deviation)
"""
if option == 'table':
mean = np.mean(table)
std = np.std(table)
t = []
for row in table:
t_row = []
if option != 'table':
mean = np.mean(row)
std ... | 4,664 |
def cache(project: Project, patterns: Sequence[str], clear: bool):
"""Inspect or clear the cache."""
if clear:
with message_fence("Clearing cache..."):
if cache_names := ", ".join(project.clear_cache(patterns)):
click.echo(f"Cache cleared successfully: {cache_names}.\n")
... | 4,665 |
def raw_input_nonblock():
"""
return result of raw_input if has keyboard input, otherwise return None
"""
if _IS_OS_WIN32:
return _raw_input_nonblock_win32()
else:
raise NotImplementedError('Unsupported os.') | 4,666 |
def get_batch_hard(draw_batch_size,hard_batchs_size,semihard_batchs_size,easy_batchs_size,norm_batchs_size,network,dataset,nb_classes, margin):
"""
Create batch of APN "hard" triplets
Arguments:
draw_batch_size -- integer : number of initial randomly taken samples
hard_batchs_size -- interger : sel... | 4,667 |
def sine(
start, end, freq, amp: Numeric = 1, n_periods: Numeric = 1
) -> TimeSerie:
"""
Generate a sine TimeSerie.
"""
index = pd.date_range(start=start, end=end, freq=freq)
return TimeSerie(
index=index,
y_values=np.sin(
np.linspace(0, 2 * math.pi * n_periods, num=l... | 4,668 |
def get_from_address(sending_profile, template_from_address):
"""Get campaign from address."""
# Get template display name
if "<" in template_from_address:
template_display = template_from_address.split("<")[0].strip()
else:
template_display = None
# Get template sender
template... | 4,669 |
def is_dwm_compositing_enabled():
"""Is Desktop Window Manager compositing (Aero) enabled.
"""
import ctypes
enabled = ctypes.c_bool()
try:
DwmIsCompositionEnabled = ctypes.windll.dwmapi.DwmIsCompositionEnabled
except (AttributeError, WindowsError):
# dwmapi or DwmIsCompositionE... | 4,670 |
def save_any_to_npy(save_dict={}, name='file.npy'):
"""Save variables to .npy file.
Examples
---------
>>> tl.files.save_any_to_npy(save_dict={'data': ['a','b']}, name='test.npy')
>>> data = tl.files.load_npy_to_any(name='test.npy')
>>> print(data)
... {'data': ['a','b']}
"""
np.sav... | 4,671 |
async def kickme(leave):
""" .kickme komutu gruptan çıkmaya yarar """
chat = await leave.get_chat()
await leave.edit(f"{PLUGIN_MESAJLAR['kickme']}".format(
id=chat.id,
title=chat.title,
member_count="Bilinmiyor" if chat.participants_count == None else (chat.participants_count - 1)
... | 4,672 |
def logging_setup(config: Dict):
"""
setup logging based on the configuration
:param config: the parsed config tree
"""
log_conf = config['logging']
fmt = log_conf['format']
if log_conf['enabled']:
level = logging._nameToLevel[log_conf['level'].upper()]
else:
level = log... | 4,673 |
def hamming_distance(seq_1, seq_2, ignore_case):
"""Hamming distance between two sequences
Calculate the Hamming distance between SEQ_1 and SEQ_2.
"""
result = pb.hamming_distance(seq_1, seq_2, ignore_case=ignore_case)
click.echo(result) | 4,674 |
def test_apply_many_flows(backend):
"""
Expect multiple flows to operate independently and produce the correct final flow rate.
"""
model = CompartmentalModel(
times=[0, 5], compartments=["S", "I", "R"], infectious_compartments=["I"]
)
model._set_backend(backend)
model.set_initial_po... | 4,675 |
def postreleaser_before(data):
"""
postreleaser.before hook to set a different dev_version_template from the
default: By default zest.releaser uses <version>.dev0. We want just
<version>.dev without the mysterious 0.
"""
if data['name'] != 'astropy':
return
data['dev_version_templ... | 4,676 |
def fgsm(x, y_true, y_hat, epsilon=0.075):
"""Calculates the fast gradient sign method adversarial attack
Following the FGSM algorithm, determines the gradient of the cost function
wrt the input, then perturbs all the input in the direction that will cause
the greatest error, with small magnitude.
... | 4,677 |
def clear_discovery_hash(hass, discovery_hash):
"""Clear entry in ALREADY_DISCOVERED list."""
if ALREADY_DISCOVERED not in hass.data:
# Discovery is shutting down
return
del hass.data[ALREADY_DISCOVERED][discovery_hash] | 4,678 |
def tour_delete(request,id):
""" delete tour depending on id """
success_message, error_message = None, None
form = TourForm()
tour = get_object_or_404(Tour, id=id)
tours = Tour.objects.all()
if request.method=="POST":
tour.delete()
success_message = "deleted tour"
... | 4,679 |
def d3():
"""Simulate the roll of a 3 sided die"""
return random.randint(1, 3) | 4,680 |
def split_file_name(file_name):
"""
splits the name from the file name.
:param file_name:
:return:
"""
return os.path.splitext(file_name)[0] | 4,681 |
def run_as_root(command, printable=True, silent_start=False):
"""
General purpose wrapper for running a subprocess as root user
"""
sudo_command = "sudo {}".format(command)
return run_command(sudo_command,
error_msg="",
stdout=subprocess.PIPE,
... | 4,682 |
def test_one_time_bonus_value():
"""Check that the value over date ranges is correct
Over 5 years, get the bonus, not more, only two week have the bonus"""
base_date = datetime.date(2018, 1, 1)
payoff_date = datetime.date(2018, 6, 6)
bonus_amount = 100000
bonus = PeriodicBonus(
amount=bo... | 4,683 |
def generate_patches(in_file, out_file, mode, remove, train_fraction, seed, epsilon, min_points):
"""
Sample the data from the source file and divide them into training and test data through a selection matrix
Result is stored in the given output HDF5 file.
:param in_file: str containing the f... | 4,684 |
def _search_qr(model, identifier, session):
"""Search the database using a Query/Retrieve *Identifier* query.
Parameters
----------
model : pydicom.uid.UID
Either *Patient Root Query Retrieve Information Model* or *Study Root
Query Retrieve Information Model* for C-FIND, C-GET or C-MOVE... | 4,685 |
def produce_summary_pdf(model_name, img_path, hyperparams, model_arch, train_stats):
"""
Produce a summary pdf containing configuration used, training curve,
model architecture and epoch training summary
:param model_name: name of current experiment/model being run
:param hyperparams: dict of a... | 4,686 |
def test_homodyne_mode_kwargs():
"""Test that S gates and Homodyne mesurements are applied to the correct modes via the `modes` kwarg.
Here the initial state is a "diagonal" (angle=pi/2) squeezed state in mode 0
and a "vertical" (angle=0) squeezed state in mode 1.
Because the modes are separable, meas... | 4,687 |
def retrieve_zoom_metadata(
stage=None, zoom_api=None, file_key=None, log=None, **attributes
):
"""General function to retrieve metadata from various Zoom endpoints."""
if "id" in attributes:
api_response = zoom_api(id=attributes["id"])
elif "meeting_id" in attributes:
api_response = zoo... | 4,688 |
def find_max_value(binary_tree):
"""This function takes a binary tree and returns the largest value of all the nodes in that tree
with O(N) space and O(1) time using breadth first traversal while keeping track of the largest value thus far
in the traversal
"""
root_node = []
rootnode.push(binar... | 4,689 |
def failed_jobs(username, root_wf_id, wf_id):
"""
Get a list of all failed jobs of the latest instance for a given workflow.
"""
dashboard = Dashboard(g.master_db_url, root_wf_id, wf_id)
args = __get_datatables_args()
total_count, filtered_count, failed_jobs_list = dashboard.get_failed_jobs(
... | 4,690 |
def test_action_in_alfred(alfred4):
"""Action."""
paths = ["~/Documents", "~/Desktop"]
script = (
'Application("com.runningwithcrayons.Alfred")'
'.action(["~/Documents", "~/Desktop"]);'
)
cmd = ["/usr/bin/osascript", "-l", "JavaScript", "-e", script]
with MockCall() as m:
... | 4,691 |
def get_vm_types(resources):
"""
Get all vm_types for a list of heat resources, do note that
some of the values retrieved may be invalid
"""
vm_types = []
for v in resources.values():
vm_types.extend(list(get_vm_types_for_resource(v)))
return set(vm_types) | 4,692 |
def plot_all_strings(args, plot_frequency=1, start_iteration=1, end_iteration=None, rescale=False, legend=True,
twoD=False,
plot_restrained=False, cv_indices=None, plot_convergence=True, plot_reference_structures=True):
"""Find all string-paths and plot them"""
runner =... | 4,693 |
def list_files(directory, suffix='.nc'):
"""
Return a list of all the files with the specified suffix in the submission
directory structure and sub-directories.
:param str directory: The root directory of the submission
:param str suffix: The suffix of the files of interest
:returns: A list of ... | 4,694 |
def interface_names(obj):
"""
Return: a list of interface names to which `obj' is conformant.
The list begins with `obj' itself if it is an interface.
Names are returned in depth-first order, left to right.
"""
return [o.__name__ for o in interfaces(obj)] | 4,695 |
def add_basic(token):
"""For use with Authorization headers, add "Basic "."""
if token:
return (u"Basic " if isinstance(token, six.text_type) else b"Basic ") + token
else:
return token | 4,696 |
def plot_convergence(x,y):
"""
Visualize the convergence of the sensitivity indices
takes two arguments : x,y input and model output samples
return plot of sensitivity indices wrt number of samples
"""
try:
ninput = x.shape[1]
except (ValueError, IndexError):
ninput = x.size
... | 4,697 |
def updateUser(token, leaderboard=None, showUsername=None, username=None):
"""
Update user account information.
Parameters-
token: Authentication token.
leaderboard: True to show user's profit on leaderboard.
showUsername: True to show the username on LN Marktes public data.
username: usern... | 4,698 |
def test_plot_segments(sersic_2d_image, segm_and_cat):
"""Test segment plotting functions"""
cat, segm, segm_deblend = segm_and_cat
plot_segments(segm, vmax=1, vmin=0)
plot_segments(segm_deblend, vmax=1, vmin=0)
plot_segment_residual(segm, sersic_2d_image.data, vmax=1, vmin=0) | 4,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.