content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Optional
import torch
def equadrupole(qc: BaseQCCalc, unit: Optional[str] = "Debye*Angst") -> torch.Tensor:
"""
Returns the electric quadrupole moment of the system, i.e. derivative of energy
w.r.t. electric field.
Arguments
---------
qc: BaseQCCalc
The qc calc obje... | 6810c122f353e40a336365518b51b01b59199726 | 3,624,400 |
def get(key, nodename=None):
"""
A function to get a node pillar configuration key.
CLI Example:
salt * node.get hostname
"""
return _get_property(key, nodename, None) | 5dde600e2aa9f4f256ae66f4468270969ecbb057 | 3,624,401 |
def quote_logvalue(value):
"""Return a value formatted for use in a logfmt log entry.
The input is quoted if it contains spaces or quotes; otherwise returned unchanged
"""
s = str(value)
if " " in s or '"' in s:
s = s.replace('"', "\\" + '"')
return f'"{s}"'
return s | 15dd0789b5a7ce4e18eece37ad0cac59d9cd2332 | 3,624,402 |
from datetime import datetime
def create_new_form_search(data):
"""Create a new form search.
:param dict data: the form search to be created.
:returns: an form search model object.
"""
form_search = FormSearch()
form_search.name = h.normalize(data['name'])
form_search.search = data['sea... | 69f3851e4b64173968264819d2cf8d1d23b07318 | 3,624,403 |
def split_filename(fn, name=None,
prefix=None, suffix=None,
stack_limit=2):
"""
Ermittle einen Namen und ein Label aus dem Dateinamen,
der ggf. aus dem Aufrufstack ermittelt wird.
Zunächst "richtige" Entwicklungs- oder installierte Quellen:
>>> split_filename(... | 59058b0513074ad8caed590aab66db01f2858252 | 3,624,404 |
from re import T
import scipy
def model2magcoords(
xg: dict[str, T.Any],
parm: xarray.DataArray,
lalt: int,
llon: int,
llat: int,
altlims: tuple[float, float] = None,
mlonlims: tuple[float, float] = None,
mlatlims: tuple[float, float] = None,
):
"""
Grid the scalar GEMINI outpu... | a70ba50945b06ea1771728b7e90750f2efd5b1d6 | 3,624,405 |
def flatten(master):
"""
:param dict master: a multilevel dictionary
:return: a flattened dictionary
:rtype: dict
Flattens a multilevel dictionary into a single-level one so that::
{'foo':
{'bar':
{
'a': 1,
'b': True,
... | d31325219e43ee5c047c1a78589d94e2d7c62709 | 3,624,406 |
def network(ip):
"""Network an IP address belongs to.
Parameters
----------
ip : str
IP address.
Returns
-------
network_ip_with_prefix : str
IP address of the network with prefix.
"""
ip, prefix = netParse(ip)
return "{}/{}".format(
ipS... | e38088b3b747deb365d061426737beb0f14fa9b1 | 3,624,407 |
def _build_pnasnet_base(images,
normal_cell,
num_classes,
hparams,
is_training,
final_endpoint=None):
"""Constructs a PNASNet image model."""
end_points = {}
def add_and_check_endpoint(endpoin... | 4ada0f21e316b50982245894e55344b3fb772071 | 3,624,408 |
def _parse_advantage_prereq(el: et.Element, function_name: str) -> str:
"""Parse a <advantage_prereq> element and its children.
Return a str of Python code that takes traits and trait_names as
arguments and evaluates to True iff the prereqs are satisfied.
"""
if el.get("has") == "no":
if le... | be9a1a85d66baf9e73452e6a890fa741185abb37 | 3,624,409 |
def m21_midievent_to_event(midievent):
"""Convert a music21 MidiEvent to a tuple of MIDI bytes."""
status = midievent.data + midievent.channel - 1
return (status, midievent.pitch, midievent.velocity) | 3950b4e6715ac4de2dbdcc2d87d5cf51387a220c | 3,624,410 |
import numpy
def populate_impl_map(data_model):
"""
Map symbols to implementations.
"""
impl_map = {
"==": _type_safe_equal,
"=": _type_safe_equal,
"!=": _type_safe_not_equal,
"<>": _type_safe_not_equal,
"<": numpy.less, # already checks types
"<=": num... | fc854ec2baf90905f9bc65018453ac64b7fbc2de | 3,624,411 |
from datetime import datetime
def friendly_time(d: datetime.datetime) -> str:
"""Return "minutes ago" style date"""
ad = Arrow.fromdatetime(d)
other = Arrow.fromdatetime(datetime.datetime.utcnow())
return ad.humanize(other) | 47f2ef48d44fbd40dbddf5ed76f37836992476f3 | 3,624,412 |
from typing import Container
from typing import Sequence
def power_set_str_v2(s: str) -> Container[Sequence]:
"""
Note: it doesn't take empty set into accout.
"""
# print all subsets of the remaining elements, with given prefix
def _power_set_str_v2(prefix: str, s: str, result) -> None:
... | 119a9e6118298f0d05ed3b14f43788e5d1c7ba49 | 3,624,413 |
from typing import Any
def build_get307_request(**kwargs: Any) -> HttpRequest:
"""Redirect get with 307, resulting in a 200 success.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an :class:`~azure.core.rest.HttpR... | 6730bb8391ff007d44533eaab25129d71719b7da | 3,624,414 |
def svm_SVR_C( xM, yV, c_l, graph = True):
"""
SVR is performed iteratively with different C values
until all C in the list are used.
"""
r2_l, sd_l = [], []
for C in c_l:
print 'sklearn.svm.SVR(C={})'.format( C)
clf = svm.SVR( C = C)
clf.fit( xM, yV.A1)
yV_pred = clf.predict(xM)
r2, sd = regress_... | 3e194e569b0c86a2047a35a58e430e814b539029 | 3,624,415 |
from typing import Union
def solar_declination(
doy: Union[np.ndarray, xr.DataArray]
) -> Union[np.ndarray, xr.DataArray]:
"""Solar declination from day of year [rad].
Parameters
----------
doy: array.py
day of the year (1-365)
Returns
-------
Union[np.ndarray, xr.DataArray]
... | b8573dd30fc0adce404ff929083616afe9d46011 | 3,624,416 |
import logging
import pandas
def load_gwas(args, use_specific_targets):
"""Watch out! Pandas parser on occasion reads the column `position` as integer. Yikes."""
columns = ["variant_id", "panel_variant_id", "chromosome", "position", "non_effect_allele", "effect_allele","zscore"]
if use_specific_targets is... | b3ece4db92bdb6aeacf950b2ac802fd48550fad3 | 3,624,417 |
import copy
def merge_dict(d1, d2, overwrite=False):
"""Merge contents of d1 and d2 and return the merged dictionary
Note:
* The dictionaries d1 and d2 are unaltered.
* If `overwrite=False` (default), a `RuntimeError` will be raised when
duplicate keys exist, else any existing keys in d1 are s... | d680dcc3039804c340fc488a488fae1d891a8d1b | 3,624,418 |
import glob
import os
import shutil
def copy_cwl_files(from_dir=CWL_PATH, to_dir=None):
"""Copy cwl files to a directory where the cwl-runner can find them.
Args:
from_dir (str): Path to directory where to copy files from (default:
the cwl directory of nlppln).
to_dir (str): Path ... | bf420ef753ebd19b11de9f26dfe58d6a8af67b7e | 3,624,419 |
import argparse
def get_args():
"""Get args from the command line."""
parser = argparse.ArgumentParser(
description='Count down the number of bottles on the wall',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-n',
'--number',
... | 97c577e3e4d86262318bfe09f080126390232ac6 | 3,624,420 |
def handle_not_found(error: NotFound) -> Response:
"""Render the base 404 error page."""
rendered = jsonify({'code': error.code, 'error': error.description})
response = make_response(rendered)
response.status_code = status.HTTP_404_NOT_FOUND
return response | 31944d23b89b60f0b6b7059ce717f52ff7c714e8 | 3,624,421 |
def compare_documents(sample_text_a: str, sample_text_b: str) -> float:
"""Compares two documents using spacy's bow model"""
doc_a = nlp_en(sample_text_a)
doc_b = nlp_en(sample_text_b)
return doc_a.similarity(doc_b) | 85dbce4ef6b8f1b6ca7cd7a8dbe54390de530ff3 | 3,624,422 |
def calc_fragment_mz(pep, frag_type, frag_num, frag_charge, mod=None) -> float:
"""
Example:
pep = 'LGRPSLSSEVGVIICDISNPASLDEMAK'
frag_type = 'y'
frag_num = 10
frag_charge = 1
mod = '15,Carbamidomethyl;26,Oxidation;'
-> 1091.5037505084001
:param pep: peptide sequence
:param frag... | 984af3bd523dcbac5a89e5405dabd8a5dabc062b | 3,624,423 |
def invert_axis(document: vp.Document, invert_x: bool, invert_y: bool):
"""Inverts none, one or both axis of the document.
This applies a relative scale operation with factors of 1 or -1
on the two axis to all layers. The inversion happens relative to
the center of the bounds.
"""
bounds = docu... | ac822e0a93f27b20043e21e72b94d394ba85ddfb | 3,624,424 |
def tokenize_tweet(inputRow, fields):
"""
A simple tokenizer that takes a tweet as input and, splitting on whitespace, and returns words in the tweet
Args:
inputRow (Row): A spark sql row containing a tweet
fields (list): A list of field names which directs tokenize on which fields to use as so... | 60e1cb52f9e4d537c0d0809b0bd75117468a0338 | 3,624,425 |
def seq_to_kmercount(seq, kmerdict, kmersize):
"""DNA sequence and count number of kmers
in the dictionary, and return this dictionary
"""
seq = str(seq).upper()
length = len(seq) - kmersize + 1
for i in range(length):
kmer = seq[i:i+kmersize]
# select lexographically lowest km... | fa8b67863092d43d5a9167048702d4b7a089f7b1 | 3,624,426 |
def create_resource_from_db_row(row):
"""Create a resource type from a database resource row.
Args:
row (Resource): the database resource row.
Returns:
Resource: the concrete resource type.
"""
parent = (
create_resource_from_db_row(row.parent) if row.parent else None)
... | 977196a83c8de1a580c408228b12379903fbb513 | 3,624,427 |
def build_embeddings(symbolic_features, integer_features,
embeddings, large_discrete, merged_inputs,
X, test_X, train_dict, test_dict, dataset):
"""Define embedding layers/inputs"""
merged_dim = 0
for (name, values) in symbolic_features.items():
feature_name... | 7aa0fa92f1aadd4f4f6554b11be378657575deea | 3,624,428 |
def get_results(job_key):
"""
Results page for <job_key>. If job is still running, this will redirect to the same page with the link to refresh again. When its done,
the refresh link will link to the tables.
"""
job = Job.fetch(job_key, connection=current_app.redis)
### Return results
if... | 4976e09be902da7e4d3c4f02558cc4d25dbb706a | 3,624,429 |
import pathlib
import os
import copy
def find_background_image_path(canvas_width, canvas_height, canvas_background_file):
"""Establish the path to the background file should one exist. The function copies it from wherever specified into the root.
Also checks the aspect ratio of the input file against the ... | 37a76e4b33c33b431a5e55948d8607998b410ddc | 3,624,430 |
def getFlipboardTitles():
""" Get title of all dashboard inside Config/ """
config_names = getConfigNames()
listNameDashboard = list()
rcx = 1
for config in config_names:
config = parseXmlLayout(config)
if 'details' in config and 'page_title' in config['details']:
listNam... | f6b54d9abb43cab02f4c9fc2d575660577f919aa | 3,624,431 |
def availability(url, session=None):
"""
Check HTTP status code of given URL.
200 or 301-308 is OK, else is not.
:param url: URL to check.
:type url: str
:param session: Requests session object, default is created on the fly.
:type session: requests.Session()
"""
status = getcode(u... | 4d895223b84b02243705878c747b0ee15b988acd | 3,624,432 |
import ctypes
def cudnnGetConvolution2dForwardOutputDim(convDesc, inputTensorDesc, filterDesc):
""""
Return the dimensions of the output tensor given a convolution descriptor.
This function returns the dimensions of the resulting 4D tensor of a 2D
convolution, given the convolution descriptor, the in... | 28d3421fdf838f93dceaeea462cad1cacdde09ee | 3,624,433 |
from datetime import datetime
def ocean_loading(time, amp, phases, lon):
"""
time is in hours from Jan 1, 1900, stationlongitude is longitude
purpose: To assess the ocean loading/gravity effect due to the
separate tidal primary components derived from the Agnew
pr... | dcfb7ae82dfeb6ace524033fafdd4ad7cb907c3a | 3,624,434 |
import os
def cancel_study(args):
"""Flag a study to be cancelled."""
if not os.path.isdir(args.directory):
return 1
lock_path = os.path.join(args.directory, ".cancel.lock")
with open(lock_path, 'a'):
os.utime(lock_path, None)
return 0 | 68401bff4cb5bdfda554cf6301e517e8ca0f452b | 3,624,435 |
def convert_ms_2_tf(tf_ckpt_path, ms_ckpt_path, new_ckpt_path):
"""
convert ms checkpoint to tf checkpoint
"""
# load MS checkpoint
ms_param_dict = load_checkpoint(ms_ckpt_path)
for name in ms_param_dict.keys():
if isinstance(ms_param_dict[name].data, Tensor):
ms_param_dict[n... | 1214438ed29c8e4e9c9f35c7f8549e837b9f423d | 3,624,436 |
def servers():
"""Unauthorized endpoint to check for configured servers. Returns the name and ID of the server for selection
when logging in. Also indicates the current server (if one is selected)
"""
server_list = []
for s in current_app.config['LABMGR_CONFIG'].list_available_servers():
s... | 78ac93693b493fea8e9583337d7e1f24aea313c5 | 3,624,437 |
def ammonia_fake() -> (oechem.OEMol, oechem.OEAtomBase):
"""
Creates an ammonia molecule with fake Wiberg bond orders. Also returns
the trivalent nitrogen in the molecule
"""
ammonia = oechem.OEMol()
oechem.OESmilesToMol(ammonia, "N")
oechem.OEAddExplicitHydrogens(ammonia)
fake_wbo = [1... | 9f0f9ec19d7d8b7a373d047dd023f361ddfa61ed | 3,624,438 |
def check_token():
""" Token checking endpoint.
---
get:
summary: Check the validity of a token.
description: This endpoint checks for the validity of a given authentication token.
parameters:
- token: The token to check.
responses:
200:
... | 14d2b08fe717f9760e0f535a455f56f1b5a667c0 | 3,624,439 |
from typing import Tuple
def subgrid(
A: xr.Dataset, subgrid_spec: Tuple[int, int, int, int], stagger: str = "outer"
) -> xr.Dataset:
"""Make a ROMS xarray Dataset on a horizontal subgrid"""
# Suppese xi_rho and eta_rho allways present
# imax = len(A.xi_rho)
# jmax = len(A.eta_rho)
# How abo... | efd709562d340bfa570086b4383d85e71e5555f3 | 3,624,440 |
def format_decimal(number):
"""Formats `number` for current locale."""
attan = Xuanzang.get_attan()
return attan.format_decimal(number) | 067dd4a02a3b7932762e124a101acc051d49aed6 | 3,624,441 |
def optimization_for_fishfeed_substitution(fishfeed_table, lipidmicro,
protmicro, carbmicro, watermicro,
ashmicro, incorporation_rate,
MJ_kgcarb, MJ_kgprot, MJ_kglip):
"""Returns the subs... | 88c2bfe33249dfd099201fab2dd0fd7c07fd218a | 3,624,442 |
import re
def remove_repeating_characters(sentence):
"""
remove non alphaneumeric characters which repeat more than 3 times by its 3 occurrence (e.g. ----- to ---)
:param sentence:
:return:
"""
sentence = re.sub('(\W)\\1{3,}', '\\1', sentence)
return sentence.strip() | 9bf8e53c3fed78b2a8cd4c91a6a68f980c270654 | 3,624,443 |
import argparse
def get_args() -> argparse.Namespace:
"""Get args."""
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--username", required=True, type=str, help="Zenfolio username")
parser.add_argument("-p", "--password", required=True, type=str, help="Zenfolio password")
parser.add_... | cc099c5cf5d60da207c19107e9c1ef90385ab85b | 3,624,444 |
import random
def crossover(p_1, p_2, r_cross):
"""
order 1 crossover / OX / order crossover
:param p_1: parent 1
:param p_2: parent 2
:param r_cross: rate of crossover
"""
if random.random() < r_cross:
c1, c2 = p_1.copy(), p_2.copy()
pt_1 = random.randint(0, len(p_1)-1)
... | d0bdc28803feed1a67864204b8b3177f70f8cda7 | 3,624,445 |
def tree_to_treesegment(canvas, t, make_node=TextWidget,
make_leaf=TextWidget, **attribs):
"""
Convert a Tree into a ``TreeSegmentWidget``.
:param make_node: A ``CanvasWidget`` constructor or a function that
creates ``CanvasWidgets``. ``make_node`` is used to convert
... | ba9e6d9546a726adefc6259d87f2a5b05f41788d | 3,624,446 |
import numpy
def borrow_for_color_red(base_color_dict, from_left, from_right):
"""!
@brief Borrows colors for the base color red.
@param base_color_dict Dictionary with arrays of all the base colors.
@param from_left Boolean flag for recursive calls, if we came from the left.
@param from_rig... | 1f3b58f11390dfd51301dce234a3df35655673f5 | 3,624,447 |
def requestPdpContextActivationReject():
"""REQUEST PDP CONTEXT ACTIVATION REJECT Section 9.5.5"""
a = TpPd(pd=0x8)
b = MessageType(mesType=0x45) # 01000101
c = SmCause()
packet = a / b / c
return packet | a34b694cd7bbd78b6c67c8362da0c6dd92b72792 | 3,624,448 |
def add_month(year, month, delta):
"""
Helper function which adds `delta` months to current `(year, month)` tuple
and returns a new valid tuple `(year, month)`
"""
year, month = divmod(year * 12 + month + delta, 12)
if month == 0:
month = 12
year = year - 1
return year, month | 8f509bba44bb27579b948c3b26e5f7c027be445c | 3,624,449 |
from datetime import datetime
def extractTime(line):
"""
extracts date or time from an event file input line
and returns a datetime object.
"""
dt = line.split(None, 1)[0]
if len(dt) > 20:
print(dt, 'Invalid dateTime string')
return
#print('extractTime : ', line )
... | 18692ef0b8ce79182ee7e98b523160dc6feea4b0 | 3,624,450 |
def ramp(width=32, height=32, density=0.25):
"""Support downward forces on a ramp."""
return staircase(width, height, density, num_stories=1) | bb0b4cb5b36047b37e43c932d9923f5541434f35 | 3,624,451 |
def zeros(shape, backend=TensorFunctions):
"""
Produce a zero tensor of size `shape`.
Args:
shape (tuple): shape of tensor
backend (:class:`Backend`): tensor backend
Returns:
:class:`Tensor` : new tensor
"""
return Tensor.make([0] * int(operators.prod(shape)), shape, ba... | 9af26b57e46984e6158168183a43c42101d73f0d | 3,624,452 |
def getInitFile():
"""
function: get init file
input : NA
output : NA
"""
if isSupportSystemOs():
return INIT_FILE_REDHAT
else:
return INIT_FILE_SUSE | a2b197ce97cf96565846427beb516803c4fd603d | 3,624,453 |
def compare(returns, benchmark, aggregate=None, compounded=True,
round_vals=None, prepare_returns=True):
"""
Compare returns to benchmark on a
day/week/month/quarter/year basis
"""
if prepare_returns:
returns = _utils._prepare_returns(returns)
benchmark = _utils._prepare_benc... | 5f04b9ba9d614424fd3244a02971809356f04850 | 3,624,454 |
import json
def __get_job_obj(profile):
"""Return the 'job' object in the profile."""
with open(profile, 'rt') as json_fobj:
data = json.load(json_fobj)
return data['jobs'][0] | 2af6658f8a54987229dffe35efe37d2dace9f0bb | 3,624,455 |
import configparser
def getconfloc() :
""" Renvoie la configuration total des localisations"""
cfg = configparser.ConfigParser()
cfg.read(clt_path)
location = {}
for i in cfg.options('Locations') :
location[i] = getlocation(i)
return location | 33101369c2d93fc47d2c198c38d7604b4458dbca | 3,624,456 |
def median(r):
"""Return the median of an iterable of numbers.
The median is the point at which half the numbers are lower than it and
half the numbers are higher. This gives a better sense of the majority
level than the mean (average) does, because the mean can be skewed by a few
extreme numbers ... | ed1bb07e39ddec8c702f55fb3555ca3b03ca0c74 | 3,624,457 |
def flatten_evidence(stmts, collect_from=None):
"""Add evidence from *supporting* stmts to evidence for *supported* stmts.
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
A list of top-level statements with associated supporting statements
resulting from bui... | c5374a57b36d3e4ad8537d05c4ce2beb76c9450b | 3,624,458 |
def get_binary_image(image):
"""Converts image to black and white"""
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
(thresh, black_white_image) = cv2.threshold(
gray_image, 150, 255, cv2.THRESH_BINARY_INV)
return thresh, black_white_image | 8bdf03ef008e9c9fc603197007b867f450dba26f | 3,624,459 |
def analyze_sentiment(text):
"""
Sends a request to the Google Natural Language API to analyze
the sentiment of the given piece of text.
"""
request = language_service.documents().analyzeSentiment(
body={
'document': {
'type': 'PLAIN_TEXT',
'content': text,
... | 62591cb06c5694c9d09b8bf43397e39bbea64fab | 3,624,460 |
def php_array_slice(_array, _offset, _length=None, _preserve=False):
"""
>>> input = Array("a", "b", "c", "d", "e")
>>> php_array_slice(input, 2)
{0: 'c', 1: 'd', 2: 'e'}
>>> php_array_slice(input, -2, 1)
{0: 'd'}
>>> php_array_slice(input, 0, 3)
{0: 'a', 1: 'b', 2: 'c'}
>>> php_arra... | c88d107da70191351a52e42e8f1a91407b0c4581 | 3,624,461 |
def scale_clips(boxes, canvas_area, density=0.40):
"""
Resizes and returns cropped words based on canvas area, density, and word complexity
Input:
`boxes` user words pandas dataframe
`canvas_area` total area of canvas
`density` float of desired area to fill on canvas
Output:
... | 5b9623041ccd3ca6d3a6a9e61a56fba39dda6fa6 | 3,624,462 |
import os
def make_root_cgroups():
"""
Build a CGroups object for the topmost cgroup
:return: CGroups for most-encompassing cgroup
:rtype: CGroupConfigurator
"""
def path_maker(hierarchy, _):
return os.path.join(BASE_CGROUPS, hierarchy)
return CGroupConfigurator("root", path_mak... | ddd28706a6d9029d4adc8b296b1427574c6cbdf6 | 3,624,463 |
def create_snippet(text):
"""
:param text:
:return:
"""
if len(text) < 500:
return text
initial_cut = text[:550]
last_index_of_space = initial_cut.rfind(' ')
last_index_of_semicolon = initial_cut.rfind(';')
last_index_of_comma = initial_cut.rfind(',')
last_index_of_per... | 171f6d9d9e8dfb9e72cd5d075b19a08370eba163 | 3,624,464 |
import sys
import argparse
def create_parser(argv=None):
"""Create CLI arguments and sub-arguments parsers.
"""
if argv is None:
argv = sys.argv[1:]
argparser = argparse.ArgumentParser(description='rerobots API command-line client', add_help=False)
argparser.add_argument('-h', '--help', d... | 7412b2f030be19809894100eb20cf830d166102a | 3,624,465 |
def collect_args():
"""
Sets up and collects necessary arguments using ArgumentParser.
Returns
-------
args : argparse.Namespace
Namespace containing the arguments and their values specified by the user.
"""
parser = ArgumentParser('python intensity.py')
parser.add_arg... | 9ea5e29af0185d329f5a33473d8430e0cfd1b20e | 3,624,466 |
def get_losses(model, dataset, criterion, device):
"""
calculates loss for each item
"""
model.eval()
loader = DataLoader(dataset, batch_size=1)
losses = []
for i,data in enumerate(loader):
data = Variable(data).to(device)
# ===================forward=====================
... | 1b26ae1eefb09ff857b1734e08221124fa3b7cc7 | 3,624,467 |
import requests
def get_dnac_jwt_token(dnac_auth):
"""
Create the authorization token required to access DNA C
Call to Cisco DNA Center - /api/system/v1/auth/login
:param dnac_auth - Cisco DNA Center Basic Auth string
:return: Cisco DNA Center JWT token
"""
url = DNAC_URL + '/dna/system/ap... | 93144fc43306eb668ff780b7a93834b9b21d2b07 | 3,624,468 |
import types
def get_reconstruction_origin(r):
"""Compute the origin of a reconstruction."""
s = r.scale
pose = types.Pose([r.rx, r.ry, r.rz], [r.tx / s, r.ty / s, r.tz / s])
return pose.get_origin() | 63c82c9b365e753ff665a6dd95c23aff3160acd2 | 3,624,469 |
import tqdm
import torch
import os
def train_loop(net, optimizer, criterion, train_data, valid_data, n_epochs, batch_size, task='mimic-mortality', save_dir=None,
verbose=False, scheduler=None, eval_every=10000, save_every=40, writer=None):
"""
net: nn.Module we are training
optimizer: pyt... | a389a7c1311ae71516cdbdf05254f1a81415be54 | 3,624,470 |
def is_empty(table: Map[Key, Value]) -> bool:
"""Is the map empty?
Args:
table: The input map.
Returns:
True if the map is empty.
"""
return table.is_empty() | 419382c02af5320dea6c754a4d32843b58e39eaa | 3,624,471 |
from typing import Optional
def to_latex(circuit: Program, settings: Optional[DiagramSettings] = None) -> str:
"""
Translates a given pyQuil Program to a TikZ picture in a LaTeX document.
Here are some high points of the generation procedure (see ``pyquil/latex/_diagram.py``):
- The most basic build... | 78b7c9f7efddbb3e874a4f4a61d7c3c3c0e44da5 | 3,624,472 |
def autodetect_filename(fn):
"""Guess based on filename.
"""
for k in EXT_MAP:
if fn.endswith(k):
return EXT_MAP[k]
return None | a2001bdead333334a9b922fa219696fcd62cc122 | 3,624,473 |
def get_password_hash(password):
"""
Se calcula el hash de un string
Parameters
----------
password : str
Texto al que se le calculara el hash.
Returns
-------
out : str
String con el hash correspondiente al texto.
"""
return pwd_context.hash(password) | d738da51c57560d6e84c91cfc46b78367fceb0b8 | 3,624,474 |
import jinja2
import os
def render_meta_yaml(text):
"""Render the meta.yaml with Jinja2 variables.
Parameters
----------
text : str
The raw text in conda-forge feedstock meta.yaml file
Returns
-------
str
The text of the meta.yaml with Jinja2 variables replaced.
"""
... | ee5ade5e1e4027d084d5591a31b714ecb3efc6b4 | 3,624,475 |
def transform_function(fromsys, tosys, copyobstime=True, priority=1):
"""
A function decorator for defining transformations between coordinate
systems.
.. note::
If decorating a static method of a class, ``@staticmethod``
should be added *above* this decorator.
Parameters
----... | c8ffde1729791c8d03611c296b8adf5f941099ed | 3,624,476 |
def remove_empty_boxes(boxes, labels):
"""Removes bounding boxes of W or H equal to 0 and its labels
Args:
boxes (ndarray): NP Array with bounding boxes as lines
* BBOX[x1, y1, x2, y2]
labels (labels): Corresponding labels with boxes
Returns:
ndarray: ... | 4f004a9d77cc39eb18d62f6386d7e51ddd077e9d | 3,624,477 |
def add_hr_zones(df):
"""Add columns with the time spent at each zone."""
df_zones = create_df_with_zones(df['file'])
out = pd.concat([df, df_zones], axis=1)
out.loc[:, 'z1/z2':'z5'] = round(out.loc[:, 'z1/z2':'z5']/60, 1)
return out | 85fd453a9735303f230d47a0e137052aa45a9ef6 | 3,624,478 |
def check_data(ctx, datasets):
"""
checks the data of the current experiment folder; note: must follow before data aggregation
:return True if all OK; False otherwise
"""
print('### checking data ###')
experiment = 'r_' + ctx['experiment_folder']
run = create_or_get_dict(datasets, experiment... | 042c10c8447c6cd51e62bb8b39f2c4fc3324a78b | 3,624,479 |
def _ParseJobIds(job_ids, sparse_log, error_log):
"""Parse job ids."""
if ':' in job_ids:
job_ids = job_ids.split(':')
assert len(job_ids) == 3
job_ids = [int(x) for x in job_ids]
job_ids = np.arange(job_ids[0], job_ids[1], job_ids[2])
job_ids = [str(x) for x in job_ids]
elif ',' in job_ids:
... | a83553a32f8882922e1b90b60bfd353b261895fb | 3,624,480 |
import torch
def model_fn(batch, model, criterion, device):
"""Forward a batch through the model."""
mels, labels = batch
mels = mels.to(device)
labels = labels.to(device)
outs = model(mels)
loss = criterion(outs, labels)
# Get the speaker id with highest probability.
preds = outs.... | 2b9907e8f0fbec50b955082efb30d8cddc88b663 | 3,624,481 |
def tree_is_to_be_used(tree):
"""
discard the input tree if:
1) the root is FRAG
2) it contains empty category such as *T*
3) a node with more than two children
"""
def rec(node):
if isinstance(node, Tree):
if len(node.children) > 2:
# logger.warn(f'more t... | 051c7c23a464573e8f687eff690c1f42cd5d9eaf | 3,624,482 |
import scipy
def score_gene_sets(ds, gs, method='mean_z_score', permutations=None,
random_state=0, smooth_p_values=True, progress=False):
"""Score gene sets.
Note that datasets and gene sets must be aligned prior to invoking this method. No check is done.
mean_z_score: Compute the z-... | 877cdf3eddfd1a1484c8a778a4106cad6dbcbaed | 3,624,483 |
import os
def read_image_stack(fn, *args, **kwargs):
"""Read a 3D volume of images in image or .h5 format into a numpy.ndarray.
The format is automatically detected from the (first) filename.
A 'crop' keyword argument is supported, as a list of
[xmax, xmin, ymax, ymin, zmax, zmin]. Use 'None' for n... | f0784fa8fa444beb1db36efa95cd4c68833a8859 | 3,624,484 |
from plotly.basedatatypes import BaseFigure, BaseLayoutType
def iplot(figure_or_data, **plot_options):
"""Create a unique url for this plot in Plotly and open in IPython.
plot_options keyword arguments:
filename (string) -- the name that will be associated with this figure
sharing ('public' | 'privat... | 4c14b04f410fa685395376a6d129af06e0e8b73f | 3,624,485 |
def _fread3_many(fobj, n):
"""Read 3-byte ints from an open binary file object."""
b1, b2, b3 = np.fromfile(fobj, ">u1",
3 * n).reshape(-1, 3).astype(np.int64).T
return (b1 << 16) + (b2 << 8) + b3 | ba3cc17a2f0b87a015a2dbfb309a947492246114 | 3,624,486 |
def _extract_rel_addr(op_bytes, mnemonic_type):
"""
Extract the relative address at the level from the
binary operation (borrowed from Koo's and Polychronakis'
implementation).
"""
addr = 0x0
mask = 0x0
# Aside from mnemonic bytes, all remaining bytes wou... | 231cbd14262fe92038a2394d9896240b8805b5c0 | 3,624,487 |
def is_transformer(actor):
"""
Checks whether the actor is a transformer.
:param actor: the actor to check
:type actor: Actor
:return: true if a transformer actor
"""
return isinstance(actor, OutputProducer) and isinstance(actor, InputConsumer) | 3b10a212dce64b472ad27651596a269a0ce02102 | 3,624,488 |
import os
import sys
def get_base_dir():
"""Attempts to locate ariadne's install directory."""
try:
d=os.environ['ARIADNE_BASE']
if d[len(d)-1] != '/':
d+='/'
return d
except:
# This may be significantly better than using the environment variable.
genpat... | b4ab46100e373f17700a06c4ccee1f82c5b97eb7 | 3,624,489 |
def ChoiceToEnum(choice, enum_type, item_type='choice', valid_choices=None):
"""Converts the typed choice into an apitools Enum value."""
if choice is None:
return None
name = ChoiceToEnumName(choice)
valid_choices = (
valid_choices or
[arg_utils.EnumNameToChoice(n) for n in enum_type.names()])
... | 291702a17fc7dcc57ed09dbf9cba0d1a466e982f | 3,624,490 |
import argparse
def get_arguments():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description="Code for evaluation")
parser.add_argument('--best_iter', type=int, default=70000,
help='iteration with best mIoU')
parser.add_argument('--normalize', type=b... | 6f3a351c9630c5b524cf5e4bb8db6ee14f995cba | 3,624,491 |
def resubmit_alert(uuid, *args, **kwargs):
"""Resubmit an alert for analysis. This means the alert will be re-analyzed as-if it was new.
:param str uuid: The uuid of the alert to be resubmitted.
:return: A result dictionary (has 'result' key).
:rtype: dict
"""
return _execute_api_call('analysis... | 18b5526544a5507061e44f454f984065f17a8833 | 3,624,492 |
def get_context(canvas):
"""Get ``cairo.Context`` used to draw onto the canvas."""
return canvas.renderer._get_context() | 1d68e6eb742dff906b6e64c85d9609e34f508b77 | 3,624,493 |
from traitsui.toolkit_traits import FontTrait
def Font(*args, **metadata):
""" Returns a trait whose value must be a GUI toolkit-specific font.
.. deprecated:: 6.1.0
``Font`` trait in this package will be removed in the future. It is
replaced by ``Font`` trait in TraitsUI package.
"""
... | ea3d97e1fab8ad177cec3defcca6d1fc99323819 | 3,624,494 |
import socket
from sys import path
def determine_instrument(setup_package_path):
"""MLZ specific way to find the NICOS instrument from the host name."""
try:
# Take the second part of the domain name (machine.instrument.frm2
# or new-style machine.instrument.frm2.tum.de)
hostname = soc... | aeba2fd237d108d3e5e47ab46ec5319aab24852d | 3,624,495 |
def ArclinkRequestSummary_Meta():
"""ArclinkRequestSummary_Meta() -> MetaObject"""
return _DataModel.ArclinkRequestSummary_Meta() | fc204332096109e44600936439fd12510f600e41 | 3,624,496 |
from datetime import datetime
def convert_datetime_to_string_date(now: datetime = datetime.now()) -> str:
"""
Converts now to string format yyyy-dd-yy-hh-mm-ss
:param now: datetime. Date in datetime format. Default value is datetime.now().
:return: str.
"""
year = now.year
month = add_zero... | f5f99498e98975409f81a90f0a1aabaca744d328 | 3,624,497 |
import math
def _sin(num):
"""The sin function.
Args:
num -- A number.
Returns:
sin(num)
"""
if var_type(num) == "number":
# This only works with 1D arrays
# Just implemented for scalar at this point
return math.sin(num)
raise Val... | c2ecc0e0607ea061d7add614ac58003503f17f02 | 3,624,498 |
import typing
import os
def merge_data_from_gen_files_with_format(root_path: str) -> typing.List[str]:
"""从生成的多个带格式的文件中读取数据,并返回一个List
"""
file_list = [os.path.join(root_path, file) for file in os.listdir(
root_path) if file.startswith('gpt2_gentext_') and file.endswith('.txt')]
tmp = []
fo... | 4b744effc8df57066e9c42c5d39aedef2fdf0510 | 3,624,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.