content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Any def try_to_cuda(t: Any) -> Any: """ Try to move the input variable `t` to a cuda device. Args: t: Input. Returns: t_cuda: `t` moved to a cuda device, if supported. """ try: t = t.cuda() except AttributeError: pass return t
9b6643f169c1eb8fc65de8b1bff55668f8cba950
58,700
def filter_status_sensitive(production_id): """ 敏感状态 :param production_id: :return: """ if not production_id: return False condition = { 'production_id': production_id, 'status_delete': STATUS_DEL_NO } production_sensitive_info = get_production_sensitive_row(*...
358bda8e224d86380a318d86cf3d1b89b65135b3
58,701
def diff6circlek(delta, gamma, energy_kev=None, wavelength=1.0, lab=None): """ Calcualte incident and final wavevectors in diffractometer axis using detector angles :param delta: float angle in degrees in vertical direction (about diff-z) :param gamma: float angle in degrees in horizontal direction (abo...
ef6d6efd7ec6892b0ead82acf66bb833144b5752
58,702
def fixtableforhtml(tablecolumn): """ fix the formatting to make the decimals into percents and add comma seps to long numbers """ new_table = [] for x in tablecolumn: if float(x) < 1: x = str(round(float(x) * 100, 2))+"%" else: x = int(float(x)) ...
f57f2ef4145a7389e6160316750e64d0903ddc02
58,703
def refine_baseline(baseline, heights, detection_maps, downsample, crop_engine, detection_threshold=0.3): """ Refines the input baseline using fitting 2nd order polynom to the baseline detection map. :param baseline: numpy array of input baseline coords :param heights: list of input line heights [ascend...
f36e5edc52fd10b69b259528421d4904acbc365e
58,704
def provides(iface): """ Matches an object that provides the given interface. """ return Provides(iface)
a142ab3aa391fc84c56a91b3c41e3e22c119ce62
58,705
def getGasDensity(grid=None, ppar=None): """Calculates the gas density distribution in a protoplanetary disk. Parameters ---------- grid : radmc3dGrid An instance of the radmc3dGrid class containing the spatial and frequency/wavelength grid ppar : dictionary A diction...
113b4a18f0a420ccea8fdaf9674521465af5132a
58,706
def extract_finding(doc, audit): """ Given a header, examine the relevant context and see if we have a finding on our hands that corresponds to the given audit. """ headers = sentences(doc, "HEADER") if not headers: return None # we know this page has a header. attempt to extract the...
657b8f9f1fcbec4646e53540c1865acad2b1f151
58,707
from scipy.optimize import brentq def s_of_rew(rew,A_w,G0,Rg,ah): """ Inverse function of rew_of_s. Uses brentq for root finding. Parameters ---------- rew : float rest equivalent width of absorption A_w : float Defined in eq. 6, Tinker & Chen 2008, ApJ G0 : float N...
f9cfe1daa8ff64385b9007981f7c07732df5e70e
58,708
def get_instance_characteristics(instance): """ Returns a tuple of the node & edge model classes and the instance_type for the provided instance """ try: # Assume a queryset of nodes was provided _NodeModel = instance._meta.model _EdgeModel = instance._meta.model._meta.get_fi...
e0df14a4c68a595493a697ac3807281e54184cf3
58,709
import argparse def _get_deploy(args: argparse.Namespace, validator: PrivateKey) -> Deploy: """Returns delegation deploy to be dispatched to a node. """ # Set standard deploy parameters. deploy_params = pycspr.factory.create_deploy_parameters( account=validator, chain_name=args.chain_...
ac24f5cff3167f11ac40560ad5f2ae44c15263ce
58,710
def zebra_puzzle(): """Return a tuple (WATER, ZEBRA) indicating their house numbers.""" houses = first, _, middle, _, _ = [1, 2, 3, 4, 5]#Replace string with number in a list print houses orderings = list(itertools.permutations(houses)) #make a list of unordered houses #print list(orderings) ret...
017e64d91f8cd1a6b0ece56dd1b15c9d020e1b9a
58,711
def open_CTmax_data(): """Return an xarray.Dataset with CTmax data from OBIS. TODO: improve provenance! """ matdata = sio.loadmat( 'data/MI-traits-data/obis_Tmax.mat', struct_as_record=False, squeeze_me=True ) data = matdata['obis'] return xr.Dataset( dict( lat=x...
36f7e3fad89be3bbcb7c68b4598afc6292722bb5
58,712
import os def _count_frames_in(input_directory = '.'): """Calculates the number of frames in the input directory. The function calculates the number of frames in the input directory. The frames should be named frame_xxxx.png, where xxxx is the number of the frame. The numbers should start from 1 and should b...
af4ef559a3e866f82fb31778920f94013ea38929
58,713
def main( argv ): """ Script execution entry point """ # initialize and start the user interface #ui = timecalc() #ui.mainloop() if len( argv ) > 1: if len( argv ) == 5: arg = ' '.join( argv[ 1 : ] ) else: arg = argv[ 1 ] num = number( arg ) ...
119d5247f1f57b7fcb7a793665c36442066d23e6
58,714
from bs4 import BeautifulSoup from pathlib import Path def clean_html(html: str) -> str: """Removes script tags and their contents""" soup = BeautifulSoup(html, "html.parser") for script in soup(FORBIDDEN_TAGS): script.decompose() for img in soup.find_all("img"): img.name = "span" ...
b21db67976ee6b4c35701a0c26408920fff497d7
58,715
import os def run_vcfeval_roc_plot(job, context, roc_table_ids, names=[], kind=None, number=0, title=None, show_scores=False, line_width=2, ps_plot=False): """ Draw some rocs from the vcfeval output. Return (snps_id, nonsnps_id, weighted_id) kind specifies the subtype of ...
d8cd5098bdf7894bd32b3be34775c3a388fc3340
58,716
import time def internalKey(key = None): """Internal Key Generates or validates an internal key so services can communicate with each other Arguments: key (str): Passed to validate a key Returns: bool """ # Pull in salt global __msSalt # Generate a timestamp iTime = int(time()) # If no key was pa...
3f9d0a92710417701f56c22b58e90fe9b517cc56
58,717
def squint2(t, r, orbit, attitude, side, sin_az=0.0, h=0.0): """Find squint angle given imaging time and range to target. """ p, v = orbit.interpolate(t) R = attitude.rotmat(t) axis = R[:,0] angle = np.arcsin(sin_az) dem = ie.pyDEMInterpolator(height=h) xyz = rdr2geo_cone(axis=axis, angl...
62033e43c5e76e9a46d682cbca9d5efe5333f671
58,718
import re def update_issue_status(condition_str): """Replace issue URL with 'True' or 'False' based on its active state. If there is an issue URL is found, this function will try to query state of the issue and replace the URL in the condition string with 'True' or 'False' based on its active state. ...
9aa4e2cd0b91e42c1ce2031eeba5fb8f33dbc67e
58,719
def generate_action_dict(): """ Generate a list of all possible uci moves and their action number lookup Return: actions: lookup dictionary for converting uci into actions(number) inverse_actions: lookup dictionary for converting actions to uni """ # normal uci moves standard_uci = [] ...
267d80bcf64d76e7742b48de2d6c49507c6710bd
58,720
import time def check_update(from_currency, to_currency): """ check if last update is over 30 mins ago. if so return True to update, else False """ if from_currency not in ccache: # if currency never get converted before ccache[from_currency] = {} if ccache[from_currency].get(to_currency) is None: ccache[from_...
be6561d9a94595499196b15b9a2eb1461bef18c5
58,721
import math def facto(mult): """ Product of factorials of multiplicities in the multiset """ if not is_natural_multiset(mult): raise Exception("Coefficient only works for natural multisets") result = 1 for a in mult.sp.iter_all(): result *= math.factorial(mult(*a)) return result
2ac95f97f65fd4c73da6ccfb53dd4055fea6b728
58,722
def export(cfg, args): """ Modifies program config variables. """ if args[1] == 'color': color_triple = export_color(args) cfg['color'] = color_triple changed = tuple(color_triple) elif args[1] == 'time': time_period = export_time(args) cfg['time'] = time_pe...
d8f9b8f4a5ca22ad6f1ffa10807e73b5078ea65c
58,723
def build_sampler(tokenizer, device=None): """Build the appropriate sampler according to the configs.""" if FLAGS.model_type == 'text': model_fn = lambda prompts: text_model_fn(tokenizer.vocab_size)( # pylint: disable=g-long-lambda prompts, is_training=False, cache_steps=FLAGS.sample_memory_size) s...
03bb0162ee076516cf35be96182e925e3606e688
58,724
import fnmatch import os def find_data_files(package_dir, patterns, excludes=()): """Recursively finds files whose names match the given shell patterns.""" paths = set() def is_excluded(s): for exclude in excludes: if fnmatch.fnmatch(s, exclude): return True return False for directory,...
4889ba4dea6b70f0935afd8efdbeaf5179d4a742
58,725
from typing import Sequence from typing import Iterator def apply(masks: Sequence[int], value: int) -> Iterator[int]: """Apply each bit mask to the given value using bitwise AND. Args: masks: Bit masks to apply. value: Value to mask. Returns: Iterator with each mask independentl...
6eafc88977eea0d50173a4c37c12b43f5c80a870
58,726
from scipy.optimize import fmin_cobyla def _fit_dipoles(fun, min_dist_to_inner_skull, data, times, guess_rrs, guess_data, fwd_data, whitener, ori, n_jobs, rank): """Fit a single dipole to the given whitened, projected data.""" parallel, p_fun, _ = parallel_func(fun, n_jobs) # parallel ove...
251a9f38ca7f8545ca2da5e2b9f70da479a23a58
58,727
import matplotlib.pyplot as plt import array def launch(x1: 'array', x2: 'array', percent: float = 20., isplot: bool = False): """ Outilers identifier for 2D data. x1 -- array of the first variable. x2 -- array of the second variable. percent -- maximum percent of data to be filtered (default 20%)...
128f66012e7ab93cd96b2d7b2a9eddb019bfe8de
58,728
import threading def thread_get_album(update: Update, context: CallbackContext) -> int: """Creates a thread to get the album""" language = context.user_data["bot_lang"] text = context.bot_data["texts"][language]["get_album"] chat_id = update.effective_user.id update.callback_query.answer() _,...
0ced06d7175717697c4aebddfceb2b8d946f72c2
58,729
import random def _compute_loss_and_metrics( params, batch, rng, model, is_experts_model, auxiliary_loss_factor, router_z_loss_factor): """Computes cross-entropy loss and metrics for classification tasks. Args: params: Model state (parameters). batch: Current batch of examples. rng: R...
553356a3c51d66809a6352947410ffb036465aa8
58,730
def filter_df_for_pred_a(df, list_freq_outliers): """ Exclude frequency outliers according to list and drop all hex bin / time window combinations with 0 RTA's """ df_pred_a = df.loc[~df["h3_zone_6"].isin(list_freq_outliers)] df_pred_a = df_pred_a.reset_index() df_pred_a = df_pred_a.drop(["uid",...
1115c845593ec2aabf55f6c5d52f4ef8b23fc121
58,731
def create_modules(module_defs): """ Constructs module list of layer blocks from module configuration in module_defs """ hyperparams = module_defs.pop(0) output_filters = [int(hyperparams['channels'])] module_list = nn.ModuleList() for i, module_def in enumerate(module_defs): modules...
5ecebd8260f6926ed63396b19adc099129d2946c
58,732
def jinja_plugin_factory(options): """ Basic implementation of the `GeneralTemplateInterface`. Supports ``loader_func`` and ``getmtime_func``, as well as string and file loading but ignores ``mode`` since it's a text based template engine. All options passed to this function are forwarded to t...
16d353ccfcbad598a92cb17767e6eca0075e5e98
58,733
import glob def build_context(**kwargs: dict): """ Build Context takes an arbitrary dictionary and merges with a dictionary which reflects configuration read from a json file. """ def read_config(config_file): # read the job configuration try: file_location = glob.glob...
b3b9f6bd975a163602ad73c1b7ffa1488ab00f89
58,734
def import_string(module: str): """ Import the given module path. """ try: _module, func = module.strip(' ').rsplit('.', 1) except ValueError: raise ImportError('It looks like module {} is not a valid module'.format(module)) mod = import_module(_module) try: ...
331fbff3851315a5ff892e7c493e726eab2ec3f9
58,735
import cdms2, cdutil, numpy def join_scalar_data(*args ): """ This function joins the results of several reduced variables into a single derived variable. It is used to produce a line plot of months versus zonal mean. """ #pdb.set_trace() nargs = len(args) M = [] for arg in args: ...
20a69cd2559c146c31a72817c79db8d0510103fe
58,736
def group(seq, groupSize, noneFill=True): """Groups a given sequence into sublists of length groupSize.""" ret = [] L = [] i = groupSize for elt in seq: if i > 0: L.append(elt) else: ret.append(L) i = groupSize L = [] L.appe...
a7314803cb3b26c9bd69a2dbc2c0594181085c2c
58,737
def client_response_factory(): """Custom response factory for client.""" return ResponseFactory()
99838198b2004d531c147141b62890ef8d29e0f3
58,738
import os def get_module_data(filepath: str): """Create module data dictionary that `cppimport` uses""" fullname = os.path.splitext(os.path.basename(filepath))[0] return setup_module_data(fullname, filepath)
9b7554f5a118aef5f2786951557373d08ddccb88
58,739
import torch def membrane(field, voxel_size=1, bound='dct2', dim=None, weight=None): """Precision matrix for the Membrane energy Note ---- .. This is exactly equivalent to SPM's membrane energy Parameters ---------- field : (..., *spatial) tensor voxel_size : float or sequence[float]...
9ac91c6b79ce10977ba51c13fcc929aa352744e2
58,740
from sys import flags def define_image(data_format=True): """Register image specific flags. Args: data_format: Create a flag to specify image axis convention. Returns: A list of flags for core.py to marks as key flags. """ key_flags = [] if data_format: flags.DEFINE_enum( name="dat...
eeb1d6dae6220ea28aa95e93164ad5e5d7d4405b
58,741
def get_dataset(config, attack_ds_config, add_x_train=None, add_y_train=None): """ @param config: @param attack_ds_config: @param add_x_train: x_train samples to add to training set @param add_y_train: y_train samples to add to training set @return: """ dataset = config.dataset.dataset ...
55b1561e513de6705dfdbb43fee2aa5eb592392a
58,742
def attrdict_setup(attrdict=milc.attrdict.AttrDict): """Setup a simple AttrDict object for testing. """ simple_dict = attrdict() simple_dict['a'] = True simple_dict['b'] = False return simple_dict
a66613df54baa1e04a435184e488dbf1b7b46123
58,743
from typing import List from typing import Any def find_duplicates(list_: List[Any]) -> List[Any]: """ Find the elements duplicated in a list. """ dbg.dassert_isinstance(list_, list) # Count the occurrences of each element of the seq. set_l = set(list_) v_to_num = [(v, list_.count(v)) for ...
5f97f384395b530527df801239340cac7fde740d
58,744
def create_response_payload_with_status(command_request, method_name, create_user_response=None): """ Helper method to create the payload for responding to a command request. This method is used for all method responses unless the user provides another method to construct responses to specific command r...
fab9c14046bbbad71f78c2671abf6786bb0a42c8
58,745
def splitdrive(p): """Split a pathname into drive and path. On Posix, drive is always empty.""" return p[:0], p
14524196f9f2018fed85081f1825592d244ac50f
58,746
def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return PartialConv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
917ded11178349308c46a3ee1187dcb6624c409d
58,747
def namespace_embedded(db_ns: str) -> bool: """Return true if this namespace requires IDs to have namespace embedded. This function first maps the given namespace to an identifiers.org namespace and then checks the registry to see if namespaces need to be embedded in IDs. If yes, it returns True. If no...
283e4436df750d6846fd549fb2aa227e3ae72c90
58,748
def NoisyNode(num_centroids=2, **kwargs): """ Returns a function that takes a graph and adds noise to the node features except for the centroids. """ def inner(data): graph, labels = data features = graph[0][:, num_centroids:] features += np.random.randn(*features.shape) * ...
44a9bad800a19ddd5abc83876f0925a974fc1cfd
58,749
def train_model_multi_output_w_tmt(x, y, param_grid=None, n_jobs=-1, cv=5): """Trains and does gridsearch on a keras nnet. Response can be multi output Args: x (np array): explanatory variables y (np array): response variables. could be more than 1 n_jobs (int): number of cores to run on...
4d12c393ce032c7dccb5a61b9acc06ccf180d66b
58,750
import torch def to_numpy(t: torch.Tensor): """Convert model output from Torch Tensor to numpy array.""" assert t.ndim == 4 # Inverse normalize [-1, 1] -> [0, 1], rescale [0, 1] -> [0, 255] out = (torch.clamp(t * 0.5 + 0.5, 0, 1) * 255) \ .permute(0, 2, 3, 1) \ .detach() \ .c...
bbf142eb7c696aa11e2c1d476cc3a7b11eeae600
58,751
import operator def decimate(x, q, n=None, ftype='iir', axis=-1, zero_phase=True): """ Downsample the signal after applying an anti-aliasing filter. By default, an order 8 Chebyshev type I filter is used. A 30 point FIR filter with Hamming window is used if `ftype` is 'fir'. Parameters -----...
e2b8258153284d943981975acc642e39cbaf9382
58,752
import hashlib def get_interface_name(name, prefix='', max_len=constants.DEVICE_NAME_MAX_LEN): """Construct an interface name based on the prefix and name. The interface name can not exceed the maximum length passed in. Longer names are hashed to help ensure uniqueness. """ requested_name = prefi...
0309fe509496393ac64d1dc61373d0a8e3c0a64e
58,753
def differentiable_cumsum_capper(x, threshold, width): """Starts out 1 and decays to 0 so that (result * x).cumsum() <= threshold.""" cumsum = x.cumsum() capped_cumsum = threshold - width * nn.softplus((threshold - cumsum) / width) capped_x = jnp.concatenate([x[:1], jnp.diff(capped_cumsum)]) # The "double whe...
166983a1ad7aab3b5070535f66cf28fdb82661f6
58,754
def angle_energy(angle_numbers, uint_crd_f, scalar_f, atom_a, atom_b, atom_c, angle_k, angle_theta0): """ Calculate the energy caused by 3-atoms angle term. Assume the number of angles is M and the number of atoms is N. .. math:: dr_{ab} = (x_b-x_a, y_b-y_a, z_b-z_a) .. math:: dr_{c...
1b34ae109dfe90c4c33a63298344d5806c896d1b
58,755
def sub_mask_1d_indexes_for_mask_1d_index_via_mask_2d(mask_2d, sub_size): """"For pixels on a 2D array of shape (rows, colums), compute a 1D array which, for every unmasked pixel on \ this 2D array, maps the 1D sub-pixel indexes to their 1D pixel indexes. For example, for a sub-grid size of 2, the followin...
4fedf5876127da4ed3b92422ce4da422e7d391a7
58,756
def plot_mc_value(observation_space: gym.spaces.Box, feature_map: FeatureMap, weights: np.ndarray, fig=None): """ Plot MountainCar value function """ xs = np.linspace(observation_space.low[0], observation_space.high[0]) ys = np.linspace(observation_space.low[1], observation_space.high[1]) gridx,...
c0481b606d9a84325bc9fece8c4b61fad02e8637
58,757
import math def currin_exp_function(X): """ Compute the CurrinExp function. The value is computed as defined in https://www.sfu.ca/~ssurjano/curretal88exp.html :param X: dictionary containing the input points. :return: the value of the CurrinExp function. """ x1 = X['x1'] x2 = X['x2'] ...
8cbcd384bcc49511a93e517c0b22c9c8d2837826
58,758
import gettext def change_email_address(): """Request a change of the current user's email address.""" current_user = g.user form = ChangeEmailAddressForm(request.form) if not form.validate(): return change_email_address_form(form) new_email_address = form.new_email_address.data.strip() ...
abf3944e25880d543f0adca884d91ecd3917126d
58,759
def run_single_with_display(wf, display): """Adds a display to the single runner. Everything still runs in a single thread. Every time a job is pulled by the worker, a message goes to the display routine; when the job is finished the result is sent to the display routine.""" S = Scheduler(error_hand...
ca22f5c7fde36ceb7cd5c69a020a77ca4a47766b
58,760
def solution(n): """Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 """ # fetchs the next number for number in range(n - 1, 10000, -1): # ...
baccd41bdab7eed9dd7069caecc650834846e0d4
58,761
import math def pressure_to_altitude(pres): """Convert a pressure (Pascals) to altitude (meters)""" for i in range(len(_heights)-1,0,-1): P0 = _basepress[i] T0 = _basetemps[i] if pres < P0: if _isotherm[i]: dh = _R * T0 / _g * math.log(P0 / pres) ...
fa46e0b438c4cf56355ecaa17f838a152f6680e5
58,762
def read(filename): """ Read a nmrglue table file. Parameters ---------- filename : str Filename of nmrglue table file to read. Returns ------- comments : list List of comments (strings terminated with newline) rec : recarray Records array with named fields....
f4d9b0dc040a3d38337783281c38cd471a7b4be7
58,763
import requests import json def get_decomposition(profile_counts, signatures='COSMIC30'): """ Decomposition of mutational profiles into a combination of signatures. It is highly recommended to use profile_counts instead of profile in order to use Maximum Likelihood method *signatures* should be one of...
be4f5a7777443c44004ae349c5fc437ffd56ed0b
58,764
from django.utils import timezone from sentry.app import tsdb from sentry.models import Organization import click from typing import OrderedDict import six def organizations(metrics, since, until): """ Fetch metrics for organizations. """ stdout = click.get_text_stream("stdout") stderr = click.ge...
5d7659d124e12470515c4421a67c410f2c97849b
58,765
import dbm from datetime import datetime import json def export(start_date: str = Form(...), end_date: str = Form(...), db: Session = Depends(dbm.get_db), user: UserModel = Depends(auth.get_user)): """Export pomodoros""" start_date = datetime.strptime(start_date, "%Y-%m-%d") end_date = datetim...
3e05075c68f8103db759270e1ca610606eea4427
58,766
def get_bin_counts(array_in: NpArray, num_bins_per_dim: int) -> NpArray: """Divide two dimensional input space into a grid and count points in each. Point on the upper edge, which does happen in the data, go into the lower bin. The occurrence of these points is an artefact of the rescaling don...
3879310d554a61fc8d9e4c675d8e62a6be82d758
58,767
def parse_comments_from_back(line): """ Scan for tokens back to front in line. Any token that does not start with a valid dice spec or a literal is a comment. Return separately the line substring without comments and the comments. Returns: (line, comment): line: Remainder of the...
75f9acc697e18fdb0beb9decb1b383a43d1e5264
58,768
import numpy import math def f_internal(x, h, core_data): """ Creates an O(1) dummy function with unit bounds. So, (I hope) the gradient and stencil are reasonably scaled. I encode scale and noise awareness in this function, too. If your function is not noise aware, I pass a zero noise back to imfil_core...
0384bc7f4c7af5cd42738f467ddff45cbf2618f0
58,769
def radius_of_curvature(line, method="osculating"): """ Compute curvature radius of LineString :param line: :param method: method for computing radius of curvature {'circumscribe', 'osculating'} :return: """ def norm(xx, yy): return np.sqrt(xx ** 2 + yy ** 2) def tangent_vector(xi,...
6d378bfb366d8f3592ef3f85174239f10a980086
58,770
def create(): """Create a new post. For a post to be created, details are submitted in the form. These details are then inserted into the posts table in the database. Returns: Success JSON response if the operation succeeded. Else a failed JSON response is returned with the correct err...
da3a657375796dc9f031ed355d0620ef0e55fd2a
58,771
def decode(ids, encoder): """ Decode a list of IDs. """ ids = list(ids) if text_encoder.EOS_ID in ids: ids = ids[:ids.index(text_encoder.EOS_ID)] return encoder.decode(ids)
200d113e7ce9ab387b83cd926b8a0d7a4762fff6
58,772
import io def _load_image_obj(fileobj): """ Turn a byte file object into an image """ return Image.open(io.BytesIO(fileobj)).convert("RGB")
8ac45f3c8dee39d1f6d4181ca78bcabc26de5c28
58,773
def submit_edit(): """ handle file edit form """ # ... including student work pages. # invoked from handle_post() # the form text data is in the form dict key, i.e. request.form['edit_text'] # print_debug(' submit_edit: request.form : {}'.format(request.form.items())) # # request.form will l...
6f88b891436f387c4425be2fba5e22abae908008
58,774
def vround(v): """Convert a numpy 1d array to a tuple for hashing. """ return tuple(np.round(v, 8))
c196a465d07793fb0b68a9055741a8d40655b404
58,775
import sys from pathlib import Path def validate_payload(file_path: str) -> str: """Return the raw payload. This allows us to read from a file or the stdin stream. """ if file_path.startswith(r'\@'): # escape @ with \ to let the cli know that the payload starts with @ return file_path...
35c9a978cb7f6713de9b2b0ea59a928104f1a099
58,776
def LSTM_triggerNG(tx, num_channels, num_outputs, kernel_init='normal', bias_init='zeros') -> Model: """Modified from Andrew Ng's Deeplearning.ai Sequence Modeling course on Coursera. Originally used for trigger word detection. Notes: - Switched GRU cells to LSTM cells - BiDirectional??? ...
877a6fce737f278bb95e6a4109c40ed5cf564d6b
58,777
import random def load_data(ticker, n_steps=60, scale=True, split=True, balance=False, shuffle=True, lookup_step=1, test_size=0.15, price_column='Price', feature_columns=['Price'], target_column="future", buy_sell=False): """Loads data from yahoo finance, if the ticker is a pd Data...
566692d3f493f58981e9b7fdd04b887a8aa257fe
58,778
import numpy as np def BestDividing(dataSet, bestFeat): """ 选出连续性特征最优划分点+返回其信息熵 Parameters ---------- dataSet:数据集 bestFeat:对哪个连续特征进行判断 Returns:最优划分点+其信息熵 ------- """ bestEntropy = 1000.0 # 初始设一个不可能的超大熵 bestValue = 0.0 features = np.sort(dataSet[bestFeat].values) ...
075834bfa205153411b49c3d431402bb93a316d6
58,779
import functools def freezeargs(func): """ Transform all mutable objects into immutables using freeze For the sake of lru_cache """ @functools.wraps(func) def wrapped(*args, **kwargs): args = tuple(freeze(arg) for arg in args) kwargs = {k: freeze(v) for k, v in kwargs.items()}...
fe7760698e816b4f7c3599581a8d3d5b60dcb904
58,780
def classify_name(name): """Classify filename `name` as "crds", "oldcdbs", or "newcdbs". >>> classify_name("jwst_miri_dark_0057.fits") 'crds' >>> classify_name("s7g1700gl_dead.fits") 'oldcdbs' >>> classify_name("07g1700gl_dead.fits") 'newcdbs' >>> classify_name("bbbbbb.fits") Tra...
2599e44cabc2fdac8d09ec820acfc101a1129b1e
58,781
import asyncio def cli(ffmpeg, source, format_img, output, extra): """FFMPEG capture frame as image.""" async def capture_image(): stream = ImageFrame(ffmpeg_bin=ffmpeg) return await stream.get_image( input_source=source, output_format=format_img, extra_cmd=extra ) im...
3b6125ff5d23dd90c83c2a4011e4e71975575cc7
58,782
def template_modify(id, attrs): """ Modifies a template, configuring it with the given attributes. Parameter *tech*: The parameter *tech* must be a string identifying one of the supported template techs. Parameter *name*: The parameter *name* must be a string giving a name for the template. Parameter *...
f40a811e1bf756561895e097a2c83ed3392e69ea
58,783
def parse_args(args): """ Parse command line argument and return parsed Namespace object. Args: args (list): List of arguments. Returns: argparse.Namespace: Parsed arguments Namespace object. """ parser = ArgumentParser() group = parser.add_mutually_exclusive_group(required...
6d00210c961898bb9f268353be4ce417551cdc01
58,784
import copy from functools import reduce def combine(beds, beds_sorted=False, postmerge=True): """ Combine a list of bed files or BedTool objects into a single BedTool object. Parameters ---------- beds : list List of paths to bed files or BedTool objects. beds_sorted : boolean ...
08e6d3dc61547bf3a6563e24aafb52c28dbc91f1
58,785
def get_lldp_neighbors(device): """Get current LLDP neighbor information. Return a two-level dictionary with the LLDP neighbor information.. The first-level key is the local port (aka interface) name. The second-level keys are 'system' for the remote system name and 'port' for the remote port ID. O...
7719e3de069bf39533ee0c9fadbc2f94be69bb61
58,786
import logging def extract_email_confirmation_link(payload: str) -> str: """Find email confirmation link inside the plain text email payload.""" start = payload.find("https") next_word = payload.find(" ", start) if next_word != -1: activation_link = payload[start:next_word] else: n...
7b7367a63ee00cc78994d210bf7fadea2c6505b8
58,787
def WLS_fit(x_data=None, y_data=None, errors=None, weight_data=None, xaxis_name=None, yaxis_name=None, f_name=None, data_lines=None, data_name=None, quiet=True): """ Takes a filename string or x and y data as input. We are fitting the equation A_ij*x_j=b_i of the form b=C+Dx....
672f552a2e6ff5e941418b98f0d837b48b97d5fb
58,788
from django.conf import settings def get_default_cachefile_backend(): """ Get the default file backend. """ return get_singleton(settings.IMAGEKIT_DEFAULT_CACHEFILE_BACKEND, 'file backend')
2a4d8bd03057a303c26b525ef087587b99a96baf
58,789
def _make_ipy(nets): """Given a list of 2-tuples of (address, netmask), returns a list of IP address objects""" return [IP(addr) for addr, mask in nets]
42e92d0b3bde9a0a4d46dcdf9ab093290b17c9b1
58,790
def Uleb128Encode(value: int) -> bytes: """Encodes the argument int to ULEB128 format. Argument: value: Unsigned integer. Returns: The values encoded as ULEB128 bytes. """ if value < 0: raise ValueError(f'Cannot uleb128 encode negative value ({value}).') uleb128_bytes = [] done = False wh...
68e3d4fb12ce82d9fcb44b634bc8570eddde9078
58,791
def ex2d_subbundle(image, imageivar, patches, spots, corners, pixpad_frac, regularize, model, psferr): """Extract an entire subbundle of patches. The patches' output shape (nspec, nwave) must be aligned. Args: image: full image (not trimmed to a particular xy range) imageivar: image inverse var...
9930d383aa3eefb01cdaafb0fda9c1ff2e277e7c
58,792
def batch_norm(x, name, _ops, is_train=True): """Batch normalization.""" with tf.variable_scope(name): params_shape = [x.get_shape()[-1]] beta = tf.get_variable('beta', params_shape, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32)) gamma =...
dbbd42dd6e290a9c2a970e39e03397946016105e
58,793
import itertools def unique_slug(model, slug, instance=None, reserved_slugs=[]): """ Return unique slug for passed django model class. :param model: Django model class :param slug: String. Slug for make unique :param instance: Django model instance :return: String """ orig, apdx = spli...
7db45470673316ab01552a936ce8b07cb9d27346
58,794
def apply_transform(x, transform_matrix, channel_axis=0, fill_mode='nearest', cval=0.): """Apply the image transformation specified by a matrix. # Arguments x: 2D numpy array, single image. transform_matrix: Numpy arra...
209f614dd2ad751a3b9e5b67024398ce62871385
58,795
def process_results(results, l1_idxes, l2_idxes): """Expands the None elements in l2 and substitutes the real l1 indexes""" return set(process_result(result, l1_idxes, l2_idxes) for result in results) - set()
4c01b7f161dd866d4acf74c2fd3f953963bbc758
58,796
def _graph_minus(graph, nodeset): """ """ newgraph = nx.DiGraph() for (n1, n2) in graph.edges(): if n1 not in nodeset and n2 not in nodeset: newgraph.add_edge(n1, n2) for n in graph.nodes(): if n not in nodeset: newgraph.add_node(n) return newgraph
30e994eb143855afcd5be9d4c0052fd60a9d4a21
58,797
import os def get_startup_path(): """Takes no arguments Gives a list of full startup paths on a computer eg: [ "C:\\Users\\ABC\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\", "C:\\Users\\John PC\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\", "C:\\Users\\Monica...
1bc38ac5f714178f1090d7b1b4adb8bdcc9d3404
58,798
def create_worker(*, db_session: Session = Depends(get_db), worker_in: WorkerCreate): """ Create a new worker contact. """ worker = get_by_code(db_session=db_session, code=worker_in.code) if worker: raise HTTPException(status_code=400, detail="The worker with this code already exists.") ...
e3f680b81e2b5180929250fd6820fc78b5978b38
58,799