content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def read_artist_albums(id, name):
"""get lists of albums for artist
"""
list_a = [(x.name, str(x.release_year), str(x.id))
for x in dmla.list_albums_by_artist('', id, 'Jaar')]
list_c = [(x['album'], x['year']) for x in dmlc.list_albums(DB_C, name)]
return list_a, list_c | 5,312,800 |
def main(argv, **kwargs):
"""
Parses command line arguments and invokes the appropriate method to respond to them
Returns
-------
None
"""
# TODO - Update this when working HARMONY-639
# DO NOT REMOVE THE FOLLOWING LINE - NEEDED AS WORKAROUND TO ARGO CHAINING ISSUE
print('MAIN START... | 5,312,801 |
def client_add(request):
""" Add new client and see the list of clients """
success_message, error_message = None, None
form = ClientForm
clients = Client.objects.all()
enquiry_form = EnquiryClientForm
enquiry_clients = EnquiryClient.objects.all()
if request.metho... | 5,312,802 |
def mult(A, B):
"""
Function to multiply two values A and B, use as "mult(A, B)"
"""
return A * B | 5,312,803 |
def remove_stopwords(sentence):
"""
Transforms a given text to its lemmatized form. Assumes clean text separated by spaces.
:param sentence: the text to be lemmatized
:type: string
:return: lemmatized text
:type: string
"""
return ' '.join([w for w in word_tokenize(sentence) if not w in ... | 5,312,804 |
def email_notification(version, build, email):
"""
Send email notifications for build failure.
:param version: :py:class:`Version` instance that failed
:param build: :py:class:`Build` instance that failed
:param email: Email recipient address
"""
log.debug(
LOG_TEMPLATE,
{
... | 5,312,805 |
def make_modular_alerts(ta_name, ta_namespace, schema_content, outputdir):
"""
Generate the alert schema with required structure.
Args:
ta_name (str): Name of TA.
ta_namespace (str): restRoot of TA.
schema_content (dict): JSON schema of globalConfig.json.
outputdir (str): ou... | 5,312,806 |
def fileparse(*args):
"""Split a path into basename, dirpath, and (optional) suffixes.
Translated from perl File::Basename for unix, plus annotations"""
fullname = args[0]
suffixes = args[1:]
if fullname is None:
raise Die("fileparse(): need a valid pathname")
fullname = str(fulln... | 5,312,807 |
def e():
"""Group Question 4
### Create a New Question [POST]
You may create your own question using this action. It takes a JSON object containing a question and a collection of answers in the form of choices.
+ question (string) - The question
+ choices (array[string]) - A collection of choices.... | 5,312,808 |
def handle_commands(bot, ievent):
""" arguments: [<plugname>] - show commands of plugin. """
try: plugin = ievent.args[0].lower()
except IndexError: plugin = ""
result = []
cmnds = getcmndtable()
for cmnd, plugname in cmnds.iteritems():
if plugname:
if not plugin or plugin i... | 5,312,809 |
def check_grad_inputs(layer, x, grad_out):
"""
Args:
layer: Layer object
x: ndarray tensor input data
grad_out: ndarray tensor gradient from the next layer
"""
grad_x_num = eval_numerical_gradient(layer.forward, x, grad_out)
grad_x = layer.backward_inputs(grad_out)
print("Relat... | 5,312,810 |
def copy_item(src_item, dest):
""" Copies a file or a directory to dest. dest may be a directory.
If src_item is a directory then all containing files and dirs will be copied into dest. """
if os.path.isfile(src_item):
shutil.copy2(src_item, dest)
elif os.path.isdir(src_item):
copy_conte... | 5,312,811 |
def lfnToEOS( path ):
"""Converts LFN to EOS.
If path is not an LFN in the first place, return path.
??? shouldn't we raise an exception?"""
if isLFN(path):
pfn = 'root://eoscms.cern.ch//eos/cms/' + path
return pfn.replace('//store','/store')
else:
return path | 5,312,812 |
def get_link_href(result_object, link_relation):
"""
Given a result_object (returned by a previous API call), return
the link href for a link relation.
'result_object' a JSON object returned by a previous API call. May not
be None.
'link_relation' the link relation for which href is required.
... | 5,312,813 |
def scanr(
fun: Callable[[Any, Any], Any], acc: Any, trav: Sequence[Any]
) -> Sequence[Any]:
"""Implementation of scanr in Python3.
This is an implementation of the right-handed
scan function from functional programming.
scanr takes the second argument and the last
item of the list and applies... | 5,312,814 |
def test_fill_na_with_str(dummy_df):
"""Fill NaN values with a specified string."""
actual = clean.fill_na_with_str(dummy_df, colname="recordlabel", fill_string="Missing")
expected = deepcopy(dummy_df)
expected["recordlabel"] = "Missing"
pd.testing.assert_frame_equal(actual, expected) | 5,312,815 |
def insertion_sort():
"""
Sort PositionalList of comparable elements into nondecreasing order.
Args:
L (PositionalList): PositionalList object whose elements are comparable
in a way that makes them sortable with comparison/identity operators.
"""
if len(L) > 1: # len() <= 1 is a... | 5,312,816 |
def _are_we_frozen():
"""Returns whether we are frozen via py2exe.
This will affect how we find out where we are located."""
return hasattr(sys, "frozen") | 5,312,817 |
def argtopk_aggregate(a_plus_idx, k, axis, keepdims):
""" Final aggregation function of argtopk
Invoke argtopk one final time, sort the results internally, drop the data
and return the index only.
"""
assert keepdims is True
a, idx = argtopk(a_plus_idx, k, axis, keepdims)
axis = axis[0]
... | 5,312,818 |
async def test_apply_service(hass):
"""Test the apply service."""
assert await async_setup_component(hass, "scene", {})
assert await async_setup_component(hass, "light", {"light": {"platform": "demo"}})
assert await hass.services.async_call(
"scene", "apply", {"entities": {"light.bed_light": "o... | 5,312,819 |
def eht():
"""Make an empty bst size of 10."""
return HashTable(10) | 5,312,820 |
def rx_filter(objs: list, attr: str, prompt: str) -> list:
"""
Filter a list of dicts based on user-entered regex match to one of their values.
"""
while True:
search_term = input(prompt+" ")
# Prefer exact match first -- otherwise can never select an item that's a substring of anothe... | 5,312,821 |
def _get_morphotactics_rules(morphotactics_dir: str) -> _RewriteRuleSet:
"""Parses morphotactics model into valid rewrite rules.
Args:
morphotactics_dir: path to the directory that contains the text files that
define rules of morphotactics FST. All files that have the ".txt" file
extension unde... | 5,312,822 |
def _get_usb_hub_map(device_info_list):
"""Creates a map of usb hub addresses to device_infos by port.
Args:
device_info_list (list): list of known usb_connections dicts.
Returns:
dict: map of usb hub addresses to device_infos by port
"""
map_usb_hub_ports = {}
for device_info in device_info_li... | 5,312,823 |
def gaussian_smoothing(eem_df, sigma, truncate):
"""Performs gaussian smooothing on the excitation-emission matrix from the input
sigma and truncation sigma.
Args:
eem_df (pandas.DataFrame): An excitation-emission matrix.
sig (int): Sigma of the gaussian distribution weight for the data smo... | 5,312,824 |
def get_current_commit(srcdir):
"""Return information about git commit checked out in the given directory.
:param srcdir: source code directory
:type srcdir: str
:return: commit information composed of brief SHA1 and subject
:rtype: str
"""
os.chdir(srcdir)
return (
subprocess.... | 5,312,825 |
def parse_pgsql_logs(data):
"""
Parse the pgsql benchmark data from ripsaw and return
the data in list format
Args:
data (str): log data from pgsql bench run
Returns:
list_data (list): data digestable by scripts with below format
e.g.:
[
... | 5,312,826 |
def send_html_mail(subject, message, message_html, from_email, recipient_list, priority="medium", fail_silently=False,
auth_user=None, auth_password=None, headers={}, attachments=None):
"""
Function to queue HTML e-mails
"""
from django.utils.encoding import force_text
from djang... | 5,312,827 |
def compute_tDCF(bonafide_score_cm, spoof_score_cm, Pfa_asv, Pmiss_asv, Pmiss_spoof_asv, cost_model, print_cost):
"""
Compute Tandem Detection Cost Function (t-DCF) [1] for a fixed ASV system.
In brief, t-DCF returns a detection cost of a cascaded system of this form,
Speech waveform -> [CM] -> [ASV]... | 5,312,828 |
def jd2gdate(myjd):
"""Julian date to Gregorian calendar date and time of day.
The input and output are for the proleptic Gregorian calendar.
Parameters
----------
myjd:
julian date (float).
Returns
-------
y, m, d, f : int, int, int, float
Four element tuple containing... | 5,312,829 |
def donation_journal_history_for_a_voter(voter_we_vote_id):
"""
:param voter_we_vote_id:
:return:
"""
donation_manager = DonationManager()
donation_journal_results = donation_manager.retrieve_donation_journal_list(voter_we_vote_id)
refund_days = get_environment_variable("STRIPE_REFUND_DAYS"... | 5,312,830 |
def imshow(
subplot,
data,
title=None,
sharex=None,
sharey=None,
vmin=-2.5,
vmax=0.0,
cmap=None,
interpolation='lanczos',
**kwargs,
):
"""Log-plot image using matplotlib.pyplot. Return plot axis and plot.
Mirror symmetry is applied along the x and y axes.
"""
fr... | 5,312,831 |
async def test_t6_project_shared_with_group_transferred_to_last_user_in_group_on_owner_removal(
simcore_services_ready, client, aiopg_engine, tests_data_dir: Path
):
"""
USER "u1" creates a GROUP "g1" and invites USERS "u2" and "u3";
USER "u1" creates a project and shares it with "g1";
USER "u1" is ... | 5,312,832 |
def task(ctx, config):
"""
Dump task context and config in teuthology log/output
The intended use case is didactic - to provide an easy way for newbies, who
are working on teuthology tasks for the first time, to find out what
is inside the ctx and config variables that are passed to each task.
... | 5,312,833 |
def sigmoid_1(x):
""" sigmoid at x """
return math.log(x / (1 - x)) | 5,312,834 |
def initialize_device_settings(use_cuda: bool,
local_rank: int=-1,
multi_gpu: bool=True) -> Tuple[List[str], int]:
"""
Returns a list of available devices.
:param use_cuda: Whether to make use of CUDA GPUs (if available).
:param local_rank: ... | 5,312,835 |
def get_action_td_zero(exploration_mode, current_state, Q, epsilon, temperature, exploration_degree, actions,
nextStates):
"""
choose action based on temporal difference learning
@param exploration_mode:
@param current_state:
@param Q:
@param epsilon:
@param temperatur... | 5,312,836 |
def get_policy_targets(context, presentation):
"""
Returns our target node templates and groups if we have them.
"""
node_templates = []
groups = []
our_targets = presentation.targets
if our_targets:
all_node_templates = \
context.presentation.get('service_template', 't... | 5,312,837 |
def main(junit_input_file, test_list, config_file):
"""Process multiple files created by tempest into a single accurate junit xml artifact"""
try:
click.echo(str(TempestZigZag.process_xml(junit_input_file, test_list, config_file)))
except(TempestXMLAccessError, Exception) as e:
click.echo(cl... | 5,312,838 |
def check_for_messages(folder, message_data, pst_name, folder_name):
"""
The check_for_messages function reads folder messages if
present and passes them to the report function
:param folder: pypff.Folder object
:param message_data: list to pass and extend with message info
:param pst_name: A st... | 5,312,839 |
def _serial() -> None:
"""A serial-interface project."""
_normal_setup('serial.py') | 5,312,840 |
def __get_host_ip():
"""
获取本地IP地址
:return:
"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip | 5,312,841 |
def uv_renew(u, s, v, X, gamma1, gamma2):
"""
This function will return the updated u, v and the corresponding lambdas.
Only for internal use for the SSVD function.
"""
n,d = X.shape
u = u.reshape((n,1))
v = v.reshape((d,1))
SSTO = np.sum(X**2)
## first, update v
#... | 5,312,842 |
def svn_get_externals(svn_url=None, revision=None, sandbox_dir=None,
debug=False, dry_run=False, verbose=False):
"""
Generate a list of tuples containing
(revision, external_url, subdirectory)
"""
try:
for line in svn_propget(svn_url, "svn:externals", revision=revision,... | 5,312,843 |
def merge_df(df1, df2):
""" Genera un dataframe seleccionant les columnes que ens
interessen dels dos dataframes, eliminant valors NA, i actualitza
les notes de '538 Grade' simplificant-les.
Keyword arguments:
df1 -- dataframe que conté les dades de les entrevistes.
df2 -- dataframe que conté l... | 5,312,844 |
def OpInfo_CONV(
conv_ps: conv.Conv2DParams, s_id: str, vin_id: str, vout_id: str
) -> OpInfo:
""" OpInfo for a CONV operation """
rd_a = (
"{{ {SID}[oh,ow] -> {VID}[id,ih,iw] "
": 0 <= oh < {OH} "
"and 0 <= ow < {OW} "
"and 0 <= id < {ID} "
"and oh <= i... | 5,312,845 |
def mean_period(data):
"""Return mean-period of signal."""
peaks = len(find_peaks(data, height=0)[0])
return len(data) / peaks if peaks > 0 else len(data) | 5,312,846 |
def rvsi_vi(imgData, wave, mask=0, bands=[-1,-1,-1]):
"""
Function that calculates the Red-edge Vegetation Stress Index.
This functions uses bands 714, 733, and 752 nm. The closest bands to these values will be used.
Citation: Merton, R. and Huntington, J. 1999. Early simulation results of the ARIES-1 ... | 5,312,847 |
def train(models, data, params):
"""Train the discriminator and adversarial Networks
Alternately train discriminator and adversarial networks by batch.
Discriminator is trained first with real and fake images,
corresponding one-hot labels and latent codes.
Adversarial is trained next with fake images pretending
t... | 5,312,848 |
def usb_pitop_peripherals():
"""Returns a list with the status of USB pi-top peripherals.
Returns:
list: list of dictionaries with the status of USB peripherals
"""
return [
{"name": "pi-top Touchscreen", "connected": touchscreen_is_connected()},
{"name": "pi-top Keyboard", "con... | 5,312,849 |
def isPD(B):
"""Check whether a matrix is positive definite.
Args:
B ([torch.Tensor]): [Input matrix.]
Returns:
[bool]: [Returns True if matrix is positive definite, otherwise False.]
"""
try:
_ = torch.cholesky(B)
return True
except RuntimeError:
return... | 5,312,850 |
def convert_TriMap_to_SelectedLEDs( best_led_config ):
""" Returns a lookup dict of the selected LEDs.
"""
d = {}
for tri_num in best_led_config:
for led_num in best_led_config[tri_num]:
d[led_num] = True
return d | 5,312,851 |
def get_stimulus_response(src_dir, src_dataset, stim_id, boundary=0,
if_get_stim=True):
"""Get stimulus-response data for all datasets.
Args :
src_dir : Location of all joint embedding datasets.
src_dataset : Dataset corresponding of a specific stimulus.
stim_id : string ID of... | 5,312,852 |
def parse_cli():
"""This function parses all the arguments, validates them and then stores them
in a dictionary that is used throughout the script."""
usage = \
'''%(prog)s [--debug] -u username -k pkey -c cert \\
(-H hostname | -F hostfile) [-a altnames] [-d write_directory]
%(pr... | 5,312,853 |
def get_by_id(id_estudiante, id_asignatura, edicion):
"""
Obtiene la tupla de la relación Estudiantes con el identificador
:param id_estudiante: El identificador del estudiante
:type id_estudiante: str
:param id_asignatura: El identificadir de la asignatura
:type id... | 5,312,854 |
def test2():
"""
测试DataLoader使用
"""
transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((227, 227)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
data_root_dir ... | 5,312,855 |
def test_two_element_sequences(seq, val, res):
"""Search a value in a sequence with two elements."""
assert isearch(seq, val) == res | 5,312,856 |
def keyword(tokens, expected):
"""Case-insensitive keyword match."""
try:
token = next(iter(tokens))
except StopIteration:
return
if token and token.name == "symbol" and token.value.lower() == expected:
return TokenMatch(None, token.value, (token,)) | 5,312,857 |
def milestone_container(request):
"""milestone container"""
template = loader.get_template('project_management/milestone_container.html')
context = {}
return HttpResponse(template.render(context, request)) | 5,312,858 |
def _run_symbolic_method(op_name, symbolic_fn, args):
"""
This trampoline function gets invoked for every symbolic method
call from C++.
"""
try:
return symbolic_fn(*args)
except TypeError as e:
# Handle the specific case where we didn't successfully dispatch
# to symboli... | 5,312,859 |
def load_input_source(input_source):
"""Load data from an arbitrary input source. Currently supported:
JSON, JSON-String, CSV, CSV-String. Returns an empty list if no data
is available."""
input_data = []
try:
input_data = load_json_from_file(input_source)
except ValueError as e:
pass
... | 5,312,860 |
def total_intensity(field):
"""Calculates total intensity of the field.
Computes intesity and sums over pixels."""
i = field2intensity(field)
return i.sum(tuple(range(i.ndim))[-2:]) | 5,312,861 |
def g_function_bernier(Fo, rba):
"""
Bernier (2001) approximation of Ingersol et al. (1954) G-function of
the cylindrical heat source problem.
Fo = Fourier number
rba = ratio of the radius where the temperature is calculated over the
external radius of the borehole.
Reference:
--... | 5,312,862 |
def clear_item_updates(api_key: str, item_id: str, *args, **kwargs):
"""Clear an item's updates.
Parameters
api_key : `str`
The monday.com v2 API user key.
item_id : `str`
The item's unique identifier.
args : `tuple`
... | 5,312,863 |
def doc_symbol(mod, usage, f):
"""generates documentation for the specified symbol. this is a
subroutine of doc_module"""
f.write('<div class="entry">')
f.write('<dl>')
modname = mod.get_modpath().name
global all_symbols
decls = [d for d in getPackageDecls(testagent, mod.filename)]
... | 5,312,864 |
def compute_aucs(pred, targ):
"""
Computes Area Under the Curve (AUC) from prediction scores.
Args:
targ: Pytorch tensor on GPU, shape = [n_samples, n_classes]
true binary labels.
pred: Pytorch tensor on GPU, shape = [n_samples, n_classes]
can either be probability estima... | 5,312,865 |
def test_parse_fasta_title_03():
"""It handles a 1 or 2 at the end of the title."""
seq_name, seq_end = blast.parse_fasta_title(
'title1/2 after', 'end_2', '2')
assert seq_name == 'title1'
assert seq_end == '2' | 5,312,866 |
def minhash(features):
# type: (List[int]) -> List[int]
"""
Calculate a 64 dimensional minhash integer vector.
:param List[int] features: List of integer features
:return: Minhash vector
:rtype: List[int]
"""
return [
min([(((a * f + b) & MAXI64) % MPRIME) & MAXH for f in featur... | 5,312,867 |
def get_gauss_beams(fwhm=7, nside=512, lmax=None):
"""the fwhm of 143GHz is 7.27,
test fwhm: 7, 6, 5, 4
"""
if lmax is None:
lmax = 3*nside + 50
bl = hp.gauss_beam(fwhm*np.pi/10800., lmax=lmax)
return bl | 5,312,868 |
def _job_monitor(job, status, watcher):
"""Monitor the status of a IBMQJob instance.
Args:
job (BaseJob): Job to monitor.
status (Enum): Job status.
watcher (JobWatcher): Job watcher instance
"""
thread = threading.Thread(target=_job_checker, args=(job, status, watcher))
thr... | 5,312,869 |
def create_long_model(model_specified, attention_window, max_pos):
"""Starting from the `roberta-base` (or similar) checkpoint, the following function converts it into an instance of `RobertaLong`.
It makes the following changes:
1)extend the position embeddings from `512` positions to `max_pos`. In Lo... | 5,312,870 |
def api_redirect():
"""Redirects the user to the API documentation page."""
return flask.redirect(flask.url_for("api_ns.api")) | 5,312,871 |
async def download_file_from_url(url: Text) -> Text:
"""Download a story file from a url and persists it into a temp file.
Returns the file path of the temp file that contains the
downloaded content."""
from rasa.nlu import utils as nlu_utils
if not nlu_utils.is_url(url):
raise InvalidURL(... | 5,312,872 |
def _decode_pem_private(lines, passphrase):
"""Decode a PEM format private key"""
pem_name, headers, data, end = _decode_pem(lines, b'PRIVATE KEY')
if pem_name == b'OPENSSH':
return _decode_openssh_private(data, passphrase), end
if headers.get(b'Proc-Type') == b'4,ENCRYPTED':
if passp... | 5,312,873 |
def kBtu_h2kW(x):
"""kBtu/h -> kW"""
return Btu_h2kW(kBtu_h2Btu_h(x)) | 5,312,874 |
def extract_translation_from_CK2_file(ck2_loc_file, extracted_translation, source_col_ck2, dest_col_ck2):
"""
Add {source_text: dest_text} to extracted_translation dict
:param ck2_loc_file: Path of the CK2 localisation file
:param extracted_translation: Dictionary which will be completed
:param sou... | 5,312,875 |
def plot_hist_centers(output, *args, **kwargs):
"""Plot 1-dimensinal output using pyplot.plot
executes pyplot.plot(x, y, *args, **kwargs) with first two arguments overridden
all other arguments are passed as is.
Options:
scale=float or 'width' - multiply bin by a scale or divide by bin width
... | 5,312,876 |
def schedule_exp(initial_value):
"""
Exponential decay learning rate schedule.
:param initial_value: (float or str)
:return: (function)
"""
def func(progress):
"""
Progress will decrease from 1 (beginning) to 0
:param progress: (float)
:return: (float)
"... | 5,312,877 |
def play_against_model(filename: Optional[str] = None,
delay: int = 0) -> None:
"""
Play an interactive game against a `Model`. The format to make a `Move`
is specified in `literature.commit_text`.
Parameters
----------
filename : Optional[str]
The location of the... | 5,312,878 |
async def test_401_refresh_failure(
aresponses, devices_list_json, event_loop, login_success_json
):
"""Test that multiple 401 responses in a row raises the right exception."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(te... | 5,312,879 |
def _relabel_darknet(arguments: Dict):
"""
Unpacks a dictionary of arguments and calls the function for replacing the
labels of a Darknet (YOLO) annotation file.
:param arguments: dictionary of function arguments, should include:
"file_path": path of the Darknet (YOLO) file to have labels rena... | 5,312,880 |
def home(request):
"""
main view that handles rendering home page
"""
all_images = UserPost.objects.all()
all_users = User.objects.exclude(id=request.user.id)
if request.method == 'POST':
form = UserPostForm(request.POST, request.FILES)
if form.is_valid():
post = form... | 5,312,881 |
def p_anyword(p):
"""anyword : anyword literal"""
p[0] = Node("anyword", value=(p[1].value + p[2].value)) | 5,312,882 |
def get_table_id(table):
"""
Returns id column of the cdm table
:param table: cdm table name
:return: id column name for the table
"""
return table + '_id' | 5,312,883 |
def all_items_present(sequence: Sequence[Hashable], values: Sequence[Hashable]) -> bool:
"""
Check whether all provided `values` are present at any index
in the provided `sequence`.
Arguments:
sequence: An iterable of Hashable values to check for values in.
values: An iterable of Hashab... | 5,312,884 |
def lnpost_hr4796aH2spf(var_values = None, var_names = None, path_obs = None, path_model = None, calcSED = False, hash_address = True, calcImage = False, calcSPF = True, Fe_composition = False, pit = False, pit_input = None):
"""Returns the log-posterior probability (post = prior * likelihood, thus lnpost = lnprior... | 5,312,885 |
def reorder(rules):
""" Set in ascending order a list of rules, based on their score.
"""
return(sorted(rules, key = lambda x : x.score)) | 5,312,886 |
def expand_np_candidates(np, stemming):
"""
Create all case-combination of the noun-phrase (nyc to NYC, israel to Israel etc.)
Args:
np (str): a noun-phrase
stemming (bool): True if to add case-combinations of noun-phrases's stem
Returns:
list(str): All case-combination of the ... | 5,312,887 |
def gantt_chart(username, root_wf_id, wf_id):
"""
Get information required to generate a Gantt chart.
"""
dashboard = Dashboard(g.master_db_url, root_wf_id, wf_id)
gantt_chart = dashboard.plots_gantt_chart()
d = []
for i in range(len(gantt_chart)):
d.append(
{
... | 5,312,888 |
def read_sharepoint_excel(file_path, host, site, library, credentials,
token_filepath=None, **kwargs):
""" Returns a panda DataFrame with the contents of a Sharepoint list
:param str file_path: a file path to an excel file in sharepoint
within a site's library (i.e. /General/file.xlsx)
:... | 5,312,889 |
def XDoG(img, sigma=0.5, k=1.6, tau=0.98, epsilon=0.1, phi=10):
"""
Improve thresholding with a tanh
"""
# Get a DoG
aux = DoG(img, sigma=sigma, k=k, tau=tau)/255
# Thresholding
for i in range(aux.shape[0]):
for j in range(aux.shape[1]):
if aux[i, j] >= epsilon:
aux[i, j] = 1 # white!
else:
aux[... | 5,312,890 |
def calc_gcc_weights(ks_calib, num_virtual_channels, correction=True):
"""Calculate coil compression weights.
Input
ks_calib -- raw k-space data of dimensions (num_kx, num_readout, num_channels)
num_virtual_channels -- number of virtual channels to compress to
correction -- apply rotation cor... | 5,312,891 |
def _ontology_info_url(curie):
"""Get the to make a GET to to get information about an ontology term."""
# If the curie is empty, just return an empty string. This happens when there is no
# valid ontology value.
if not curie:
return ""
else:
return f"{OLS_API_ROOT}/ontologies/{_ont... | 5,312,892 |
def _is_LoginForm_in_this_page(driver):
""" 用于判断一个页面是否有账号密码框 """
try:
get_username_input(driver)
get_password_input(driver)
except Errors.LoginFormIsNotFound:
return False
else:
return True | 5,312,893 |
def get_native_instance() -> native.new_word_finder.NewWordFinder:
"""
返回原生NLPIR接口,使用更多函数
:return: The singleton instance
"""
return __instance__ | 5,312,894 |
def reconstruct(analysis):
"""Main reconstruct method"""
reconstruction = Reconstruction(analysis)
reconstruction.reconstruct()
return reconstruction.data | 5,312,895 |
def test_with_parameters(case_data, # type: CaseDataGetter
version # type: str
):
""" This test checks that you can blend with your own pytest fixtures/parameters """
# 1- Grab the test case data
i, expected_o, expected_e = case_data.get(version)
... | 5,312,896 |
def validate_str(value=None, min_length=None, max_length=None, required=True, name=None):
""" validate string """
name_str = __name(name)
# no input / no required
if not value and not required:
return True
if not value and required:
raise TypeError(('{name_str} expected str, string must be input').format(\
... | 5,312,897 |
def ore_required_for(target: Reactant, reactions: Dict[str, Reaction]) -> int:
"""Return the units of ORE needed to produce the target."""
ore = 0
excess: Dict[str, int] = defaultdict(int)
needed = [target]
while needed:
cur = needed.pop()
if cur.ID == "ORE":
ore += cur... | 5,312,898 |
async def websocket_lovelace_update_card(hass, connection, msg):
"""Receive lovelace card config over websocket and save."""
error = None
try:
await hass.async_add_executor_job(
update_card, hass.config.path(LOVELACE_CONFIG_FILE),
msg['card_id'], msg['card_config'], msg.get('... | 5,312,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.