content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def getFromLongestMatchingKey(object, listOfKeys, caseInsensitive=True): """ Function to take an object and a list of keys and return the value of the longest matching key or None if no key matches. :param object: The object with the keys. :type object: dict :param listOfKeys: A list of keys to...
25271697197c5c16c2ad5ae7320fc452bc3c8205
44,500
def get_subscribers(): """Get all global subs""" return _SUBSCRIBERS
03b080796a4688b039f0380ee3ba95202067aabe
44,501
def python_version_is_greater_or_equal(major, minor=0, micro=0): """Alias for `~json_indent.pyversion.python_version_is_at_least()`:py:func:.""" return python_version_is_at_least(major, minor, micro)
d3a1b2680b13e20c439ae12cb334bec50f958d42
44,502
def parse_mimetype(mimetype): """Parses a MIME type into its components. :param str mimetype: MIME type :returns: 4 element tuple for MIME type, subtype, suffix and parameters :rtype: tuple Example: >>> parse_mimetype('text/html; charset=utf-8') ('text', 'html', '', {'charset': 'utf-8'}) ...
ae6136ecc9602a162853204642a443e904cac4b8
44,503
def generate_summary_movement_report( movement_detail_report: pd.DataFrame, ) -> pd.DataFrame: """ Aggregate by source time for period statistics. """ summary_movement_report = movement_detail_report.groupby("source_time")[ [ "transportation_units", "transportation_co...
e2ebc246486ef5de62d223d86ae12ab4dc8e7142
44,504
def object_key(obj): """Generate a checksum for a nested object or list.""" key = sha1() if isinstance(obj, (list, set, tuple)): for o in obj: o = object_key(o) if o is not None: key.update(o) elif isinstance(obj, dict): for k, v in obj.items(): ...
7f503cf03d98f03a75dec53e289065ca6aec4c2b
44,505
import numpy def gfalternate_gotdataforgaps(data,data_alternate,alternate_info,mode="verbose"): """ Returns true if the alternate series has data where the composite series has gaps. """ return_code = True ind = numpy.where((numpy.ma.getmaskarray(data)==True)&(numpy.ma.getmaskarray(data_alternate)...
6bf3bdb84ceaf2a1a9e16efd9199b30774291281
44,506
def key_type(key): """String identifying if the key is a 'name' or an 'ID', or '' for None. This is most useful when paired with key_id_or_name_as_string. Args: key: A datastore Key Returns: The type of the leaf identifier of the Key, 'ID', 'name', or ''. """ if key.id(): return 'ID' elif k...
8d055fc97313b7f613e5927d0f8f38d060a2cb2b
44,507
def cvReadString(*args): """cvReadString(CvFileNode node, char default_value=None) -> char""" return _cv.cvReadString(*args)
25124e0ad0e1490ed3742d64f14cee4e43ec11e9
44,508
def compare_graph_properties(graph_properties): """ This function takes a dataframe of graph properties. Each graph property is compared to other groups with the Mann-Whitney test. Takes a pandas dataframe of graph properties with the following columns: Network, Group, Network type, Conserved fract...
2fd164bda1fe37e70efefbc9df75fc91b232f373
44,509
def _select_encoding(consumes, form=False): """ Given an OpenAPI 'consumes' list, return a single 'encoding' for CoreAPI. """ if form: preference = [ 'multipart/form-data', 'application/x-www-form-urlencoded', 'application/json' ] else: pre...
81cac06c34f3df0d3c570ebcae90545a3a988fbc
44,510
def execute_command(command: str, new_image: Image, threshold=True) -> Image: """ __author__ = "Trong Nguyen" Return a new image given a valid command, an image and if required, a threshold value. >>> execute_command("E", new_image, 10) """ functions = {"L": load, "S": save_as, ...
54e87e4124ad05f21aeac99c5712da0863c8075a
44,511
from sys import getsizeof from typing import Mapping import weakref from typing import Container def deep_getsizeof(o, ids): """Find the memory footprint of a Python object This is a recursive function that rills down a Python object graph like a dictionary holding nested ditionaries with lists of lists ...
031f1da7931ab0df69aaa5eeb65a71534f126d49
44,512
def previous_prime(x): """前一个质数""" if x <= 2: return None if x == 3: return 2 if x % 2 == 0: x -= 1 else: x -= 2 while True: if is_prime(x): return x else: x -= 2
6ae7e33d55f3794da904db2040bea49a58eafb84
44,513
def other_classes(nb_classes, class_ind): """ Heper function that returns a list of class indices without one class :param nb_classes: number of classes in total :param class_ind: the class index to be omitted :return: list of class indices without one class """ other_classes_list = list(ra...
05b88e49827523508b14400aa83aa83dd48f2b2e
44,514
def manage_frozen_objects(): """ Manage objects that have been frozen due to being unsuitable for preservation for time being """ return render_template( "tabs/manage_frozen_objects/manage_frozen_objects.html" )
b688fdf93b144a546215ea0206a580776e951b49
44,515
import os import re import warnings def retrieve_datasets(source_path, countries_cities_dict, pollutants, years): """ Retrieve the selected EEA air pollution datasets from the local storage. The EEA datasets are csv files. Parameters ---------- source_path : str Local path in which t...
b3ca939d3cc0d8220486cff00796655e398a08f3
44,516
def get_gvf(data_list, num_classes): """ The Goodness of Variance Fit (GVF) is found by taking the difference between the squared deviations from the array mean (SDAM) and the squared deviations from the class means (SDCM), and dividing by the SDAM """ breaks = get_jenks_breaks(data_list, num_class...
531454ece4102db986b8d37f21e666cad17412c8
44,517
def init_capacities(edges, transactions, amount_sat, verbose=False): """Initialize capacity map for path search""" tx_targets = set(transactions["target"]) # init capacity dict keys = list(zip(edges["src"], edges["trg"])) is_trg = edges["trg"].apply(lambda x: x in tx_targets) # [current_cap, tot...
cf1de4433c52d07ccd75f7ef39d2899974ec8517
44,518
import torch import os def train(net, dataloader, emb, caption, device, n_epoch=10, unfreeze_epoch=0, lr=1e-5, verbose=True, ignore_bg=False, floss=F.l1_loss): """ :param net: neural network to be trained :param dataloader: dataset :param emb: embedding system (see embeddings) :para...
252918ffedf5f42ba36cce1d3f399f82e2995de8
44,519
def calculate_iou(gt, pr, form='pascal_voc') -> float: """Calculates the Intersection over Union. Args: gt: (np.ndarray[Union[int, float]]) coordinates of the ground-truth box pr: (np.ndarray[Union[int, float]]) coordinates of the prdected box form: (str) gt/pred coordinates format ...
c093fb8b36a87e2aad862d842e71f1f76b3dd791
44,520
import json from datetime import datetime def create_task(tenant_id='tenant_id'): """ Create a new task entry. POST format: { "name": "My New Task", "config": "\{\"task\": \"do something\"\}", "agent_url": "swift://region-a.geo-1/mycontainer/myagent.py", "email": "jeff.kramer@hp.com", "interval": "300",...
543213c5c370500b7076687901fcddbaa9da5ae9
44,521
from typing import Dict from io import StringIO def interpolate(s: str, registers: Dict) -> str: """ Interpolates variables in a string with values from a supplied dictionary of registers. The parser is very lax and will not interpolate variables that don't exist, as users may not be intending to int...
a877e455771e09bcca85455ffefe87c4622255f2
44,522
def login(user=None, verified=False, admin=False, overrides=None, return_field=None): """ Logs in user and returns the User object. If a user object is not specified, one is randomly generated. The user object is force authenticated on the DRF API client. If the return_field is specified it returns the ...
7da1a5f50d10bce6cc4231cdb084e6a635d169a3
44,523
def retrieve_from_any(ecli, rootpath=None): """ Checks if it can find the xml document in the filesystem, otherwise retrieves it from the web. :param ecli: :param rootpath: :return: xml element """ el = None if rootpath is not None: el = retrieve_xml_from_filesystem(ecli, r...
37daf8adb654e941c1fdfd075470375860569759
44,524
def defineNodePositions(smax,pmin,fun,nodegap,L=200.): """ Loop through sections and determine optimal placement of nodes in order to prevent vignetting/collisions """ #Loop through sections and construct node positions N = len(smax) rsec = [] rext = [] gap = L*3e-3+0.4 #.4 mm glass ...
52a08fa1dc25d80ff5aff5e166eec8f9b396a257
44,525
import numexpr def normalize_mi_ma(x, mi, ma, clip=True, eps=1e-20, dtype=np.float32): # dtype=np.float32 """This function is adapted from Martin Weigert""" if dtype is not None: x = x.astype(dtype, copy=False) mi = dtype(mi) if np.isscalar(mi) else mi.astype(dtype, copy=False) ma = d...
c8a93fff58dfa9d288128278d2d894df82427122
44,526
def read_image(img_path): """Keep reading image until succeed. This can avoid IOError incurred by heavy IO process.""" got_img = False while not got_img: try: img = Image.open(img_path).convert('RGB') got_img = True except IOError: print("IOError incur...
26d0d0061d14e6916273a4fd418d5364ea1256ec
44,527
def check_image_valid(im_source, im_search): """Check if the input images valid or not.""" if im_source is not None and im_source.any() and im_search is not None and im_search.any(): return True else: return False
d5bc706df271163b1857158820ee707a0229b83c
44,528
def fabric_inband_net_create(module, inband_static_part): """ Method to create in-band network. :param module: The Ansible module to fetch input parameters. :param inband_static_part: It contains ip address of inband ip till third octet. :return: The output messages fo...
a44edd0e3998cd3ac622876a852d9e2aafa045e2
44,529
def create_match_apds_input_filenames(from_date, to_date, datestring): """ Create the list of filenames for match_apt_trajectories.py. """ return [create_flights_filename(CPR_FR24, datestring), create_apds_flights_filename(from_date, to_date), create_events_filename(CPR_FR24, datestring)...
118c214bfe1da657b2020ff4cc977cbef43266d5
44,530
def get_emoji_modifier_sequences(age=None): """Return map of modifier sequences to name, optionally limited to those <= the provided age.""" _load_emoji_sequence_data() return _age_map_select(_emoji_modifier_sequences, age)
ad3f48d2492caa24bcbc4d055a95a2d088921795
44,531
def update_taxes_with_shipping_lines(taxes, shipping_lines, shopify_settings): """Shipping lines represents the shipping details, each such shipping detail consists of a list of tax_lines""" for shipping_charge in shipping_lines: if shipping_charge.get("price"): taxes.append({ "charge_type": _("Actual"), ...
21a30b6d9e83432b9772c70bce30cd722ccb10c5
44,532
from typing import List def equal_accuracy(confusion_matrix_list: List[np.ndarray], tolerance: float = 0.2, label_index: int = 0) -> np.ndarray: """ Checks if accuracy difference of all grouping pairs is within tolerance. .. note:: This function expects a list...
f7bd87ae947acd1496fd11b5c96b492d5af978eb
44,533
def vm_snapshot_list_cb(result, task_id, vm_uuid=None, snap_ids=None): """ A callback function for DELETE api.vm.snapshot.views.vm_snapshot_list. """ snaps = Snapshot.objects.filter(id__in=snap_ids) action = result['meta']['apiview']['method'] if result['returncode'] == 0: vm = snaps[0]...
d57eb75d596a414ec77b4a3fe471c665b34f40b0
44,534
import array import math def fpart(x): """FRACTIONAL PART OF A REAL NUMBER""" if type(x) in [array, list]: if len(x) == 1: x = x[0] return math.modf(x)[0]
03659c7b0ae133d226019141af59f4ec039c7dde
44,535
import os def get_mfp(path, recursive): """many,flat,prefix""" path = normalize_path(path) flat = not recursive many = recursive prefix = "" if path[-2:] == "**": many = True flat = False prefix = os.path.basename(path[:-2]) elif path[-1:] == "*": many = True flat = True prefix =...
a34b315bb466c0374b40c0a32a84e5334b69a56e
44,536
def BinomialNum(n, p): """Generate a binomially distributed random number with parameters n (int) and p (float)""" assert type(n) == int, "n must be an integer" assert n >= 1, "n must be greater than or equal to 1" assert 0 < p < 1, "p must be between 0 and 1, exclusive" return sum([BernoulliNum(p) for x in range(...
d96a49b07d9068e2c7352e241c515d6c5f2642b7
44,537
def graph_size_filter(graph, edge_weigths, node_sizes, min_size, node_labels=None, relabel=False): """ """ n_nodes = graph.numberOfNodes if node_labels is None: seeds = np.zeros(n_nodes, dtype='uint64') assert n_nodes == len(node_sizes) keep_nodes = node_si...
8509d6f207bbd2ed8e676c2909b2daa2792a596e
44,538
def prepare_arguments_deps(parser): """Parse arguments that belong to this verb. Args: parser (argparser): Argument parser Returns: argparser: Parser that knows about our flags. """ parser.description = """ Manage dependencies for one or more packages in a catkin workspace....
a81760948787921c0bdaa6d34a34f688392f2a0f
44,539
from typing import Optional def bar(a: Optional[int], b: t.Optional[int]) -> int: """WHAT""" return (a or 42) + (b or 0)
b2e43cb30c8af5fa8b03220ae0f7260084a5f9fd
44,540
from functools import reduce def checkarrays(f): """ Similar to the @accepts decorator """ def new_f(*args, **kwd): assert reduce(lambda x, y: x == y, map(np.shape, args))\ , """Array and Subarray must have same dimensions, got %s and %s"""\ .replace(' ', '') % (ar...
50c579f02cd99a84eb7c9e11a1daf63e652d7f52
44,541
from PCAfold import PCA def outlier_detection(X, scaling, method='MULTIVARIATE TRIMMING', trimming_threshold=0.5, quantile_threshold=0.9899, verbose=False): """ Finds outliers in the original data set, :math:`\mathbf{X}`, and returns indices of observations without outliers as well as indices of the outli...
d5d596616ab8ee838cfbf0c679f07a7bfbb06c32
44,542
import subprocess import sys import os def read_coverage(chrom, cov=10, length=249250621, path="data/exacv2.chr{chrom}.cov.txt.gz"): #length may need to be fixed in the future, if new chromosome lengths are established in GRCh38 #or data/Panel.chr{chrom}.coverage.txt.gz for exacv1 """ read ExAC coverage from ...
e5e2d3ac416c52f6529e7abaac3408ee64c93133
44,543
import typing import math def list_to_mathutils(values: typing.List[float], data_path: str) -> typing.Union[Vector, Quaternion, Euler]: """Transform a list to blender py object.""" target = get_target_property_name(data_path) if target == 'delta_location': return Vector(values) # TODO Should be ...
04da3947be4fa82c67707d62bc8d092c6729252a
44,544
def count_smileys(arr): """count valid smileys from an array, better reading""" count = 0 eyes = ":;" noses = "-~" smiles = ")D" for i in arr: if len(list(i)) > 2: if i[0] in eyes and i[1] in noses and i[2] in smiles: count += 1 else: if i[0] in eyes and i[1] in...
ebcd9147614b47a9911dfcb408bfd74c71de4203
44,545
def apply_mlrun( model, context: mlrun.MLClientCtx = None, X_test=None, y_test=None, model_name=None, generate_test_set=True, **kwargs ): """ Wrap the given model with MLRun model, saving the model's attributes and methods while giving it mlrun's additional features. examples...
8b84c7ea83d9c67a481afd423218150594ecaf4f
44,546
def process_file(filename,word_to_id,cat_to_id,max_length=600): """ Args: filename:train_filename or test_filename or val_filename word_to_id:get from def read_vocab() cat_to_id:get from def read_category() max_length:allow max length of sentence Returns: x_pad: sequence data from preprocessing sentence ...
0eca98da162000b1d86a707514eb4b4b13fa85ce
44,547
def get_key_list(u_id: str, um_status: int) -> list: """ 获取某个用户保存的友盟keys :param u_id: :param um_status: :return: """ _filter: Q = Q(u_id=u_id) & Q(um_status=um_status) return list(UmKey.objects.filter(_filter).values())
09d4808161994c4515588bf9b7761842ced490e0
44,548
def balanced_tree(ordered): """Create balanced binary tree from ordered collection""" bt = BinaryTree() add_range(bt, ordered, 0, len(ordered)-1) return bt
50fc5c843c581107df8b1db1d1bb8db74a0b5147
44,549
def tf_split(x, num_or_size_splits, axis=0, num=None, keep_dims=False): """Split feature map of high dimension into list of feature map of low dimension.""" x_list = tf.split(x, num_or_size_splits, axis, num) if not keep_dims: x_list2 = [tf.squeeze(x_, axis) for x_ in x_list] return x_list2...
529f713c9fcd94599f4eb320d8529ed53f551f11
44,550
def stringify_edge_set(s: set): """ Convert an agent-piece graph into a string, for display and testing """ return str(sorted([(agent.name(), piece) for (agent,piece) in s]))
8d95fa4174a37bac1094a13449f92143993bdd23
44,551
def rholoc(A1: tn.Tensor, A2: tn.Tensor) -> tn.Tensor: """ -----A1-----A2----- | |(3) |(4) | | | | | | |(1) |(2) | -----A1*----A2*----- returned as a (1:2)x(3:4) matrix. Assuming the appropriate Schmidt vectors have been contracted into the As, np.trac...
c05735c17f0ca58f19388c691366c51c07d2f584
44,552
def _d(n, j, prec, sq23pi, sqrt8): """ Compute the sinh term in the outer sum of the HRR formula. The constants sqrt(2/3*pi) and sqrt(8) must be precomputed. """ j = from_int(j) pi = mpf_pi(prec) a = mpf_div(sq23pi, j, prec) b = mpf_sub(from_int(n), from_rational(1,24,prec), prec) c ...
f2a37ee3df6dc2d5a1e615df88ef43e37031f872
44,553
def render_show_category_json(category_id): """ METHOD=GET. Returns a JSON object of a specific category """ category = session.query(Category).filter_by(id=category_id).one() items = session.query(Item).filter_by(category_id=category_id).all() if category and items: return jsonify(...
29f14e41b91820c883d33539d71c96bbd9dbf047
44,554
def get_fully_qualified_class_name(cls): """Returns fully dot-qualified path of a class, e.g. `ludwig.models.trainer.TrainerConfig` given `TrainerConfig`.""" return ".".join([cls.__module__, cls.__name__])
dc3cbbb8be4503b562a381aa45842399a623971e
44,555
import sys def set_completed_todo(todo_id): """The route handler setting a todo item to completed. Args: todo_id: A str representing the id of the todo item that was completed Returns: Response: A json object signalling the update request was successful """ error = False try...
85bd8b15887b1716f73734f3207c626344ded86e
44,556
import sys def extARRAYPROC_ZIP(argu): """ allow processing the data using multicore capabilities This is a temporary method, as python cannot process using multicores within classes. So we have to call a method from within the class to run multicores. you provide a - ** parameters**, **types**, **r...
273d732310c01c460d7700480c58de547d1a3f52
44,557
from typing import Union def convert_bytes(bytes: int, unit: str = "Mi") -> Union[str, int]: """Converts a number of bytes to a string representation. By default, the output is in MiB('Mi') format. If unit is 'b', the output would be an integer value. (e.g., convert_bytes(1024, 'b') -> 1024) Onl...
dc38268c668e1b49718f167b5fc2767613d055b1
44,558
def global_settings(request): """ Expose various settings """ return { 'global_settings': { 'google_analytics_tracking_id': settings.GOOGLE_ANALYTICS_TRACKING_ID, 'IMIS_SSO_LOGIN_URL': settings.IMIS_SSO_LOGIN_URL, 'HELIX_LOGOUT_URL': settings.HELIX_LOGOUT_URL ...
0f83b5000a8946d46fba244bdc67b5f2141ee0dc
44,559
def index(): """ The landing page of the site :return: Returns a rendering of the landing page. """ form = Transaction(request.form) return render_template("transaction.html", form=form)
e85ff39e1525b303604c815eea6b33d69290ac35
44,560
def determine_flow_unit(stock_unit: str, time_unit: str = "h"): """For example: >>> determine_flow_unit("m³") # m³/h >>> determine_flow_unit("kWh") # kW """ flow = to_preferred(ur.Quantity(stock_unit) / ur.Quantity(time_unit)) return "{:~P}".format(flow.units)
b359cba095f94101ac5c9ef1d6815897db33cff9
44,561
from typing import List def handle_hosts( actapi: act.api.Act, content: Text, hosts: List[Text] ) -> List[act.api.fact.Fact]: """handle the hosts part of a hybrid-analysis report""" feeds_facts: List[act.api.fact.Fact] = [] for host in hosts: (ip_type, ip) = act.api.helpers.ip_obj(host) ...
14aee6fbe5eb2d51c8ae2349648f6f32573030e7
44,562
def parsevROps(payload, alert): """ Parse vROps JSON from alert webhook. Returns a dict. """ if (not 'alertId' in payload): return alert alert.update({ "hookName": "vRealize Operations Manager", "AlertName": payload['alertName'] if ('alertName' in payload and payloa...
8149dd87f26c0767692dcd79ab88a36e1f2e328b
44,563
def as_chunks(l, num): """ :param list l: :param int num: Size of split :return: Split list :rtype: list """ chunks = [] for i in range(0, len(l), num): chunks.append(l[i:i + num]) return chunks
6bf6a2efed8e4830447319dd1624e70463faaf41
44,564
def extract_average_values_roc(nb_random_realizations, fpr_list, tpr_list, auc_values): """This function extracts the average values for the ROC curve across the random realizations Args: nb_random_realizations (int): number of cross-validation runs that were performed fpr_list (list...
710a904ce50f6fd0f7c8b0cec1a44c72f4417041
44,565
def prepare_for_training(data, polynomial_degree=0, sinusoid_degree=0, normalize_data=True): """Prepare dataset for training on prediction.""" # Calculate the number of examples. num_examples = data.shape[0] # Prevent original data from being modified. data_processed = np.copy(data) # Normali...
c20ac524ed44bb9c1bff0943c85ec16251a6915a
44,566
def z_curvature_stacks(z_fit_params, z_contour_stack): """ Calculates curvature, normal, and tangent vectors of contours on a given image stack on z-slice Iteratively steps through z_fit_params and z_contour_stack and calls curvature_z_slice Parameters ---------- z_fit_params : list ...
8af26fb34a9a1d6b78adf6d2192c040504f0f355
44,567
import requests def get_ec2_instance_ip(): """Try to obtain the IP address of the current EC2 instance in AWS""" try: ip = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.01).text except requests.exceptions.ConnectionError: return None return ip
b9b403124daba52236218d75225c537b450f283b
44,568
import random def e_greedy(options, e=0., reverse=False): """ Epsilon-greedy algorithm for selecting sampled bandits Parameters ---------- options : list list of the bandits samples e : float, default = 0 epsilon value between 0 and 1 that determines how random the chosen bandit i...
648ceccf20ac19078557f8185f83c29c985f8ae8
44,569
from typing import Tuple from typing import List def get_all_serialization_annotations( annotation: Annotation ) -> Tuple[Annotation, List[SerializationAnnotation]]: """Gets the type T of Annotation[T, SerializationAnnotation] Args: annotation (Any): The annotation Returns: Tuple...
a88818a33ec311fb39ad7d42ecd6abc3b651b062
44,570
def _name_to_agent_class(name: str): """ Convert agent name to class. This adds "Agent" to the end of the name and uppercases the first letter and the first letter appearing after each underscore (underscores are removed). :param name: name of agent, e.g. local_human :return: ...
6ac0dbf4fb8ab90e592b85216be6d9c109a1310c
44,571
def bin_search_recursive(array, what_to_find, left=0, right=None): """ Finds element in a sorted array using recursion. :param list array: A sorted list of values. :param what_to_find: An item to find. :returns: Index of the searchable item or -1 if not found. """ right = right if right is...
83ff4dbcd9cab179c5e83f73d5fdc7c5a6bca4d4
44,572
from typing import List def extensions_to_glob_patterns(extensions: List) -> List[str]: """Generate a list of glob patterns from a list of extensions. """ patterns: List[str] = [] for ext in extensions: pattern = ext.replace(".", "*.") patterns.append(pattern) return patterns
a04ed356bfa5db7c0210b86dff832d32bfef6dbf
44,573
def is_classvar(t): """ >>> is_classvar(typing.ClassVar[int]) True >>> is_classvar(int) False """ return is_from_typing_module(t) and str(t).startswith("typing.ClassVar[")
611092fa7c2f430aa755bbd667d40abcd7ccf693
44,574
from typing import Tuple def get_reduced_powers(values: Tuple, power: int) -> Tuple[Expr, Symbol]: """ For a variable v only taking finitely many values v**n can be written as linear combinations of powers < |values|. This function computes this linear combination. The values ought be passed as a sort...
edb4977ec5ee84129f35b1d8bafed59ad948b3f0
44,575
def detect_cross_pnt(arr, thr, way='up', gap=1): """ detect the data rise/down point, returns the index of the point right above the threshold. arguments: - arr: data array (1d) - thr: threshold (scale) key arguments: - way: either be "up" or "down", for data rise/ data down respective...
0cf5db8f78cb0ee81174a7d662551c095480de97
44,576
def check_resource(drink_ingredients): """Checks whether the ingredients in the machine enough to make the drink""" for items in resources: if drink_ingredients[items] > resources[items]: print(f"Sorry there's not enough {items}!") return False return True
ecd869d4f09032e57d151ec6816fc2b08dce41b8
44,577
def handler(event, context): """ https://docs.aws.amazon.com/lambda/latest/dg/with-scheduled-events.html """ print(event, context) publisher.handle(event, context) return {}
049029afedc796f86fd2b82637464e724d722bf9
44,578
from typing import Union from typing import Mapping def extract_image( inputs: Union[jnp.ndarray, Mapping[str, jnp.ndarray]] ) -> jnp.ndarray: """Extracts a tensor with key `image` or `x_image` if it is a dict, otherwise returns the inputs.""" if isinstance(inputs, dict): if "image" in inputs: retur...
2a4ecc20c861532736a4725fbe5a19b53847a53e
44,579
def drop_duplicate_cols(df: pd.DataFrame) -> pd.DataFrame: """Remove duplicated colulms from a df # https://stackoverflow.com/questions/14984119/python-pandas-remove-duplicate-columns/40435354#40435354 Args: df (pd.DataFrame): df with duplicated column names Returns: pd.DataFrame: df ...
3b5ffa67b363e59271a5c6392fec0365c2034daf
44,580
def find_sources(indegrees: dict) -> deque: """Find sources (nodes that have 0 inbound edges). Args: indegrees (dict): A dictionary where the key is a graph node \ and the value is the number of inbound edges. Returns: deque: A deque containing source nodes. """ sources = d...
f31c67eedebe9d15aa65fbbcc1b36cf52c4eccc7
44,581
def stretch_audio(x, rate, window_size=512): """Stretch the audio speech using spectrogram. Args: x (numpy.ndarray): Input waveform. rate (float): Rate of stretching. window_size (int, optional): Window size for stft. Defaults to 512. Returns: numpy.ndarray: The stretched a...
cd07aca4db84eb8934510afd6770b439289bc264
44,582
async def email_subscribe_confirm(token, hood=Depends(get_hood_unauthorized)): """Confirm a new subscriber and add them to the database. :param token: encrypted JSON token, holds the email of the subscriber. :param hood: Hood the Email bot belongs to. :return: Returns status code 200 after adding the s...
441ec97f6534749fb6a006a443326f56ebe75f8f
44,583
def pairing_gen(email_addresses): """This function generates the final pairings and outputs an alphabetically sorted pandas dataframe with all elements in both columns """ pairing_1 = [] pairing_2 = [] for first_member, second_member in grouper(email_addresses, 2, SUBSTITUTE): pairing_1.appe...
5efa2b3a7f6de73c2c117dd3e7a0407e8ce52e57
44,584
import torch def get_joint_loss(data_dict, device, config, weights, detection=True, caption=True, reference=True, use_lang_classifier=True, num_ground_epoch=50): """ Loss functions Args: data_dict: dict config: dataset config instance reference: flag (False/True) Returns: ...
66d5358286b20dc2e4efa5ed71bea298c4a5eeca
44,585
def specr_model(fn, a,b,c1,c2,d,e): """ Description: ------------ Theoretical model for spectral ratio. Preferred model is determined by the values of d & e and they are user-defined. Input: ----------------- fn --> freqeuncy bins a --> fc main event b --> fc egf ...
1355ba14569cb87ebe6d8f937db81db89fc8c952
44,586
import re def get_operation_id_groups(expression): """Takes an operator expression from an .mmcif transformation dict, and works out what transformation IDs it is referring to. For example, (1,2,3) becomes [[1, 2, 3]], (1-3)(8-11,17) becomes [[1, 2, 3], [8, 9, 10, 11, 17]], and so on. :param str ...
8ec6fdca5209de1d658a2ae938fc840e9d1b0c23
44,587
from typing import Optional def is_plus(char: Optional[str]) -> bool: """Check if character is a plus symbol.""" return char == PLUS
9a9a1141f87150ec621e283362a1831eb0bb8288
44,588
def mrt_alert_msg(mrt_line, direction, stations, public_bus, mrt_shuttle, mrt_shuttle_dir): """ Message that will be sent if there is an MRT alert/breakdown/delay :param mrt_line: "DTL/NSL/EWL..." :param direction: "Both"/specific MRT station name("Jurong East") :param stations: "NS17, NS16, NS15, N...
df03473dab23748f42bfe9fc8bc0fe9a80fc7c74
44,589
import re def normalize(contentData): """ The primary normalization and de-obfuscation function. Runs various checks and changes as necessary. Args: contentData: Script content Returns: contentData: Normalized / De-Obfuscated content """ # Passes modificationFlag to each fun...
5bd34668e536aaf4d497f517fe5fde2197796baa
44,590
def clusters_tournament(ptree, labels): """A cluster 'wins' if some node inside the cluster is the ascendant of another node in the other cluster""" L = np.max(labels) + 1 T = np.zeros((L, L), dtype=int) for i, m in enumerate(ptree.match): li = labels[i] if li != -1: for ...
8ccf7ad28e58c44c7f12051bded48136fe7598c5
44,591
from datetime import datetime import requests from bs4 import BeautifulSoup def _load_quebec(start_date=datetime(2020, 1, 1), end_date=datetime.today(), verbose=True): """ Parameters: - `start_date` datetime object, the date of the earliest news release to be retrieved. By default, only ...
295b723a4e7ab6d36c540e1910e954b0efd439bd
44,592
def batch_to_model_inputs(batch, aux, prog, diag, forcing, constants): """Prepare batch for input into model This function reshapes the inputs from (batch, time, feat) to (time, z, x, y) and includes the constants """ batch = merge(batch, constants) def redim(val, num): if num == 1: ...
b0268c72499823bad747fb30e4be8d091c3060d6
44,593
def is_envvar(buff, pos): """:return: start, end, pos or None, None, None tuple.""" try: while buff[pos] in ' \t': pos += 1 start = pos while True: if buff[pos] in '\0"\'()- \t\n': return None, None, None if buff[pos] == '=': ...
ee424577dd91a7d7011996c5f185f15855e1d2f5
44,594
def application(): """Create an application.""" return flaked.Application()
067fc7e8763678b1ba3387f95f8b90fc3f1075bd
44,595
from bs4 import BeautifulSoup def urlscraper(url: str, pattern: str, regex:bool=False) -> list: """urlscraper is a simple method to scrape information from a url based on a given string pattern :param url: the url to run pattern against :param pattern: the string representation of the pattern :param ...
a1788fb1e6d98d1fb65dd3bdb617bf9a22f0a053
44,596
def load_model(filename): """ Return a model stored within a file. This routine is for specialized model descriptions not defined by script. If the filename does not contain a model of the appropriate type (e.g., because the extension is incorrect), then return None. No need to load pickles o...
2be8d79119538c31606dfccffd8560aa82dc4e7a
44,597
def climb_stairs(stairs): # """You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example: Input: 2 Output: 2 3 1 1 1 1 2 2 1 """ ...
c32a05ab1013b769c2d040a00c622605d7893398
44,598
def measure_nearest_neighbor_performance(accuracy_label, encoder, family_accessions, batch_size, train_samples, shuffle_seed, sample_random_state): """Measures nearest neighbor classification p...
defbc8a86978062997fb6bacb912c014ede6fbf0
44,599