content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
import sys def bisection(f, a, b, power, iter_guess="yes"): """Given f(x) in [`a`,`b`] find x within tolerance, `tol`. Root-finding method: f(x) = 0. Parameters ---------- f : expression Input function. a : float Left-hand bound of interval. b : float Right-hand ...
eaaa1a28201fceaae39ced5edeb9e819a0c76ae1
3,652,806
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
import requests import json import click def get_examples_version(idaes_version: str): """Given the specified 'idaes-pse' repository release version, identify the matching 'examples-pse' repository release version. Args: idaes_version: IDAES version, e.g. "1.5.0" or "1.5.0.dev0+e1bbb[...]" R...
6f9ee4d6cf9e9c542065d77ae6b7dcc41848247c
3,652,808
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
from typing import List import os def find_files( path: str, skip_folders: tuple, skip_files: tuple, extensions: tuple = (".py",), ) -> List[str]: """Find recursively all files in path. Parameters ---------- path : str Path to a folder to find files in. skip_folders : tupl...
c3513c68cb246052f4ad677d1dc0116d253eae1a
3,652,816
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
import os import re def writeBremDecay( # Might want a config later lhe, mAp, eps, zlims, seed, outdir, outname, nevents=10_000 ): ""...
c6ab2695ce8d4984acc9f1e50898089ab4f7aaf1
3,652,829
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 unpack_request(environ, content_length=0): """ Unpacks a get or post request query string. :param environ: whiskey application environment. :return: A dictionary with parameters. """ data = None if environ["REQUEST_METHOD"] == "GET": data = unpack_get(environ) elif environ["R...
02280666d6e4aee3ec1465cca17d7118a72b072b
3,652,845
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
def get_unquoted_text(token): """ :param token: Token :return: String """ if isinstance(token, UnquotedText): return token.value() else: raise exceptions.BugOrBroken( "tried to get unquoted text from " + token)
0fabfb504f725a84a75cada6e5d04a9aeda9a406
3,652,860
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 profile_tags(profile): """ Get the tags from a given security profile. """ # TODO: This is going to be a no-op now, so consider removing it. return profile.id.split('_')
3d3cda3d67e9574f31a7fea4aee714cca39af5db
3,652,866
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 increase_structure_depth(previous_architecture, added_block, problem_type): """Returns new structure given the old one and the added block. Increases the depth of the neural network by adding `added_block`. For the case of cnns, if the block is convolutional, it will add it before the flattening operation....
3735ca2c66a1a5856fb7fac69b6e02daf25868d2
3,652,872
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
from pathlib import Path import os def path_to_dnd(path: Path) -> str: """Converts a `Path` into an acceptable value for `tkinterdnd2.`""" # tkinterdnd2 will only accept fs paths with forward slashes, even on Windows. wants_sep = '/' if os.path.sep == wants_sep: return str(path) else: ...
61c4f88b944551f16f1baf127ddc3ccc5018267a
3,652,874
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
import os def boto3_s3_upload(s3, dst, file): """Upload Item to s3. :param s3: -- Sqlalchemy session object. :param dst: -- str. Location to storage ??? :param file: -- ???. File object. Return Type: Bool """ s3.Object(settings.config_type['AWS_BUCKET'], file).put(Body=open(os.path.join(...
487d25cad72225ddde8ee91f8b12e1696c3163a0
3,652,878
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
def conv_res_step(x, hparams, padding, mask): """One step of convolutions and mid-residual.""" k = (hparams.kernel_height, hparams.kernel_width) k2 = (hparams.large_kernel_size, 1) dilations_and_kernels1 = [((1, 1), k), ((1, 1), k)] dilations_and_kernels2 = [((1, 1), k2), ((4, 4), k2)] with tf.variable_scop...
e0d2728f4991112a0dbd504121048f8670a4406b
3,652,889
import six from typing import Any def _get_kind_name(item): """Returns the kind name in CollectionDef. Args: item: A data item. Returns: The string representation of the kind in CollectionDef. """ if isinstance(item, (six.string_types, six.binary_type)): kind = "bytes_list" elif isinstance(i...
094298763f9bf1e3e7a421c19e08016f2138b7d7
3,652,890
def Froude_number(v, h, g=9.80665): """ Calculate the Froude Number of the river, channel or duct flow, to check subcritical flow assumption (if Fr <1). Parameters ------------ v : int/float Average velocity [m/s]. h : int/float Mean hydrolic depth float [m]. g : in...
754225397baa6a27ae58adc63f09bba5287f18e9
3,652,891
from typing import Callable from typing import Any def handle_error( func: Callable[[Command | list[Command]], Any] ) -> Callable[[str], Any]: """Handle tradfri api call error.""" @wraps(func) async def wrapper(command: Command | list[Command]) -> None: """Decorate api call.""" try: ...
1604f8ae224a9fb565f81ae70d74c24e68e60b9e
3,652,892
def write(ser, command, log): """Write command to serial port, append what you write to log.""" ser.write(command) summary = " I wrote: " + repr(command) log += summary + "\n" print summary return log
769e345d90121d4bf2d8cc23c128c2a588cba37c
3,652,893
def anscombe(x): """Compute Anscombe transform.""" return 2 * np.sqrt(x + 3 / 8)
9a47318733568892c4695db2cf153e59e78bb8d7
3,652,894
def max_accuracy(c1, c2): """ Relabel the predicted labels *in order* to achieve the best accuracy, and return that score and the best labelling Parameters ---------- c1 : np.array numpy array with label of predicted cluster c2 : np.array numpy array with label of true ...
7ec438b500463859c27ea94d315312b88f5954f1
3,652,895
def create_sphere(): """Create and return a single sphere of radius 5.""" sphere = rt.sphere() sphere.radius = 5 return sphere
a8d5e2e8c0ec7d00f75c4007214d21aa0d2b64ad
3,652,896
def calc_entropy(data): """ Calculate the entropy of a dataset. Input: - data: any dataset where the last column holds the labels. Returns the entropy of the dataset. """ entropy = 0.0 ########################################################################### # TODO: Implement...
418054f9a36b100daf788814e8549bc818e2e27a
3,652,897
import time def get_input(prompt=None): """Sets the prompt and waits for input. :type prompt: None | list[Text] | str """ if not isinstance(prompt, type(None)): if type(prompt) == str: text_list = [Text(prompt, color=prompt_color, new_line=True)] ...
bbcd5bbd7f97bff8d213d13afe22ae9111849e10
3,652,898
def alpha_liq(Nu, lyambda_feed, d_inner): """ Calculates the coefficent of heat transfer(alpha) from liquid to wall of pipe. Parameters ---------- Nu : float The Nusselt criterion, [dimensionless] lyambda_feed : float The thermal conductivity of feed, [W / (m * degreec celcium)] ...
13d0371248c106fb0f12d26335381675d7484000
3,652,899