content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def convert_F_units(F, lbda, in_unit='cgs', out_unit='si'):
"""
Function to convert Flux density between [ergs s-1 cm-2 um-1],
[W m-2 um-1] and [Jy].
Parameters
----------
F: float or 1d array
Flux
lbda: float or 1d array
Wavelength of the flux (in um)
in_unit: str, opt... | 024f553870711258963c248f9303bbdabddf6d47 | 3,628,500 |
from game import Directions
def tiny_maze_search(problem):
"""Return a sequence of moves that solves tiny_maze.
For any other maze, the sequence of moves will be incorrect,
so only use this for tiny_maze.
"""
s = Directions.SOUTH
w = Directions.WEST
return [s, s, w, s, w, w, s, w] | 9205bdf5dfe45023dfe15afede6313c4f568f2b2 | 3,628,501 |
from ibmsecurity.appliance.ibmappliance import IBMError
import os.path
def export_metadata(isamAppliance, name, filename, check_mode=False, force=False):
"""
Export a federation
"""
ret_obj = search(isamAppliance, name)
fed_id = ret_obj['data']
if fed_id == {}:
raise IBMError("999", "C... | 8b6f446cc3e41fa060e148207c67cf77d4555430 | 3,628,502 |
def wkt_of_any(string):
"""Wkt of user input"""
out = osr.GetUserInputAsWKT(string)
if isinstance(out, str):
return out
else:
prj = None
with Env(_osgeo_use_exceptions=False):
gdal_ds = gdal.OpenEx(string, conv.of_of_str('raster'))
if gdal_ds is not None:
... | 64f981db275286a66f525487f6ecb58fc4bae685 | 3,628,503 |
import json
import traceback
def getDatial(request):
"""输入文章id,返回文章的metadata。代表用户点击,记录session
Args:
request (GET): arxivID:String,article的ID
Returns:
json: 该article的metadata,调用ORM接口查数据库
"""
try:
ret_dict = {}
arxiv_id = request.GET.get("arxivID")
arxiv_do... | 834bd01d550cc06eaefea6eea0bd3ca49bffec78 | 3,628,504 |
def trajectory_overlap(gt_trajs, pred_traj):
"""
Calculate overlap among trajectories
:param gt_trajs:
:param pred_traj:
:param thresh_s:
:return:
"""
max_overlap = 0
max_index = 0
thresh_s = [0.5, 0.7, 0.9]
for t, gt_traj in enumerate(gt_trajs):
top1, top2, top3 = 0,... | 14e5d52828ca198634a3e09557b501e7bc14c193 | 3,628,505 |
def adding_detail(request):
"""Контроллер изменение деталей из расчета"""
calc_id = request.POST.get("calc_id")
crud_details_in_calc(request)
return JsonResponse(current_details_in_calc_and_main_calc_info(calc_id=calc_id)) | d81bf4def024f7cf25ff4eaa1e0aec639d96b0cb | 3,628,506 |
def create_futures_list(futures, executor):
"""creates a new FuturesList an initiates its attrs"""
fl = FuturesList(futures)
fl.config = executor.config
fl.executor = executor
return fl | 04c0363ff623acee3c1eabe62c85264551d4fc84 | 3,628,507 |
def unittestResultsToXml(*, name='launch_test', test_results={}):
"""
Serialize multiple unittest.TestResult objects into an XML document.
A testSuites element will be the root element of the document.
"""
# The test_suites element is the top level of the XML result.
# launch_test results conta... | efe1ce547341310c4bf6a9a66747d531580857b7 | 3,628,508 |
def time_sa_to_s(t, clock_freq):
"""
convert from time in samples to time in seconds
"""
return float(t / clock_freq) | eabf76cda8529dc9c9ad0acc6466c5037062b295 | 3,628,509 |
import subprocess
def get_raw_containers():
"""
Runs the shell command to get the container all data from Docker.
:returns: The raw information from the `docker ps` command.
:rtype: str
"""
cmds = ["docker", "ps", "-a"]
out = subprocess.Popen(
cmds,
stdout=subprocess.PIPE,... | 17afb1fd5144e635ed95812b5e485ba9675ec1ac | 3,628,510 |
def create_positions(ranges, numpts):
"""Create a sequence of np.prod(nupmts) over the ranges.
Args:
ranges: list of 2-tuples, each tuple being [min, max] of a numerical range.
numpts: list of integers -- the number of equally spaced points
between [min, max] including the ... | a0efabfaa92c7686d99ac8186203e8134ddaed31 | 3,628,511 |
def mod(ctx, arg):
"""
"""
action = ctx.copy_last_action()
return action | e9007ffab406df13ddf01c6d65d58deaa713799c | 3,628,512 |
def kdcompare(r, p, depth):
"""
Returns the branch of searching on a k-d tree
Input
r: root
p: point
depth : starting depth of search
Output
A value of -1 (left branch), or 1 (right)
"""
k = len(p)
dim = depth%k
if p[dim] <= r.point[dim]:
return -1
... | c11aa24718b8a2d8d9e39852ca53e09118d3c215 | 3,628,513 |
import base64
def get_props(paths):
"""Return a hash of hashes of props for PATHS, using the svn client. Convert
each embedded end-of-line to a single LF character."""
# It's not kosher to look inside .svn/ and try to read the internal
# property storage format. Instead, we use 'svn proplist'. After
#... | 1323a896ba548d955662bab08f587058ca69cb71 | 3,628,514 |
def _calc_centers(graph, X, labelling, method='nearest'):
"""Return the new centers
graph : sparse matrix
Indicates the graph constructed from X
X : ndarray
Original Data
labelling: 1d array
The labelling of the vertices
method : one of 'nearest', 'floyd_warshall', 'eros... | 5d77bb871b5f80e3e7d97586faa2618e9f6ae04f | 3,628,515 |
def greaco_latin_square(k, factor_1_labels=None, factor_2_labels=None, seed=None):
""" Creates a k by k Greaco-Latin Square Design
A greaco-latin square is a design comprised of two orthogonal latin
squares. Note, there are no designs for k = 6.
Arguments:
k: the number of treatments.
... | 75eed4abd44d03486da2d5e3222f558bef35cde9 | 3,628,516 |
def get_poly_clock(params_array,section_str):
"""
Get list with poly from params array and section string.
Clock correction.
Parameters
----------
params_array : list
information from delay model ini file (see lib_ini_files.py).
section_str : str
section of the ini f... | efb11a1ebdfc997d8a274906549e5c28e506604d | 3,628,517 |
def hash_to_G2(data: bytes) -> G2:
"""Hashes a byte string to an element in G2."""
return G2(_relic.hash_to_G2(data)) | b36a86c0691d78ff333bd793bff1afb05eae058f | 3,628,518 |
def build_filter_stack(stack, options):
"""Setup and return a filter stack.
Args:
stack: :class:`~sqlparse.filters.FilterStack` instance
options: Dictionary with options validated by validate_options.
"""
# Token filter
if options.get('keyword_case'):
stack.preprocess.append(
... | 9504322b6e145a47a10f935e5c80fffdf3854500 | 3,628,519 |
def get_nuclear_mgc(data, meta):
"""
Determines the going marginal_cost for this technology
@ In, data, dict, request for data
@ In, meta, dict, state information
@ Out, data, dict, filled data
@ In, meta, dict, state information
"""
return {'reference_price': get_trunc_mgc(trunc, meta, 'nucle... | bd5f69f88b2c50ce23095393119a9e845434e85e | 3,628,520 |
from typing import Any
def efficientnet_b1(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> EfficientNet:
"""
Constructs a EfficientNet B1 architecture from
`"EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks" <https://arxiv.org/abs/1905.11946>`_.
Args:
... | 2dc6c00bbc0b4fc403b1a145cefb610b57b7c74e | 3,628,521 |
def StepToGeom_MakeParabola2d_Convert(*args):
"""
:param SC:
:type SC: Handle_StepGeom_Parabola &
:param CC:
:type CC: Handle_Geom2d_Parabola &
:rtype: bool
"""
return _StepToGeom.StepToGeom_MakeParabola2d_Convert(*args) | 0146754d635869627bbb19d712f2f115cc8302c9 | 3,628,522 |
def read_corpus(file_path, source):
""" Read file, where each sentence is dilineated by a `\n`.
@param file_path (str): path to file containing corpus
@param source (str): "tgt" or "src" indicating whether text
is of the source language or target language
"""
data = []
for line in open(f... | c3922030cf621a7bcadfc1f8fb12fce675db5034 | 3,628,523 |
def del_find(data, ID, cur_id, intlist, num_start):
"""ID - int ID человека, чей лог меняется
cur_id - list id высвеченных данных лога
intList - list номеров, введенных пользователем
return is_change, inter
is_change - bool были ли осуществлены изменения
"""
cur_index = data_index_for_k... | e01eef91ef04821ad1aff47c9d010e6916544754 | 3,628,524 |
def rechunk_to_single_chunk_if_more_than_one_chunk_along_dim(ds, dim):
"""Rechunk an xarray object more than one chunk along dim."""
if dask.is_dask_collection(ds) and dim in ds.chunks:
if isinstance(ds, xr.Dataset):
nchunks = len(ds.chunks[dim])
elif isinstance(ds, xr.DataArray):
... | 0d10e93c00a39e68c623c6d329c16d44b140e6d7 | 3,628,525 |
def update_payin(
db, payin_id, remote_id, status, error,
amount_settled=None, fee=None, intent_id=None, refunded_amount=None,
):
"""Update the status and other attributes of a charge.
Args:
payin_id (int): the ID of the charge in our database
remote_id (str): the ID of the charge in th... | 0964f6ef00d311d25f2ede1d9e858c6987b02776 | 3,628,526 |
def stack(x, num_block, size, stride, stack_index, block=basic):
""" A stack of num_block blocks. """
for block_index, s in enumerate([stride]+[1]*(num_block-1)):
x = block(x, size, s, stack_index, block_index)
return x | 1ad5b1eab9ecf85d19183d9b565828ab85b53f43 | 3,628,527 |
def twist2msg(twist):
"""
Converts a 6x1 twist vector into a geometry_msgs/Twist message
:type twist: numpy.array
:param twist: 6x1 twist matrix
:rtype: geometry_msgs.msg.Twist
:return The ROS Twist message
"""
twist2=np.reshape(twist, (6,))
return Twist(Vector3(twist2[3], twist... | 37bbcc30c607ba2bc31dbccccbbacbcc07801baf | 3,628,528 |
def z1FromAngles(wavelength, stt, om, chi, phi):
"""
Calculate the scattering vector z1 from angles
@param wavelength
@param om angle in radians
@param chi angle in radians
@param phi angle in radians
@return The z1 vector
"""
th = stt/2.
z4 = np.array([
(2. * sin(th) * c... | 58af195ba10fc1b5145e5512d6a4b6689ccf5212 | 3,628,529 |
import requests
import json
def sparqling(sparql_query, libraries, is_basic = True,
no_sequence = False, progress = True):
"""
the function querys "https://synbiohub.org/" for parts
Parameters
----------
path : STRING
Path to Excel Spreadsheet
sparql_query
libraries... | e088ea8e78d83400c2f2e252c2ac47ce80b69499 | 3,628,530 |
from typing import List
def convert_slide_binary_metadata_to_base64(slide: Slide) -> List[Slide]:
"""
Converts all binary data contained in the slide metadata to base64
"""
if slide.metadata is not None:
for metadata_key, metadata_value in slide.metadata.items():
if is_byte_data(me... | b1a8b1e5e8d65cbd32993363c1f7c1d7fce820bd | 3,628,531 |
def _has_class(domElement, className):
"""
Helper function to test if the provided element has the provided class
"""
return className in domElement.get_attribute('class').split(" ") | 9a20557cc8d3e3dc91ac33764a6d94139b70f6f2 | 3,628,532 |
def exponent(Cz, C):
"""Recover z such that C ** z == Cz (or equivalently z = log Cz base C).
For exponent(1, 1), arbitrarily choose to return 3"""
return 3 if (Cz == C == 1) else int(round(log(Cz, C))) | ded746c7231207b475b59dc13c57adfe42a039b1 | 3,628,533 |
def _remove_markers(sentence: str):
"""
removes the lemma markers from a sentence.
:param sentence: a string
:return: a string
"""
return sentence.replace(START_MARKER_TOKEN, '').replace(END_MARKER_TOKEN, '') | 7aac8959fb2795a2cbaec26a8cccbb948498bb4d | 3,628,534 |
def product():
"""
Import the test utils module to be able to:
- Create apigee test product
- Update custom scopes
- Update environments
- Update product paths
- Update custom attributes
- Update proxies to the product
- Update cust... | 883c74a19bc5e8e0f39fe314735b93b973f7642b | 3,628,535 |
def role_required(role, api=False):
"""flask view decorator implementing role based authorization; does not redirect to login for api views/routes"""
def _role_required(fnc):
@wraps(fnc)
def decorated_view(*args, **kwargs):
if not current_user.is_authenticated:
if ap... | 87276077c5b19ab9bdcfbaa7f84dc8315bac62b2 | 3,628,536 |
from typing import Tuple
from typing import List
from typing import Optional
from typing import Dict
from pathlib import Path
import sys
def dock_ligand(ligand: Tuple[str, str], software: str, receptors: List[str],
center: Tuple[float, float, float],
size: Tuple[int, int, int] = (10, 1... | 4d5b92e2e3dbe6f88d4dcee4b7c86b3964a33e8c | 3,628,537 |
def read_cof_file(cof_file, headerlength=12, as_shc_order=True):
"""Get coefficients from a cof-format file.
Read a .cof file and output the n,m, mixed gh arrays (1D)
gh can then be split into separate g,h arrays with convert_gh
Args:
cof_file (str): full path to the file to read
heade... | 5eff7c723b3fbd1d3af18b6e9af89fc1bac76d4c | 3,628,538 |
import torch
def get_mlp_models(level_params_list):
"""Get models based on level params and put them into level_algo_kwargs_list."""
level_algo_kwargs_list = []
for level_params in level_params_list:
model_kwargs = level_params["model_kwargs"]
algo_kwargs = deepcopy(level_params["algo_kw... | fdda720e6d0de3911e4d4c6b83835c2c3c635902 | 3,628,539 |
def format_datestamp(datestamp):
"""Format datestamp to an OAI-PMH compliant format.
Parameters
----------
datestamp: datetime.datetime
A datestamp.
Return
------
str:
Formatted datestamp.
"""
return datestamp.strftime('%Y-%m-%dT%H:%M:%SZ') | f050dd4f18691034c0414a4d9fa51629b0208d6a | 3,628,540 |
def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10):
"""
Demmel p 312
"""
p = b.copy()
r = b.copy()
x = np.zeros_like(b)
rdotr = r.dot(r)
fmtstr = "%10i %10.3g %10.3g"
titlestr = "%10s %10s %10s"
if verbose: print titlestr % ("iter", "residual norm", "... | 55df65c77b1179a8c30dca1d2722cca965b9c57e | 3,628,541 |
def output_handler(data, context):
"""Post-process TensorFlow Serving output before it is returned to the client.
Args:
data (obj): the TensorFlow serving response
context (Context): an object containing request and configuration details
Returns:
(bytes, string): data to return to ... | 01ae2b0f746570165ea632242a89fe71fc5f4c93 | 3,628,542 |
def create_pdna_net(gdf_nodes, gdf_edges, predistance=500):
"""
Create pandana network to prepare for calculating the accessibility to destinations
The network is comprised of a set of nodes and edges.
Parameters
----------
gdf_nodes: GeoDataFrame
gdf_edges: GeoDataFrame
predistance: in... | 8ce49525923d9b7436e4ef9f4f8252c5ad168e08 | 3,628,543 |
from typing import Counter
def quality_checks_qids(qids_to_relevant_passageids, qids_to_ranked_candidate_passages):
"""Perform quality checks on the dictionaries
Args:
p_qids_to_relevant_passageids (dict): dictionary of query-passage mapping
Dict as read in with load_reference or load_reference_f... | 42f42044bf723d5fba3772565521124441347cb9 | 3,628,544 |
def make_jinja_element_parser(name_parsers, content):
"""
`name_parsers` must be a list of tag name parsers. For example,
`name_parsers` can be defined as follow in order to parse `if` statements:
name_parsers = [P.string(n) for n in ['if', 'elif', 'else', 'endif']]
"""
if len(name_parsers... | e4d595093739b3b63a694a67f1399a615a0454f3 | 3,628,545 |
import base64
def encode_base64(data: bytes) -> bytes:
""" Creates a url safe base64 representation of an input string, strips
new lines."""
return base64.urlsafe_b64encode(data).replace(b"\n", b"") | 472ff045dc1df4ad5fe2a0e3001477a4d1c738fd | 3,628,546 |
from typing import Iterable
from typing import Optional
def non_none(iterable: Iterable[Optional[_T]]) -> Iterable[_T]:
"""
Make an iterator which contains all elements from *iterable* which are not *None*.
"""
return (x for x in iterable if x is not None) | cb10578c24c52cdbc97feaca5341e08ee5cb77c4 | 3,628,547 |
def extract_encoding(response: str) -> str:
"""Extract information about text encoding from HTTP Header or HTML meta tags.
Looks for charset in HTTP Content-Type Header and for HTML meta tags with attributes
http-equiv="Content-Type" and content="text/html; charset=XXX" or attribute charset="XXX".
res... | 0c07c835e960c7129f81b1633af71c92d2314093 | 3,628,548 |
from typing import Dict
def validate_403_response(integration_response: Dict, transaction: Transaction) -> Dict:
"""
Ensures the response returned from `process_sep6_request()` matches the definitions
described in SEP-6. This function can be used for both /deposit and /withdraw
endpoints since the res... | d5ce3526687eb0bc01984bfc7889d2593e17a4ce | 3,628,549 |
def _badge_color_mode(owner, repo):
"""Return badge (color, mode) for a repository."""
redis = utils.get_redis_for_cache()
if redis.sismember("badges", owner + "/" + repo):
return "success", "enabled"
return "critical", "disabled" | 6c05ed689d81a5843f46aa7b8f444e2d59f4712d | 3,628,550 |
def fetch(uri, fetcher):
""" fetch? Use this function to :download and [fetch]; a web resource into a specified
directory. Part of the [Interface] """
resource = download(uri, fetcher)
resource.origin_dir = Fs(fetcher.fetch_dir)
if resource.the_head_id.is_directory:
Make(resource.path).... | feb0791f120958c260ce7619d2f848ced5919893 | 3,628,551 |
def fillArray(data, mask=None, fill_value=None):
"""
Fill masked numpy array with value without demasking.
Additonally set fill_value to value.
If data is not a MaskedArray returns silently data.
"""
if mask is not None and mask is not False:
data = np.ma.MaskedArray(data, mask=mas... | 5e5c32cc02ecfb45429e6b96d473a0254a1baf22 | 3,628,552 |
def bio_hash_loss(weights: Array, x: Array, probs: Array) -> Array:
"""Calculates bio-hash loss from "Bio-Inspired Hashing for Unsupervised
Similarity Search"
(arXiv:2001.04907)
Args:
weights: model weights of shape output_features x input_features
x: input of shape batch x input_features
probs: p... | 60903b7dfa4cd978382301eff4fdc539b6086e31 | 3,628,553 |
import os
import subprocess
import time
def start_jupyter(instance, local_port=8889):
"""
This function tries to SSH onto the instance, remotely start a Jupyter notebook server, and forward given
local port to it.
"""
# Check onif key is available
key_name = instance["KeyName"]
key_path = ... | 3bc0b5186ea37757879e66492e0a5c1f0f7a06ca | 3,628,554 |
from typing import Dict
def train_model(data: Dict[str, Dataset], parameters: dict) -> Booster:
"""Train a model with the given datasets and parameters"""
# The object returned by split_data is a tuple.
# Access train_data with data[0] and valid_data with data[1]
model = lightgbm.train(params=paramet... | a66e616bb51499f74bcb6d4f353f0cbcf482127d | 3,628,555 |
def _bblock_hack(bc, bblock):
"""
The Tcl compiler has some annoying implementation details which must be
recognised before any reduction.
"""
# 'variable' does not push a result so the Tcl compiler inserts a push.
variableis = []
changes = []
for i, inst in enumerate(bblock.insts):
... | b8ffef65776bbf70d6874f130d723ce61cc1036e | 3,628,556 |
def yellow_bold(payload):
"""
Format payload as yellow.
"""
return '\x1b[33;1m{0}\x1b[39;22m'.format(payload) | 2ae528c9dcc5a4f9b5f685f201f4d6696387a256 | 3,628,557 |
def add_trial_name_as_number(warm_up_data_df):
"""add column where trial_name is converted to number and before-/after-correction is added"""
warm_up_data_df.insert(
warm_up_data_df.shape[1], "trial_name_corrected_by_before_and_after", float(100)
)
offset = 0
for index, row in warm_up_data_d... | 160907c14f377cae0c2067dac1dd898f4e343056 | 3,628,558 |
from typing import Optional
def get_language(request: Request) -> str:
"""Get language based on request Accept-Language header or 'lang' query parameter."""
lang: Optional[str] = request.query_params.get("lang")
language_code: Optional[str] = getattr(request, "LANGUAGE_CODE", None)
if lang and lang i... | b58ca8df0ac9856a06965affd156b4fc6bfc5288 | 3,628,559 |
def is_installed(package_name):
"""Checks if the app is installed."""
output = adb.run_shell_command(['pm', 'list', 'packages'])
package_names = [line.split(':')[-1] for line in output.splitlines()]
return package_name in package_names | 3ec3921415cfbbeed7ae51133364c60736745a29 | 3,628,560 |
import numpy
def int_L1_keldysh(ngr, ngi, L1f, L1b, L1i, tir, tii, D1, gr, gi, Gr, Gi):
"""Return L1bar."""
L1i_out = numpy.zeros(L1i.shape, dtype=complex)
for s in range(ngi):
dt = numpy.zeros((ngi))
for y in range(s, ngi):
dt[y] = tii[s] - tii[y]
gtemp = numpy.exp(dt[... | 6e46755434cdf0fc91f6bc60c59ffae46d548b7a | 3,628,561 |
def cosine_similarity(v, u):
"""Calculate the cosine similarity between two vectors."""
v_norm = np.linalg.norm(v)
u_norm = np.linalg.norm(u)
similarity = v @ u / (v_norm * u_norm)
return similarity | e4cc38d5d6ed43d59a2515ebde7cde3553a31767 | 3,628,562 |
def normalize(rendered):
"""Return the input string without non-functional spaces or newlines."""
out = ''.join([line.strip()
for line in rendered.splitlines()
if line.strip()])
out = out.replace(', ', ',')
return out | 02a87a7a5e596b45d15bb2559403e92cb69a2f1d | 3,628,563 |
import aiohttp
import asyncio
async def test_download_speed(session: aiohttp.ClientSession, url: str) -> int:
"""Count the amount of data successfully downloaded."""
result = 0
try:
async with session.get(url) as resp:
while True:
chunk = await resp.content.read(56)
... | c6ca9504f90cbb9091051931054f12f8498b8535 | 3,628,564 |
def scale_design_mtx(X):
"""utility to scale the design matrix for display
This scales the columns to their own range so we can see the variations
across the column for all the columns, regardless of the scaling of the
column.
"""
mi, ma = X.min(axis=0), X.max(axis=0)
# Vector that is True ... | 00f78d7be5bf4e521e07ad00dac9285623a6d929 | 3,628,565 |
from typing import Dict
def check_domain_filter(item: Dict, cfg: Config) -> bool:
"""
Validate that a given post is actually one that we can (or should) work on
by checking the domain of the post against our filters.
:param item: a dict which has the post information in it.
:param cfg: the config... | 504ccf76438da5437d360226dcf4a26c712cb1f2 | 3,628,566 |
from typing import Optional
from typing import List
def get_epistatic_seqs_for_landscape(landscape: potts_model.PottsModel,
distance: int,
n: int,
adaptive: bool = True,
... | 8e5bd9ae8ab3e1c88158c2df4917ffcd87179ce2 | 3,628,567 |
def compare_nodal_prices(df_dcopf, df_mppdc):
"""Find max absolute difference in nodal prices between DCOPF and MPPDC models
Parameters
----------
df_dcopf : pandas DataFrame
Results from DCOPF model
df_mppdc : pandas DataFrame
Results from MPPDC model
Returns
... | 2368bb7f8534ac466ab7858fa1056e3fe5f48f16 | 3,628,568 |
def add(a, b):
"""A dummy function to add two variables"""
return a + b | 4914b8d73e6808d93e8e8ee98902ad3b093f1ce6 | 3,628,569 |
def get_interconnect_regs(interconnect: Interconnect):
"""function to loop through every interconnect object and dump the
entire configuration space
"""
result = []
for x, y in interconnect.tile_circuits:
tile = interconnect.tile_circuits[(x, y)]
# cb first
for cb_name, cb in... | 58c620276133bce0fa04343dc7c4fe2721029ae3 | 3,628,570 |
def add_bg(sc):
""" Choose a background and add it to a scaper object (check the duration).
Args:
sc: scaper.Scaper, a scaper object to add a background to.
Returns:
scaper.Scaper object with the background added.
"""
sc.add_background(
label=("choose", []), source_file=("c... | f4f55cd627aa2b0b6c35657a077d91e0bf82c143 | 3,628,571 |
from typing import Optional
from typing import Mapping
from typing import Any
from typing import Type
import torch
from typing import Sequence
import time
import collections
def pipeline(
*,
dataset: HintOrType[DatasetLoader],
model: HintOrType[Model],
model_kwargs: Optional[Mapping[str, Any]] = None,... | 6c921d664f93439d30b7f58ac2a2e64c2646309f | 3,628,572 |
import hashlib
def sha224(binary: bytes) -> str:
"""
Overview:
SHA224 hash.
Arguments:
- binary (:obj:`bytes`): Binary data to be hashed.
Returns:
- digest (:obj:`str`): SHA224 digest string.
Examples::
>>> from hbutils.encoding import sha224
>>> sha224(b... | b992800e81861fcf6ff188d700577e662c7228fb | 3,628,573 |
from typing import Dict
from typing import Any
def get_telephone_number(input: Dict[str, Any]) -> str:
"""loop through JSON sample to find a specific response where
element reference is equal to 'TelNo'
and extract the telephone value of that specific response"""
print(f"Getting telephone number, plea... | 392f9600054f6c0a8cecc1865e1e4acde1f47c11 | 3,628,574 |
async def async_setup(hass: HomeAssistant, config: dict):
"""Cannot setup using YAML"""
return True | f2dc5691573ab4a5fceba2929af980d4ba382731 | 3,628,575 |
def get_next_on_schedule():
"""Returns a list of current and 6 next assigned slots
No request params.
"""
try:
data = [{
'time' : slot.time.strftime( '%H:%M' ),
'editor' : slot.editor.first_name + ' ' + slot.editor.last_name
} for slot in Slot.get_nex... | 5b88a9e50f1033ec2b4c933fdd31ee264422db3f | 3,628,576 |
def getErdosSectors(topm_dict,minimum_incidence=None):
"""Make Erdös sectorialization and return dict with main variables"""
if not minimum_incidence:
minimum_incidence=max(2,int(topm_dict["nnodes"]*0.01))
t=topm_dict
max_degree_empirical=max(t["degrees_"])
prob=t["nedges"]/(t["nnodes"]*(t[... | a8e0c336c7b790a4dba95d09f6cdad71b0eb972b | 3,628,577 |
def truncate(s, eps):
"""
Find the smallest k such that sum(s[:k]**2) \geq 1-eps.
"""
mysum = 0.0
k=-1
while (mysum < 1-eps):
k += 1
mysum += s[k]**2
return k+1 | fc9b5984316e969961b496fd54425e4f52f025ff | 3,628,578 |
def transform_pose_msg(msg, child_frame_current, child_frame_new):
"""
transform pose in given msg
"""
def pose_msg_to_matrix(msg):
translate = [msg.position.x, msg.position.y, msg.position.z]
angles = tf.transformations.euler_from_quaternion([msg.orientation.x, msg.orientation.y, msg.or... | 2d063e5f5a3906cd5811dcc589bf2e121037eb00 | 3,628,579 |
import six
def validate_uuid4(uuid_string):
"""Validate that a UUID string is in fact a valid uuid4.
Happily, the uuid module does the actual checking for us.
It is vital that the 'version' kwarg be passed
to the UUID() call, otherwise any 32-character
hex string is considered valid.
"""
... | 12608245047e62a5ad56e755245675810601b107 | 3,628,580 |
def nmi(vanilla_result, fair_result, seed=0):
"""
calculate normalized mutual information (NMI)
:param vanilla_result: vanilla mining result
:param fair_result: debiased mining result
:param seed: random seed
:return: NMI between vanilla mining result and debiased mining result
"""
# kme... | 4f7a5800e620c0cf05baa0fe259bfc8ce21a9ed9 | 3,628,581 |
def list_to_str(items):
"""
:param items:
:return:
"""
mystr = ''
for item in items:
mystr += item
return mystr | 6530a33641f261888094d4ecb6fff469a97d6c10 | 3,628,582 |
def prefixed_collapsible_map(m, prefix):
"""
Return a dict of params corresponding to those in m with the added prefix
"""
if m == values.unset:
return {}
def flatten_dict(d, result=None, prv_keys=None):
if result is None:
result = {}
if prv_keys is None:
... | 7007da04faf43d0b1b0293767cd4c6c89d3edb33 | 3,628,583 |
import torch
def to_minmax_form(boxes):
"""
:param boxes: (n, 4) tensor, (xmin, ymin, xmax, ymax) form.
:return: (n, 4) tensor, (cx, cy, w, h) form
"""
xmin = boxes[:, 0] - boxes[:, 2] / 2 + 0.5
ymin = boxes[:, 1] - boxes[:, 3] / 2 + 0.5
xmax = boxes[:, 0] + boxes[:, 2] / 2 - 0.5
ymax... | f00f703c78db7926bbea684147facc6fa553ac67 | 3,628,584 |
def apps(request):
"""
apps
"""
return render_mako_context(request, '/demo/apps.html') | f25b54236f582e8fcf87b3bf90009181bab4aa37 | 3,628,585 |
def compute_unfolded_dimension(xtypes):
"""
Returns x dimension (int) taking into account unfolded categorical features
"""
res = 0
for xtyp in xtypes:
if xtyp == FLOAT or xtyp == INT:
res += 1
elif isinstance(xtyp, tuple) and xtyp[0] == ENUM:
res += xtyp[1]
... | cf3c47d7c97b00fd05e888fc85575f594841647d | 3,628,586 |
async def report_exc_info(
exc_info=None, request=None, extra_data=None, payload_data=None, level=None, **kw
):
"""
Asynchronously reports an exception to Rollbar, using exc_info (from calling sys.exc_info())
exc_info: optional, should be the result of calling sys.exc_info(). If omitted, sys.exc_info()... | e677fe7d4d4b13658ec331129b3aeeae9b66733e | 3,628,587 |
from typing import Dict
def validate_input_parameters(
input_parameters: Dict, original_parameters: Dict
) -> Dict:
"""Validate input parameters.
:param input_parameters: dictionary which represents additional workflow input parameters.
:param original_parameters: dictionary which represents original... | f31c025ce8c8b345fc2a84f98aed3cd2dd8aa179 | 3,628,588 |
from datetime import datetime
def getHirlamSimulationEndTime(root, datetime_format):
"""Helper function for getting the ending time for the latest simulation from HIRLAM XML-response."""
try:
# get the starting time by finding the tags "resultTime" and "timePosition"
result_time_elem = [elem f... | 36c5edbf8b9ed70bdcdda1605d32f9cbcc8073a9 | 3,628,589 |
import re
def GFFParse(ref_file):
"""Extracting annotated features from a GFF file based on feature identifier mapping."""
genes, transcripts, exons, utr5, utr3, cds = dict(), dict(), dict(), dict(), dict(), dict()
ref_fh = open(ref_file, 'rU')
for gln in ref_fh:
gln = gln.strip('\n\r').split... | f28cd187bcd27cfe69b0a151a9b7e120ff632a74 | 3,628,590 |
def get_all_compiler_versions():
"""Returns a sorted list of strings, like "70" or "80" or "9.0"
with most recent compiler version first.
"""
versions=[]
if is_windows:
if is_win64:
keyname = 'Software\\WoW6432Node\\Intel\\Compilers\\C++'
else:
keyname = 'Soft... | 2c8e712e054f5588f7331ac31e943b3bcc87ea23 | 3,628,591 |
import re
def detect_resolution(paths):
"""Attempt to detect the input resolution from a list of paths.
Args:
paths (list): List of file paths.
Raises:
ResolutionDetectionException: If there are too many possible resolutions in a path.
ResolutionDetectionException: If there are i... | 76458ba30b4f0c065915946e06238b7f59375c8a | 3,628,592 |
def configure_plotting_functions(
db_conn, read_bundled_simulation_results_from_db, extract_simulation_result,
n_simulation_results, simulation_result_name, extract_display_info,
compile_plot_annotation_text, node_names, output_dirpath, is_single_process,
pdf_page_limit, image_formats_an... | 065eaa7687cd3674c2eadab75d76c3992729c899 | 3,628,593 |
def compute_mean_nutrient_intake(nutrient_intake):
"""Compute mean nutrient intake"""
nutrient_totals = nutrient_intake.sum()
total_count = nutrient_intake.count()
carb_mean = (nutrient_totals[0]/total_count)
fiber_mean = (nutrient_totals[1]/total_count)
fat_mean = (nutrient_totals[2]/total... | ff79f816162a8f555d5deb582eb9647f1cef66b9 | 3,628,594 |
def __(string):
"""Emojize a text, wrapping ``use_aliases``.
Args:
string (str): string to emojize.
Returns:
An emojized string.
"""
return emojize(string, use_aliases=True) | ecf6e8907961aa21c0f8cba866d9919ed9f5ab49 | 3,628,595 |
def preserve_channel_dim(func):
"""Preserve dummy channel dim."""
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2:
result = np.expand_dims(resul... | 709dfce7404eaa40d395ec273fb85b2ca42764ce | 3,628,596 |
import traceback
def redirect_auth_oidc(auth_code, fetchtoken=False, session=None):
"""
Finds the Authentication URL in the Rucio DB oauth_requests table
and redirects user's browser to this URL.
:param auth_code: Rucio assigned code to redirect
authorization securely to IdP via... | ec70b5c5d1b264ad48569fa955f0edcaaa1374fa | 3,628,597 |
def inception_crop_with_mask(
image, mask, resize_size=None, area_min=5, area_max=100):
"""Applies the same inception-style crop to an image and a mask tensor.
Inception-style crop is a random image crop (its size and aspect ratio are
random) that was used for training Inception models, see
https://www.cs.... | 2f342b49035fd9a6e095a2debae3df6250718ec9 | 3,628,598 |
import os
def delete_outputs(config, outcfg):
"""
Remove pipeline outputs to save memory
after running the job
Parameters
----------
config : dict-like
Input configuration of job. Uses
config["management"]["delete"] (list of key
used to index outcfg) to determine
... | 1edf02ae14a755f77899c6d3be05ff11a2d6bcf3 | 3,628,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.