content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _print_violations(violation_dicts, limits, limit_type):
"""
Format and print limit violations.
:param violation_dicts: A list of dicts of axis violations
:param limits: A list of robot robot axes limits
:param limit_type: Name string of the limit type
:return:
"""
warning = ''
wa... | 46,700 |
def echo_handler(*args, **kwargs):
"""
Mainly for testing.
"""
log.info("Echo: {:}".format(args)) | 46,701 |
def getservbyport(*args,**kw):
"""getservbyport(port[, protocolname]) -> string
Return the service name from a port number and protocol name.
The optional protocol name, if given, should be 'tcp' or 'udp',
otherwise any protocol will match."""
pass | 46,702 |
def cmd_structure():
"""Commands to create and inspect `StructureData` nodes.""" | 46,703 |
def post_demo(module_id):
"""
validation为数据验证装饰器,类似于wtf,这里做成yaml文件方便配置,易于阅读
返回值在tflask中有定制,这里使用字典也是为了更直观(不为了少些几个单词而牺牲可读性)
:param module_id:
:type module_id:
:return:
:rtype:
"""
post_form = parse_json_formdict('module_update')
code = update_module(module_id, post_form)
retur... | 46,704 |
def SimpleDrape(DataDirectory,Base_file, Drape_prefix, cmap = "jet", cbar_loc = "right", cbar_label = "drape colourbar", size_format = "ESURF", fig_format = "png", dpi = 250, out_fname_prefix = "", coord_type = "UTM_km", use_scalebar = False, drape_cnorm = "none", colour_min_max = []):
"""
This function makes a... | 46,705 |
def get_soup_at_url(
url, detect_meta=False, detect_rel=False, detect_angular=False, save_in_file=False
):
"""Get content at url as BeautifulSoup.
url is a string
detect_meta is a hacky flag used to detect comics using similar plugin to
be able to reuse code at some point
detect_rel is a ha... | 46,706 |
def local_angle_2D(points, times=None):
"""
Calculates 2-dimensional absolute step angles in radians where step angle
is deviation from a straight path when going from one time point to the next
Parameters
----------
points: np.ndarray
Array of track points in matrix coordinates (origin... | 46,707 |
def run(input_path, output_path, model_path):
"""Run MonoDepthNN to compute depth maps.
Args:
input_path (str): path to input folder
output_path (str): path to output folder
model_path (str): path to saved model
"""
print("initialize")
# select device
device = torch.dev... | 46,708 |
def calculate_geometry_stats(df):
"""Calculate total network miles, free-flowing miles (not in waterbodies),
free-flowing unaltered miles (not in waterbodies, not altered), total
perennial miles, total free-flowing unaltered perennial miles, and count of
segments.
Parameters
----------
df :... | 46,709 |
def unshelve(ui, repo, *shelved, **opts):
"""restore a shelved change to the working directory
This command accepts an optional name of a shelved change to
restore. If none is given, the most recent shelved change is used.
If a shelved change is applied successfully, the bundle that
contains the s... | 46,710 |
def SyntaxSpec(lang_id=0):
"""Syntax Specifications
@param lang_id: used for selecting a specific subset of syntax specs
"""
if lang_id == synglob.ID_LANG_JAVA:
return SYNTAX_ITEMS
else:
return list() | 46,711 |
def build_workflow(opts, retval):
"""
Create the Nipype Workflow that supports the whole execution
graph, given the inputs.
All the checks and the construction of the workflow are done
inside this function that has pickleable inputs and output
dictionary (``retval``) to allow isolation using a
... | 46,712 |
def test_update_enrollments_for_email_email_does_not_exist(mocker):
"""Verify that update_enrollments_for_email call update_enrollments_for_user job"""
mock_task = mocker.patch(
"course_catalog.etl.enrollments.update_enrollments_for_user"
)
update_enrollments_for_email.delay("fake_email")
mo... | 46,713 |
async def _discover_persistent_devices(
hass: HomeAssistant, entry: ConfigEntry, gateway: BaseAsyncGateway
) -> None:
"""Discover platforms for devices loaded via persistence file."""
new_devices = defaultdict(list)
for node_id in gateway.sensors:
if not validate_node(gateway, node_id):
... | 46,714 |
def handler404(request):
"""
Utility handler for people wanting EXCEPTIONAL_INVASION, since we can't trap the Http404 raised when the
URLconf fails to recognise a URL completely. Just drop this in as handler404 in your urls.py. (Note that
if you subclass ExceptionalMiddleware to override its render() me... | 46,715 |
def get_pipeline(name, outfolder):
"""
Build and return pipeline instance associated with given name.
:param str name: Name of the pipeline to build.
:param str outfolder: Path to output folder for use by pipeline instance.
:return SafeTestPipeline: A test-session-safe instance of a Pipeline.
"... | 46,716 |
def get_idw_interpolant(distances, p=2):
"""IDW interpolant for 2d array of distances
https://pro.arcgis.com/en/pro-app/help/analysis/geostatistical-analyst/how-inverse-distance-weighted-interpolation-works.htm
Parameters
----------
distances : array-like
distances between interpolati... | 46,717 |
def _render_html_attributes(attributes):
"""
Safely renders attribute-value pairs of an HTML element.
"""
if attributes and isinstance(attributes, dict):
def map_key(key):
# Map and case converts keys
return _kebab(ALIASES.get(key, key))
def map_value(key, value)... | 46,718 |
def interpolate_force_line2(form, x, tol=1E-6):
"""Interpolates a new point in a form polyline
Used by the `add_force_line` function
(I think it is assumed that the )
"""
if len(form) < 1:
raise ValueError('interpolate_force_line2 : form must not be an empty list')
form_out1 = [form[0]]
... | 46,719 |
def load_hdf5(infile):
"""
Load a numpy array stored in HDF5 format into a numpy array.
"""
with h5py.File(infile, "r", libver='latest') as hf:
return hf["image"][:] | 46,720 |
def transform_scalars(dataset, clipNum=5):
"""Set values outside a cirular range to minimum(dataset) to
remove reconstruction artifacts"""
from tomviz import utils
import numpy as np
array = utils.get_array(dataset)
# Constant values
numX = array.shape[1]
numY = array.shape[2]
min... | 46,721 |
def enqueue_crawling_job(delegate_or_broadcast_svc, job_id, urls, depth):
"""
Used to enqueue a crawling job (or delegate a sub-url on a current job)
to the worker pool.
:type delegate_or_broadcast_svc: ZeroMQDelegatorService or
ZeroMQBroadcastService.
:param delegate_or_broadcast_svc: The ... | 46,722 |
def show_control_sidebar_tabs():
"""Show the control sidebar tabs"""
# Default the show recent activity tab to true
default_dict = {
'SHOW_RECENT_ACTIVITY_TAB': True,
}
# Pull the settings for the control sidebar from settings.
# It is possible that the show recent activity will be
... | 46,723 |
def preprocess_b(image_name: str, output_file: str) -> None:
"""preprocesses second part of image"""
preprocess(image_name, output_file, 1125, 2035) | 46,724 |
def unsubscribe(login, rec):
"""Unsubscribe from user
"""
try:
if login == env.user.login:
raise SubscribeError
if rec:
if users.check_subscribe_to_user_rec(login):
fn = users.unsubscribe_rec
else:
return xmpp_template('sub_... | 46,725 |
def build_script(configurators):
"""
Loops over configurators, calling gather_input on them and then renders the script sections
in a template.
"""
def gather_input(configurator):
cfg = configurator.Config()
dialog.set_background_title(cfg.description)
return {"config": cfg,... | 46,726 |
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of YAML data,
as written by the Serializer above.
"""
if isinstance(stream_or_string, basestring):
stream = StringIO(stream_or_string)
else:
stream = stream_or_string
# Reconstruct the flat obj... | 46,727 |
def _save_metrics(metrics: dict, output_path: str):
"""Export the metrics of trained lgb model."""
with tf.io.gfile.GFile(output_path, 'w') as eval_file:
eval_file.write(json.dumps(metrics)) | 46,728 |
def container_image(name, binary, base, **kwargs):
"""Constructs a container image for the given binary.
Args:
name: Name of the target.
binary: The binary to embed in the image.
base: Base image to use for the image.
**kwargs: See arguments of app_layer.
"""
app_layer(... | 46,729 |
def fix_source_eol( path, is_dry_run = True, verbose = True, eol = '\n' ):
"""Makes sure that all sources have the specified eol sequence (default: unix)."""
if not os.path.isfile( path ):
raise ValueError( 'Path "%s" is not a file' % path )
try:
f = open(path, 'rb')
except IOError... | 46,730 |
def truew(crse=None,
cspd=None,
hd=None,
wdir=None,
wspd=None,
zlr=DEFAULT_ZRL,
wmis=DEFAULT_MISSING_VALUES,
):
"""
FUNCTION truew() - calculates true winds from vessel speed, course and
relative wind
INPUTS
crse real Co... | 46,731 |
def save_append(list_: List[Text], location: Text) -> None:
"""Appends 'list_' to 'location' as txt file. Returns None."""
with open(location, "a+") as f:
for element in list_:
f.write(element)
f.write("\n") | 46,732 |
def ascii_encode(string):
"""Return the 8-bit ascii representation of `string` as a string.
:string: String.
:returns: String.
"""
def pad(num):
binary = baseN(num, 2)
padding = 8 - len(binary)
return "0"*padding + binary
return "".join(pad(ord(c)) for c in string) | 46,733 |
def test_gitconfig(gitconfig: Path):
"""Test that a GIT configuration can be generated."""
assert gitconfig.exists() | 46,734 |
def print_statement(processor, composer, searcher):
# type: (Parser, Compiler, scanner.Scanner) -> Tuple[Parser, Compiler]
"""Evaluates expression and prints result."""
processor, composer = expression(processor, composer, searcher)
processor = consume(
processor,
searcher,
scan... | 46,735 |
def gmm_sky(values, **extras):
"""Use a gaussian mixture model, via expectation maximization.
of course, there's only one gaussian. could add another for
faint sources, bad pixels, but..."""
gmm = sklearn.mixture.GMM()
r = gmm.fit(values)
return r.means_[0, 0], np.sqrt(r.covars_[0, 0]) | 46,736 |
def does_translations():
"""Callback interface is able to inject Translator filter"""
genshi = current_app.extensions['genshi']
@genshi.template_parsed
def callback(template):
Translator(lambda s: s.upper()).setup(template)
rendered = Assert(render_template('i18n.html'))
expected = ('<... | 46,737 |
def getLocalTime(utc_dt, tz):
"""Return local timezone time
"""
import pytz
local_tz = pytz.timezone(tz)
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
return local_dt | 46,738 |
def test_finder_priority_file_over_page():
"""Test PackageFinder prefers file links over equivalent page links"""
req = InstallRequirement.from_line('gmpy==1.15', None)
finder = PackageFinder([find_links], ["http://pypi.python.org/simple"])
link = finder.find_requirement(req, False)
assert link.url.... | 46,739 |
def SyncSleep(delay, name=None):
"""Pause for `delay` seconds (which need not be an integer).
This is a synchronous (blocking) version of a sleep op. It's purpose is
to be contrasted with Examples>AsyncSleep.
Args:
delay: tf.Tensor which is a scalar of type float.
name: An optional name for the op.
... | 46,740 |
def admin():
"""
Adminページ
"""
return redirect(url_for('rooms')) | 46,741 |
def timer(interval):
"""
Decorator for registering a function as a callback for a timer thread. Timer object deals with delegating event
to callback function.
"""
def decorator(f):
timers = timer.__dict__.setdefault('*timers', [])
timers.append(Timer(f, interval))
return f
... | 46,742 |
def test_tablemodel(mock_program_dao):
"""Get a data manager instance for each test function."""
# Create the device under test (dut) and connect to the database.
dut = RAMSTKProgramInfoTable()
dut.do_connect(mock_program_dao)
yield dut
# Unsubscribe from pypubsub topics.
pub.unsubscribe(d... | 46,743 |
def common_start(stra, strb):
""" returns the longest common substring from the beginning of stra and strb """
def _iter():
for a, b in zip(stra, strb):
if a == b:
yield a
else:
return ""
return ''.join(_iter()) | 46,744 |
def write_3darray(fn, arr):
""" write 3d-array to ascii file
@param
@return
"""
with open(fn, "w") as fo:
for w0 in range(arr.shape[0]):
fo.write( "{}\n".format(w0) )
for w1 in range(arr.shape[1]):
for w2 in range(arr.shape[2]):
fo... | 46,745 |
def auto_weight(X, Y, model, resolution=0.01, limits=0.05, **kwargs):
"""Automatically determine the weight to use in the CPD algorithm.
Parameters
----------
X : ndarray (N, D)
Fixed point cloud, an N by D array of N original observations in an n-dimensional space
Y : ndarray (M, D)
... | 46,746 |
def max(self, parameter_max):
"""
It returns the maximum value of a parameter and the value's indexes.
Parameters
----------
parameter_max: str
Name of the parameter.
Returns
-------
max_dict: dict
Dictionary with the following format:
... | 46,747 |
def search(query):
"""
Searches your bucket. query can contain plaintext, and can also contain clauses
like $key:"$value" that search for exact matches on specific keys.
Returns either the request object (in case of an error) or a list of objects with the following keys:
key: key of the object
... | 46,748 |
def save_images(
image, directory=None, axis='z',
channel=None, global_norm=True,
image_format='PNG', progress=True):
"""
Serialize a 3D or 4D array into a series of PNGs for visualization.
image: A 3D or 4D numpy array. Supported dtypes: integer, float, boolean
axis: 'x', 'y', 'z'
channel: None, 0, ... | 46,749 |
def camel_to_snake(text: str) -> str:
"""
A helper function to convert `camelCase` to `snake_case`.
- e.g. `bestBigBrawlerTime` -> `best_big_brawler_time`
### Parameters
text: `str`
The text to restructure from `camelCase` to `snake_case`.
### Returns
`str`
The r... | 46,750 |
def check_and_create_tenant_udfs():
"""Checks if UDFs required for Cisco ACI are already present in BAM and creates them if they aren't."""
udf_attributes = {
'type': 'TEXT',
'defaultValue': '',
'validatorProperties': '',
'required': False,
'hideFromSearch': False,
... | 46,751 |
def get_stats(distance_results):
"""
list order: median, mean, min, max
:param distance_results:
:return: dictionary of stats
"""
if len(distance_results) == 0:
return {'median': 0, 'mean': 0, 'min': 0, 'max': 0}
else:
return {'median': median(distance_results), 'mean': mean(... | 46,752 |
def import_processor(lang: str, country: str = None, debug: bool = False) -> Dict:
"""
Import all task processors available for a given lang & country
"""
if debug:
print(".. IMPORT FROM:", lang, "/", country, file=sys.stderr)
if lang == TASK_ANY:
name = TASK_ANY
path = _LANG... | 46,753 |
def which(program):
"""which() acts like the unix utility which, but is portable between os.
If the program does not exist in the PATH then 'None' is returned.
"""
def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpat... | 46,754 |
def create(collection_id):
"""Create a mapping.
---
post:
summary: Create a mapping
parameters:
- description: The collection id.
in: path
name: collection_id
required: true
schema:
minimum: 1
type: integer
example: 2
reques... | 46,755 |
def project_onto_potential(r, D, q, F):
"""
TODO: add documentation
"""
n_iter = 0
rmag, rmag0 = np.sqrt((r * r).sum()), 0
lam, nu = r[0] / rmag, r[2] / rmag
dc = np.array(
(lam, np.sqrt(1 - lam * lam - nu * nu), nu)) # direction cosines -- must not change during reprojection
... | 46,756 |
def set_server_oidc_config(data, issuer, client_id, client_secret, scopes, group_claim, enable, default_role):
"""Set OpenID Connect server."""
oidc = {}
doit = False
if enable != None:
doit = True
oidc["enable"] = enable
if default_role != None:
doit = True
if defaul... | 46,757 |
def get_arc_proxy_lifetime(proxy_file=None):
"""
Returns the remaining lifetime of the arc proxy in seconds. When *proxy_file* is *None*, it
defaults to the result of :py:func:`get_arc_proxy_file`. Otherwise, when it evaluates to
*False*, ``arcproxy`` is queried without a custom proxy file.
"""
... | 46,758 |
def LLR_alt2(pdf, s0, s1):
"""
This function computes the approximate generalized log likelihood ratio (divided by N)
for s=s1 versus s=s0 where pdf is an empirical distribution and
s is the expectation value of the true distribution.
pdf is a list of pairs (value,probability). See
http://hardy.uhasselt.be/Fishtes... | 46,759 |
def load_configs(ex_dir):
""" Loads all configuration files into a list from the given experiment directory. """
configs = []
run_nums = get_run_nums(ex_dir)
for run_num in run_nums:
loc = ex_dir + '/' + run_num
try:
configs.append(extract_config(loc))
except:
... | 46,760 |
def create_app(item_model: Type[Item], db_session: Session) -> StacApi:
"""Create application with a custom sqlalchemy item"""
api = StacApi(
settings=ApiSettings(indexed_fields={"datetime", "foo"}),
extensions=[
TransactionExtension(
client=TransactionsClient(item_ta... | 46,761 |
def test_get_mri_head_t():
"""Test converting '-trans.txt' to '-trans.fif'"""
trans = read_trans(fname)
trans = invert_transform(trans) # starts out as head->MRI, so invert
trans_2 = _get_mri_head_t_from_trans_file(fname_trans)
assert_equal(trans['from'], trans_2['from'])
assert_equal(trans['to... | 46,762 |
def reducemin(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]):
""" ONNX ReduceMin to XLayer AnyOp conversion function """
return generic_reduce("ReduceMin", node, params, xmap) | 46,763 |
def mass(query,ts):
"""Calculates Mueen's ultra-fast Algorithm for Similarity Search (MASS) between a query and timeseries. MASS is a Euclidian distance similarity search algorithm."""
#query_normalized = zNormalize(np.copy(query))
m = len(query)
q_mean = np.mean(query)
q_std = np.std(query)
me... | 46,764 |
def get_matching_s3_objects(
bucket: str,
prefix: Sequence[str] = "",
suffix: str = "",
session: Optional[boto3.Session] = None,
) -> Iterator[ObjectTypeDef]:
"""Generate objects in an S3 bucket.
Args:
bucket: Name of the S3 bucket.
prefix: Only fetch objects whose key starts wi... | 46,765 |
def concept_categories():
"""概念类别映射{代码:名称}"""
db = get_db()
collection = db['同花顺概念']
pipeline = [
{
'$project': {
'_id': 0,
'概念编码': 1,
'概念名称': 1,
}
}
]
ds = collection.aggregate(pipeline)
df = pd.DataFram... | 46,766 |
def schema_validate(stack, schema_json):
"""Check that the schema is valid.
.. warning: TidyWidget index is hardcoded!
Parameters
----------
stack: pd.DataFrame
The stacked data.
schema_json: json
Full description
Returns
-------
"""
# Import library
from d... | 46,767 |
def MergeFilteredData(exp_type = "MDCK_WT_Pure"):
""" Merge all filtered data to a single txt.file,
Change the cellID naming from current '1', '2', etc to '1-pos0-17_07_31'
Args:
exp_type (string); "MDCK_WT_Pure" by default -> cell type to be analysed
Return:
None.
Wr... | 46,768 |
def test_toppra_linear(basic_constraints, basic_path, solver_wrapper):
"""Solve some basic problem instances.
Passing this test guaranetees that the basic functionalities are
inplace.
"""
vel_c, acc_c, ro_acc_c = basic_constraints
instance = toppra.algorithm.TOPPRA(
[vel_c, acc_c], basi... | 46,769 |
def hipotez_grafigi(X, y, teta):
"""
:param X: Ongorucu Degiskenler, Sinav Notlari
:param y: Hedef Degisken, Kabul Edilip Edilmedigi
:param teta: Parametreler
"""
pos_index = y.nonzero()[0]
neg_index = (y == 0).nonzero()[0]
plt.plot(X[pos_index, 0], X[pos_index, 1], '+', markeredgecol... | 46,770 |
def dict_to_config_str(config_dict):
"""Produces a version of a dict with keys (and some values) replaced with
shorter string version to avoid problems with over long file names in
tensorboard"""
key_abrv = {
"embedding_dimension": "ed",
"loss_type": "lt",
"initialize_uniform": ... | 46,771 |
def load_kernel_modules():
"""
Load kernel modules needed by the temperature sensor
if they are not already loaded.
If the base directory then does not exist an exception is raised an the kernel module loading
should be treated as failed.
:raises KernelModuleLoadError: if the kernel module coul... | 46,772 |
def wait_erased(fout,
prog,
erased_threshold=20.,
interval=3.0,
prog_time=None,
passn=0,
need_passes=0,
timeout=None,
test=False,
verbose=False):
"""
erased_threshold: ... | 46,773 |
def get_installed_reqs(site_packages_dir):
"""
Return the installed pip requirements as text found in `site_packages_dir`
as a text.
"""
if not os.path.exists(site_packages_dir):
raise Exception(f"site_packages directory: {site_packages_dir!r} does not exists")
# Also include these packa... | 46,774 |
def settle(people, rates, bills, decimal_places=2):
"""Calculate the smallest set of transactions needed to settle debts.
For each person we sum the money spent for her and subtract the money she
paid. We get the amount she should pay (it does not matter to whom from her
point of view). After she does,... | 46,775 |
def locate_in_services(fav_view, services_view, parent_window):
""" Locating and scrolling to the service """
model, paths = fav_view.get_selection().get_selected_rows()
if not paths:
return
elif len(paths) > 1:
show_dialog(DialogType.ERROR, parent_window, "Please, select only one item!... | 46,776 |
def destroy_ipset(name, sock=None):
""" Remove an ipset in the kernel. """
sock.destroy(name) | 46,777 |
def extract_ast_class_def_by_name(ast_tree, class_name):
"""
Extracts class definition by name
:param ast_tree: AST tree
:param class_name: name of the class.
:return: class node found
"""
class ClassVisitor(ast.NodeVisitor):
"""
Visitor.
"""
def __init__(se... | 46,778 |
def test_binarise_mask(od_mask_rects):
""" Test that `binarise_mask` works. """
binary_masks, mask, _, _ = od_mask_rects
assert np.all(binarise_mask(mask) == binary_masks) | 46,779 |
def restart():
""" Restarts gunicorn and nginx. """
gunicorn.restart()
nginx.restart() | 46,780 |
def checkIfNumberOfInstanceEnough(df):
"""
o Çok az satır varsa daha fazla veri toplanması sağlanmalıdır
o Aşırı çok satır varsa kısmi sampling yapılabilir.(Detayları göreceğiz)
o Data çokluğundan emin değilseniz tamamıyla deneyin. Eğitim süresi çok uzun sürüyorsa aşamalı olarak azaltabilirsiniz.
... | 46,781 |
def getAttribute(v, key):
"""
This function is mainly for retrive @@transducer/xxx property, and fantasy-land/xxx property.
We assume dict/object in Python may own such properties.
dict case:
d = {'@@transducer/init': lambda: True}
init_fn = getAttribute(d, '@@transducer/init')
obj case:
class T... | 46,782 |
def getdata(mca):
""" Extract the data contained in spectrum files
INPUT:
mca; path
OUTPUT:
Data; 1D-array """
name = str(mca)
name = name.split("\\")[-1]
name = name.replace('_',' ')
# custom MC generated files
if 'test' in name or 'obj' in name or 'newtest' ... | 46,783 |
def merge_dicts(dict_a, dict_b):
"""Recursively merge dictionary b into dictionary a.
If override_nones is True, then
"""
def _merge_dicts_(a, b):
for key in set(a.keys()).union(b.keys()):
if key in a and key in b:
if isinstance(a[key], dict) and isinstance(b[key], ... | 46,784 |
def adjust_contrast(inp, contrast_factor):
"""
Adjust Contrast of an image.
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
The inp image is expected to be in the range of [0, 1].
"""
if not isinstance(inp, torch.Tensor):
raise TypeErr... | 46,785 |
def sanity(k1, k2, name="sanity", n=None, tors=100):
""" test approximations and inequalities """
if n is None:
aggs = math.ceil(tors * 0.1) # tors * 2 / 24
cores = math.ceil(tors * 0.05) # aggs * 2 / 10 ?
n = tors + aggs + cores
xs = []
ys = []
ps = [0.5**i for i i... | 46,786 |
def geo(output_file):
"""
Quickly write out the initial and the final configuration of a nwchem
optimization to xyz files.
Args:
output_file (str): Output file of the nwchem calculation.
"""
data = nwchem.NwOutput(output_file).data[-1]
data['molecules'][0].to(fmt='xyz', filename='in... | 46,787 |
def test_hours_worked_format():
""" test if in one line the hours worked detail the format is incorrect """
calculate_payment = CalculatePayment(line="ANA=JA08:00-09:00", idx=0)
hours_worked = calculate_payment.get_hours_worked()
assert calculate_payment.check_hours_worked_format(hours_worked) == False | 46,788 |
def default_tiling():
"""Return default tiling options for GeoTIFF driver.
Returns
-------
dict
GeoTIFF driver tiling options.
"""
return {"tiled": True, "blockxsize": 256, "blockysize": 256} | 46,789 |
def read_template():
"""Loads a html template for jinja.
Returns:
str: The loaded template.
"""
html = 'image_template.html'
package = '.'.join([__name__, 'templates'])
return importlib.resources.read_text(package, html) | 46,790 |
def read_configs_from_yml(strategy_file_path: Optional[str] = None):
"""
Read global config and selected strategy yml files and save the values to corresponding config map
If a yml file is outdated, it gets reformatted with the new template
"""
from hummingbot.client.config.in_memory_config_map impo... | 46,791 |
def parse_training_labels(train_box_df, train_image_dirpath):
"""
Reads and parses CSV file into a pandas dataframe.
Example:
{
'patientId-00': {
'dicom': path/to/dicom/file,
'label': either 0 or 1 for normal or pnuemonia,
'boxes': list of box(es)
},
... | 46,792 |
def retryable_request(retries: Optional[Union[int, Retry]] = 1, *,
session: Session = None,
backoff_factor: float = None) -> Session:
"""Возвращает объект Session, который способен повторять запрос указанное число раз.
:param retries: Количество повторов.
:param ... | 46,793 |
def get_timeouts(timeout=None):
"""Ensures that both read and connect timeout are passed in
final patched requests call. In case any of it is missing in initial
call by the caller, default values are added"""
if timeout:
return timeout
return (Config.connect_timeout(), Config.read_timeout()) | 46,794 |
def configure_ip_on_tunnel_interface(
device,
interface,
ip_address,
mask,
tunnel_source,
tunnel_destination,
keepalive_timer = 10,
ip_mtu = None,
ipv6_address=None
):
""" Configure tunnel interface
Args:
device (`obj`): Device object
interface (`... | 46,795 |
def populateDayOverview(excelDataConsolidated:ExcelDataConsolidation, overviewSheetData) -> DayOverview:
"""Populates the Day Overview Object
Arguments:
excelDataConsolidated {ExcelDataConsolidation} -- [description]
overviewSheetData {[type]} -- [description]
Returns:
DayO... | 46,796 |
async def get_loading_images(mobi_app: str = "android", platform: str = "android",
height: int = 1920, width: int = 1080,
build: int = 999999999, birth: str = "",
credential: Credential = None):
"""
获取开屏启动画面
Args:
... | 46,797 |
def main():
"""Run a simple example that prints IR codes received on a Raspberry PI"""
# Set up GPIO on raspberry pi
ir_pin = 14
pi = pigpio.pi()
pi.set_mode(ir_pin, pigpio.INPUT)
decoder = irreceiver.NecDecoder()
collector = PiPulseCollector(
pi, ir_pin, ir_callback,
irrec... | 46,798 |
def bio():
"""Biometric recognition commands."""
pass | 46,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.