content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from functools import reduce def overlay(xss): """ Interleave two playlists by overlaying unique elements. Elements from YS are only picked if they are unique. Non-unique YS elements are ignored, and an element from XS is picked instead. Thus, the unique elements of YS are "overlaid" onto XS. ...
9b00f6b11c4e148c05b16553d092bcb304fdb828
3,609,700
def uniquify_mask(lhs, ctx): """Element ÞU (any) -> A list of booleans describing which elements of a will remain after uniquifying. """ lhs = iterable(lhs, ctx=ctx) # TODO (user/cgccuser): Reduce code duplication here? if isinstance(lhs, list): seen = set() mask = [...
d651f4d40fe8d7b150a6d4b0eb112d6dbba75c34
3,609,701
def UpdateName(new_name): """ Method for the dApp owner to update the dapp name :param new_name: new name of the dapp :type new_name: str :return: whether the update succeeded :rtype: bool """ if not CheckWitness(OWNER): Log("Must be owner to update name") return False...
6e083bdb27439f86cc1250e59ac242c4dae65263
3,609,702
def get_entrez_df( force: bool = False, ) -> pd.DataFrame: """Get the Entrez mappings dataframe.""" return ensure_df( PREFIX, url=ENTREZ_XREFS_URL, sep="\t", names=[ "mgi_id", "symbol", "status", "name", "position", ...
b37da140e085fe126cb4902130b0d013b32f1a44
3,609,703
def ks_unif_pelz_good(samples, statistic): """ Approximates the statistic distribution by a transformed Li-Chien formula. This ought to be a bit more accurate than using the Kolmogorov limit, but should only be used with large squared sample count times statistic. See: doi:10.18637/jss.v039.i11 and...
aa774a88f4720694ad3c801e70ef829a96181f7c
3,609,704
def tm_team_transfers(club, season, position_group='All', main_position='All', window='All', currency='EUR'): """ Extracts basic player information for each player in a squad including basic player information, market value, and contract expiration Parameters: club (string): club name season (strin...
04f277d2ff957f274eef91fb9102c376e7404e07
3,609,705
def Month(year, month): """Define an smv.panel.Month Month extends smv.panel.PartialTime base class Args: year (int): month (int): Example: >>> m = Month(2012, 5) >>> m.smvTime() u'M201205' >>> m.timeIndex() ...
4d92e668caf08b8db81553b78d719c978a180e80
3,609,706
def single_threaded_session(): """Returns a session which will only use a single CPU""" return make_session(1)
1ce0f094ae26e178a9588f4fb87a97588a159af6
3,609,707
def buoyancy(sig0, rho0=1025.0): """Calculate buoyancy [m/s^2] based on potential density. Inputs ------ sig0: DataArray, ndarray Potential density [kg/m^3] rho0: int, float, optional Reference density [kg/m^3]. Returns ------- DataArray or ndarray of calculated buoyanc...
0c7500601d365a847235edcbb265db16ddcc678e
3,609,708
import signal def shrink_mask(mask, kernel): """Shrink mask wrt to a kernel Parameters ---------- mask : 2D boolean array_like the mask to be shrinked by... kernel : 2D float array_like ... the corresponding array Returns ------- 2D boolean array the correspon...
f43e760a3442651c50d0ee6a7d56d35b8450a659
3,609,709
import platform def host_clang(xcrun_toolchain): """ Return a Toolchain for the host platform. If no appropriate compilers can be found, return None. """ if platform.system() == 'FreeBSD': # See: https://github.com/apple/swift/pull/169 # Building Swift from source requires a recent...
fb7c19fa6941d680444ca9282eb87b91dbd43f26
3,609,710
def bootstrap(a, nboot=1000, summary_fn=np.mean): """ Calc vectorised bootstrap sample of array of observations By default return the mean value of the observations per sample I.e if len(a)=20 and nboot=100, this returns 100 bootstrap resampled mean estimates of those 20 observations ""...
ebd7379c1b3b6d078175601683fe22dc50d71d9c
3,609,711
def element2obs(obs, allow_null=False): """ Remaps the old format to new api Observation model for a single observation. Returns a dictionary, not an observation instance. """ # Should only be one _obs = {} #For now we require non-empty strings if obs['answer']: _obs['value']...
49dd82639b5099eed9b7251ddde903429c0fff38
3,609,712
from resources.lib.kodi import ui import base64 import json def _get_authentication_key_data(file_path, pin): """Open the auth key file""" try: file_content = load_file(file_path) iv = '\x00' * 16 cipher = AES.new((pin + pin + pin + pin).encode("utf-8"), AES.MODE_CBC, iv.encode("utf-8"...
3268324ad452a9844b930c1c62bf6ff3bed213cd
3,609,713
def mark(label, func=None): """Mark the function/class with the given label. This may be used as a decorator. """ if func is None: def decorator(func): return mark(label, func) return decorator if isinstance(func, type): cls = func apply_to_test_methods(c...
960360545f01ed17c27b8045fadebd92a70b0e9b
3,609,714
def managerSpecificKey(key): """ Produces a manager-localised key for persistent options, etc.. """ manager = FnAssetAPI.SessionManager.currentManager() if not manager: return key identifier = manager.getIdentifier() # Hiero doesn't seem to like dots in tag names safeIdentifier = identifier.replace...
35bcaf7bd390608bb8cffb2f1d9518b99ab88bc3
3,609,715
def parse_load_balancer_name(load_balancer_arn): """ Parse name out from load balancer ARN Example: ARN of load balancer: 'arn:aws:elasticloadbalancing:us-east-1:881508045124:loadbalancer/app/alb-1/72074d479748b405', Load balancer name: 'alb-1' return: load balancer name """ return load_...
c64e4545d30c18bca2c05df3433958e012f0ed47
3,609,716
def unsupervised_labels(y, yp, n_classes, n_clusters): """Linear assignment algorithm Arguments: y (tensor): Ground truth labels yp (tensor): Predicted clusters n_classes (int): Number of classes n_clusters (int): Number of clusters """ assert n_classes == n_clusters...
71d4f98492b4b289353be0d139b5fba0da2a76a7
3,609,717
def process_and_validate_ref(ref, paper_database): """Takes a reference and database. First tests if the reference is an alias in the database. Then attempts to extract arxiv id from the reference (which might be a whole url). Then returns the processed reference or throws an error if it is not a valid ...
305a54ae561724a965fbbe8a67e360d7057796d5
3,609,718
def taggifier(tag: str, **kwargs) -> Macro: """ Create a Builder Modifier that wraps the text in HTML tags. The tag name is mandatory. Attributes can be added as keyword arguments. All attributes are forced to be lowercase so you can avoid name collisions by capitalizing words like "class". """...
2660310c82dc7607fde4c7a67cbfe1c9578bb57e
3,609,719
import uuid import logging def _AddTask( queue_name, payload, target=None, name=None, eta=None, transactional=False): """Add a task using a selected task scheduler implementation. Args: queue_name: a queue name. payload: a task payload. target: a target module name. name: a task name. eta...
43212dfa518f53882d4529e9b2bdedd6c49aa084
3,609,720
def adjust_course_account(): """ This api adjusts the course credit account for a student. """ student_id = request.json.get('student_id', None) course_id = request.json.get('course_id', None) transaction_type = request.json.get('transaction_type', None) amount = request.json.get('amount', N...
669a1499a69b3ef60687bc835d26140813d25108
3,609,721
from typing import Optional def get_gateway(gateway_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetGatewayResult: """ Resource schema for AWS::IoTSiteWise::Gateway :param str gateway_id: The ID of the gateway device. """ __args__ = dict() ...
0f0cbbd7fee198941fb58f3bcfb37b8e6c6c2593
3,609,722
import json def __get_categorical(self, sock=None): """ Transform column to numpy array Args: sock: Socket connecting the Python API with the getML engine. """ # ------------------------------------------- # Build command string cmd = dict() cmd["name_"] = self....
c7c84d90c622470eaf0ff6cb2d61bbd2ae16eb80
3,609,723
def getUnicodeIndexGroup(name): """ Return a group letter for `name`, which must be a unicode string. Currently supported: Hangul Syllables (U+AC00 - U+D7AF) @param name: a string @rtype: string @return: group letter or None """ c = name[0] if u'\uAC00' <= c <= u'\uD7AF': # Hangul S...
9a7c53619781acd606d8f823012c6e9a0030cd71
3,609,724
import json import time import requests def job_run(jobId): """ Run a saved job RouteParams: jobId: the id of a job GetParams: account: an account user: a user Returns: a json representation of a job """ account = request.form['account'] user = request...
c418774bee6b7d1967ae4de756ff2183e6cb4d72
3,609,725
from typing import List from datetime import datetime import os import json def generate_context_csv( event_extractor, paths:List[str], seq: bool=True, window_size:int=30, step:int=5, columns:List[str]=None, outdir:str='./' )->str: """Writes a context.csv fi...
24443421e3b34e4d5180cda0911735280b46d0dd
3,609,726
def get_embedding(x: Tensor, base_model: nn.Module) -> Tensor: """ apply f until the last layer, instead return that as the embedding """ out = x # if it has a get embedding later if hasattr(base_model, 'get_embedding'): out = base_model.get_embedding(x) return out # for handling mod...
d238bdd4e8735f0b723a63ced7ea1d13be21a570
3,609,727
def plot_confusion_matrix(cm, class_names, title='Confusion matrix'): """ This function prints and plots the confusion matrix. """ cm = cm.round(decimals=2) figure = plt.figure(figsize=(30, 25)) df_cm = pd.DataFrame(cm) # , index=class_names, columns=class_names sn.set(font_scale=4) # for...
32a800ff3810fb52106ae7958eb08502bc90b088
3,609,728
def iint(number): """This method behaves in the same way as the **INT()** function described by Meeus in his book: Greatest integer which is not greater than number. :param number: Number or expresion :type number: int, float :returns: Greatest integer which is not greater than number :rtype: ...
ca5f4a288d7063d70695dee221cc875407745d8f
3,609,729
def init_xena(api, logger, owner, ip=None, port=57911): """ Create XenaApp object. :param api: cli/rest :param logger: python logger :param owner: owner of the scripting session :param ip: rest server IP :param port: rest server TCP port :return: Xena object :rtype: XenaApp """ ...
e62640b7a0449f29311f171e806d55916c9c21d7
3,609,730
from pathlib import Path def get_paths(dir_name, glob): """ returns a generator of the recursive paths on input glob """ return Path(f'./{dir_name}').rglob(glob)
6803981e40397d000900dd0a8fc8ee32eddc6bc4
3,609,731
def priceVector(A: np.matrix, rho: float, a: int | float, c: int | float, alpha) -> np.matrix: """ Parameters ---------- A : Network rho : network strength a : stand alone util c : marginal cost. Should be less than a Returns ------- Vector reprsenting what price to charge indiv...
f6d42670cd1e987169244c3c579783fa64f9dc46
3,609,732
def discover(email, credentials=None, auth_type=None, retry_policy=None): """ Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request, ...
2b2a77e6d670ff7343883e21bb24c29162673c55
3,609,733
def batch_local_dist(x, y, min_val): """ Compute local distance for batch Args: x: pytorch Variable, with shape [N, m, d] y: pytorch Variable, with shape [N, n, d] min_val: Minimal distance (for preventing division by zero) Returns: dist: pytorch Variable, with shape [N] """ ...
c0b444ce708907e06dc72510338339059e02dda8
3,609,734
def get_title_block(txt): """ Get the general doc of the cmake code. Should be at the top of the file, from the first '#!' to the next text block """ res = "" in_title = False for line in txt.splitlines(): if line.startswith("#!"): in_title = True res += c...
928f4623172711b7116772183299a1034aecac2a
3,609,735
import math def cudasolve(A, b, tol=1e-3, normal=False, regA = 1.0, regI = 0.0): """ Conjugate gradient solver for dense system of linear equations. Ax = b Returns: x = A^(-1)b If the system is normal, then it solves (regA*A'A +regI*I)x= b Returns: x = (A'A +reg*I)^(-1...
7519a656fadf3bb8c99eed28b4ace9f228a296c7
3,609,736
def fiyat(baslangic_tarihi=__dt.datetime.today().strftime("%Y-%m-%d"), bitis_tarihi=__dt.datetime.today().strftime("%Y-%m-%d"), periyot="saatlik"): """ İlgili tarih aralığı için saatlik GÖP, GİP, DGP fiyat bilgilerini vermektedir. Parametreler ------------ baslangic_tarihi : %YYYY-%AA-%GG...
0e2fc1bc1c7caf9265e0388819c2d656b2942ed1
3,609,737
def inverse_relation(dst, rel): """ Similar to :meth:``forwards_relation`` but selects the source nodes instead, given a destination node. :param dst: The destination node. :param rel: The relation. """ statement = 'SELECT src FROM %s WHERE dst = ?' return statement % rel, (dst,)
f3dd3ab848ccad4d5594710659fc342ad584e6b7
3,609,738
def PyUnicode_AsUnicodeEscapeString(space, pyobj): """Encode a Unicode object using Unicode-Escape and return the result as Python string object. Error handling is "strict". Return NULL if an exception was raised by the codec.""" if not pyunicode_check(pyobj): PyErr_BadArgument(space) w_un...
53cd2fb958e0935b70180f10d4484acf1c4506df
3,609,739
def normalize_bridge_id(bridge_id: str): """Normalize a bridge identifier.""" bridge_id = bridge_id.upper() # discovery: contains 4 extra characters in the middle: "FFFF" if len(bridge_id) == 16 and bridge_id[6:10] == "FFFF": return bridge_id[0:6] + bridge_id[-6:] # deCONZ config API conta...
be5230a4678f404613975ffc348fd5f9b8d1c631
3,609,740
def vdcorput(n, base=2): """[summary] Arguments: n ([type]): [description] Keyword Arguments: base (int): [description] (default: {2}) Returns: [type]: [description] """ return [vdc(i, base) for i in range(n)]
96e55e00a6801f4376a6b1b1e45a395b76f99ae4
3,609,741
def load_nib(fpath): """ Load nifti image :param fpath: path of nifti file """ im = nib.load(fpath) return im
16015584bd0a87dff19647fcebc559c0c55f82ec
3,609,742
def list_of_exchanges(test_mode: bool = False) -> list: """Get List of Exchanges available""" try: return ListOfExchanges(test_mode=test_mode) except Exception as exception: logger.error('Oops! An error Occurred ⚠️') raise exception
45048c97bb8078f33e541ef0f38d9ecafd508ee3
3,609,743
def Min(a, axis, keep_dims): """ Min reduction op. """ return np.amin(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis), keepdims=keep_dims),
22b62410f8360c0a2be9febcaa2fe8c87c8a7383
3,609,744
from datetime import datetime def generate_tea_config(event, context): """ Lambda function to return a TEA configuration. Requires that event contain the following: * CMR must be configured with an env variable * Path Parameter named 'id' with CMR provider name * HTTP Header named 'Authorizati...
7f369017223f4185bfb019661dc721da670c15a8
3,609,745
from typing import List from typing import Tuple from typing import Dict import time def run_on_dataset(tf_manager: TensorFlowManager, runners: List[BaseRunner], dataset_runner: DatasetRunner, dataset: Dataset, postprocess: Postprocess, ...
6bca17a57facce6c6732315317fa3139fff13b22
3,609,746
def rmflvec(self, **kwargs): """Writes eigenvectors of fluid nodes to a file for use in damping APDL Command: RMFLVEC parameter extraction. Notes ----- RMFLVEC extracts the modal information from the modal results file for all nodes specified in a node component called 'FLUN'. This compone...
cd4f63f2e9a3addcbf6f711ee80133392c6d7d2a
3,609,747
from typing import OrderedDict def group_by_until(self, key_mapper, element_mapper, duration_mapper) -> ObservableBase: """Groups the elements of an observable sequence according to a specified key mapper function. A duration mapper function is used to control the lifetime of groups. When a group expires,...
5cafd38378a312f271cd65cd9e4cf3313b933f1c
3,609,748
def createIniFile(name, subdir=None): """ Returns the path to the named configuration file. Deprecated: Use createSettingsFile() instead. """ return createSettingsFile(name, subdir)
d68fd24457f603cb261759f18ba68376ff2beb4e
3,609,749
def _nose_2eyes(landmarks): """ :param landmarks: :return: nose, right eye corner, left eye corner """ return np.array([_centroid_nose(landmarks), _centroid_right_eye(landmarks), _centroid_left_eye(landmarks)], dtype=np.double)
55a4ac088dffaafc39e296c2fd4d19d4bbe013b0
3,609,750
import pickle def load_model(model_path): """Loads existing model Parameters: model_path - path to the model file Returns: loaded model """ with open(model_path, 'rb') as f: return pickle.load(f)
a9bf3abd5717e05a381bbaf7228a02217b8bccc5
3,609,751
def get_package_attribute(name): """Retrieve package attributes from the package itself.""" with open("darwin/__init__.py") as init_file: for line in init_file: if line.startswith(name): return eval(line.split("=")[-1])
33e7cdb53fffa844576e4e9387218b3ccbe6926d
3,609,752
def legacy_redirect(id): """Redirect to the documents.""" error = { "code": PIDDoesNotExistRESTError.code, "description": PIDDoesNotExistRESTError.description, } try: record = get_record_by_legacy_recid(Record, id) except PIDDoesNotExistError: return error schema ...
9e1716a3b978922954360334271c285a14d80708
3,609,753
def get_service(hass, config, discovery_info=None): """Get the Pushetta notification service.""" api_key = config[CONF_API_KEY] channel_name = config[CONF_CHANNEL_NAME] send_test_msg = config[CONF_SEND_TEST_MSG] pushetta_service = PushettaNotificationService( api_key, channel_name, send_tes...
5ae13b5dc464d597b144632770067ca97dd173ae
3,609,754
from typing import Optional from typing import Dict from typing import Any import copy def filter_end_events_per_object_type(ocel: OCEL, object_type: str, parameters: Optional[Dict[Any, Any]] = None) -> OCEL: """ Filters the events in which an object for the given object type terminates its lifecycle. (E....
1cc42b4c362802516ea410b6856868c0cebf08ed
3,609,755
import logging def scrape_inverter(): """ Connect to the inverter and scrape the metrics """ client.connect() if "sungrow-" in options['model']: for i in bus["read"]: if not load_registers("read", i["start"], int(i["range"])): return False for i in bus["holdin...
9426618499ef6663ef62bfc5bd071fe21f6abc26
3,609,756
def call(cfg, clargs, cmds, **kwargs): """ IMPURE Delegates work to appropriate `call_*` functions. Parameters ---------- cfg: dict Configuration dictionary. clargs: Namespace Command line arguments (normalized). cmds: iter(tuple) Iterator of commands to be passed to `subpro...
098269efe7a3f20a15fd55b3d9aaa69cc288e772
3,609,757
import scipy def plotPeaks(x, y, peaks, showPeaks=True, plotLabels=False, fig=10, plotScore=False, plotsmooth=True, plothalf=False, plotbottom=False, plotmarker='.-b'): """ Plot detected peaks Arguments --------- x,y : numpy arrays scandata peaks : list list of pe...
db8475879ec60cd0de7750927ec2710196ce3ed5
3,609,758
def connect(creds): """ Connect to cloudformation, with user-provided options. :param region_creds: The region name and AWS credentials. :type region_creds: kaws.config.AwsCreds or kaws.config.RegionAwsCreds :rtype: boto.cloudformation.connection.CloudFormationConnection Note: IAM cannot authenticate a user us...
b45794b343115f87daae68d38805ae602678ad30
3,609,759
import re def isBaidu(url): """Return True if this url matches the pattern for Baidu searches""" #Example: http://www.baidu.com/s?wd=mao+is+cool&rsv_bp=0&ch=&tn=baidu&bar=&rsv_spt=3&ie=utf-8 pattern = 'http://www.baidu.com/s\?wd=[\S+]+' matches = re.match(pattern, url) if matches != None: return True...
b4c06154f1f4f2bd6a18bbcb08c2ce0b4d2cbbc9
3,609,760
def table_to_json(table): """ returns a table as JSON """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") return arcpy.RecordSet(table).JSON
40eb4469853779144cb1a60df706bfeb21030a94
3,609,761
def epost_history_with_retries(qids, dbname, maxretries): """Entrez EPost for a batch of queryids. qids - Collection of query IDs dbname - target NCBI database maxretries - maximum download attempts Returns the generated history, as parsed by Entrez.read() """ trie...
232bd19d3366e3a1c67a786c948d2deb67dc59a2
3,609,762
def cross_join(df1, df2): """ Return a dataframe that is a cross between dataframes df1 and df2 ref: https://github.com/pydata/pandas/issues/5401 """ if len(df1) == 0: return df2 if len(df2) == 0: return df1 # Add as lists so that the new index keeps the items in #...
5db6b7184e133f1bb2c7c63aff791292a4ad3dbf
3,609,763
import FWCore.ParameterSet.Modules def getModulesOfSequence(sequence): """ returns the modules found in a sequence. Note that a module can appear more than once. """ class Visitor: #---------------------------------------- def __init__(self): self.modules_found = [] ...
79fc93d5a5ea798db419b1156a596993d32b0f40
3,609,764
def client(clusterrole, namespace, kubeconfig, port, admin_client): """I have <clusterrole> permissions in <namespace>.""" needs_admin = namespace == 'all namespaces' if needs_admin: return admin_client ensure_namespace(admin_client, namespace) k8s_client = kubernetes.config.new_client_fro...
aed5faafc2cc194ed4a69a2d6815b5e4f5fa4b3b
3,609,765
import numpy as np def read_cnf_mols ( filename, with_v=False, quaternions=False ): """Read in molecular configuration.""" with open(filename,"r") as f: n=int(f.readline()) # Number of atoms box=float(f.readline()) # Simulation box length (assumed cubic) revw=np.loadtxt(filename,...
f9ff9578d66d4f57740a10fae727202796b58cc6
3,609,766
from re import T def multiply_series(*series) -> Series[T]: """ multiple addition """ if len(series) < 2: return series[0] return multiply_2series(series[0], multiply_series(*series[1:]))
025adb3b0ce42170438a28d88010942d87935a27
3,609,767
def get_app_id(c, app_name): """ Retrieve app-id for a given app name (in full). Called from get_id, not for use as sub-task. :return: False on error, True on not found (continue), or string with app uuid """ print(f'{CYAN}Retrieving app-id for {app_name}...{COL_END}') response = c.config.contro...
5be7a04a770fc927909ebc9d9eba6fff0524080f
3,609,768
def lnL_EB(time: np.ndarray, flux: np.ndarray, sigma: float, R_EB: float, EB_fluxratio: float, P_orb: float, inc: float, a: float, R_s: float, u1: float, u2: float, companion_fluxratio: float = 0.0, companion_is_host: bool = False): """ Calculates the log likelihood o...
9d17cbff17eefe29d271778b6c819f514026e374
3,609,769
def detect_burst(relevant_list, total_list): """ Assume (num. of relevant docs, total num. docs) as the two input lists returns state costs """ state_costs = [(0.0, 0.0)] # for the initial step s = 2 R = sum(relevant_list) D = sum(total_list) p_0 = (1.0 * R) / D p_1 = p_...
bf4d505d47eb0db2e2f32e254877391359ed408a
3,609,770
def generate_inside_field(center, segment, n, max_features, min_features, feature_variance): """ Args: "center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Ar...
2355631e9dc43b766c0420478f49629da0b29c9c
3,609,771
import os def ecr_used_images(): """ Check currently running ECS tasks for their used image and return images from ECR that are not in use. """ used_images = [] ecs = boto3.client('ecs') response = ecs.list_clusters() for c in response['clusterArns']: tasks = ecs.list_tasks(cluster...
8732fc02884659cd6be42e4b21f5c51c3f5f682a
3,609,772
import torch def diversity_score(xyz, distance_type:str, **kwargs) -> torch.tensor.shape == [1]: """ :param xyz: [B, P, N, 3] tensor :param distance_type: shape/part :param kwargs: {downsample_type:None, npoint_per_part:10} :return: [1] tensor of divs_score """ if distance_type == "shape":...
c04112b7dc8e0049ee318a118720bf7345ee7526
3,609,773
def find_left_element(sorted_data, right, comparator): """! @brief Returns the element's index at the left side from the right border with the same value as the last element in the range `sorted_data`. @details The element at the right is considered as target to search. `sorted_data` must ...
7edc5ba49da8dbcbdc45310331b68c8ebe0c4ee1
3,609,774
from typing import List def burn_io(instance_ids: List[str] = None, execution_duration: str = "60", configuration: Configuration = None, secrets: Secrets = None) -> List[AWSResponse]: """ Increases the Disk I/O operations per second of the virtual machine. Parameters ...
3c3c5dc0990944d3a69616e83802d695279def72
3,609,775
import sys import json def register_insert(gearman_worker, gearman_job): """ registering new user """ sys.stdout.write("[%s] :: Registering new user\n" % t) # convert string > datetime object gearman_data = json.loads(gearman_job.data) gearman_data.update({'datetime': parse(gearman_data['datetime'...
0d62041b4b54c57f0d24dc5ba2e1d8a937ae1a6c
3,609,776
def CreateTestBudget(client): """Creates a budget to run tests with. Args: client: AdWordsClient client to obtain services from. Returns: int Budget ID """ budget_service = client.GetBudgetService(SERVER, VERSION, HTTP_PROXY) budget = { 'name': 'Budget #%s' % Utils.GetUniqueName(), 'am...
881095c68260a96195b3c97f4cf83f6a7d30e8f7
3,609,777
def logout(): """Used to logout users""" logout_user() return redirect(url_for('home'))
6e59dbb50b6813c67b0804e226dc1ce951d39daa
3,609,778
def gaussian_kernel(x1: np.ndarray, x2: np.ndarray, sigma: int) -> np.ndarray: """ Compute the Gaussian kernel between x1 and x2. Args: x1: The first vector. x2: The second vector. sigma: The sigma of the Gaussian function. Returns: The Gaussian kernel between x1 an...
912f71fe3063b44b39f24886637d3e71cf1f0178
3,609,779
from datetime import datetime def make_windows_timestamp_value_getter(value_name): """ return a function that fetches the value from the registry key as a Windows timestamp. """ f = make_value_getter(value_name) def _value_getter(key): try: return parse_windows_timestamp(...
3ad16c5a76cc50a1b1e8632da95807ceb62dc179
3,609,780
def compute_area(c, target_layer): """ Compute area of the component on a given layer """ _print("Computing area ", c.name) c.flatten() # return c.area(by_spec=True)[layer] polys_by_spec = c.get_polygons(by_spec=True) _area = 0 for (layer, polys) in polys_by_spec.items(): _pr...
89039cd084a51353c2b8b539c9580c38f416b24a
3,609,781
import os def Sourceify(path): """Convert a path to its source directory form.""" if '$(' in path: return path if os.path.isabs(path): return path return srcdir_prefix + path
702a8998455ef077f8d237116752b39de2c0efc6
3,609,782
import json def admin_add_user(request): """ :param request: :return: """ # Make sure user has permissions # Get data group_results = group.objects.filter( is_deleted=False, ).values() permission_set_results = permission_set.objects.filter( is_deleted=False, ...
8903f410b05c27a3d26a32f1943958dd7180cc88
3,609,783
def generate_flac_dirname(library_root, metadata): """Build the directory for a track's FLAC file. :arg str library_root: the FLAC library directory :arg dict metadata: the finalized metadata for a single track :return: an absolute directory path :rtype: :obj:`str` """ _log.call(library_ro...
7e58d138ef98df8e08ca002f8920b5bc0a9a032c
3,609,784
def NamedParameterNames(fn): """! @brief Get names available to use as named parameters. """ try: co = fn.__code__ except AttributeError: return () return co.co_varnames[co.co_posonlyargcount:co.co_argcount+co.co_kwonlyargcount]
6d62a5d10d02483ee288b765c7e63a060871d839
3,609,785
def random_noise_model_profile(num_voters, num_cand, p, phi, distance="hamming"): """ Generate a random profile using the *Random Noise* probability distribution. Parameters ---------- num_voters : int The desired number of voters in the profile. num_cand : int ...
6da5526333ed61e92b821c008c6deb560f7ff69e
3,609,786
def create_and_validate_config(parsed_config: YAML = None) -> Config: """Run validation on config values.""" if parsed_config is None: parsed_config = fetch_config_from_yaml() # specify the data attribute from the strictyaml YAML type. _config = Config( app_config=AppConfig(**parsed_con...
ddb4eeb5a0b73d82cee49ca7fe652ba96d31b47e
3,609,787
def optimizer(): """ Get the optimizer to use for training :return: optimizer object """ opt = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) return opt
ba1fbe6e59287f31423be28dfc33efd70a29e3d1
3,609,788
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload Trafikverket Weatherstation config entry.""" return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
160038c53297a915087c591ed64e00f5d049a2cb
3,609,789
import argparse def valid_write_option(string): """ This method checks whether the string is one of the valid write options and if not raises an error. :param string: The write option :type string: str :return: str """ valid_options = ["w", "a"] if string not in valid_options: ...
8784d7af1bf4c35172bf61e8c08f08eed2ce68fa
3,609,790
from typing import Union from typing import List import os def get_relative_path(kid: str, parent: str) -> Union[List[str], None]: """ Return the relative path depth if relative, otherwise MAX_INT. Both the `kid` and `parent` should be absolute paths without trailing / """ # Note that os.path.com...
70d01d141585d39f288179b36b9821e8e7e224d5
3,609,791
from typing import List from typing import Tuple from typing import Any def min_w_ind(lst: List) -> Tuple[int, Any]: """ Returns the min value and its index :param lst: The list to get the max value in :return: Min value and its index """ val = min(lst) ind = lst.index(val) return ind,...
d0da7d1ab1c762f1af2333de6e8b829f8218fd25
3,609,792
def run_transition(): """ Transition execution/"stepping" - run color change for long dimming periods - runs the generated color dimming generators :return: Execution verdict """ if None not in Data.FADE_OBJ: try: r = Data.FADE_OBJ[0].__next__() g = Data.F...
ec9df50fa790384d570fbe8c2e4a30515defbecb
3,609,793
def DatetimesRangeFieldWidget(field, request): # pylint: disable=invalid-name """Datetimes range widget factory""" return FieldWidget(field, DatetimesRangeWidget(request))
d389b5a8388813add654afe5084b24c8c75a2edd
3,609,794
from typing import List from typing import Dict def get_company_news( ticker: str, s_start: str, s_end: str, ) -> List[Dict]: """Get news from a company. [Source: Finnhub] Parameters ---------- ticker : str company ticker to look for news articles s_start: str date to ...
8bbcadb8a1278203bb5c7e76a7a06f1bee4ce718
3,609,795
def count(iterable): """ Returns the number of items in `iterable`. """ return sum(1 for whatever in iterable)
a9bb4ac70cef36613372c1225202f97f70a642cf
3,609,796
def scipy_rankdata(a): """ Ranks the data, dealing with ties appropriately. Equal values are assigned a rank that is the average of the ranks that would have been otherwise assigned to all of the values within that set. Ranks begin at 1, not 0. Parameters ---------- a : array_like ...
a3b3cd0e87550238ecc3d0be3b444091b5b864dd
3,609,797
def _return_4roles(Z_com_deg, parti_coef): """private function for computing 4 roles""" assert Z_com_deg.shape[0] == parti_coef.shape[0], ("Error, Z_com_deg {} \ should have same length as parti_coef {} ".format(Z_com_deg.shape[0], parti_coef.sha...
7e680891f07eabe5ee226227962acb50b2f1461a
3,609,798
import torch def xy_to_cxcy(xy): """ Convert bounding boxes from boundary coordinates (x_min, y_min, x_max, y_max) to center-size coordinates (c_x, c_y, w, h). :param xy: bounding boxes in boundary coordinates, a tensor of size (n_boxes, 4) :return: bounding boxes in center-size coordinates, a tensor...
46eef5bb63c85a84050a57a2fb27618721b31eaa
3,609,799