content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from .config import Section
def format_print_text(text: str, *, color_fg: str = None, color_bg: str = None) -> str:
"""Format given text using ANSI formatting escape sequences.
Could be useful for print command.
:param text:
:param color_fg: text (foreground) color
:param color_bg: text (backgro... | 5e988bb693d9c4ad1efd9a2718c72eba1d27c9b2 | 3,613,694 |
def get_emb_sz_list(dims: list):
"""
For all elements in the given list, find a size for the respective embedding through trial and error
Each element denotes the amount of unique values for one categorical feature
Parameters
----------
dims : list
a list containing a number of integers.... | 65509869e99f08bbbd1fbaf7a7d3fe364e55b053 | 3,613,695 |
def evaluate_topic_models(data, varying_parameters, constant_parameters=None, n_max_processes=None, return_models=False,
metric=None, **metric_kwargs):
"""
Compute several Topic Models in parallel using the "gensim" package. Calculate the models using a list of varying
parameters `... | 5cec9eeb505bffd6d8300b787c14f8823d28bd0d | 3,613,696 |
from typing import Union
def convert_weblogo_color(color: Color, color_format: str) -> Union[tuple, str]:
"""Convert weblogo Color to Bokeh color object
Note: Weblogo colors are RGB but fractional [0, 1],
whereas Bokeh and draw_alignment are [0, 255]
:sa: https://github.com/WebLogo/weblogo/blob/mast... | 56838285486880cd04a036c19989d5f0ee6f6307 | 3,613,697 |
def BenfordDQ(impath):
"""
Main driver for ADQ3 algorithm.
Args:
impath: Input image path, required to be JPEG with extension .jpg
Returns:
OutputMap: Output of ADQ3 algorithm (2D array).
"""
if impath[-4:] == '.jpg':
try:
im = jio.read(impath)
excep... | 59dec79063c84a3e9d8608e8d6af2400641113ae | 3,613,698 |
def yuanshan_weir_ecological_base_stream_flow():
"""
Real Name: YuanShan Weir Ecological Base Stream Flow
Original Eqn: 198720
Units: m3
Limits: (None, None)
Type: constant
2.3cms, equals 198720 m^3 per day
"""
return 198720 | adebe3b4b18400903a54cf9d537ec6d8ec57c9a0 | 3,613,699 |
from typing import Callable
from typing import Tuple
def generate_repr_factor_batch(dataset: BaseDataset,
repr_fn: Callable[[Tensor], Tensor],
batch_size: int,
num_points: int
) -> Tuple[np.ndar... | 98cceb8b536c1884feaa5d00e4a09462d1ee58b2 | 3,613,700 |
from typing import Union
import configparser
from pathlib import Path
def get_config(path_to_config: Union[PosixPath, WindowsPath]) -> tuple:
"""Function to get config file and retrive data that is needed
for the script to run
Args:
path_to_config (Union[PosixPath, WindowsPath... | c858f577829a843f9ea83280da91713522d939ff | 3,613,701 |
from typing import List
from typing import Tuple
def parse_sdl_attrs(prefix: str, all_names: List[str]) -> Tuple[str, str]:
"""Return the name/value pairs, and the final dictionary string for the
library attributes with `prefix`.
Append matching names to the `all_names` list.
"""
names = []
l... | 49ea245dfc33d4d0f325e81e655ac6c71976c2d5 | 3,613,702 |
def get_doc_id_filter(doc_id_set):
"""
This function returns a filter which removes any documents not in
doc_id_set.
This filter does not alter record_dict, but instead returns either true or
false indicating whether to document should be kept or not.
Parameters
----------
doc_id_set :... | 7a62a6cf8a290947174183c97fdfc398781d5b19 | 3,613,703 |
def ldrpc_source_address(line):
"""Calculate the absolute source address of a PC-relative load.
'line' is a line returned by disassembly_lines().
If it doesn't look like the right kind of instruction, returns None.
"""
# Example: ldr r2, [pc, #900] ; (0x000034b4)
if line.op == 'ldr' and l... | de9ffb9a3e7f1b6a66c6f6727c6d4e37fc42a4b7 | 3,613,705 |
import torch
def load_cifar10_class_subsets(classes, train=True, device="cpu", dtype=torch.float, minmax=(0, 1.0)):
"""
Load and return a subset of the CIFAR10 dataset, including only the
specified classes.
- classes: a list of class indices (as returned by label_class_list()
- minmax: transform ... | e9eed9237614acc21d35fca0e4d743c2bd3de7fb | 3,613,706 |
import numpy
def ROCData_from_results(results, clf_index, target):
"""
Compute ROC Curve(s) from evaluation results.
:param Orange.evaluation.Results results:
Evaluation results.
:param int clf_index:
Learner index in the `results`.
:param int target:
Target class index (i... | 880ea120ac992cfa643093a8e350afe88864503a | 3,613,707 |
def readFileOrGz(file, defStr = None):
""" read a file and return its contents. If the file ends in .gz, use gunzip on it """
if file.endswith(".gz"):
return readPipe("gunzip < '" + file + "'", defStr)
else:
return readFile(file, defStr) | 0beb209ea116f60d051187c0cb01786ee47d54c2 | 3,613,708 |
import pathlib
def check_input(linkerpad, rechterpad, seltype):
"""parse input
"""
if linkerpad == "":
return 'Geen linkerbestand opgegeven'
else:
if not pathlib.Path(linkerpad).exists():
return 'Bestand {} kon niet gevonden/geopend worden'.format(
linkerpad... | b8ae7a7f2d8f25d0054b4670ff8acb3ebadf0384 | 3,613,709 |
def vm_parser():
""" Create a ArgumentParser. """
return create_vm_parser() | 163d150f1983931deee233179a20330eaf118c91 | 3,613,710 |
from typing import Optional
def mempool_assert_my_coin_id(
condition: ConditionVarPair, unspent: CoinRecord
) -> Optional[Err]:
"""
Checks if CoinID matches the id from the condition
"""
if unspent.coin.name() != condition.var1:
return Err.ASSERT_MY_COIN_ID_FAILED
return None | 5f0db392c645938b69d52992b1d9a2012e11599c | 3,613,711 |
from typing import Dict
def delete_bucket(name: str, aws_auth: Dict[str, str] = {}) -> bool:
"""Delete an S3 bucket.
Parameters
----------
name : str
Name of the bucket to delete.
aws_auth : Dict[str, str], optional
Contains AWS credentials, by default {}
Returns
-------... | accc4a2d0ae1c1b9e75d177032dc9db18f216c35 | 3,613,712 |
def does_component_need_db(component):
"""Return whether the component needs DB to run tests.
Useful to determine which components need a Postgres DB container to run the tests.
:param component: standard component name
:type component: str
:return: True/False whether the component needs DB
:... | a1e068f68c479a2a6fc773b74fd2229638594290 | 3,613,713 |
def has_normal_exit_message(output_string):
""" does this output string have a normal exit message?
"""
pattern = ('The final electronic energy is' +
app.one_or_more(app.WILDCARD) +
'This computation required')
return apf.has_match(pattern, output_string, case=False) | fae499e7d97bab3eb17757c76541fb3fb2c059a8 | 3,613,715 |
import torch
def _vector(weights, u):
"""
Performs systematic resampling of a 1D array log weights.
:param weights: The weights to use for resampling
:type weights: torch.Tensor
:return: Resampled indices
:rtype: torch.Tensor
"""
n = weights.shape[0]
probs = (torch.arange(n, dtype=... | 640aa0ed95dc1eb7994ff9b15edb757867f60d33 | 3,613,716 |
def post_list(request, topic=None, cache_key='', extra_context=dict(), template_name="post_list.html"):
"""
Post listing. Filters, orders and paginates posts based on GET parameters.
"""
# The user performing the request.
user = request.user
# Parse the GET parameters for filtering information
... | b57384f6b6fdf6d970000310cff8f38a523d6ec0 | 3,613,717 |
from mmdet3d.core.bbox import points_cam2img
import copy
import torch
def draw_camera_bbox3d_on_img(bboxes3d,
raw_img,
cam_intrinsic,
img_metas,
color=(0, 255, 0),
thic... | f610259cd23eeb61301b473597a340f0196c0cd6 | 3,613,718 |
import requests
def get(endpoint: str, parametros: dict = None) -> dict:
"""
Realiza um requisição HTTP do tipo GET para a API da Lomadee
:param endpoint: Endpoint da requisição
:type endpoint: str
:param parametros: Parâmetros da requisição
:type parametros: dict
:return: Dados da Resp... | 78ccb1888ad3cb4e73fddaa9c47ac868d8148300 | 3,613,719 |
def tool_shed_client(gi=None):
"""
Get an instance of the `ToolShedClient` on a given Galaxy instance. If no
value is provided for the `galaxy_instance`, use the default provided via
`load_input_file`.
"""
if not gi:
gi = galaxy_instance()
return ToolShedClient(gi) | a040852377a4752cc5c9012fc8d68705c200737f | 3,613,720 |
def move_file_to_s3(local_filename, hash_digest, destination_filename):
"""Considered making this a celery task, but don't think the file created on `web` is available on `worker`
so lets wait to see if we even need the async.
"""
s3_client = boto3.client('s3')
try:
response = s3_client.u... | d6e784cc9c9106bc2e0324f7939e77727352f3f1 | 3,613,721 |
def create_commits_to_prs_mapping(linege, prs):
"""create a mapping from commits to the pull requests that the commit is
part of
"""
commits_to_prs = {}
# make a copy of this list to avoid side effects from calling this function
my_prs = list(prs)
commit_data = cache_commit_data(my_prs)
... | 48c9753151621638ed41a01b886b758ce351c0b4 | 3,613,722 |
def class_to_json(obj):
"""
function that returns dictionary description with simple data structure
for JSON serialization of an object
"""
return obj.__dict__ | d3b044a62d1c6142959923f0963e438675ef7bbf | 3,613,723 |
def ITE(s, d1, d0, simplify=True, factor=False):
"""Factory function for Boolean If-Then-Else expression."""
s = Expression.box(s)
d1 = Expression.box(d1)
d0 = Expression.box(d0)
expr = ExprITE(s, d1, d0)
if factor:
expr = expr.factor()
elif simplify:
expr = expr.simplify()
... | 83ba93b3d74943d08c5b8420340c2dddaff0d803 | 3,613,724 |
import _ctypes
def key_generate(key_type=KEY_TYPE.SYMMETRIC,
key_bit_length=KEY_BIT_LENGTH.L256BIT):
"""Generates a secure key or key generation parameters
(or an Initialization Vector)."""
key = _ctypes.c_void_p()
_lib.yaca_key_generate(key_type.value, key_bit_length,
... | 39b9c91d01d396226e47c57e9c41467fe2bac62d | 3,613,725 |
import ipaddress
def is_allowed(yaml, ifname, iface_addresses, ip_interface):
"""Returns True if there is at most one occurence of the ip_interface (an IPv4/IPv6 prefix+len)
in the entire config. That said, we need the 'iface_addresses' because VPP is a bit fickle in
this regard.
IP addresses from th... | c8e7dbf5b1708062bc24cb8ebc640fd8588a9244 | 3,613,726 |
def string(text, is_return_null=False):
"""
sql字符串拼接专用函数
会在字符串两边添加'单撇号,用于生成数据库sql语句
:param text: 需要添加'的字符串
:param is_return_null: 是否返回null,是的话在字符串为空时返回null,否则返回''
:return:
"""
if not text is None and text != '':
return "'" + str(text) + "'"
elif not is_return_null:
re... | e02ac1f120e79985fb15de05c667dfd248476ff1 | 3,613,727 |
def addDhcpHostEntry(dhcpGroup, hostEntry):
"""
Adds a host entry in the group section if not already there.
Return True or False, depending on whether the entry was added or not.
"""
# Next we check if the host entry needs to be created.
if dhcpGroup.contains(DhcpConfEntry.Type.Host, hostEntry... | 45e83b29f6794e014e88fee45ea730d8f38ccb4f | 3,613,728 |
from datetime import datetime
def do_pack():
"""Do_pack function"""
today = datetime.datetime.now()
file_local = 'versions/web_static_{}{}{}{}{}{}.tgz'.format(today.year,
today.month,
... | d8c1b317b5d2682ace886d9e954f24b88607dd62 | 3,613,729 |
def get_logistic_regression_dataset(dimension, num_samples_per_client, num_clients):
"""Creates logistic regression datset.
Returns:
A `(train, test)` tuple where `train` and `test` are `tf.data.Dataset` representing
the test data of all clients.
"""
beta = tf.random.normal(shape = (dimension,... | 884c78f6fd6eed38fd10f9f1d69a71a1c1e65efb | 3,613,730 |
def get_available_benchmark_files():
"""
Returns a list of dicts containing metadata of the available benchmark files for tests on the
nussl External File Zoo (EFZ) server (http://nussl.ci.northwestern.edu/).
Each entry in the list is in the following format:
.. code-block:: python
{
... | e59a7ed4a653507d98f3c2a3199d66076ce1935a | 3,613,731 |
def DecodeMappingPairs(MappingPairs):
"""Decode mapping pairs, return a list of (offset, length) tuples.
In these tuples, both items refer to clusters. Sparse ranges have the offset item set to None.
"""
data_runs = []
i = 0
curr_offset = 0
while True:
if i >= len(MappingPairs):
... | ca5947218c95d60ca7d850a0debf50c2870dd21c | 3,613,732 |
def to_time_major(tensor: tf.Tensor) -> tf.Tensor:
"""Transposes batch majored tensors to time major."""
dimensions = tf.nest.map_structure(lambda x: x.get_shape().ndims, tensor)
def _transpose(value, dimension):
if dimension > 1:
# Swap the first dimension (batch) with the second (time)
return t... | 4594e9122e51b0f955a0bd9d5aec01b7512176d4 | 3,613,733 |
def get_swap_targets(node):
""" All pairs of columns that do not have the same types in every cell """
pairs = []
n_col = node.table.n_col
for i in range(n_col):
col_i = node.table.get_col(i)
for j in range(i + 1, n_col):
col_j = node.table.get_col(j)
same = True... | 372d2fed3c2e1544f20f69a3166b5773f954736e | 3,613,735 |
import functools
import operator
def product (nums):
"""
get the product of numbers in an array.
"""
return functools.reduce(operator.mul, nums, 1) | 801b3e9c3fe9229eaf8ad58fe73a9a1e63506b41 | 3,613,736 |
def string_is_hex(color_str):
"""
Returns whether or not given string is a valid hexadecimal color
:param color_str: str
:return: bool
"""
if color_str.startswith('#'):
color_str = color_str[1:]
hex_regex1 = QRegExp('^[0-9A-F]{3}$', Qt.CaseInsensitive)
hex_regex2 = QRegExp('^[0-... | 94a8f263bf626b7e88f87e7fd27298e6dc58beab | 3,613,737 |
def _get_parameters(kwargs):
"""
get the parameters for searching
The format of input could be a name of parfile, a dictionary, or standard python function arguments.
"""
#check whether input parameters are surpportted
_parameters_legal(kwargs)
#read parfile and parameters
if "parfil... | 6ffa237929bf3ef15b9de1ef2372f79517e93ebc | 3,613,738 |
def set_colors(dictionary):
"""
This function takes the values in a dictionary and attributes them an RGB color.
:param dict dictionary: dictionary with variables to be attributed a color, as values.
:return: Dictionary where 'dictionary' values are keys and random RGB colors are the values.
"""
... | ab59e91c60923604827a04d559f99346ad173bb2 | 3,613,740 |
import numpy
def GetSeries(ds,ThisOne,si=0,ei=-1,mode="truncate"):
""" Returns the data, QC flag and attributes of a series from the data structure."""
# number of records
if "nc_nrecs" in ds.globalattributes:
nRecs = int(ds.globalattributes["nc_nrecs"])
else:
nRecs = len(ds.series[Thi... | 91bb59d4b0aa3551c044c738ef29e6b6ff9e7fe3 | 3,613,741 |
def many_constants():
"""Generate Python code which includes >256 constants."""
return "".join(f'a = {i}\n' for i in range(300)) | 8b06dac948ebf7467824221161161d8d8cacef1d | 3,613,742 |
from typing import Optional
from typing import Dict
def face(
draw,
raw_strategy: Optional[SearchStrategy[dlib.full_object_detection]] = None,
frame_strategy: Optional[SearchStrategy[Frame]] = None,
landmarks_strategy: Optional[
SearchStrategy[Dict[FaceFeature, PointSequence]]
] = None,
) ... | ffb87db487dc6e38e0c9844f1d7f61dc75f8bf29 | 3,613,743 |
def mosaic_register(outroot, refImage, diffPA):
"""
Register images for a mosaic. This only calculates the exact
shifts between each image... it doesn't do the combining.
@param outroot: The root for the output image. The resulting
shifts will be written into a file called <outroot>.shifts
@typ... | 2381ebb1dee37ac9d577229debe85741c4a5f459 | 3,613,744 |
import numpy
def USgraph_Random(N,L):
"""
Generates a connected ultra-short graph, random case.
Generates a graph with shortest possible pathlength (largest possible
efficiency) by adding edges randomly to an initial star graph.
Reference and citation
^^^^^^^^^^^^^^^^^^^^^^
G. Zamora-Lóp... | 819ccec9f7b4eddb42b23f3c90f9e51fe70d3725 | 3,613,745 |
import re
def remove_parentheses(s: str) -> str:
"""Returns the string without the parts in parentheses."""
while s != ( s:= re.sub( r"\([^(]*?\)", "", s ) ):
pass
return s | a8a4f9cfe536997be1277d16682f8bb65b833e3d | 3,613,747 |
def import_examples_main(examples_pkg, original_sub, redone_sub, example_names):
"""
Import the main() function of sereral original and redone example modules.
The main() functions are returned in two lists that contain the original main()s
and the redone main()s respectively, and in the same order as ... | 44964ea185a07d88593f5fdf731b0df9dbfe5b8a | 3,613,748 |
def _model_class_key(model_class: BaseModelParamsT) -> str:
"""Retrieves a model key from the model class."""
path = model_class.__module__ + '.' + model_class.__name__
# Removes model_registry from `...lingvo.jax.model_registry.`.
prefix = _model_class_key.__module__.replace('.model_registry', '.')
return pa... | d70ab139d1a246b2628a368c25f00a692600f0c2 | 3,613,749 |
import numpy
def GetConformerRMS(mol, confId1, confId2, atomIds=None, prealigned=False):
""" Returns the RMS between two conformations.
By default, the conformers will be aligned to the first conformer
of the molecule (i.e. the reference) before RMS calculation and,
as a side-effect, will be left in the align... | 047f9232044a550b0c6cb96e1817e4f02fabe53c | 3,613,750 |
def covert_excel_list(path: str, sheet_name=None, fill_merged_cell=True) -> list:
"""
pandas 读取 excel 内容转换为 List
:param path: 数据文件路径
:param sheet_name: sheet 名
:param fill_merged_cell: 是否填充合并的单元格,默认需要
:return: 数据列表 list[dict]
"""
return convert_data_file_2_list(path, pd.read_excel, sheet... | e9c1ef63385b602b6c3cdd2c2fc239208dad03d6 | 3,613,752 |
def parse_docker_local_ports(docker_ports):
"""
Take a docker publish port formatted string and return the local port
Args:
docker_ports: string representation of a docker port publish format
Returns:
The parsed local port string
"""
if not isinstance(docker_ports, list):
... | ba585c535c37fcfbf57d410b68071215e46654a7 | 3,613,753 |
def SelectComponent(ds, idxs):
"""
Select / reorder components from datapoints.
Args:
ds (DataFlow): input DataFlow.
idxs (list[int]): a list of component indices.
Example:
.. code-block:: none
dp: [c1, c2, c3]
idxs: [2,1]
output dp: [c3, c2]
"""
r... | a16942c4d9044a78370f9a243dc8dc47c973a18e | 3,613,754 |
import random
def any_process_info_by_state(state):
""" Return a copy of any process in state 'state' in database. """
info = random.choice([info for info in ProcessInfoDatabase if info['state'] == state])
return extract_process_info(info) | 58e248a658550fd4427db98506ceec8f88eb3970 | 3,613,755 |
import array
def entryfunc_namedtuple(buf: bytes, pos: array, globaloffset: int) -> Entry:
"""
Build a FASTQ entry as a namedtuple with attributes header, sequence,
and quality.
- buf: bytes-like object
- pos: array of indices/positions in `buf`
"""
header = buf[(pos[0]+1):pos[1]]
se... | 7b2cfea70015b26630d315306d653e081cd290ca | 3,613,756 |
def generate_tiles(crs, zoom):
"""
Generate tiles for the manifest.
"""
#generate tiles
tiles = []
#calculate bbox for input geometry if geom is none:
for tile in mt.tiles(*DEFAULT_TILES, zoom, truncate=False):
tile_id = f"{tile.z}_{tile.x}... | 26e4119ba7d3681d3e53f154a6ae08462770b5c6 | 3,613,757 |
def _darknet_conv2d(inputs, params, attrs, prefix):
"""Process the convolution 2d operation."""
new_attrs = {}
kernel = attrs.get('kernel')
strides = attrs.get('stride', 1)
pads = attrs.get('pad', 0)
new_attrs['channels'] = attrs.get('num_filter')
new_attrs['kernel_size'] = (kernel, kernel)... | 58fb8eab94d0d6463e2a589097bb40c261c355a2 | 3,613,759 |
import re
def filter_emoji(desstr, restr=''):
"""
过滤特殊表情,只保留中文、英文、数字
"""
# 一个网名为【......】的网友,随机生成为6位的字符
if desstr == r'......':
return make_random_string(6)
cop = re.compile("[^\u4e00-\u9fa5^.^a-z^A-Z^0-9]")
return cop.sub(restr, desstr) | cc9378cef9438f47f8f3fe0b5d2124f2d27ef9eb | 3,613,760 |
def solve_gurobi(mu, nu, c, mtd=-1):
"""Base routine for calling gurobi solver
"""
m, n = c.shape
M = Model("OT")
M.setParam('OutputFlag', 0)
M.setParam(GRB.Param.Method, mtd)
s = gurobi_set_model(mu, nu, c, M)
M.optimize()
sx = M.getAttr("x", s)
ans = np.array([sx[i, j] for ... | e4bf7f018bec44ad703c0ed56ba01dc1e28be891 | 3,613,761 |
def dataset_for_train_test_split(X_train, X_test, Y_train, Y_test, threshold=1,
multi_word_queries=False, scaler='standard'):
"""Make dataset from a train-test-split
This function scales the input data und generates queries and query-weights
from the training set vocabulary... | 228041dc7375f789a7f0608d60bb4436a9245909 | 3,613,762 |
from datetime import datetime
def get_site_mau_history_metrics(site, months_back):
"""Quick adaptation of `get_monthly_history_metric` for site MAU
The `months_back` gets the previous N months back not including current
month because we do not capture the current month until it is over. Meaning
we wa... | 8a8b2ceebaf4db358030bd183ed5c9d9384da04d | 3,613,763 |
def diehard_pybites():
"""Return a Stats namedtuple (defined above) that contains the user that
made the most PRs (ignoring the users in IGNORE) and a challenge tuple
of most popular challenge and the amount of PRs for that challenge.
Calling this function on the dataset (held tempfile) should ... | a8620b63323476101ca6d61519aed8dd5c98e048 | 3,613,764 |
def get_mapindex(res, index):
"""Get the index of the atom in the original molecule
Parameters
----------
res : prolif.residue.Residue
The residue in the protein or ligand
index : int
The index of the atom in the :class:`~prolif.residue.Residue`
Returns
-------
mapindex... | 21c1724a5da26cc98857ef3dbaba6806ca653ef8 | 3,613,765 |
from typing import Iterable
from typing import Optional
import torch
import tqdm
def predict(model, smis: Iterable[str], batch_size: int = 50, ncpu: int = 1,
uncertainty: bool = False, scaler: Optional[StandardScaler] = None,
use_gpu: bool = False, disable: bool = False):
"""Predict the t... | ca0f9940b11f4219fe7377a261b81f6039af6cdc | 3,613,766 |
def funcOnModels(f, models):
"""
If you have a big array of models, this function allows you
to extract big arrays of model outputs. For example, suppose
that you have a 2x5x20 nested list of models and you want to
find the last critical temperature of each model. Then use
>>> Tcrit = funcOnMod... | c2e7dfb6edf6cfeb21c28db29625e1ecb02c56fe | 3,613,767 |
def find_projection(Lm, Lb, Rm, Rb, ORIGINAL_SIZE, UNWARPED_SIZE,
HozTop = 50, HozBottom = 0, porc = 0.3):
""" Find projection surface parameters from lane lines
Args:
Lm: `float` linear regression slope of left lane line
Lb: `float` linear regression y-intercept of left lane line
... | 7a937f0469dbe9877187c960ee78b643cdb7eb20 | 3,613,768 |
def tensors_from_dataset(dataset):
"""Converts a tf.data.Dataset to nested tf.Tensors."""
tensors = list(dataset)
if tensors:
return tf.nest.map_structure(lambda *tensors: tf.stack(tensors), *tensors)
# Return empty tensors if the dataset is empty.
shapes_dtypes = zip(
tf.nest.flatten(dataset.output... | 8e16855bdb13105222d713d426dc58fe098fe3e4 | 3,613,769 |
def gain_selection(waveform, charges, peak_time, threshold):
"""
Custom lst calibration.
Update event.dl1.tel[telescope_id] with calibrated image and peakpos
Parameters
----------
waveform: array of waveforms of the events
charges: array of calibrated pixel charges
peak_time: array of ... | c8d50e460fa70dc4f487ecba1d76c299b62cc5b6 | 3,613,770 |
from io import StringIO
def magic_to_rdb(magic_input: str, input_file_path: str = "UNKNOWN") -> str:
"""
>>> print(magic_to_rdb('''RAM8
... ----------------------------------------
... P-diff distance to N-tap must be < 15.0um (LU.3)
... ----------------------------------------
... 17.990um 2... | 137cff6cc654f95a60d2ced923f82e5a7a4b5919 | 3,613,771 |
def minos_style(smerr):
"""Convert minos error to style"""
return Struct(
is_valid=good(smerr.is_valid, True),
lower_valid=good(smerr.lower_valid, True),
upper_valid=good(smerr.upper_valid, True),
at_lower_limit=good(smerr.at_lower_limit, False),
at_upper_limit=good(smerr... | 4b4b1c7f260877bdd333cf5b8a98ee868666928d | 3,613,772 |
def is_dummy_definition(definition: hou.HDADefinition) -> bool:
"""Check if this definition is a dummy definition.
A dummy, or empty definition is created by Houdini when it cannot find
an operator definition that it needs in the current session.
:param definition: The definition to check.
:return... | 40598333612abbc020ad650c50560aef815c89c6 | 3,613,773 |
def float_to_uint8(x: np.ndarray[np.float32]) -> np.ndarray[np.uint8]:
"""Transforms an np.float32 image into a np.uint8 image
Parameters
----------
x: np.array[np.float32]
Input image of shape (width,height,channels)
Returns
-------
output: np.array[np.uint8]
Output image ... | f926cdf4af8db6161bd381c11a8ea90fd3aef2a1 | 3,613,774 |
def transform_password(password_str):
"""Transform the password string into 32 bit MD5 hash
:param password_str: <str> password in plain text;
:return: <str> Transformed password fixed length
"""
h = MD5.new()
h.update(password_str.encode())
return h.hexdigest() | 59f7f39acbd05116fcdcfff75fb9461b3a13b352 | 3,613,775 |
def bootstrap_messages(context, *args, **kwargs):
"""
Show request messages in Bootstrap style
"""
return get_template("bootstrap_toolkit/messages.html").render(context) | 96ac6e0ee55734950e94810912c8dd9f972f3205 | 3,613,776 |
def get_combos(itr1, itr2):
"""Returns all the combinations of elements between two iterables."""
return [[x, y] for x in itr1 for y in itr2] | 5a57a1237cc73692abd077360f19916c9f366900 | 3,613,777 |
def get_special_character_treatment(behavior='remove'):
""" Provides the correct utility function for desired special character parsing
:param behavior - the desired operation to perform on special characters
:returns a utility function to apply to the string with special characters
"""
return {'re... | 898ea1c3eefe9069a73c4001a38167b831fa2a60 | 3,613,778 |
def compute_new_world_origin(poses, method):
"""
Computes the origin of the new world coordinate system (W2) given
N pose matrices.
Each of the N pose matrices can transform a point from a camera
coordinate system to a arbitrary world coordinate system (W1).
In this function, we want to comp... | 1673b17e3e701512ed71f30626e4b0aaa9630e2b | 3,613,781 |
def _build_forward_graph(model, single_gpu_build_func):
"""Construct the forward graph on each GPU."""
all_loss_gradients = {} # Will include loss gradients from all GPUs
# Build the model on each GPU with correct name and device scoping
for gpu_id in range(cfg.NUM_GPUS):
with c2_utils_NamedCud... | 186d5ccc488102246878f7f42688729f3ea88721 | 3,613,782 |
def numpy_compiler(model):
"""Take a triflow model and return optimized numpy routines.
Parameters
----------
model: triflow.Model:
Model to compile
Returns
-------
(numpy function, numpy function):
Optimized routine that compute the evolution equations and their
ja... | 74660971e44a68cc7f5b3bc9701d3daae99a9da1 | 3,613,783 |
from typing import Any
import numbers
def is_num(a: Any) -> bool:
"""Checks if the specified Python object is a number (int, float, long, etc)."""
return isinstance(a, numbers.Number) | 437aed69142ea7a3e15eac27aa4c7d9026c8de8e | 3,613,784 |
from typing import Optional
import inspect
def format_docstring(obj: ObjType) -> Optional[str]:
"""Format the docstring with bold docstring sections.
Parameters:
- `obj`: The python object to get the docstring from.
Returns:
- Bold formatted docstring sections of docstring or `None`.
"""
docstring =... | 3f15082251a82b651c5899e1218fd614ecc1d190 | 3,613,785 |
def _resnet_cifar10(name, block, layers, pretrained, **kwargs):
"""Constructs a ResNet model for CIFAR-10 classification.
Args:
name: A string. Name of the ResNet model. Choose from 'resnet20', 'resnet32', 'resnet44', 'resnet56', 'resnet110', 'resnet1202'
block: The building block class.
... | 42136aef149512c0882bc0c19d48a836b5a76f68 | 3,613,787 |
import json
def cmd_project_build_stat(mixcli: MixCli, latest: bool = False, version: bool = False, **kwargs: str):
"""
Default function when MixCli project get command is called. Processing concept list command.
:param version: Only include the build version(s)
:param mixcli: MixCli, a MixCli instan... | 61c7b858a4025223a6904bc53a23829764c6685b | 3,613,788 |
def get_all_users():
""" For example:
>>> get_all_users()
[<User 1>, <User 2>, <User 3>, <User 4>, <User 5>, <User 6>,
<User 7>, <User 8>, <User 9>, <User 10>,<User 12>, <User 12>]
"""
return User.query.all() | cd3b49b9e14c43f747ba750014a0914350d5ecf8 | 3,613,789 |
import time
def strftime(dt, *args, **kwargs):
"""Version of datetime.strftime that always uses the C locale.
This is because date strings are used internally in the database, and
should not be localized.
"""
if hasattr(dt, 'strftime'):
return dt.strftime(*args, **kwargs)
else:
... | c4fd0f707915e0e26a1a59ab8c5c72f2d22ce8f0 | 3,613,790 |
def create_swag_from_ctx(ctx):
"""Creates SWAG client from the current context."""
swag_opts = {}
if ctx.type == 'file':
swag_opts = {
'swag.type': 'file',
'swag.data_dir': ctx.data_dir,
'swag.data_file': ctx.data_file
}
elif ctx.type == 's3':
... | 4cd40c64f5e01ade0c390c25cb146abc42818d39 | 3,613,791 |
def indent_empty_lines(s: str, compiler: CommandCompiler) -> str:
"""Indents blank lines that would otherwise cause early compilation
Only really works if starting on a new line"""
initial_lines = s.split("\n")
ends_with_newline = False
if initial_lines and not initial_lines[-1]:
ends_with_... | 8314daf99e8db48c781055bed84cc4ed52533d4a | 3,613,794 |
def _get_config_kwargs(**kwargs):
"""Get the subset of kwargs which pertain the config object"""
valid_config_kwargs = ["websockets", "cipher", "proxy_options", "keep_alive"]
config_kwargs = {}
for kwarg in kwargs:
if kwarg in valid_config_kwargs:
config_kwargs[kwarg] = kwargs[kwarg... | 3e01d1df4b8bddc1c53dfcd8007269894b963eaf | 3,613,795 |
def get_test_lines(test_case, test_params):
"""
Create a list of strings corresponding to the lines in a single test case.
Uses TensorFlow to compute the expected results for the given parameters,
and provides the code to call the test fixture to run the test.
"""
channel_idx = -1 if test_param... | 3f089c4c51ff27fa8209cb45aa8c4bde12fa145d | 3,613,797 |
def _g1(x,f1,a,f2,b):
"""g1: exponential decay"""
return a * (b*np.exp(-f1*x) + (1-b) * np.exp(-f2*x)) | 6322b879aa1a71164e3b7a2461efad6574a1f525 | 3,613,798 |
def getLocationInfo(field, response={}):
""" Get location info from field
:param field: field row data from influxdb
:param response: initial response body
:return: location info response
"""
coords = pgh.decode(field['geo'])
response['locationID'] = field['time']
response['georeferencedBy'] = 'CanAirIO... | 7cac48f87bfe72381fa18425b8fffeddab438202 | 3,613,799 |
def alpha(flux1, flux2, freq1=ufloat(144e6, 24e6),
freq2=ufloat(1400e6, 0)):
"""Get spectral index with error. Default is LDR2 and FIRST.
"""
return log(flux1 / flux2) / log(freq1 / freq2) | f026a77697265194136a222a0ea8825d63fc0ebe | 3,613,800 |
def decline_pr(script, project_key, repo_slug, pr_id, pr_version=0):
"""
Decline a PR
:param script: a TestScript instance
:type script: TestScript
:param project_key: The project key
:type project_key: str
:param repo_slug: The repo slug
:type repo_slug: str
:param pr_id: The PR id ... | 92b5c280e029090f6129dc1c420d8207e77dd2a0 | 3,613,801 |
import torch
def register(fixed=None, moving=None, dim=None, lam=1., loss='mse',
optim='ogm', hilbert=None, max_iter=500, sub_iter=16,
lr=1, ls=6, steps=8, plot=False, klosure=RegisterStep,
velocity=None, kernel=None, verbose=True, **prm):
"""Diffeomorphic registration betwe... | 8f376b717a60ed6dc1431aec151c5c23ab39f6bd | 3,613,803 |
import csv
from re import VERBOSE
def geocode_addr(in_path, type, start, end, geo_coords):
""" geocode_addr
Input:
<str> in_path, relative path to data file
<str> type, "AG" for allGas, otherwise gasBuddy
<int> start, line number of data file to start reading ... | d55d43545102914d1d9cd2d1795177c2dce951c6 | 3,613,804 |
def get_nodes(api_url=None, verify=False, cert=list()):
"""
Returns info for all Nodes
:param api_url: Base PuppetDB API url
"""
return utils._make_api_request(api_url, '/nodes', verify, cert) | 6b6974790375cab3598ffa03b61906e2b3aa901f | 3,613,805 |
import itertools
def _fit_coil_order_dev_head_trans(dev_pnts, head_pnts):
"""Compute Device to Head transform allowing for permutiatons of points."""
id_quat = np.concatenate([rot_to_quat(np.eye(3)), [0.0, 0.0, 0.0]])
best_order = None
best_g = -999
best_quat = id_quat
for this_order in iterto... | 80cf4040c8f4946706f5779530e8042f8d890b53 | 3,613,809 |
import struct
import time
def test_eap_proto_gpsk(dev, apdev):
"""EAP-GPSK protocol tests"""
def gpsk_handler(ctx, req):
logger.info("gpsk_handler - RX " + req.encode("hex"))
if 'num' not in ctx:
ctx['num'] = 0
ctx['num'] = ctx['num'] + 1
if 'id' not in ctx:
... | 3114b91d380de7f78d6a36e3e3973e3e9fba854e | 3,613,810 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.