content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def test() -> ScadObject:
"""
Create something.
"""
result = IDUObject()
result += box(10, 10, 5, center=True).translated((0, 0, -1)).named("Translated big box")
result -= box(4, 4, 4, center=True)
result += box(10, 10, 5)
result *= sphere(7).translated((0, 0, 1))
return (
r... | 2d8c413a6b60969de60746c4fb356da88a95e06a | 3,652,777 |
def rollout(policy, env_class, step_fn=default_rollout_step, max_steps=None):
"""Perform rollout using provided policy and env.
:param policy: policy to use when simulating these episodes.
:param env_class: class to instantiate an env object from.
:param step_fn: a function to be called at each step of... | d5ac3246338165d3cfdb5e37ae5a6cbbe5df0408 | 3,652,778 |
def get_source(location, **kwargs):
"""Factory for StubSource Instance.
Args:
location (str): PathLike object or valid URL
Returns:
obj: Either Local or Remote StubSource Instance
"""
try:
utils.ensure_existing_dir(location)
except NotADirectoryError:
return Re... | 6b240d7ad523c2a45ca21c3030a96ec5aebb69c2 | 3,652,779 |
def about(request):
"""
Prepare and displays the about view of the web application.
Args:
request: django HttpRequest class
Returns:
A django HttpResponse class
"""
template = loader.get_template('about.html')
return HttpResponse(template.render()) | ecf2a890e49a5fe786024f7d7f524e1396064f48 | 3,652,780 |
import math
import logging
def getAp(ground_truth, predict, fullEval=False):
"""
Calculate AP at IOU=.50:.05:.95, AP at IOU=.50, AP at IOU=.75
:param ground_truth: {img_id1:{{'position': 4x2 array, 'is_matched': 0 or 1}, {...}, ...}, img_id2:{...}, ...}
:param predict: [{'position':4x2 array, 'i... | ac44c514166f8e70a6625f4e1ad89b36564ffba4 | 3,652,782 |
def aumenta_fome(ani):
""" aumenta_fome: animal --> animal
Recebe um animal e devolve o mesmo com o valor da fome incrementado por 1
"""
if obter_freq_alimentacao(ani) == 0:
return ani
else:
ani['a'][0] += 1
return ani | 377e3800e12877f1b8cd1cba19fe3a430ade0207 | 3,652,783 |
import warnings
def match_inputs(
bp_tree,
table,
sample_metadata,
feature_metadata=None,
ignore_missing_samples=False,
filter_missing_features=False
):
"""Matches various input sources.
Also "splits up" the feature metadata, first by calling
taxonomy_utils.split_taxonomy() on it ... | 92a97fc39c233a0969c24774d74fdd6b304f5442 | 3,652,784 |
def im_adjust(img, tol=1, bit=8):
"""
Adjust contrast of the image
"""
limit = np.percentile(img, [tol, 100 - tol])
im_adjusted = im_bit_convert(img, bit=bit, norm=True, limit=limit.tolist())
return im_adjusted | 2bbccc08d4dd6aeed50c6fb505ff801e3201c73a | 3,652,785 |
import math
def FibanocciSphere(samples=1):
""" Return a Fibanocci sphere with N number of points on the surface.
This will act as the template for the nanoparticle core.
Args:
Placeholder
Returns:
Placeholder
Raises:
Placeholder
"""
points = []
phi = ma... | ea47b7c2eed34bd826ddff1619adac887439f5e0 | 3,652,786 |
import inspect
def get_code():
"""
returns the code for the activity_selection function
"""
return inspect.getsource(activity_selection) | 3bae49b5feea34813c518a3ec3a62a4cde35445f | 3,652,787 |
def calc_luminosity(flux, fluxerr, mu):
""" Normalise flux light curves with distance modulus.
Parameters
----------
flux : array
List of floating point flux values.
fluxerr : array
List of floating point flux errors.
mu : float
Distance modulus from luminosity distance.... | 8cfebee024ae73355daf64b96260d45e57115c8f | 3,652,788 |
def inference(images):
"""Build the CIFAR-10 model.
Args:
images: Images returned from distorted_inputs() or inputs().
Returns:
Logits.
"""
###
# We instantiate all variables using tf.get_variable() instead of
# tf.Variable() in order to share variables across multiple GPU training runs.
# If... | 224c6792b4f2b066d8627d222e6f89b469921de3 | 3,652,790 |
def cluster_molecules(mols, cutoff=0.6):
"""
Cluster molecules by fingerprint distance using the Butina algorithm.
Parameters
----------
mols : list of rdkit.Chem.rdchem.Mol
List of molecules.
cutoff : float
Distance cutoff Butina clustering.
Returns
-------
pandas.... | ba98342d10512b4ee08e756644a26bc8585f5abc | 3,652,791 |
import timeit
def exec_benchmarks_empty_inspection(code_to_benchmark, repeats):
"""
Benchmark some code without mlinspect and with mlinspect with varying numbers of inspections
"""
benchmark_results = {
"no mlinspect": timeit.repeat(stmt=code_to_benchmark.benchmark_exec, setup=code_to_benchmar... | c4038b98968c9c44b5cbd0bfc9e92654dae8aca2 | 3,652,792 |
def detect_version():
"""
Try to detect the main package/module version by looking at:
module.__version__
otherwise, return 'dev'
"""
try:
m = __import__(package_name, fromlist=['__version__'])
return getattr(m, '__version__', 'dev')
except ImportError:
pass
... | c9cb3a30d84c7e9118df46dcc73ce37278788db5 | 3,652,793 |
def model(p, x):
""" Evaluate the model given an X array """
return p[0] + p[1]*x + p[2]*x**2. + p[3]*x**3. | fe923f6f6aea907d3dc07756813ed848fbcc2ac6 | 3,652,794 |
def normalize(x:"tensor|np.ndarray") -> "tensor|np.ndarray":
"""Min-max normalization (0-1):
:param x:"tensor|np.ndarray":
:returns: Union[Tensor,np.ndarray] - Return same type as input but scaled between 0 - 1
"""
return (x - x.min())/(x.max()-x.min()) | 6230077008c084bdcbebfc32d25251564c4266f0 | 3,652,795 |
import warnings
import Bio
def apply_on_multi_fasta(file, function, *args):
"""Apply a function on each sequence in a multiple FASTA file (DEPRECATED).
file - filename of a FASTA format file
function - the function you wish to invoke on each record
*args - any extra arguments you want passed to the f... | e204322e512a0f1eb875d7a6434ab6e3356cff10 | 3,652,796 |
def resize_bbox(box, image_size, resize_size):
"""
Args:
box: iterable (ints) of length 4 (x0, y0, x1, y1)
image_size: iterable (ints) of length 2 (width, height)
resize_size: iterable (ints) of length 2 (width, height)
Returns:
new_box: iterable (ints) of length 4 (x0, y0,... | 3b6a309e6ccf0e244bb5a51a922bcf96303116ea | 3,652,797 |
import time
def perf_counter_ms():
"""Returns a millisecond performance counter"""
return time.perf_counter() * 1_000 | 55f1bbbd8d58593d85f2c6bb4ca4f79ad22f233a | 3,652,798 |
import struct
def make_shutdown_packet( ):
"""Create a shutdown packet."""
packet = struct.pack( "<B", OP_SHUTDOWN );
return packet; | 6d696d76c9aa783e477f65e5c89106b2fff6db6d | 3,652,799 |
def unique():
"""Return unique identification number."""
global uniqueLock
global counter
with uniqueLock:
counter = counter + 1
return counter | 12ac0e8f9ec5d4f8d6a41066f2325ef57d593d26 | 3,652,800 |
def pointCoordsDP2LP(dpX, dpY, dptZero, lPix = 1.0):
"""Convert device coordinates into logical coordinates
dpX - x device coordinate
dpY - y device coordinate
dptZero - device coordinates of logical 0,0 point
lPix - zoom value, number of logical points inside one device point (... | 2494b5d95756aab33434969fe2b02917a4529ef9 | 3,652,801 |
def geocode_input(api_key, input, geolocator):
"""
Use parallel processing to process inputted addresses as geocode
Parameters:
api_key (string): Google API key
input (string): user inputted addresses
geolocator: object from Google Maps API that generate geocode of address
Returns:... | b7c31ccc1364364a704602438e263b107de9046c | 3,652,802 |
def satContact(sat_R, gs_R):
"""
Determines if satellite is within sight of a Ground Station
Parameters
----------
sat_R : numpy matrix [3, 1]
- Input radius vector in Inertial System ([[X], [Y], [Y]])
gs_R : numpy matrix [3, 1]
- Input radius vector in Inertial System ([[X], [Y... | 6fb6d5fc9121ddb0627f276a13446891f1da7542 | 3,652,803 |
def determine_visible_field_names(hard_coded_keys, filter_string,
ref_genome):
"""Determine which fields to show, combining hard-coded keys and
the keys in the filter string.
"""
fields_from_filter_string = extract_filter_keys(filter_string, ref_genome)
return list(set(hard_coded_keys) | set... | 2d885e7caa183916691def8abf685a6560f55309 | 3,652,804 |
def get_data_day(data: pd.DataFrame):
"""Get weekday/weekend designation value from data.
:param pandas.DataFrame data: the data to get day of week from.
:return: (*numpy.array*) -- indicates weekend or weekday for every day.
"""
return np.array(data["If Weekend"]) | 3e4654cf3ad3c2f0e213563e0dac3b21c7fb847c | 3,652,805 |
def make_pretty(image, white_level=50):
"""Rescale and clip an astronomical image to make features more obvious.
This rescaling massively improves the sensitivity of alignment by
removing background and decreases the impact of hot pixels and cosmic
rays by introducing a white clipping level that should... | c6d95a76db8aee7a8e2ca2bbc881094577e547ca | 3,652,807 |
def hash(data: bytes) -> bytes:
"""
Compute the hash of the input data using the default algorithm
Args:
data(bytes): the data to hash
Returns:
the hash of the input data
"""
return _blake2b_digest(data) | 62dec8f0e05b668dd486deb87bd3cc64a0cd5d08 | 3,652,809 |
import torch
def compute_cd_small_batch(gt, output,batch_size=50):
"""
compute cd in case n_pcd is large
"""
n_pcd = gt.shape[0]
dist = []
for i in range(0, n_pcd, batch_size):
last_idx = min(i+batch_size,n_pcd)
dist1, dist2 , _, _ = distChamfer(gt[i:last_idx], output[i:last_id... | b7e1b22ab63624afd154a3228314a954304a3941 | 3,652,810 |
def find_sub_supra(axon, stimulus, eqdiff, sub_value=0, sup_value=0.1e-3):
"""
'find_sub_supra' computes boundary values for the bisection method (used to identify the threeshold)
Parameters
----------
axon (AxonModel): axon model
stimulus (StimulusModel): stimulus model
eqdiff (function): ... | 6efe62ac2d00d946422b1e0f915714cb9bd4dc50 | 3,652,811 |
def constantly(x):
"""constantly: returns the function const(x)"""
@wraps(const)
def wrapper(*args, **kwargs):
return x
return wrapper | 7fdc78248f6279b96a2d45edaa2f76abe7d60d54 | 3,652,812 |
def ToBaseBand(xc, f_offset, fs):
"""
Parametros:
xc: Señal a mandar a banda base
f_offset: Frecuencia que esta corrido
fs: Frecuencia de muestreo
"""
if PLOT:
PlotSpectrum(xc, "xc", "xc_offset_spectrum.pdf", fs)
# Se lo vuelve a banda base, multiplicando por una exponencial con fase f_offset / fs
x_b... | 0389c3a25b3268b04be8c47cebaf1bbb6b863235 | 3,652,813 |
def hvp(
f: DynamicJaxFunction,
x: TracerOrArray,
v: TracerOrArray,
) -> TracerOrArray:
"""Hessian-vector product function"""
return jax.grad(lambda y: jnp.vdot(jax.grad(f)(y), v))(x) | 585ca7a5c749b6d393ae04e1e89f21f87c6f0269 | 3,652,814 |
def concat_all_gather(tensor):
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
return hvd.allgather(tensor.contiguous()) | 97b2a3e43cf36adda6c517264f3307deb4d98ed6 | 3,652,815 |
def get_min_area_rect(points):
"""
【得到点集的最小面积外接矩形】
:param points: 轮廓点集,n*1*2的ndarray
:return: 最小面积外接矩形的四个端点,4*1*2的ndarray
"""
rect = cv2.minAreaRect(points) # 最小面积外接矩形
box = cv2.boxPoints(rect) # 得到矩形的四个端点
box = np.int0(box)
box = box[:, np.newaxis, :] # 从4*2转化为4*1*2
return bo... | 59b801e77d03d3f81227c645a55b2c56f2ce5959 | 3,652,817 |
def vector_to_cyclic_matrix(vec):
"""vec is the first column of the cyclic matrix"""
n = len(vec)
if vec.is_sparse():
matrix_dict = dict((((x+y)%n, y), True) for x in vec.dict() for y in xrange(n))
return matrix(GF(2), n, n, matrix_dict)
vec_list = vec.list()
matrix_lists = [vec_list... | 79fdb28f1b254de4700e1e163b95b4bdbf579294 | 3,652,818 |
def cfn_resource_helper():
""" A helper method for the custom cloudformation resource """
# Custom logic goes here. This might include side effects or
# Producing a a return value used elsewhere in your code.
logger.info("cfn_resource_helper logic")
return True | 865216f77f09681e36e8b8409a8673c8dbcdffa0 | 3,652,819 |
def get_ts_code_and_list_date(engine):
"""查询ts_code"""
return pd.read_sql('select ts_code,list_date from stock_basic', engine) | 4bd31cbadfdb92a70983d53c74426b0727ad4d0b | 3,652,820 |
def nested_cv_ridge(
X, y, test_index, n_bins=4, n_folds=3,
alphas = 10**np.linspace(-20, 20, 81),
npcs=[10, 20, 40, 80, 160, 320, None],
train_index=None,
):
"""
Predict the scores of the testing subjects based on data from the training subjects using ridge regression. Hyper... | 47d5d8821b796031298a194aaf1781dc4df68a2f | 3,652,821 |
def absolute_time(time_delta, meta):
"""Convert a MET into human readable date and time.
Parameters
----------
time_delta : `~astropy.time.TimeDelta`
time in seconds after the MET reference
meta : dict
dictionary with the keywords ``MJDREFI`` and ``MJDREFF``
Returns
-------... | dd6c02be87840022e88769d3d70e67ce50f24d64 | 3,652,822 |
from controllers.main import main
from controllers.user import user
def create_app(object_name, env="prod"):
"""
Arguments:
object_name: the python path of the config object,
e.g. webapp.settings.ProdConfig
env: The name of the current environment, e.g. prod or dev
""... | a2760a759f3afebf8e09c498398712fb26d44de8 | 3,652,823 |
from datetime import datetime
def yyyydoy_to_date(yyyydoy):
"""
Convert a string in the form of either 'yyyydoy' or 'yyyy.doy' to a
datetime.date object, where yyyy is the 4 character year number and doy
is the 3 character day of year
:param yyyydoy: string with date in the form 'yyyy.doy' or 'yyy... | b289419c14321afc37ea05501307e36203191fec | 3,652,824 |
from typing import Optional
def create_selection():
""" Create a selection expression """
operation = Forward()
nested = Group(Suppress("(") + operation + Suppress(")")).setResultsName("nested")
select_expr = Forward()
functions = select_functions(select_expr)
maybe_nested = functions | nested... | 38a3eaef51d0559e796ce7b6bef6127a771a395d | 3,652,825 |
def move_nodes(source_scene, dest_scene):
"""
Moves scene nodes from the source scene to the destination scene.
:type source_scene: fbx.FbxScene
:type dest_scene: fbx.FbxScene
"""
source_scene_root = source_scene.GetRootNode() # type: fbx.FbxNode
dest_scene_root = dest_scene.GetRootNode()... | 26a413736ab5fee46182f05247fe989d66358f19 | 3,652,826 |
def extract_values(*args):
"""
Wrapper around `extract_value`; iteratively applies that method to all items
in a list. If only one item was passed in, then we return that one item's
value; if multiple items were passed in, we return a list of the corresponding
item values.
"""
processed = [... | 2906ca3aa42bfb47b231fd23b2a69a816399c255 | 3,652,827 |
def predefined_split(dataset):
"""Uses ``dataset`` for validiation in :class:`.NeuralNet`.
Examples
--------
>>> valid_ds = skorch.dataset.Dataset(X, y)
>>> net = NeuralNet(..., train_split=predefined_split(valid_ds))
Parameters
----------
dataset: torch Dataset
Validiation data... | 4f4f775e41b07efba3425bc2243d9766b41f5bc1 | 3,652,828 |
from typing import Union
def bgr_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:
"""Convert an image from BGR to RGBA.
Args:
image (Tensor[B, 3, H, W]):
BGR Image to be converted to RGBA.
alpha_val (float, Tensor[B, 1, H, W]):
A float number or tenso... | 654cb3df7432d799b2a391bf5cfa19a15a26b1fa | 3,652,830 |
def d_matrix_1d(n, r, v):
"""Initializes the differentiation matrices on the interval.
Args:
n: The order of the polynomial.
r: The nodal points.
v: The Vandemonde matrix.
Returns:
The gradient matrix D.
"""
vr = grad_vandermonde_1d(n, r)
return np.linalg.lstsq(v.T, vr.... | a8d1df34726ea1ac6ef7b49209c45374cb2bed04 | 3,652,831 |
import functools
def compile_replace(pattern, repl, flags=0):
"""Construct a method that can be used as a replace method for sub, subn, etc."""
call = None
if pattern is not None and isinstance(pattern, RE_TYPE):
if isinstance(repl, (compat.string_type, compat.binary_type)):
repl = Re... | eb753edeb9c212a28968eaf9c070aeeec8678d49 | 3,652,832 |
import six
def python_2_unicode_compatible(klass):
"""
From Django
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to th... | 18c290d649e0299c72f85209c4db6a7a4b716300 | 3,652,833 |
import re
import logging
def ParseNewPingMsg(msg):
"""Attempt to parse the message for a ping (in the new format). Return the request and response strings
(json-ified dict) if parsing succeeded. Return None otherwise.
"""
parsed = re.match(kNewPingMsgRe, msg)
if not parsed:
return None
try:
return... | 6bca164892ea13b598af75d468580a7d4bd04d4c | 3,652,834 |
from faker import Faker
def parse_main_dict():
"""Parses dict to get the lists of
countries, cities, and fakers. Fakers allow generation of region specific fake data.
Also generates total number of agents
"""
Faker.seed(seed) # required to generate reproducible data
countries = main_dict.key... | 7cf9870c86c40bb2d1565479d6789d9cd7114024 | 3,652,835 |
import json
def format_payload(svalue):
"""formats mqtt payload"""
data = {"idx": IDX, "nvalue": 0, "svalue": svalue}
return json.dumps(data) | 1cbee0d5169acde802be176cc47a25c2db1c2f62 | 3,652,836 |
def load_auth_client():
"""Create an AuthClient for the portal
No credentials are used if the server is not production
Returns
-------
globus_sdk.ConfidentialAppAuthClient
Client used to perform GlobusAuth actions
"""
_prod = True
if _prod:
app = globus_sdk.Confidenti... | 8e16303fa80e775d94e669d96db24a9f7a63e0b6 | 3,652,837 |
def DCGAN_discriminator(img_dim, nb_patch, bn_mode, model_name="DCGAN_discriminator", use_mbd=True):
"""
Discriminator model of the DCGAN
args : img_dim (tuple of int) num_chan, height, width
pretr_weights_file (str) file holding pre trained weights
returns : model (keras NN) the Neural Net... | 7aeabfffcc15a10c2eb2c81c795cbc4ff70a890b | 3,652,838 |
def common_stat_style():
"""
The common style for info statistics.
Should be used in a dash component className.
Returns:
(str): The style to be used in className.
"""
return "has-margin-right-10 has-margin-left-10 has-text-centered has-text-weight-bold" | 899381fc56e28ecd042e19507f6bc51ceeca3ef0 | 3,652,839 |
def TourType_LB_rule(M, t):
"""
Lower bound on tour type
:param M: Model
:param t: tour type
:return: Constraint rule
"""
return sum(M.TourType[i, t] for (i, s) in M.okTourType if s == t) >= M.tt_lb[t] | 0495e2d01c7d5d02e8bc85374ec1d05a8fdcbd91 | 3,652,840 |
import json
def build_auto_dicts(jsonfile):
"""Build auto dictionaries from json"""
dicts = {}
with open(jsonfile, "r") as jsondata:
data = json.load(jsondata)
for dicti in data:
partialstr = data[dicti]["partial"]
partial = bool(partialstr == "True")
dictlist = data[... | 50978acc9696647746e2065144fda8537d0c6dba | 3,652,841 |
def log_gammainv_pdf(x, a, b):
"""
log density of the inverse gamma distribution with shape a and scale b,
at point x, using Stirling's approximation for a > 100
"""
return a * np.log(b) - sp.gammaln(a) - (a + 1) * np.log(x) - b / x | 27bc239770e94cb68a27291abd01050f9780c4fb | 3,652,842 |
from pathlib import Path
def read_basin() -> gpd.GeoDataFrame:
"""Read the basin shapefile."""
basin = gpd.read_file(Path(ROOT, "HCDN_nhru_final_671.shp"))
basin = basin.to_crs("epsg:4326")
basin["hru_id"] = basin.hru_id.astype(str).str.zfill(8)
return basin.set_index("hru_id").geometry | 9d590d478b71bdd2a857ab8f0864144ac598cc58 | 3,652,843 |
from typing import Callable
from typing import Tuple
def cross_validate(estimator: BaseEstimator, X: np.ndarray, y: np.ndarray,
scoring: Callable[[np.ndarray, np.ndarray, ...], float], cv: int = 5) -> Tuple[float, float]:
"""
Evaluate metric by cross-validation for given estimator
Para... | c127b1cf68d011e76fdbf813673bf1d84a7520bb | 3,652,844 |
def GetMembership(name, release_track=None):
"""Gets a Membership resource from the GKE Hub API.
Args:
name: the full resource name of the membership to get, e.g.,
projects/foo/locations/global/memberships/name.
release_track: the release_track used in the gcloud command,
or None if it is not a... | b2232faec0a2302ec554a8658cdf0a44f9374861 | 3,652,846 |
def receive_messages(queue, max_number, wait_time):
"""
Receive a batch of messages in a single request from an SQS queue.
Usage is shown in usage_demo at the end of this module.
:param queue: The queue from which to receive messages.
:param max_number: The maximum number of messages to receive. T... | dd422eb96ddb41513bcf248cf2dc3761a9b56191 | 3,652,847 |
def get_snmp_community(device, find_filter=None):
"""Retrieves snmp community settings for a given device
Args:
device (Device): This is the device object of an NX-API enabled device
using the Device class
community (str): optional arg to filter out this specific community
Retu... | ae36269133fcc482c30bd29f58e44d3d1e10dcd1 | 3,652,848 |
def get_header_size(tif):
"""
Gets the header size of a GeoTIFF file in bytes.
The code used in this function and its helper function `_get_block_offset` were extracted from the following
source:
https://github.com/OSGeo/gdal/blob/master/swig/python/gdal-utils/osgeo_utils/samples/validate_cloud... | f7d41b9f6140e2d555c8de7e857612c692ebea16 | 3,652,849 |
def format_x_ticks_as_dates(plot):
"""Formats x ticks YYYY-MM-DD and removes the default 'Date' label.
Args:
plot: matplotlib.AxesSubplot object.
"""
plot.xaxis.set_major_formatter(mpl.dates.DateFormatter('%Y-%m-%d'))
plot.get_xaxis().get_label().set_visible(False)
return plot | 00838b40582c9205e3ba6f87192852af37a88e7a | 3,652,850 |
def operations():
"""Gets the base class for the operations class.
We have to use the configured base back-end's operations class for
this.
"""
return base_backend_instance().ops.__class__ | 845d50884e58491539fb9ebfcf0da62e5cad66d4 | 3,652,851 |
import mimetypes
def office_convert_get_page(request, repo_id, commit_id, path, filename):
"""Valid static file path inclueds:
- index.html for spreadsheets and index_html_xxx.png for images embedded in spreadsheets
- 77e168722458356507a1f373714aa9b575491f09.pdf
"""
if not HAS_OFFICE_CONVERTER:
... | 48a3c5716b833e639a10c0366829185a1ce623aa | 3,652,852 |
def tensorize_data(
uvdata,
corr_inds,
ants_map,
polarization,
time,
data_scale_factor=1.0,
weights=None,
nsamples_in_weights=False,
dtype=np.float32,
):
"""Convert data in uvdata object to a tensor
Parameters
----------
uvdata: UVData object
UVData object co... | 0a780bb022854c83341ed13c0a7ad0346bb43016 | 3,652,853 |
import torch
def _normalize_rows(t, softmax=False):
"""
Normalizes the rows of a tensor either using
a softmax or just plain division by row sums
Args:
t (:obj:`batch_like`)
Returns:
Normalized version of t where rows sum to 1
"""
if not softmax:
# EPSILON hack av... | 3ffcedbaf279ead72414256290d2b88078aff468 | 3,652,854 |
def calculate_baselines(baselines: pd.DataFrame) -> dict:
"""
Read a file that contains multiple runs of the same pair. The format of the
file must be:
workload id, workload argument, run number, tFC, tVM
This function calculates the average over all runs of each unique pair of
workload id and... | 69cd0473fc21366e57d20ee39fceb704001aba1b | 3,652,855 |
def pick_ind(x, minmax):
""" Return indices between minmax[0] and minmax[1].
Args:
x : Input vector
minmax : Minimum and maximum values
Returns:
indices
"""
return (x >= minmax[0]) & (x <= minmax[1]) | 915a1003589b880d4edf5771a23518d2d4224094 | 3,652,856 |
def read_files(file_prefix,start=0,end=100,nfmt=3,pixel_map=None):
"""
read files that have a numerical suffix
"""
images = []
format = '%' + str(nfmt) + '.' + str(nfmt) + 'd'
for j in range(start,end+1):
ext = format % j
file = file_prefix + '_' + ext + '.tif'
arr = r... | 95d283f04b8ef6652da290396bb4649deedff665 | 3,652,857 |
def describing_function(
F, A, num_points=100, zero_check=True, try_method=True):
"""Numerical compute the describing function of a nonlinear function
The describing function of a nonlinearity is given by magnitude and phase
of the first harmonic of the function when evaluated along a sinusoidal
... | 4e9b779ba30f2588262e2ecff7a993d210533b59 | 3,652,858 |
from typing import List
def _read_point(asset: str, *args, **kwargs) -> List:
"""Read pixel value at a point from an asset"""
with COGReader(asset) as cog:
return cog.point(*args, **kwargs) | 246c98d55fd27465bc2c6f737cac342ccf9d52d8 | 3,652,859 |
import torch
def image2tensor(image: np.ndarray, range_norm: bool, half: bool) -> torch.Tensor:
"""Convert ``PIL.Image`` to Tensor.
Args:
image (np.ndarray): The image data read by ``PIL.Image``
range_norm (bool): Scale [0, 1] data to between [-1, 1]
half (bool): Whether to convert to... | 86ab04d599ac9b1bfe2e90d0b719ea47dc8f7671 | 3,652,861 |
def panda_four_load_branch():
"""
This function creates a simple six bus system with four radial low voltage nodes connected to \
a medium valtage slack bus. At every low voltage node the same load is connected.
RETURN:
**net** - Returns the required four load system
EXAMPLE:
i... | dd5bc45a75943f0c078ab3bde9aa94b4bafc804f | 3,652,862 |
def word_flipper(our_string):
"""
Flip the individual words in a sentence
Args:
our_string(string): Strings to have individual words flip
Returns:
string: String with words flipped
"""
word_list = our_string.split(" ")
for idx in range(len(word_list)):
word_list[idx]... | fd484079407342925fc13583fb1fbee9ee472b14 | 3,652,863 |
import json
import base64
def load_json(ctx, param, value):
"""Decode and load json for click option."""
value = value[1:]
return json.loads(base64.standard_b64decode(value).decode()) | 99236d6fcde6c69a4bdadad4c6f3487d88fb7ce0 | 3,652,864 |
def hyperparam_search(model_config, train, test):
"""Perform hyperparameter search using Bayesian optimization on a given model and
dataset.
Args:
model_config (dict): the model and the parameter ranges to search in. Format:
{
"name": str,
"model": sklearn.base.BaseE... | 8f496a2c4494545ffdba2a5f63512ff45da4bb03 | 3,652,865 |
def _sawtooth_wave_samples(freq, rate, amp, num):
"""
Generates a set of audio samples taken at the given sampling rate
representing a sawtooth wave oscillating at the given frequency with
the given amplitude lasting for the given duration.
:param float freq The frequency of oscillation of the sa... | 4691fb94e1709c5dc1a1dcb8ed02795d0b3cfe40 | 3,652,867 |
from keras.models import Model
from keras.layers import Conv2D, SpatialDropout2D
from keras.layers import UpSampling2D, Reshape, concatenate
from keras.applications.resnet50 import ResNet50
def ResNet_UNet_Dropout(dim=512, num_classes=6, dropout=0.5, final_activation=True):
"""
Returns a ResNet50 Nework with ... | 6d99cbb9f5986a87e79653b03cc91ca652ca2d2d | 3,652,868 |
import sqlite3
def _parse_accounts_ce(database, uid, result_path):
"""Parse accounts_ce.db.
Args:
database (SQLite3): target SQLite3 database.
uid (str): user id.
result_path (str): result path.
"""
cursor = database.cursor()
try:
cursor.execute(query)
except s... | 05538c21342f854d8465a415c32f5e2ea4f3f14d | 3,652,869 |
from flask import current_app
def resolve_grant_endpoint(doi_grant_code):
"""Resolve the OpenAIRE grant."""
# jsonresolver will evaluate current_app on import if outside of function.
pid_value = '10.13039/{0}'.format(doi_grant_code)
try:
_, record = Resolver(pid_type='grant', object_type='rec'... | e3217aeda5e6dec935c3ccb96e1164be66083e4f | 3,652,870 |
from typing import Union
from pathlib import Path
def from_tiff(path: Union[Path, str]) -> OME:
"""Generate OME metadata object from OME-TIFF path.
This will use the first ImageDescription tag found in the TIFF header.
Parameters
----------
path : Union[Path, str]
Path to OME TIFF.
... | 98ed750bba4b6aeaa791cc9041cf394e43fc50f9 | 3,652,871 |
def create_table_string(data, highlight=(True, False, False, False), table_class='wikitable', style=''):
"""
Takes a list and returns a wikitable.
@param data: The list that is converted to a wikitable.
@type data: List (Nested)
@param highlight: Tuple of rows and columns that should be highlighte... | f586fac681e1b4f06ad5e2a1cc451d9250fae929 | 3,652,873 |
def registry_dispatcher_document(self, code, collection):
"""
This task receive a list of codes that should be queued for DOI registry
"""
return _registry_dispatcher_document(code, collection, skip_deposited=False) | 530b2d183e6e50dc475ac9ec258fc13bea76aa8d | 3,652,875 |
from typing import Collection
import requests
def get_reddit_oauth_scopes(
scopes: Collection[str] | None = None,
) -> dict[str, dict[str, str]]:
"""Get metadata on the OAUTH scopes offered by the Reddit API."""
# Set up the request for scopes
scopes_endpoint = "/api/v1/scopes"
scopes_endpoint_url... | 0a55facfd07af259c1229aa30417b516b268602b | 3,652,876 |
def beta_reader(direc):
"""
Function to read in beta values for each tag
"""
path = direc
H_beta = np.loadtxt('%s/Beta Values/h_beta_final2.txt' % path)
Si_beta = np.loadtxt('%s/Beta Values/si_beta_final2.txt' % path)
He_emi_beta = np.loadtxt('%s/Beta Values/he_emi_beta_final2.txt' % path)
... | ab8aef0acd6a9cd86301d5cc99e45511cf193a10 | 3,652,877 |
def get_logging_format():
"""return the format string for the logger"""
formt = "[%(asctime)s] %(levelname)s:%(message)s"
return formt | 3380cdd34f1a44cf15b9c55d2c05d3ecb81116cb | 3,652,879 |
def plot_hydrogen_balance(results):
""" Plot the hydrogen balance over time """
n_axes = results["times"].shape[0]
fig = plt.figure(figsize=(6.0, 5.5))
fig.suptitle('Hydrogen production and utilization over the year', fontsize=fontsize+1, fontweight='normal', color='k')
axes = fig.subplots(n_axes)
... | e352b1885b53ec9f5fc41f32f67afc5f86cae647 | 3,652,880 |
def ref_dw(fc, fmod):
"""Give the reference value for roughness by linear interpolation from the data
given in "Psychoacoustical roughness:implementation of an optimized model"
by Daniel and Weber in 1997
Parameters
----------
fc: integer
carrier frequency
fmod: integer
modu... | adf7a67c7b9d4448074f6ccd5fbf8e62c52b113d | 3,652,881 |
from typing import Optional
def points_2d_inside_image(
width: int,
height: int,
camera_model: str,
points_2d: np.ndarray,
points_3d: Optional[np.ndarray] = None,
) -> np.ndarray:
"""Returns the indices for an array of 2D image points that are inside the image canvas.
Args:
width:... | 95d235e475555c184e95b1e30c3cac686fe3e65f | 3,652,882 |
import torch
def list2tensors(some_list):
"""
:math:``
Description:
Implemented:
[True/False]
Args:
(:):
(:):
Default:
Shape:
- Input: list
- Output: list of tensors
Examples::
"""
t_list=[]
for i in some_list... | 35efe7c13c8c4f75266eceb912e8afccd25408cf | 3,652,883 |
def interpret_input(inputs):
""" convert input entries to usable dictionaries """
for key, value in inputs.items(): # interpret each line's worth of entries
if key in ['v0', 'y0', 'angle']: # for variables, intepret distributions
converted = interpret_distribution(key,... | 5a68f8e551ae3e31e107ab5a6a9aacc2db358263 | 3,652,884 |
def time(prompt=None, output_hour_clock=24, milli_seconds=False, fill_0s=True, allow_na=False):
"""
Repeatedly ask the user to input hours, minutes and seconds until they input valid values and return this in a defined format
:param prompt: Message to display to the user before asking them for inputs. Defa... | 82c0d8fae1f82e3f19b6af220ada5fadcea63bb3 | 3,652,885 |
def byol_a_url(ckpt, refresh=False, *args, **kwargs):
"""
The model from URL
ckpt (str): URL
"""
return byol_a_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs) | c9a8ce31ae5b6b59832d8ae9bb4e05d697f96cc9 | 3,652,886 |
def bellman_ford(g, start):
"""
Given an directed graph with possibly negative edge weights and with n vertices and m edges as well
as its vertex s, compute the length of shortest paths from s to all other vertices of the graph.
Returns dictionary with vertex as key.
- If vertex not present in th... | dd09de61d26a6ee988e549c5a0f8aafdf54b78ab | 3,652,887 |
import locale
from datetime import datetime
def _read_date(settings_file):
"""Get the data from the settings.xml file
Parameters
----------
settings_file : Path
path to settings.xml inside open-ephys folder
Returns
-------
datetime
start time of the recordings
Notes
... | 2f762bd7e190323acc44e5408c5f0977069d8828 | 3,652,888 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.