content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import requests
def get_message(message_id):
"""
Shows details for a message, by message ID.
:param message_id: Specify the message ID in the messageId parameter in the URI.
:return: message details formatted in JSON
"""
api_node = "{}messages/{}".format(SPARK_API_URL, message_id)
headers... | abd124781eb8002c2ff27f5c603e9061523ff352 | 3,632,800 |
def testsuite(*args, **kwargs):
"""
Annotate a class as being a test suite
An :py:func:`@testsuite <testsuite>`-annotated class must have one or more
:py:func:`@testcase <testcase>`-annotated methods. These methods will be
executed in their order of definition. If a ``setup(self, env)`` and
``t... | ad1885ff95a43823ee6411c50b03d0d460b5f7f1 | 3,632,801 |
def GetClusterAdjcency(clusters, facedge):
""" Creates sparse cluster adjcent matrix """
# Get boundary clusters for adjcent cluster computation
edgeclus = clusters[facedge]
bmask = edgeclus[:, 0] != edgeclus[:, 1]
bclus = edgeclus[bmask]
a = np.hstack((bclus[:, 0], bclus[:, 1]))
b... | b335d48069bda241208f81b80462097ec5fa927c | 3,632,802 |
def _strip(g, base, orbits, transversals):
"""
Attempt to decompose a permutation using a (possibly partial) BSGS
structure.
This is done by treating the sequence ``base`` as an actual base, and
the orbits ``orbits`` and transversals ``transversals`` as basic orbits and
transversals relative to... | 999f5ed33d895dae446d8aa8eabf58eb82bcb30b | 3,632,803 |
def list_physical_devices(device_type=None):
"""Return a list of physical devices visible to the runtime.
Physical devices are hardware devices locally present on the current machine.
By default all discovered CPU and GPU devices are considered visible. The
`list_physical_devices` allows querying the hardware ... | d9683db64be013df5c258aa6573456005863e74e | 3,632,804 |
def awards_grants_honors(p):
"""Make sorted awards grants and honors list.
Parameters
----------
p : dict
The person entry
"""
aghs = []
for x in p.get('funding', ()):
d = {'description': '{0} ({1}{2:,})'.format(
latex_safe(x['name']),
x.get('currency... | c1b0f2626109fe59ca71654a86f46e34a1da8a7d | 3,632,805 |
import re
from datetime import datetime
def string_to_time(course_time): # '二1-2 三3-4'
"""
:param course_time: '二1-2'
:return: 十周或若干周的上课下课时间 [{start_time, end_time},...]
"""
course_times = []
course_minutes = [0, 55, 120, 175, 250, 295, 370, 425, 480, 535, 600, 655, 710]
available_weeks... | be4722163f776d44bdf80257664d25be8da0b571 | 3,632,806 |
def get_parameters(model: str, group_id: int = 0,
t_in: int = 0, t_out: int = 0, p_th: int = 0) -> pd.DataFrame:
"""
Loads the content of the database for a specific heat pump model
and returns a pandas ``DataFrame`` containing the heat pump parameters.
Parameters
----------
... | 041d55d2ed839413a8213f3c4c8cbdb09759b933 | 3,632,807 |
def gauss(x, mu, var, a=1):
"""
Gauss distribution value at x
:param x:
:param mu: expected value
:param var: variance, (sigma^2)
:param a: coefficient in cases total area != 1
:return:
"""
return a/(np.sqrt(2*var*np.pi)) * np.exp(- (x-mu)**2/(2*var)) | 6b0843ab4372a7f3f75fd709fbdc32be826a2626 | 3,632,808 |
def build_backbone(
image_size: tuple, out_channels: int, model_config: dict, method_name: str
) -> tf.keras.Model:
"""
Backbone model accepts a single input of shape (batch, dim1, dim2, dim3, ch_in)
and returns a single output of shape (batch, dim1, dim2, dim3, ch_out)
:param image_size: tuple, di... | 31d1f329bf7344a6db6d9fbf0e417ff0f3d20de8 | 3,632,809 |
def create_subnet(client, cidr_blk, vpc_id):
"""
Create a subnet in the given CIDR block and VPC using client.
:param client: a valid boto3 EC2 client.
:param cidr_blk: a valid IP range in the format 'a.b.c.d/XX'
:type cidr_blk: str
:param vpc_id: the VpcID of the Databricks VPC.
:type vpc_i... | ff34f2c2ac89edcbc568a80890c90ca0b3616c09 | 3,632,810 |
import math
def get_hertz_feed(reference_timestamp, current_timestamp, period_days, phase_days, reference_asset_value, amplitude):
"""
Given the reference timestamp, the current timestamp, the period (in days), the phase (in days), the reference asset value (ie 1.00) and the amplitude (> 0 && < 1), output the curre... | 4da9ae370e4a68119a8fe64b2442275f249d5ed2 | 3,632,811 |
def find_list_in_list(reference_array, inp):
"""
---------------------------------------------------------------------------
Find occurrences of input list in a reference list and return indices
into the reference list
Inputs:
reference_array [list or numpy array] One-dimensional reference l... | 7a4db527c6f73dcaf3436afa46317ffe443bc5bc | 3,632,812 |
import torch
def accuracy(output, target):
"""Computes the accuracy over the top predictions"""
with torch.no_grad():
batch_size = target.size(0)
_, preds = torch.max(output.data, 1)
correct = (preds == target).sum().item()
return correct/batch_size | 8f4dfde0e00f12d889b403265d50a379930ba3c8 | 3,632,813 |
from bs4 import BeautifulSoup
def get_absolute_url(body_string: str):
"""Get absolute manga mangadex url"""
parser = BeautifulSoup(body_string, 'html.parser')
for link_elements in parser.find_all('link'):
# aiming for canonical link
try:
rel = link_elements.attrs['rel']
... | 35ca71dba04c243ab7c4cfa4893326ddeb480336 | 3,632,814 |
def panel_grid(hspace, wspace, ncols, num_panels):
"""Init plot."""
n_panels_x = min(ncols, num_panels)
n_panels_y = np.ceil(num_panels / n_panels_x).astype(int)
if wspace is None:
# try to set a wspace that is not too large or too small given the
# current figure size
wspace =... | 4da67af64bfcead3309f3ba3622d441301fcfbf6 | 3,632,815 |
import scipy.linalg as LA
import re
def ma_rhythm(ppath, recordings, ma_thr=20.0, min_dur = 160, band=[10,15],
state=3, win=64, pplot=True, pflipx=True, pnorm=False):
"""
calculate powerspectrum of EEG spectrogram to identify oscillations in sleep activity within different frequency bands;
o... | f5fee2d602f5f186f0aaa881938a396ab5c9d977 | 3,632,816 |
from typing import Dict
async def find_file_ids(paths: Dict[str, int]) -> Dict[str, str]:
"""Parameter 1: dict of "file path" -> file size."""
fpaths = [p for p in paths.keys() if p]
if not fpaths:
return {}
query = "select path, size, file_id from file_ids where path in ({})".format(
... | c43567330b8a4ca7430dfbb337df518831c92a6f | 3,632,817 |
def select_curve(message='Select one curve.'):
"""Select one curve in the Rhino view.
Parameters
----------
message : str, optional
Instruction for the user.
Returns
-------
System.Guid
The identifer of the selected curve.
"""
return rs.GetObject(message, preselect... | 65952f2f2ea76c196ec55db4766de0d07cfe1b5b | 3,632,818 |
def fetch_cert(url: str) -> Certificate:
"""
Fetch a certificate from a URL.
:param url: the URL to the certificate file
:return: a certificate object
"""
with fetch_file(url) as cert_file:
return ssl_serializer.deserialize_cert(cert_file.read()) | 3a18eca6e5c8e51ad3ca96860972ead48b74c029 | 3,632,819 |
def import_execute(request, extra_context={}):
"""
This is the view that actually processed the import based on the options
set by the user in import_options (above).
In addition to calling the appropriate import function (see below) this
view also prepares the status information dictionary that will be used
by... | 0850d79c1d7f23b848e2e52cf7322485122f0e98 | 3,632,820 |
def get_default_view(source_type, source_name, menu_name=None,
source_transform=None, viewer_transform=None, **kwargs):
""" Create default view metadata for a single source.
Arguments:
source_type [str] - type of the source, either "image" or "segmentation"
source_name [str... | 056eb43104acea60c51a84da06aee036a1127c46 | 3,632,821 |
def PullToBrepFace(curve, face, tolerance, multiple=False):
"""
Pull a curve to a BrepFace using closest point projection.
Args:
curve (Curve): Curve to pull.
face (BrepFace): Brep face that pulls.
tolerance (double): Tolerance to use for pulling.
Returns:
Curve[]: An a... | ac8ac6e5de10b7012c4650915fd5af1de52659f4 | 3,632,822 |
def floatX(X):
""" Change data to theano type """
return np.asarray(X, dtype=theano.config.floatX) | ee2e8863fcdc5475cef461b75c557f1e96a73457 | 3,632,823 |
def primes_sieve3(n):
""" Sieve method 3: Returns a list of primes < n
>>> primes_sieve3(100)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
"""
# begin half-sieve, n>>1 == n//2
sieve = [True] * (n>>1)
upper = int(n**0.5)+1
fo... | 629942c738eb08624672e20af1923cf78d3dcec7 | 3,632,824 |
import os
def __detect_app_dir(name):
"""
如果app目录不存在,报错
:param name:
:return:
"""
app_dir = services.detect_app_dir(name)
if not os.path.exists(app_dir):
raise ServiceException("无法找到应用根目录")
return app_dir | be7549cbd57a254bb27d6c5ceda226400b1a7a32 | 3,632,825 |
def kl_mvg_diag(
pm: jnp.ndarray, pv: jnp.ndarray, qm: jnp.ndarray, qv: jnp.ndarray
) -> jnp.ndarray:
"""
Kullback-Leibler divergence from Gaussian pm,pv to Gaussian qm,qv.
Also computes KL divergence from a single Gaussian pm,pv to a set
of Gaussians qm,qv.
Diagonal covariances are assumed. Di... | c0f28495a2b8c18b8563d66152dc62019b3f2e60 | 3,632,826 |
from typing import Any
def isstring(var:Any, raise_error:bool=False) -> bool:
"""Check if var is a string
Args:
var (str): variable to check
raise_error (bool, optional): TypeError raised if set to `True`. Defaults to `False`.
Raises:
TypeError: raised if var is not string
R... | 897c43539099c3d0b9b38abccce88869a90b9d9e | 3,632,827 |
def run_simulation(solution, times, conditions=None,
condition_type = 'adiabatic-constant-volume',
output_species = True,
output_reactions = True,
output_directional_reactions = False,
output_rop_roc = False,
... | 352516d021b17589d60de5645076c25258df5e9c | 3,632,828 |
def first_second_person_density(doc):
"""Compute density of first|second person.
:param doc: Processed text
:type doc: Spacy Doc
:return: Density 1,2 person
:rtype: float
"""
return first_second_person_count(doc) / word_count(doc) | 29fa561361e1d3b4846accf206103fd3a99d774f | 3,632,829 |
def create_map(*columns):
"""
Creates a new map column. The input columns must be grouped as key-value pairs, e.g.
(key1, value1, key2, value2, ...). The key columns must all have the same data type, and can't
be null. The value columns must all have the same data type.
"""
return _with_expr(exp... | 40d09e0f5c16c935d741ef0c5cff2a07f62fbaa9 | 3,632,830 |
import six
import logging
def for_review_request_field(context, nodelist, review_request_details,
fieldset):
"""Loops through all fields in a fieldset.
This can take a fieldset instance or a fieldset ID.
"""
s = []
request = context.get('request')
if isinstance(... | 592092f0c6909b18fb92309c72ced4d8c0ee8d7b | 3,632,831 |
import warnings
def bayesian_optimization(f, gpr, acq_func, bounds, max_iter = None,
prop_kwargs = None, minimize = None,
verbose = False, noise=0.0):
"""
Implement Bayesian optimization to maximize or minimize a scalar function.
Arguments
-----... | 6f1eab7d21c6385532151656a9b9a80e78b78fa0 | 3,632,832 |
def to_nearest(num, tick_size):
"""
Given a number, round it to the nearest tick. Very useful for sussing float error
out of numbers: e.g. toNearest(401.46, 0.01) -> 401.46, whereas processing is
normally with floats would give you 401.46000000000004.
Use this after adding/subtracting/multiplying nu... | 662a4e0cb2956161f5b776bc65cb6c35e32aaf32 | 3,632,833 |
from typing import List
def create_epub(raw_articles: List[Article], title: str) -> str:
"""
Create an EPUB book from multiple articles.
:returns temp path to created ebook
"""
epub_path = mkdtemp()
logger.debug(f"Creating epub folder in {epub_path}")
articles = [EPUBArticle(raw_article,... | 4befa8bb1a0b1d2d6efc3be4abc42e7dccb774dc | 3,632,834 |
def placeholder(value, token):
""" Add placeholder attribute, esp. for form inputs and textareas """
value.field.widget.attrs["placeholder"] = token
return value | 16bb46a6e92c3a59972589ed28315e681a7580f3 | 3,632,835 |
def create_xml_element(connection, token, name):
"""A helper function creating an etree.Element with the necessary
attributes
:param name: The name of the element
:returns: etree.Element
"""
return etree.Element(
name,
nsmap={None: XHTML_NAMESPACE},
shop_id=connection.s... | 00427ffa2ce582674d78cf6597624c0bbe29edfc | 3,632,836 |
from typing import Optional
def generate_categorical_dataframe(
sm: nx.DiGraph,
n_samples: int,
distribution: str = "logit",
n_categories: int = 3,
noise_scale: float = 1.0,
intercept: bool = False,
seed: int = None,
kernel: Optional[Kernel] = None,
) -> pd.DataFrame:
"""
Gener... | 5cd72c10e6fdede53b2051eef2bdac82045ed7af | 3,632,837 |
def bias_cross_func(data, *args, **kwargs):
"""
生成一条年利率 4% 的模拟货币基金基准线
支持QA add_func,第二个参数 默认为 indices= 为已经计算指标
理论上这个函数只计算单一标的,不要尝试传递复杂标的,indices会尝试拆分。
"""
if (ST.VERBOSE in data.columns):
print('Phase bias_cross_func', QA_util_timestamp_to_str())
# 针对多标的,拆分 indices 数据再自动合并
code ... | 7b89c7ab3be1c6d2079dd9cbbf1f0dde8044b042 | 3,632,838 |
from typing import Optional
def login(uid: str, pwd: str) -> Optional[Admin]:
"""
登录
:return:
"""
sql = '''SELECT admins.id, admins.uid, admins.is_super FROM admins WHERE uid=%s AND pwd=%s LIMIT 1'''
connect = get_connect()
with connect.cursor() as cursor:
cursor.execute(sql, (uid... | 1c207ab29b6d793c7ac513cf901d5c9588c566d4 | 3,632,839 |
import aiohttp
async def catch_uniqueness_error(
request: aiohttp.web.Request, handler: swift_browser_ui.common.types.AiohttpHandler
) -> aiohttp.web.Response:
"""Catch excepetion arising from a non-unique primary key."""
try:
return await handler(request)
except asyncpg.exceptions.UniqueViola... | 177faf3497fa8d048b6fc1c1dc8058ed78785cf4 | 3,632,840 |
def df_canonicalize_from_smiles(df, smiles_col: str, include_stereocenters=True)->pd.Series:
"""
Canonicalize the SMILES strings with RDKit.
Args:
df: dataframe
smiles_col: column name in df
include_stereocenters: whether to keep the stereochemical information in the canonical SMILES... | 846c01b71201411ed36d5270b83f8f32d832e9f4 | 3,632,841 |
from re import T
def mse_loss(y, pred, w):
""" Regression loss function, mean squared error. """
return T.mean(w * (y - pred) ** 2) | bb6f127fd69dcbaa1e64dd811caa0b356de9f741 | 3,632,842 |
def compute_gradients(
state,
supermatrices,
supergradients,
super_oplabels,
observables,
observables_labels,
num_discretes,
):
"""
Compute the gradients of a symplectic acyclic_graph for the cost function
<psi|sum_n H_n |psi>, with H_n the element at `observables[n]`, acting on
... | 378cbc6ee3e147ca67d62edbb1929459dfb2993a | 3,632,843 |
import os
import subprocess
def running_from_pacman():
""" Return True if the parent process is pacman """
debug = InformantConfig().get_argv_debug()
ppid = os.getppid()
p_name = subprocess.check_output(['ps', '-p', str(ppid), '-o', 'comm='])
p_name = p_name.decode().rstrip()
if debug:
... | e85707aaf5e0596df74b4ec055e6100d78eee64e | 3,632,844 |
def _cs_count_top_bottom(fragments):
"""Counting: top and bottom of the entire core sample"""
cs_top, cs_bottom = 1e10, 0
for fragment in fragments:
cs_top = min(cs_top, float(fragment['top']))
cs_bottom = max(cs_bottom, float(fragment['bottom']))
return cs_top, cs_bottom | 3b9a98993a837ff7c08980f644abbb6aad13f908 | 3,632,845 |
def get_index_from_filename(
file_name: str
) -> str:
"""
Returns the index of chart from a reproducible JSON filename.
:param file_name: `str`
The name of the file without parent path.
:returns: `str`
The index of the chart (e.g., 1) or an empty string.
"""
assembled_ind... | 2cddcbcd9bf5079d58c75f19b5d2bf5b44ded173 | 3,632,846 |
def get_box_transformation_matrix(box):
"""
Create a transformation matrix for a given box pose.
"""
# tx,ty,tz = box.center_x,box.center_y,box.center_z
tx,ty,tz = box[0], box[1], box[2]
c = np.cos(box[6])
s = np.sin(box[6])
sl, sw, sh = box[3], box[4], box[5] # 这里如果读取的是 det3d 的 det... | dae86d3260d0463d8e974c4fdba055781b520c93 | 3,632,847 |
def get_redirect_target():
"""
获取跳转目标
:return:
"""
for target in request.args.get('next'), request.referrer:
if not target:
continue
if is_safe_url(target):
return target | 2ff373be5ad9d44124304454a5f89dd7d1f7d939 | 3,632,848 |
def mixer_carrier_cancellation(SH, source, MC,
chI_par, chQ_par,
frequency: float=None,
SH_ref_level: float=-40,
init_stepsize: float=0.1,
x0=(0.0, 0.0),
... | 792f998cf2382d889ecfc2e6335c55a805d234df | 3,632,849 |
def create_single_wall_box(box_dimensions):
"""
width, depth, height, thickness,
fold_margin, wing_width
returns ShapeArray
"""
width = box_dimensions['width']
height = box_dimensions['height']
depth = box_dimensions['depth']
thickness = box_dimensions['thickness']
fold_margin ... | d7ee5700cebd083bf6800d636563d08fb1e645d3 | 3,632,850 |
from typing import Optional
def correct_start_cell_number(
start_cell_number: Optional[int], mcnp: Optional[str]
) -> int:
"""Define cell number to start with on output to accompanying excel.
Args:
start_cell_number: number from command line or configuration, optional.
mcnp: MCNP file nam... | c5fa474970be0f4f23c02ef6dead6f5028c3fc88 | 3,632,851 |
from typing import List
def convert_labels_to_one_hot(
label_list: List[List[str]], label_dict: Dictionary
) -> List[List[int]]:
"""
Convert list of labels (strings) to a one hot list.
:param label_list: list of labels
:param label_dict: label dictionary
:return: converted label list
"... | 856ae66a591ec7c32bbd5cf91e97ff87852f5b83 | 3,632,852 |
def create(container_dir, distro_config):
"""Create a container using chocolatey."""
return _fetch_choco(container_dir, distro_config) | e342101c8723b62e79b7f455e5444f2e214d9621 | 3,632,853 |
def notas(*num, sit=False):
"""
Essa função cria um dicionário que guarda várias informações sobre o boletim de um aluno
:param num: lista de notas do aluno
:param sit: situação do aluno (aprovado, reprovado, recuperação)
:return: retorna o dicionário completo
"""
boletim = {}
boletim['Q... | a154d39be15018ce764e71c7bc97d9b4b25575df | 3,632,854 |
from operator import concat
def columnize(student: 'StudentResult',
longest_user: str,
max_hwk_num: int,
max_lab_num: int,
max_wst_num: int,
highlight_partials: bool = True):
"""Build the data for each row of the information table"""
name =... | 5d4d2c20713883e6380d16b1e55ea72487b4e2d5 | 3,632,855 |
from typing import Iterable
from typing import Callable
from typing import Iterator
from typing import Tuple
def relate_one_to_many(
lhs: Iterable[Left],
rhs: Iterable[Right],
lhs_key: Callable[[Left], Key]=DEFAULT_KEY,
rhs_key: Callable[[Right], Key]=DEFAULT_KEY,
) -> Iterator[Tuple[Left, Iterator[Ri... | d49906eb86f645093b2b75f3a84f5a9f8faaba8d | 3,632,856 |
def cut(vid, bx, by):
"""Scales image without changing aspect ratio but instead growing to at least the size of box bx/by."""
ix = vid.get(cv.CAP_PROP_FRAME_WIDTH)
iy = vid.get(cv.CAP_PROP_FRAME_HEIGHT)
if bx / float(ix) > by / float(iy): # fit to width
scale_factor = bx / float(ix)
... | 7e66f170b54bc421389609efd9ce88f3b8c05b41 | 3,632,857 |
def _conserve_heat(m, t):
"""
TODO
"""
sources = m.NuCap
sinks = -(m.Turbine[t] / ECONV_RATE) + m.NPP_unused[t]
battery = 0
for tes in HEAT_TECHS:
charge = getattr(m, f'{tes}_charge')[t]
discharge = getattr(m, f'{tes}_discharge')[t]
battery += (charge + discharge)
... | cd3ae71678c5342404cd08c8ed7715ecd091347e | 3,632,858 |
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
def files_to_daisy_chain(ifg_names, figures = True):
"""
Given a list of interfergram names (masterDate_slaveDate), it:
- finds all the acquisition dates
- forms a list of names of the simplest daisy chain of inte... | 0c21bfc09fb93979715daaf8407ea9ed083cbad9 | 3,632,859 |
def find_region_candidates_volume(volume, peak_threshold, shifts = (0, 0)):
"""
:param volume:
:param peak_threshold:
:param shifts: (x, y)
:return:
"""
results = list()
for i in range(volume.shape[-1]):
slice = volume[..., i].copy()
cv2.GaussianBlur(slice, (3, 3), 0.4, ... | c0f61a6907bb1eb326daafc22274d90f281b5255 | 3,632,860 |
def summarize(text):
""" Summarizes some text
"""
if len(text) > 20:
summary = text[0:10] + " ... " + text[-10:]
else:
summary = text
summary = summary.replace("\n", "\\n")
return summary | 5c37f7a50e2b533bf3e05b598ce68b2c4de88fe1 | 3,632,861 |
from datetime import datetime
def create_nic(fco_api, cluster_uuid, net_type, net_uuid, vdc_uuid, name=None):
"""
Create NIC.
:param fco_api: FCO API object
:param cluster_uuid: Cluster UUID
:param net_type: Network type; currently recommended 'IP'
:param net_uuid: Network UUID
:param vdc... | 4709f215662bed8a1c76920ca0d5d49e501a50a6 | 3,632,862 |
def clean_logger(name = settings["app_name"]):
"""
Removes all handlers associated with a given logger
Parameters
----------
name : string
name of the logger
Returns
-------
logger.logger
"""
logger = lg.getLogger(name)
handlers = logger.handlers
for handler i... | fee9743c57ef054a9dbbd53bf8ab0dcd1d2801bd | 3,632,863 |
def model_from_json(json_string, custom_objects=None):
"""Parses a JSON model configuration string and returns a model instance.
Usage:
>>> model = tf.keras.Sequential([
... tf.keras.layers.Dense(5, input_shape=(3,)),
... tf.keras.layers.Softmax()])
>>> config = model.to_json()
>>> loaded_model ... | 3e929b5f2c07cb214edea5ed042fe0e49f0971ad | 3,632,864 |
def get_stock_stream(symbol, params={}):
""" gets stream of messages for given symbol
copied from api.py (found on GitHub)
"""
all_params = ST_BASE_PARAMS.copy()
return R.get_json(ST_BASE_URL + 'streams/symbol/{}.json'.format(symbol), params=all_params) | f6b5aa3601473eba52f3a736b4befa5ae1163be7 | 3,632,865 |
def get_free_swap_memory() -> int:
"""Get the free swap memory size in bytes."""
return swap_memory().free | 141313acb49baff1a25d837daec73048b9accd53 | 3,632,866 |
def get_application(application_id: str = None):
"""
Returns an application.
:param application_id: The numeric ID of the application you're interested in.
:returns: String containing xml or an lxml element.
"""
return get_anonymous('getApplication', application_id=application_id) | 53142b0ac238876f52e26e00f3af190643443671 | 3,632,867 |
def sexastr2deci(sexa_str):
"""Converts as sexagesimal string to decimal
Converts a given sexagesimal string to its decimal value
Args:
A string encoding of a sexagesimal value, with the various
components separated by colons
Returns:
A decimal value corresponding to the sexagesimal... | 46a9d8752b05b1579ecc2b85d94c28613a08ab3c | 3,632,868 |
def run_extractor_on_dataset(dataset_path):
"""Run the feature extractor pipeline on the target dataset then consolidate results.
Note: This function runs on all images within SUB DIRECTORIES of the dataset path.
Output will be a single features JSON for each frame ID. All emitted individual image
fea... | 79b816110cca7bf5ecf258f8380bbf285f0b9018 | 3,632,869 |
from typing import Callable
from typing import Mapping
def run_pipeline_func_on_cluster(
pipeline_func: Callable,
arguments: Mapping[str, str],
run_name: str = None,
experiment_name: str = None,
kfp_client: Client = None,
pipeline_conf: dsl.PipelineConf = None,
):
"""Runs pipeline on KFP-e... | c44069b016706f5cdcbab1fd9319cf96ef4f2dfa | 3,632,870 |
import os
import hashlib
def find_duplicates(dirname, extension):
"""Write a program that searches a directory and all of its subdirectories, recursively, and returns
a list of complete paths for all files with a given suffix (like .mp3)."""
possible_duplicates = dict()
for file in filter_files_with_exte... | 07e44327681975fbf95a7b011d5908a5ce706121 | 3,632,871 |
def reverb2mix_transcript_parse(path):
"""
Parse the file format of the MLF files that
contains the transcripts in the REVERB challenge
dataset
"""
utterances = {}
with open(path, "r") as f:
everything = f.read()
all_utt = everything.split("\n.\n")
for i, utt in enumerate... | c8a1aa0c8a4d0dec6626cf8e9d2491336ee42d5a | 3,632,872 |
def extract_qa_bits(qa_band, start_bit, end_bit):
"""Extracts the QA bitmask values for a specified bitmask (starting
and ending bit).
Parameters
----------
qa_band : numpy array
Array containing the raw QA values (base-2) for all bitmasks.
start_bit : int
First bit in the bit... | 523dc1ee149af5c5e9a494b5fe3a3c14bc3186d2 | 3,632,873 |
def is_scalar(v,value=None):
"""Returns True if v evaluates to a scalar. If value is provided, then
returns True only if v evaluates to be equal to value"""
if isinstance(v,Variable):
if not v.type.is_scalar(): return False
return value is None or v.value == value
elif isinstance(v,Cons... | 831d539c634d812b42a1c9716aab994145bf8cd2 | 3,632,874 |
def cluster_homogeneity(df:pd.DataFrame, edge_type="Edge", iteration_type="Iteration"):
"""
# Create Graph
from soothsayer_utils import get_iris_data
df_adj = get_iris_data(["X"]).iloc[:5].T.corr() + np.random.RandomState(0).normal(size=(5,5))
graph = nx.from_pandas_adjacency(df_adj)
graph.nodes... | e077ff0f3e1660ea5788880282fbc3862b5737df | 3,632,875 |
import json
def to_json_for_storage(desc: SomeRunDescriber) -> str:
"""
Serialize the given RunDescriber to JSON as a RunDescriber of the
version for storage
"""
return json.dumps(to_dict_for_storage(desc)) | cdda5322acf1da6e704bdea47cd1cee9019019ad | 3,632,876 |
def astar(graph, start, end, heuristic={}):
"""
Performs A-star search to find the shortest path from start to end
Args:
graph (gennav.utils.graph): Dictionary representing the graph where keys are the nodes
and the value is a list of all neighbouring nodes
start (gennav.utils.R... | 90c60cc7b14e7d223889316a49223450fa4806f4 | 3,632,877 |
def extractFileName(form, id, cleanup=True, allowEmptyPostfix=False):
"""Extract the filename of the widget with the given id.
Uploads from win/IE need some cleanup because the filename includes also
the path. The option ``cleanup=True`` will do this for you. The option
``allowEmptyPostfix`` allows to ... | 8aeccba3be2f4a4de781efaff88bf1835645c293 | 3,632,878 |
def find_pointing_start(asn_table_name):
"""
Parameters:
asn_table_name : string
For example, 'gs2-01-189-g102'. Targname-visit-PA-filter
Returns:
0 : if visit starts with direct image
1 : if visit starts with grism
Outputs:
"""
# Parse out the asn tab... | ee700ddc8903914956c42ec82763a2463186e38b | 3,632,879 |
def data_logs(recipe_id=None):
""" Flask controller: show logs for a recipe
"""
level = flask.request.args.get('level', 'WARNING').upper()
recipe = recipes.Recipe(recipe_id)
return flask.render_template("data-logs.html", recipe=recipe, level=level, in_logger=True) | fc0bd90c04449eb2e0748e87490fb35eff991975 | 3,632,880 |
def slice_metadata_using_already_sliced_data_df(data_df, row_meta_df, col_meta_df):
"""Slice row_meta_df and col_meta_df to only contain the row_ids and col_ids
in data_df.
Args:
data_df (pandas df)
row_meta_df (pandas df)
col_meta_df (pandas df)
Returns:
out_gct (GCToo... | 423ed7a9d50f5d831dc3eff58bcab120dd30d22e | 3,632,881 |
def create_user(request, template_name='create_user.html',
redirect_field_name=REDIRECT_FIELD_NAME,
user_creation_form=UserCreationForm,
current_app=None, extra_context=None):
"""
Displays the login form and handles the login action.
"""
# noinspection PyU... | 1b551723d9dfcc3db407f5c10fb680d664e43ca2 | 3,632,882 |
def found_table(schema:str, table_name:str) -> bool:
"""Returns whether the given table is found in the list of cached tables"""
return len(
[
table for table in tables
if table.table_name == table_name and table.schema == schema
]
) == 1 | eac5a1dbe43f07ca664ab6f0aeb40a7952f80823 | 3,632,883 |
import wget
def download_url(url, pth_download=None, speak=False):
"""Download data from URL."""
if wget is None:
raise ImportError('wget not available')
bar = None
if speak:
def bar(current, total, width=80):
print("Downloading %s to %s | Progress: %d%% (%d/%d bytes)"
... | 715da8fecd5fe1442024acf8150314b5c2e64f99 | 3,632,884 |
def openurl(url):
"""Retries urlopen.
:param url: url to open
"""
return urlopen(url) | eae62fa336ac0eab462354a805c61ca0834ef3c4 | 3,632,885 |
from datetime import datetime
from typing import Tuple
def portfolio_return(holdings: float,
asset_percent: float,
bond_percent: float,
asset_etfs: pd.DataFrame,
bond_etfs: pd.DataFrame,
start_date: datetime,
... | dbf78f636e4f5f3a57baf15e94b8937582e63fcd | 3,632,886 |
def rewofzt2(x,y):
"""Real part of asymptotic representation of wofz function 1 for |z|**2 > 111 (for e = 10e-6)
See Zaghloul (2018) arxiv:1806.01656
Args:
x:
y:
Returns:
f: Real(wofz(x+iy))
"""
z=x+y*(1j)
q=(1j)*z/(jnp.sqrt(jnp.pi))*(z*z - 2.5)/(z*z*... | 3b820a6be8b4cccc220e8616a5f0b7807a4295de | 3,632,887 |
import struct
def _macos_bundle_impl(ctx):
"""Implementation of the macos_bundle rule."""
additional_resource_sets = []
additional_resources = depset(ctx.files.app_icons)
if additional_resources:
additional_resource_sets.append(AppleResourceSet(
resources=additional_resources,
))
# TODO(b/3... | db90378ffece90caf08666f35892a78b970e1003 | 3,632,888 |
import logging
def combine_ecgs_and_clinical_parameters(ecgs, clinical_parameters):
"""
Combines ECGs and their corresponding clinical parameters
:param ecgs: List of ECGs
:param clinical_parameters: Corresponding clinical parameters
:return: Medical data for each patient including ECGs and th... | 91ca17f62ff36776980a74ecd5334ae9a55ade18 | 3,632,889 |
def is_territory_group(group: inkex.ShapeElement) -> bool:
"""
Checks if element is a territory group. It is a territory group if it is a non-layer Group
and has two children, one of which is a territory, the other of which is a center point
group.
:param group:
:return:
"""
valid = isin... | 5fcb8ef53e915f6040e9d661076e7fa2867c2620 | 3,632,890 |
def filter_tracks(tracks, size_th, mask_file):
"""Filter tracks that doesn't fulfill requirement"""
print('filtering tracks...')
del_idx = []
for i,t in enumerate(tracks):
dets = t.dump()
if not np.any(filter_detections(dets, size_th, mask_file)):
del_idx.append(i)
prin... | 767bd8cdef8a9a949b89e969b9c106d48c9a0fae | 3,632,891 |
def disable_chat_bot_callback(message):
"""
Disable chat bot callback.
:param message: The message.
:return: The return from the function.
"""
return disable_chat_bot(message.guild.name) | c98d2fba6e91158df614a43b56b798947a88771e | 3,632,892 |
import nibabel as nib
import os
def write_anat(t1w, bids_path, raw=None, trans=None, landmarks=None,
deface=False, overwrite=False, verbose=False):
"""Put anatomical MRI data into a BIDS format.
Given a BIDS directory and a T1 weighted MRI scan for a certain subject,
format the MRI scan to... | 985ac12171dc0681cbbf9b3d8587f164d4ba8fdb | 3,632,893 |
def new_post(request):
"""The new post publication"""
form = PostForm(request.POST or None, files=request.FILES or None)
if form.is_valid():
form.instance.author = request.user
form.save()
return redirect('/')
return render(request, 'new.html', {'form': form}) | 31dab55dbbe450ff46a2a111ed9996ef6fbba2ae | 3,632,894 |
import numpy as np
def get_fake_prediction(anchors, coords, config):
"""
Generates the anchor labels with random noise to fake a good prediction.
Used for testing non-model related code.
anchors
The list of anchor coordinates generated from get_anchors().
coords
The list of ground... | e05f9746c4c6255401b02975c7a76e7b0c25a4e7 | 3,632,895 |
import requests
def service(schema):
"""Service fixture"""
assert schema.namespaces # this is pythonic way how to check > 0
return pyodata.v2.service.Service(URL_ROOT, schema, requests) | 8b48865b57487493fdf829dad62551d76b40536d | 3,632,896 |
def register_handlers(cls, nsmap, events, stanzas):
"""Register all special handlers in a plugin."""
## Sanity check
st_handlers = set(m for (_, (_, m)) in stanzas)
for (_, callbacks) in events:
dup = st_handlers.intersection(set(callbacks))
if dup:
raise PluginError('Stanza... | c8a5b6c69632cf5c6671b84055d1457a89d31f86 | 3,632,897 |
def get_question_types(container):
""" SELECTOR FOR RETURNING QUESTION TYPES """
return container.keys() | 0c667e893323c106319038d19f333d233a5d1e07 | 3,632,898 |
import requests
import urllib3
def uploader(dict_in):
"""Post the global dictionary to the server
This function contains a post request to the flask server. The global
dictionary in the patient GUI that saved all the information to be upload
will be posted. This function will also catch the exception... | a454bb7e0523e48d851efb2a46d877aea12dd38e | 3,632,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.