content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def map_pair_name_to_exchange_name(pair_name): """ We're preparing to add the notion that exchanges can have multiple trading pairs into our system. Each exchange is going to have a single ExchangeData db object but have one wrapper for each pair. Order.exchange_name is going to refer to the pair, b...
314d82d234eb5d096f7bad4c8e75e7f7bde32b75
3,610,331
from typing import Optional async def handle_list_comparisons( project_id: str, session: Session = Depends(database.session_scope), kubeflow_userid: Optional[str] = Header(database.DB_TENANT), ): """ Handles GET requests to /. Parameters ---------- project_id : str session : sqlal...
ff6737cf6811f8cd5fe5c75952702854d38806c1
3,610,332
import pickle def load_model(file_name="model.pkl"): """ Parameters: file_name (string): exact path of the target saved model Returns: built chefboost model """ f = open('outputs/rules/'+file_name, 'rb') model = pickle.load(f) #restore modules from its references modules = [] for model_name in model["...
daf76d3a160090f9b706efa839a56c2669ca4edd
3,610,334
def lower_first(string): """Return a new string with the first letter capitalized.""" if len(string) > 0: return string[0].lower() + string[1:] else: return string
fc6fba78d15633f1ab21105fbd46883797444fb1
3,610,336
def get_annotations_dict(members): """Get __annotations__ from a members map. Returns None rather than {} if the dict does not exist so that callers always have a reference to the actual dictionary, and can mutate it if needed. Args: members: A dict of member name to variable Returns: members['__an...
36d296c880b43a434abbcd6412b76c4e6330b3c8
3,610,337
def exp(pda : pdarray) -> pdarray: """ Return the element-wise exponential of the array. Parameters ---------- pda : pdarray Returns ------- pdarray A pdarray containing exponential values of the input array elements Raises ------ TypeError Rai...
3374d1cb9d626d7929c62953a6fadecaf43dd035
3,610,338
from typing import Optional def findchallenge(name: str) -> Optional[HTBChallenge]: """Finds a specific challenge by name. Searches HTB for a specific challenge matching the specified name and returns it if one is found. Otherwise returns None. Args: name: An exact challenge name to lookup. ...
b03a7da8177a64cc68567626981fe7ec32003d48
3,610,339
def create_result_dataframe(y_test: DataFrame, y_pred: DataFrame, model_name: str) -> DataFrame: """ :param y_test: DataFrame with target values :param y_pred: DataFrame with predicted values :param model_name: Actual model name :return: DataFrame with models scores """ scores = _prepare_sc...
f7d3b8827664b1c7300fcb3ebcb371d1d3288d68
3,610,340
def create_custom_tiling_node(tile_mode, tile_level=TileLevel.L1, tensor_name=DEFAULT_STRING, tile_pos=DEFAULT_VALUE, tile_band=DEFAULT_VALUE, tile_axis=DEFAULT_VALUE, ...
2cd86602987f971fadc0d2a9e578fbb4212453af
3,610,341
import torch def get_surface_distance(seg_pred, seg_gt, distance_metric="euclidean"): """ (from MONAI) This function is used to compute the surface distances from `seg_pred` to `seg_gt`. Args: seg_pred: the edge of the predictions. seg_gt: the edge of the ground truth. di...
33bc2da4ef41398ec1ad64bc2c1a77509aa4f9cb
3,610,342
def makeState(fromacct,toacct,amount): """ make a tranfer state parameter currently due to the compiler problem, must be created as this format :param fromacct: :param toacct: :param amount: :return: """ return state(fromacct, toacct, amount)
79d43214656e7c8420732b945138bfaa39f251ba
3,610,343
def brocher_vp(f): """ V_p derived from V_s via Brocher (2005) eqn 9. """ f *= 0.001 f = 0.9409 + f * (2.0947 - f * (0.8206 - f * (0.2683 - f * 0.0251))) f *= 1000.0 return f
20c8d4961f1660384ecccd081db84a5351ec4d6e
3,610,345
from typing import Dict def new_swapped_deployment( old_deployment: Dict, container_to_update: str, run_id: str, expose: PortMapping, add_custom_nameserver: bool, ) -> Dict: """ Create a new Deployment that uses telepresence-k8s image. Makes the following changes: 1. Changes to s...
fa40bfdc2d045928a8d8dc46999d628332e3490a
3,610,346
def final(data): """ Last evolution time point, can be used to obtain parameters at the very end of the run. :param data: numpy ndarray containing the history of the system. :return: selection of the last evolution point. """ return ([data.shape[0]-1],)
46a489d0674bece12476af74db4cf4d17f623c4b
3,610,347
def detach_project_from_that_group(request): """ detach that group from the requested project """ id_project = request.matchdict[u'id'] id_group = request.matchdict[u'group_id'] project = request.dbsession.query(Project).options( joinedload(Project.groups)).get(id_project) group = r...
8f782c4f92199201fdddad47677e1c0078e83b02
3,610,348
def dec_resource(resource_port, expr, stream_port): """Decrease the count of available resource by the specified number, waiting for the processes capturing the resource as needed.""" r = resource_port e = expr s = stream_port expect_resource(r) expect_expr(e) expect_stream(s) expect_sam...
7ce455e33a22f3c4137e6449e92c956573d0d255
3,610,349
def _compute_v2_quantities(v2_arr, bias_arr, n_blocks): """Compute the squared visibilities quantities: - average ('v2') over the cube, - covariance ('v2_cov'), - avar ('avar') and - 'err_avar'.""" n_ps = v2_arr.shape[0] n_baselines = v2_arr.shape[1] v2 = np.zeros(n_baselines) v2_cov = np.zeros...
f281eeb58810caea461bc0156a35c43ed463b029
3,610,350
def make_default_config(project): """ Return a default configuration for exhale. **Parameters** ``project`` (str) The name of the project that will be searched for in ``testing/projects/{project}``. **Return** ``dict`` The global default testing conf...
7b913634f0df656a870d4886cf29391727eb4b21
3,610,351
def remove_bad_data(net, init='flat', tolerance=1e-6, maximum_iterations=10, calculate_voltage_angles=True, rn_max_threshold=3.0): """ Wrapper function for bad data removal. INPUT: **net** - The net within this line should be created **init** - (string) Initial voltage ...
1fe5225f28d9119f8433b5b848dee7d2353d38c7
3,610,352
from imjoy_rpc.hypha import RPC import msgpack import json async def execute_model( inputs, server_url=None, model_name=None, config=None, select_outputs=None, request_id="", model_version="", compression_algorithm="gzip", serialization="triton", decode_bytes=False, decode_...
a5725c3978f7bc5e23608b67c19c962d00fe1fd3
3,610,353
def find_suspicious_regions(misassemblies, min_cutoff = 2): """ Given a list of miassemblies in gff format """ regions =[] for misassembly in misassemblies: regions.append([misassembly[0], misassembly[3], 'START', misassembly[2]]) regions.append([misassembly[0], misassembly[4], 'EN...
e05b359745cdfc97d4f4584d02254bbcc49e543b
3,610,354
from typing import List import uuid from datetime import datetime import pytz def make_accounts(n) -> List[AccountSchema]: """Make n test accounts.""" return [ AccountSchema( uuid=uuid.uuid4(), bank_name=f"Starling Personal {i}", account_name=f"Account {i}", ...
d8d9c069e10d36618f354dee5356556f871de2da
3,610,355
def fabonacci(n): """ Return the n'th number of the fabonacci sequence """ if n == 0: return 0 elif n == 1: return 1 else: return fabonacci(n-1) + fabonacci(n-2)
d644de5bd5a175d4995a3747df431c2b66695d00
3,610,356
def read_file(filepath, *args, **kwargs) -> str: """Try different encoding to open a file in readonly mode.""" for mode in ("utf-8", "gbk", "cp1252", "windows-1252", "latin-1", "ascii"): try: with open(filepath, *args, encoding=mode, **kwargs) as f: content = f.read() ...
aa332522a08382f05e5da7b7cb890686db0131b5
3,610,357
def s3_set_extension(url, extension=None): """ Add a file extension to the path of a url, replacing all other extensions in the path. @param url: the URL (as string) @param extension: the extension, defaults to the extension of current. request """ ...
a3d18dfd1859d328b2e4e795ba5e5839d8684e73
3,610,358
def fill_from_root(filename, spectrum_name="", config=None, spectrum=None, bipo=False, **kwargs): """ This function fills in the ndarray (dimensions specified in the config) with weights. It takes the parameter specified in the config from the events in the root file. Args: fil...
f42b96dec5f797ffb003d7abbc69c4d0a3066c3e
3,610,359
def low_rank_cov_root(covs, rank, implementation='randomized_svd'): """ return X: (n_data, n_dim, rank) matrix so that X[i].dot(X[i].T) ~ covs[i] """ n_data, n_dim = covs.shape[:2] if implementation == 'randomized_svd': X = np.empty((n_data, n_dim, rank)) for i in xrange(n_data): ...
f5193d9ceb5671c6773fe7d28a75727d935bb917
3,610,360
def _map(term, predicate): """ A 'generic-function' verison of map, which defers to term.map, if one exists, and otherwise calls predicate on term. Actually iterable mapping is handled by term.map """ # validate(predicate, collections.Callable) if _IS_LOGICAL(term): return term.m...
de50498a57a64ac1703dd4ba159a5be06355801a
3,610,361
def has_byobu() -> bool: """Determines whether byobu can run.""" return _has_command('byobu')
f180b3df833f03c41b65f645280b4d152a8f65b7
3,610,362
def cylinder_divergence(xi, yi, zi, r, v): """ Calculate the divergence of the velocity field returned by the cylinder_flow() function given the path of a streamtube providing its path components xi, yi, zi. The theoretical formula used to calculate the returned variable 'div' has be...
23ef35bee21270f2255e1b378c5e6cc5839b4d40
3,610,363
def aggregate(df, signal_names, geo_resolution='county'): """Aggregate signals to appropriate resolution and produce standard errors. Parameters ---------- df: pd.DataFrame County block group-level data with prepared signals (output of construct_signals(). signal_names: List[str] ...
e2a29202fcfc532b05e2e0e36b2c5a687ff87571
3,610,364
def _equal_mstype(x, y): """ Determine if two mindspore types are equal. Args: x (mstype): first input mindspore type. y (mstype): second input mindspore type. Returns: bool, if x == y return true, x != y return false. """ return const_utils.mstype_eq(x, y)
7011dcd254c65f370571704a9b115bf1822c3a5e
3,610,365
def LM(f, *gens, **args): """ Return the leading monomial of ``f``. **Examples** >>> from sympy import LM >>> from sympy.abc import x, y >>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y) x**2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **arg...
bf5de86cc9c3b17bc1c4e9818d140e98be5ae25d
3,610,366
from typing import Dict def markers( data: AnnData, head: int = None, de_key: str = "de_res", sort_by: str = "auroc,WAD_score", alpha: float = 0.05, ) -> Dict[str, Dict[str, pd.DataFrame]]: """ Parameters ---------- data: ``anndata.AnnData`` Annotated data matrix with rows...
fb9af8b4c75402f1c5224e7bfaeee2ea2824a519
3,610,367
def vggcif16_bn(): """VGG 16-layer model (configuration "D") with batch normalization""" return VGGcif(make_layers(cfg['D'], batch_norm=True))
c289110f89c92016966bdc50d85496d42005dd3b
3,610,368
def get_platforms(): """Return the list of all the platforms""" controller = PlatformController return controller.get_list(MySQLFactory.get())
42eb217645fcf062ab181ae3afcb278a5e36cbd9
3,610,369
def metade(x=0, cvsao=False): """ ==> Divide o valor de x pela metade :param x: valor recebido. :param cvsao: (opcional) Se deseja ou não exibir o valor convertido em moeda local :return: valor de x pela metade com ou não conversão para moeda local. """ x /= 2 if cvsao: x = moeda...
b852f5c002e29b1e0eb6f53ff53a972265211310
3,610,370
def to_conll_iob(annotated_sentence): """ `annotated_sentence` = list of triplets [(w1, t1, iob1), ...] Transform a pseudo-IOB notation: O, PERSON, PERSON, O, O, LOCATION, O to proper IOB notation: O, B-PERSON, I-PERSON, O, O, B-LOCATION, O """ proper_iob_tokens = [] for idx, annotated_token in enumerate(annotat...
92fd0904782d241c9729df8a167840e38dfde605
3,610,371
def get_moves(player): """Based on th tuple of player's position, return the list of acceptable moves Parameters ---------- player : tuple Player move data >>> GAME_DIMENSIONS = (2, 2) >>> get_moves((0, 2)) ['RIGHT', 'UP', 'DOWN'] """ x, y = player moves = ['LEFT',...
5bec5eac969a38e68b3ef8429423b7f160b1882c
3,610,372
def find_auto_threshold(trace_log, variants, decreasingFactor): """ Find automatically variants filtering threshold based on specified decreasing factor Parameters ---------- trace_log Trace log variants Dictionary with variant as the key and the list of traces as the va...
41cd3a5e96b148e86463c18b432fedf50464207f
3,610,374
import re def insert_references(text, last_ref=0): """ Insert references section to the page according to local manual of style. last_ref parameter is used for transfering last reference position: it will be used for additional checks. If last_ref equals -1, references section will not be added. ...
754e2b1d6b8089a2da3665cdfa45f0935f62ba29
3,610,375
def KK_RC44(w, Rs, R_values, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ return ( Rs + (R_values[0] / (1 + w * 1j * t_values[0])) + (R_values[1] / (1 + w * 1j * t_values[1])) + (R_values[2] / (...
628d19332ce3f7dcacc75e26074f4776453ace25
3,610,376
import torch def collate_rank_eval(data): """Collate multiple datapoints for candidate product ranking during evaluation Parameters ---------- data : list of 3-tuples Each tuple is for a single datapoint, consisting of DGLGraphs for reactants and candidate products, scores for candida...
b184992536128ed06a79a0ae19b649a5d9748148
3,610,377
from typing import IO from re import U def fifo(FALL_THROUGH=0, DATA_WIDTH=32, DEPTH=8): """ args: FALL_THROUGH: fifo is in fall-through mode DATA_WIDTH: default data width if the fifo is of type DEPTH: depth can be arbitrary from 0 to 2**32 """ ADDR_DEPTH = int...
706a906b4ba1374cf9b9281a0d623772dd7926a6
3,610,379
def from_snbt(snbt : str, pos : int = 0): """Create a TAG from SNBT when type is unknown""" #print(f'Starting tests at {pos}') for i in sorted(Base.subtypes, key = lambda i : i.snbtPriority): try: value, pos = i.from_snbt(snbt, pos) except ValueError: ...
c4fe439ba11030737bba880943f5ac4255202ffa
3,610,380
def parse_data_txt(zip_file_path): """ Extract the tables in fastqc_data.txt from FastQC results contained in a zip file. Returns a dictionary representing the tables in the file, keyed by section headers in the form: {u'Basic Statistics': {'column_labels': (u'Measure', u'Value'), ...
d1c9329802d3f398b151d9007cd69562a75d358f
3,610,381
def _construct_lookup( orders, dists, growth, recurrence_algorithm, rules, tolerance, scaling, n_max, ): """ Create abscissas and weights look-up table so values do not need to be re-calculatated on the fly. """ x_lookup = [] w_look...
7127bcc3c4884a2f4a757e3249e74f6902ff3464
3,610,382
def feedback_system(request): """ get: Get the contents of the system feedback. post: Add a new system feedback from a user. delete: Delete a the user's system feedback. """ if request.method == 'GET': feedback = SystemFeedback.objects.all() serializer = S...
36d285589a8dad6b3dd43f96ea6e5de6c43530f6
3,610,383
def parse_mr_job_stderr(stderr, counters=None): """Parse counters and status messages out of MRJob output. :param stderr: a filehandle, a list of lines (bytes), or bytes :param counters: Counters so far, to update; a map from group (string to counter name (string) to count. Return...
202115802abd963fc8389b12ec84997a24dbd531
3,610,385
from typing import Union def ckd(xparentkey: Octets, index: Union[Octets, int]) -> bytes: """Child Key Derivation (CDK) Key derivation is normal if the extended parent key is public or child_index is less than 0x80000000. Key derivation is hardened if the extended parent key is private and child...
3c4f414763e8c862d947bfa5dcfc7a82707805c6
3,610,387
import copy def _treeizeAvailabilityZone(zone): """Build a tree view for availability zones.""" AvailabilityZone = availability_zones.AvailabilityZone az = AvailabilityZone(zone.manager, copy.deepcopy(zone._info), zone._loaded) result = [] # Zone tree view item az.z...
d03c4d614b5fd424d3be656b311528cbdb5fd0da
3,610,388
from typing import OrderedDict def parseDisambig(html): """Parse disambiguation page and return list of (article, text) tuples.""" sections = OrderedDict() soup = bs4.BeautifulSoup(html, 'lxml') for i in soup.find_all(True, class_=skipclass): i.decompose() sections[''] = _processDisambigSe...
a7e4d998ef138f11db139c2d2819c9ead62c60ab
3,610,390
import json def get_rookie_prediction(input): """This function receives the data from the requests, parses it as a dictionary and gets the prediction Args: input (json) The request body Returns: The prediction for the input value """ try: data = json.loads(input) ...
5cedd4204187c898789697b42d20b86ef6a6abd0
3,610,391
def config_register(value): """Register a value or values. Parameters: -A Value """ return ConfigurationSettings().register(value)
00fafeb6d288191e7306e637544bbc9cb29906c8
3,610,394
import unicodedata import re def normalize(text): """ Normalizes text before keyword matching. Converts to lowercase, performs KD unicode normalization and replaces multiple whitespace characters with single spaces. """ return unicodedata.normalize('NFKD', re.sub(r'\s+', ' ', text.lower()))
c03a3148d39161cfd5751a306ca842362c46fb28
3,610,395
def gdb_path(): """ Get path to the gdb """ return _get_ya_plugin_instance().gdb_path
67fcce8eccd59ca981b08e7f55868e986ae29a81
3,610,396
import base64 def pass_to_key(password): """Return a key from the given password for encryption.""" byte_pass = password.encode() kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=b"\r7\xb6bT\xa0\xd5\xdcG.'+\xb7\xdb\r\xcd", iterations=100000, backend=defa...
ba5ee669edc02e80c700c257c2eaa08c1b2ed6f5
3,610,397
def _ProcessCards(data): """Process the set lines and corresponding data""" # Reset all values # ------------------------------------------------------------------------- setLine = [] sd = {"brN": None, "branches": None, "histN": None, "histories": None, "times": None, "units": None} ...
3ada5c8f85d3833e10626b82dce82a99492b8159
3,610,398
def sigmoid_backward(x): """ derivation of sigmoid Paras ----------------------------------- x: output of the linear layer Returns ----------------------------------- max of nums """ s = sigmoid(x) return s * (1 - s)
e165a08c0642257fcac163f3bc98c87f5dee6ab1
3,610,399
def csv_announcement_email(df_matched): """ This function returns the df_matched in the format that can be used for the email messaging: Announcing buddies to the participants. Use of the email template email_responses.py. """ df_email_og = df_matched.copy() df_email_og.drop(["id_user_1", "id_us...
f95d4c8502352930051a1929a65a8844e2084cdd
3,610,400
import typing def some_class_from( value: typing.Any, id: str, other_classes_registry: typing.Mapping[ str, some.graph.OtherClass], some_classes_registry: typing.Mapping[ str, some.graph.SomeClass], ref: str, errors: some....
5ed95db2c6fe605b67fa0575a9900c3074ae929b
3,610,401
from typing import List import itertools def multiple( context: mgp.ProcCtx, start_points: List[mgp.Vertex], end_points: List[mgp.Vertex], metrics: str = "m", ) -> mgp.Record(distances=List[float]): """ This distance calculator procedure for multiple entries returns 1 field. * `distanc...
7d2a3e4f1eb754d0b0ab5d4430fb538d9b41bd90
3,610,402
def merge_reads_with_novelty(reads, novelty): """ Given a data frame of reads and a transcript novelty data frame, perform a left merge to annotate the reads with their novelty status. """ merged = pd.merge(reads, novelty, on = "transcript_ID", how = "left") return merged
7f6e90e86fa4f51981e4756d23195353d7ff5608
3,610,403
def cash (): """*****for retrieving cash data from stock.csv FILE and use it accordingly.*****""" fp = open("stock.csv","r") #*****FILE pointer which is opening the file stock.csv as in read mode***** first = fp.readline() split_line = first.split(",") cash = float(split_line[0]) stockCash.appen...
e40dbe26edf45cd1a7956741169658bc2ba67dd5
3,610,405
import numpy def compute_bin_efficiencies(y_score, bin_indices, cut, sample_weight, minlength=None): """Efficiency of bin = total weight of (signal) events that passed the cut in the bin / total weight of signal events in the bin. Returns small negative number for empty bins""" y_score = column_or_1d(...
18b59376d4930168b97012441713efb3551a7cc9
3,610,406
from math import floor def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): """ Utility function for computing output of convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ if type(kernel_size) is not tuple: kernel_size = (kernel_size, kernel_size) ...
938ad68c9999b6255b5b1c0186da7807cabd16ad
3,610,407
import random def random_int(n=5): """ Create a random string of ints :return: """ return str(random.randint(1, 10 ** n))
e5fa29ac6177a5c4f6cdd2ee73a5d72736667505
3,610,408
def generate_dataset(data_dir, train=True, n_noisy=30000, k=5): """generate mnist noisy dataset""" data = [] img_sampler = get_noisy_sampler(data_dir) num_sampler = get_number_sampler(load_mnist(data_dir, 'train' if train else 'test')) for i in range(10): print('Generate for number %d ...' %...
e9d81ef168eadc3ee679c60911cacab4b90f5d55
3,610,409
def always_no_state(function, interval): """ This constraint ensures that a state function is undefined on an interval. This function returns a constraint that ensures that *function* is undefined everywhere on an interval (interval variable *interval* when it is present or fixed interval [*start*, *end*))...
2d07f65275af5465e9e136791827cc18a8e8fe68
3,610,410
def merged_stis_data(filename, extension=1): """Get spectrum data from all STIS spectral orders. If only filename is given, use SCI extension. Returns ------- wavs: numpy array, all wavelengths, sorted flux: all fluxes at these wavelengths errs: all errors at these wavelengths """ ...
cfbd361d66a8f5e1a01d6563438c15c87d5b7157
3,610,411
import itertools import random def generate_tuples(parameters): """ :param parameters: :return: """ if len(parameters.keys()) % 2 != 0: parameters['dummy'] = [] keys = parameters.keys() max_0 = keys[0] max_1 = keys[1] for key in keys[1:]: if len(parameters[key]) >= ...
e10c8326c4bdf95c5df36ceb24a3b2ff439d73c7
3,610,412
def run_augment(*args, **kwargs): """Run augment routines.""" return estims_routine(**init_all(*args, routine='augment', **kwargs))
12d00793f80bc758435e94eea43118029bf3329e
3,610,413
import re import string def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def remove_articles_ar(text): return re.sub('\sال^|ال', ' ', text) def white_space_fix(...
f2f7e783676a933fac61d0f0c11fc0212030c4fb
3,610,414
def check_prime(number): """ Checks if the given number is prime :param: number Number to evaluate for primality :rtype: bool True if the number is a prime, false otherwise """ for divisor in range(2, int(number**0.5) + 1): if number % divisor == 0: return False return Tr...
37c7cc341c07d02d4c95bf9b95223368504d79e9
3,610,415
import typing import types def is_higher_version( module_o_version: typing.Union[types.ModuleType, str, tuple[int, ...]], version: typing.Union[tuple[int, ...], str], /, *, sep: str = ".", keep_dev_version: bool = True, semver: bool = False, ) -> bool: """ MODULE_o_VERSION > VERSIO...
e1394d9483b7dbbb28f18d7bc2e6a50f3f85a54d
3,610,416
def get_bot_and_update_from_args(args): """Find bot and update instance in the given args. Args: args(iterable): arguments to search for the bot and update. Returns: tuple. telegram.Bot. instance of bot that found in args. telegram.Upate. instance of update that found i...
6080b1d93b2ed9d4d908e18c53ae43555ba9753d
3,610,417
def tally_date_handler(request: HttpRequest, enclosure_slug): """Called from tally page to change date tally""" # if it's a POST: pull out the date from the cleaned data then send it to "count" if request.method == "POST": form = TallyDateForm(request.POST) if form.is_valid(): t...
2fd6088e3b2c4f86d5c480de605dc56d1091d648
3,610,418
import torch def kldiv_normal(y, sigma): """ may be unstable because of often small length of y compared to the number of bins. """ delta = sigma/10 width = 10*sigma x = torch.arange(0, width, delta) x = torch.cat([-x.flip(0)[:-1], x]) p = (y.view(-1)-x.view(-1, 1)).div(delta).pow(...
65e3425844dc87725f2e223a5a395924d6efbf3d
3,610,420
def calcDelta(r, x_e, n_ae): """ Calculate topocentric distance to the asteroid. Parameters ---------- r : float (1) Heliocentric/barycentric distance in arbitrary units. x_e : `~numpy.ndarray` (N, 3) Topocentric position vector in same units as r. n_ae : `~numpy.ndarray` (N...
57b52d19225454cc21c2f01f0271cb8ce976a21f
3,610,421
def ParseModel(model): """Parses a model ID into a model resource object.""" return resources.REGISTRY.Parse( model, params={'projectsId': properties.VALUES.core.project.GetOrFail}, collection=MODELS_COLLECTION)
7c90e02c4d2fb6c8ab4e3a34dbac7130da5b018d
3,610,422
import html def update_accordions(clicks): """create bot accordions""" acc_list = [] pair_count = 0 for i in tg_wrapper.helper.get_all_bot_list(): tg_wrapper.helper.read_data(i) state = "defaulted" if "botcontrol" in tg_wrapper.helper.data: state = tg_wrapper.helper...
37acb543ade2efa268aecd9e8f4d0a0f29aabddd
3,610,423
def is_bootstrap_started(): """Checks to see if bootstrap has started. Returns: True if the bootstrap has started, else False. """ return config_model.Config.get('bootstrap_started')
c1c22018da8fa93637a0e55558fabe7d3422286d
3,610,424
def get_feature(feature, first_stage): """FPN, C4, C5""" cfg = load_yml(feature_yml) key = f'{feature}-{first_stage}' return cfg.get(key, None)
296502d5057a4d68e6e637ebc59a5736ace69337
3,610,425
from .. import sim from ..support.morlet import MorletSpec def plotRatePSD(include=['eachPop', 'allCells'], timeRange=None, binSize=5, minFreq=1, maxFreq=100, transformMethod='morlet', stepFreq=1, NFFT=256, noverlap=128, smooth=0, norm=False, overlay=True, popColors=None, ylim=None, figSize=(10,8), fontSize=12, lineW...
76ac27b163a593a73aade5505c7a3e5ad68f6cd2
3,610,426
import numpy import scipy def _evaluate_airy_function_at_point(x, y, z, wavelength, numerical_aperture, refractive_index): """ Evaluates the Airy point spread function at a point. Args: x: Float, x coordinate, in meters. y: Float, y coordinate, in meters. z: Float, z coordinate, i...
e1c4ce7fa3d467ae776efe37177792e23cf305ab
3,610,427
import json def ge_in_wall_dimmer_switch_state_fixture(): """Load the ge in-wall dimmer switch node state fixture data.""" return json.loads(load_fixture("zwave_js/ge_in_wall_dimmer_switch_state.json"))
133814c8e5ce0af2d6aec83e3468488d9430fd8e
3,610,428
import datasets def synthetic_regression_5k_features(dataset_dir): """ Synthetic regression generator from sklearn http://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_regression.html TaskType:regression NumberOfFeatures:5000 NumberOfInstances:100K """ return dataset...
b7d9f4c759beaf3618a28cdd756dd0b4d78abcd2
3,610,429
def genify(options_list, gen): """ Choose position from interval of discrete parameters based on gen value :param options_list: List of discrete values :param gen: DNA gen value :return: """ # Probability steps for projecting to given gen prob_step = 1 / len(options_list) for i in range(len(options_list)): ...
e0b277da2843cf3d7191bbf0445cd80358e7bdcc
3,610,430
def to_int(value): """Return the absolute value.""" try: return int(float(value)) except (ValueError, TypeError): try: return int(float(value.replace(',','').replace('/','.').replace('\\','.'))) except Exception: return 0
460d4317ee02c9c27a5574f95e9b4cdcc6d55e6b
3,610,431
def getCharsSegments(rows, bounds): """ Gets the char segments of text row images acording to chars bounds. rows and bounds are list of the same matching sizes. Parameters ---------- rows(list) : The list of segmented text row images bounds(list) : Bounds matching chars iamges sizes in a t...
d9a14ec47e5bc384cb2df1d5e69fc41613dd9d29
3,610,433
def make_lsgst_experiment_list(opLabelSrc, prepStrs, effectStrs, germList, maxLengthList, fidPairs=None, truncScheme="whole germ powers", keepFraction=1, keepSeed=None, includeLGST=True): """ Create a list of all the op...
cfb52bec4cc02855f6ef7ba8e8d5f1d3294911b1
3,610,434
def getArrDiffs(dataSet): """ Compares each successive number in a size n numpy array to its predecessor, generating a list of differences, returning a size (n - 1) numpy array. to a list. :param dataSet: A numpy array of numbers :return: An array containing the differences from the imput array....
34d4640f3e174e9714c339041b70f5ab5974c107
3,610,435
def _decide_indices_order(indices): """ arrange indices such the first entry in list has smallest index, the second has the second smallest index """ indices = list(np.roll(indices, -np.argwhere(indices == np.min(indices))[0][0])) second_entry, last_entry = indices[1], indices[-1] if second_ent...
29b4fcd300fbbcd1c89a9ea22d521b97cff049a6
3,610,436
def percent(mylist, item): """Return the percentage of an item of a list. :param mylist: (list) list of elements :param item: (any) an element of the list (or not!) :returns: percentage (float) of item in mylist """ return 100.0 * freq(mylist, item)
a8c0d9df2af5497fff03dd1e2b66c68c70e71bb6
3,610,438
import json def load_cat_to_name(json_path): """Load Label Name from JSON file.""" with open(json_path, 'r') as f: cat_to_name = json.load(f) return cat_to_name
43c30e9dbe29e29d507a873e6cc37f22bc7984c4
3,610,439
def dtc(messages): """ converts a frame of 2-byte DTCs into a list of DTCs """ codes = [] d = [] for message in messages: d += message.data # look at data in pairs of bytes # looping through ENDING indices to avoid odd (invalid) code lengths for n in range(1, len(d), 2): # ...
ae141efef0ec7cb7a5a32f9f3882cacd67018118
3,610,440
def id_overlap_count(input_ids: ListColumn, matching_ids: ListColumn): """ Returns the number of overlaps between two lists of ids Parameters --------- input_ids: First list of ids matching_ids: Second list of ids Examples ------- >>> import torcharrow as ta >>> from torcharrow...
d565fac45ca99a1617f4521b98840d4f29dda68f
3,610,441
def BLVGG(input_tensor, first_filter, hidden_filter, first_dilation, num_classes): """ Build the baseline VGG model :param input_tensor: input tensor :param first_filter: number of first filters :param hidden_filter: number of hidden filters :param first_dilation: number of first dilati...
524b10b649b0e4177bfa146a8e551334949f2afe
3,610,442
def _mined_attributes_required() -> bool: """Returns True if mined attributes will be required for this batch. Returns: True if mined attributes will be required for the optimizers being run in this batch, false otherwise. """ for optimizer_parameter in _OPTIMIZERS_THAT_USE_MINED_ATTRIBUTES: if _ex...
47c6373769a448f441100f40e9ae04b591d8fbcf
3,610,444
def multi_blend(arrays, colors, alphas=None, modes=None, input_max=1, color_max=1): """Composite one or more one-channel images atop one another, colorizing each. The arrays will be blended in reverse order: arrays[0] will be the base and arrays[-1] will be the top image. Parameters: arrays: l...
92db9b23a203a27c8970ec08ddebeb692ab8c735
3,610,445