content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def gamescriptToJson(title: str, version: str = None) -> dict: """ Get game script heirarchy as a dictionary (for saving as json, etc) """ scripts = GameScript.objects.all().filter(title=title) if version: scripts = scripts.filter(version=version) if len(scripts) == 0: print("No...
c76779b76b69fb1816f9e96136fdee903212d831
3,659,400
def is_ignored_faces(faces): """Check if the faces are ignored faces. Args: faces: Encoded face from face_recognition. Returns: bool: If a not ignored face appeared, return false, otherwise true. """ global ignored_faces for face in faces: matches = face_recognition.co...
bda7703cfb471ac5c95cb6aa30f6d758129ae8a5
3,659,401
from typing import Optional def get_prediction_model_status(hub_name: Optional[str] = None, prediction_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> ...
14ff24d3f7edf674c5cd29a643ae28a1a3d8ed99
3,659,402
def build_2d_grid(ir): """ Build simple grid with a column for each gate.""" grid = [] for g in ir.gates: step = [None] * ir.ngates if g.is_single(): step[g.idx0] = g if g.is_ctl(): step[g.ctl] = g.ctl step[g.idx1] = g grid.append(step) ...
55c17327fb530301ca505b42cdb8d47426491374
3,659,403
import argparse import os def parse_args(): """ Wrapper function of argument parsing process. """ parser = argparse.ArgumentParser() parser.add_argument( '--save_loc', type=str, default='.', help='where to save results' ) parser.add_argument( '--log_dir', type=str,...
2083d01de27f7f3b4481fe90dbc39614257aeb5d
3,659,404
from typing import Union from typing import List from typing import Tuple from typing import Dict from typing import Any import copy def emmental_collate_fn( batch: Union[List[Tuple[Dict[str, Any], Dict[str, Tensor]]], List[Dict[str, Any]]], min_data_len: int = 0, max_data_len: int = 0, ) -> Union[Tuple[D...
b18c7ebf50f5554055da5de8a2ddce9e758ea1ef
3,659,405
def trap_jac_factory(j, dt): """Factory function to return a function for evaluating the Jacobian of the trapezoidal formula. This returns a function of x_n (x at this time step). :param j: Jacobian of the function of x. :param dt: time step. :returns: trap_jac, callable which takes x_n and ev...
5e6c365b6b92c13577249d34e7580827dc894604
3,659,406
from pathlib import Path def get_position_object(file_path: FilePathType): """ Read position data from .bin or .pos file and convert to pynwb.behavior.SpatialSeries objects. If possible it should always be preferred to read position data from the `.bin` file to ensure samples are locked to ecephys...
2d20e5b0a4f7077748650e7a3e3054c79b68185c
3,659,407
import random def throw_dice(n): """Throw `n` dice, returns list of integers""" results = [] while n > 0: results += [random.randint(1,6)] n = n-1 return results
68c56b468ecd1eff59932099dd4620bae9581f45
3,659,408
import json def verify_token_signature(token): """Verify the signature of the token and return the claims such as subject/username on valid signature""" key = jwk.JWK.from_password(flask.current_app.config.get("SECRET_KEY")) try: jwttoken = jwt.JWT(key=key, jwt=token, algs=["HS256"]) r...
d93233acb8a26ba0552ddc26777ccab4e40c4306
3,659,409
def logtime_r2(t, y, ppd): """ Convert y=f(t) data from linear in time to logarithmic in time. Args: t: is the input time vector, linearly spaced y: is the input vector of y values ppd: number of points per decade for the output Returns: A 3-tuple (tout, you...
ed77d7665488d3620d5cb62f4ba443b2361944b4
3,659,410
def parcours_serpentin(n): """Retourne la liste des indices (colonne,ligne) (!!attention ici ligne et colonne sont inversées!!) des cases correspondant à un parcours de tableau de taille n x n en serpentin. Ex: pour T = [ [1,2,3], [4,5,6], [7,8,9] ] le parcour...
189e486ad82d75923244daf51c223254f7b29fcc
3,659,411
def bdev_rbd_unregister_cluster(client, name): """Remove Rados cluster object from the system. Args: name: name of Rados cluster object to unregister """ params = {'name': name} return client.call('bdev_rbd_unregister_cluster', params)
03bf70352b8df65044eba1c9ece4b156590e11bc
3,659,412
def get_rndc_secret(): """Use the singleton from the DesignateBindCharm to retrieve the RNDC secret :returns: str or None. Secret if available, None if not. """ return DesignateBindCharm.singleton.get_rndc_secret()
b6fb5aebd272a6bc4db7d6541112566109e28195
3,659,413
def transform_tweet(source_tweet): """ Perform transformation on one tweet, producing a new, transformed tweet. :param source_tweet: Tweet text to transform :type source_tweet: str :return: Transformed tweet text :rtype: str """ no_emojis = replace_emojis(source_tweet) as_tokens = tokenize_string(no_...
9c4722200c7c85157aefca0c65946b6dd0e264d5
3,659,414
import json def pdFrame(file): """Creates a pandas data frame from a json log file Args: file: json log file to read Returns: pandas data frame """ logger.debug("creating pandas data frame from {}".format(file)) data = [] with open(file) as f: for line in f: ...
bfb299820e4cd3001de89f3598a664a11988edc4
3,659,415
import scipy import time def fitDataBFGSM2(M, val, c_w_l, init=None, nozero=True, k=3e34, lam=1., name='W_Abundances_grid_puestu_adpak_fitscaling_74_0.00000_5.00000_1000_idlsave'): #init is the three initial values of the gaussian needed to fit the data """ function for determining the optimal fit given the desir...
35ddd0690e2ed60d6271f9be232cea3d808d562f
3,659,416
def set_complete_cfg_spacy(false_or_true: str): """Set all SpaCy configuration parameters to the same logical value.""" return pytest.helpers.backup_config_params( cfg.cls_setup.Setup._DCR_CFG_SECTION_SPACY, [ (cfg.cls_setup.Setup._DCR_CFG_SPACY_TKN_ATTR_CLUSTER, false_or_true), ...
10ac74714e11b8c8492de7ec1d2809323819b8eb
3,659,417
import sys import traceback def guard_unexpected_errors(func): """Decorator to be used in PyObjC callbacks where an error bubbling up would cause a crash. Instead of crashing, print the error to stderr and prevent passing to PyObjC layer. For Python 3, print the exception using chaining. Accomplished...
42b8e4ce05cca51272679ab5024d07798dafb357
3,659,418
def get_lun_ids(service_instance=None): """ Return a list of LUN (Logical Unit Number) NAA (Network Addressing Authority) IDs. """ if service_instance is None: service_instance = get_service_instance(opts=__opts__, pillar=__pillar__) hosts = utils_esxi.get_hosts(service_instance=service_in...
6194a8f73a71730d928391a492d5e8fe0fdb3f50
3,659,419
def parse_midi_file(midi_file, max_notes=float('Inf'), max_time_signatures=1, max_tempos=1, ignore_polyphonic_notes=True, convert_to_drums=False, steps_per_quarter=16): """Summary Parameters ...
6c3ce0135bf45a8992f94197f5b10ab472407f40
3,659,420
def filter_prediction(disable_valid_filter, disable_extra_one_word_filter, pred_token_2dlist_stemmed): """ Remove the duplicate predictions, can optionally remove invalid predictions and extra one word predictions :param disable_valid_filter: :param disable_extra_one_word_filter: :param pred_token_2...
8cbeb93c6fdfdc64cfa5819baa903699544ccb3d
3,659,421
def simple_dict_event_extractor(row, condition_for_creating_event, id_field, timestamp_field, name_of_event): """ Takes a row of the data df and returns an event record {id, event, timestamp} if the row satisfies the condition (i.e. condition_for_creating_event(row) returns True) """ if condition_fo...
2195acf5df6f465fdf3160df3abbac54e5ac0320
3,659,422
def split_fused_prelu(input_graph_def: util.GraphDef) -> util.GraphDef: """ This function looks for fused operations that include a 'Prelu'-activation. Matching nodes will be split into individual operations. TFJS uses fused operations for performance. Some fused activations aren't supported by TF ...
36b22afa67dd9259aae9f7be8ec6c4ffdf7c1167
3,659,423
import gc def test_harvest_lost_resources(pool): """Test unreferenced resources are returned to the pool.""" def get_resource_id(): """ Ensures ``Resource`` falls out of scope before calling ``_harvest_lost_resources()``. """ return id(pool.get_resource()._resource) ...
04b8b29520c2ae9c2c47cef412659e9c567c6a8a
3,659,424
def __call__for_keras_init_v1(self, shape, dtype=None, partition_info=None): """ Making keras VarianceScaling initializers v1 support dynamic shape. """ if dtype is None: dtype = self.dtype scale = self.scale scale_shape = shape if partition_info is not None: scale_shape = partition_info.full_shape ...
860dc27ecd133b5bb193c4856736f9bb1a52d243
3,659,425
def create_line(net, from_bus, to_bus, length_km, std_type, name=None, index=None, geodata=None, df=1., parallel=1, in_service=True, max_loading_percent=nan): """ create_line(net, from_bus, to_bus, length_km, std_type, name=None, index=None, \ geodata=None, df=1., parallel=1, in_serv...
218a3a16bce0d746465991c0992f614bddf98892
3,659,426
def get_initmap(X, A=None, standardize=False, cov_func=None): """ Give back parameters such that we have the L U decomposition of the product with A (if given, or the PCA scores if not). That is we will get back: X[:, perm]*L*U + b = ((X-meanvec)/stdvec)*A where A are PCA directions if not g...
53ec26f8efe4c0869b4e4423419db32ed08128e0
3,659,427
def read_FQ_matlab(file_open): """ Opens FISH-quant result files generated with Matlab (tab-delimited text file). Args: file_open (string): string containing the full file name. Returns: dictionary containing outlines of cells, and if present the detected spots. """ # Open file ...
01c2c2263573e754c216c69496f648a883bb1843
3,659,428
def create_default_reporting_options(embedded=True, config={}): """ config must follow this scheme: { `table_name`: { `option1`: `value1` } } The different options will depend on the table role. - for ALL tables: {n 'data' : { 'remove_...
cc7d341a0d63979bbf3223a241c5707acf057547
3,659,429
def get_patient_note(state, patient_id, note_id, *args, **kwargs): """ Return a note for a patient. --- tags: ["FHIR"] parameters: - name: patient_id in: path description: ID of the patient of interest required: true schema: type: string ...
399212c31d2ae34b96a5617ca73063745c22621c
3,659,430
def _html_build_item(tag: str, text: str, attributes: map = None, include_tags=True) -> str: """Builds an HTML inline element and returns the HTML output. :param str tag: the HTML tag :param str text: the text between the HTML tags :param map attributes: map of attributes :param bool include_ta...
13b165a98679c2ebaf9a1dec7619a3297c729a63
3,659,431
from typing import Dict from typing import Optional import random def sim_sample( out_prefix: str, sample_id: int, chrom_start: int = 0, chrom_end: int = 10000, start_rate: float = 0.001, end_rate: float = 0.01, mut_rate: float = 0.01, ) -> Dict[str, File]: """ Simulate sequencing ...
d8a858b3f8099dd57cdc7abb4f1473e238038536
3,659,432
def vif_col(X, y, col_name): """计算vif 计算具体一个column的vif, 一般阈值在5或者10,超过这个数字则表明有 共线性。 Attributes: X (pd.DataFrame): 自变量 y (pd.Series): 因变量 col_name (str): 需要判断的列 References: James, Gareth, Daniela Witten, Trevor Hastie, and Robert Tibshirani. An Introduct...
6d9c88d928934d60182b597a89c6da6d1f7d1194
3,659,433
def get_mesh_stat(stat_id_start_str, attr_value, xmin, ymin, xmax, ymax): """ 地域メッシュの統計情報を取得する @param stat_id_start_str 統計IDの開始文字 この文字から始まるIDをすべて取得する. @param attr_value cat01において絞り込む値 @param xmin 取得範囲 @param ymin 取得範囲 @param xmax 取得範囲 @param ymax 取得範囲 """ rows = database_proxy.ge...
9a861925436c2cf10eb4773be9dfa79c901d43f4
3,659,434
def babel_extract(fileobj, keywords, comment_tags, options): """Babel extraction method for Jinja templates. .. versionchanged:: 2.3 Basic support for translation comments was added. If `comment_tags` is now set to a list of keywords for extraction, the extractor will try to find the best...
35ee7c05ee91afc1ccf7c752bdff72e3c3d30d78
3,659,435
def main(directory='.', verbose=True): """Lists "data" files recursively in a given directory, tar files are extracted. The "data" files have :file:`info` and :file:`pickle` extensions. TODO: not only recognize .tar and .tar.gz and .tgz but .zip... """ filelist = list() director...
40cf44878b88e2a0ea312602e98ea7c6821c4c03
3,659,436
import numpy def onedthreegaussian(x, H, A1, dx1, w1, A2, dx2, w2, A3, dx3, w3): """ Returns two 1-dimensional gaussian of form H+A*numpy.exp(-(x-dx)**2/(2*w**2)) """ g1 = A1 * numpy.exp(-(x-dx1)**2 / (2*w1**2)) g2 = A2 * numpy.exp(-(x-dx2)**2 / (2*w2**2)) g3 = A3 * numpy.exp(-(x-dx3)**2 /...
f93ea1339fe1498fdaeaee91f75b7ba316455646
3,659,437
def match_any_if_key_matches(audit_id, result_to_compare, args): """ We want to compare things if we found our interested key Even if the list does not have my interested name, it will pass Match dictionary elements dynamically. Match from a list of available dictionaries There is an argument: matc...
2fc5f4dea92fdc231f496b1cbe4d78554a32e930
3,659,438
from typing import Optional from typing import Union def confusion_matrix_by_prob(true: np.ndarray, predicted_prob: np.ndarray, thresholds: Optional[Union[list, tuple, np.ndarray]] = None, pos_label: Union[bool, str, int] = _DEFAUL...
29bc8808ae1f35f13e52ac26e4e1993c423c6dc6
3,659,439
from typing import Sequence from typing import Mapping import itertools def group_slaves_by_key_func( key_func: _GenericNodeGroupingFunctionT, slaves: Sequence[_GenericNodeT], sort_func: _GenericNodeSortFunctionT = None, ) -> Mapping[_KeyFuncRetT, Sequence[_GenericNodeT]]: """ Given a function for gro...
c3e286d2ff618758cd86c16f1b6685faea4b4d7a
3,659,440
def init_clfs(): """ init classifiers to train Returns: dict, clfs """ clfs = dict() # clfs['xgb'] = XGBClassifier(n_jobs=-1) clfs['lsvc'] = LinearSVC() return clfs
4725656eda4e6991cc215bcd5a209ff23171eea6
3,659,441
def get_field_types(): """Get a dict with all registration field types.""" return get_field_definitions(RegistrationFormFieldBase)
a9fe05535a541a7a5ada74dc9138a6c2ab29f528
3,659,442
def get_md_links(filepath): """Get markdown links from a md file. The links' order of appearance in the file IS preserved in the output. This is to check for syntax of the format [...](...). The returned 'links' inside the () are not checked for validity or subtle differences (e.g. '/' vs no '/' at...
3076f77802965cb281101530f4ab360e5996f627
3,659,443
import tqdm def dask_to_zarr(df, z, loc, chunk_size, nthreads: int, msg: str = None): # TODO: perhaps change name of Dask array so it does not get confused with a dataframe """ Creates a Zarr hierarchy from a Dask array. Args: df (): Dask array. z (): Zarr hierarchy. loc (): L...
aa05321183cf086f6a397f6a3cb1f3493eb6689d
3,659,444
def get_reactor_logs(project_id, application_id, api_key=None, **request_kwargs): """ Get the logs of a Reactor script. :param project_id: The Project of the Application. :type project_id: str :param application_id: The Application to get the script logs for. :type application_id: str :para...
82743619292f387708e7b1dc3fe93c59e232d1cf
3,659,445
import os def bids_init(bids_src_dir, overwrite=False): """ Initialize BIDS source directory :param bids_src_dir: string BIDS source directory :param overwrite: string Overwrite flag :return True """ # Create template JSON dataset description datadesc_json = os.path.j...
3f728dbeaabf575fb6395a28175e8d94d4260e68
3,659,446
def summation_i_squared(n): """Summation without for loop""" if not isinstance(n, int) or n < 1: return None return int(((n*(n+1)*(2*n+1))/6))
dec0aba274bcaf3e3a821db5962af51d39835438
3,659,447
def str_to_number(this): """ Convert string to a Number """ try: return mknumber(int(this.value)) except ValueError: return mknumber(float(this.value))
e67df9c0de5a5cdbc76a3026f7e31cd3190013c4
3,659,448
import logging def _LinterRunCommand(cmd, debug, **kwargs): """Run the linter with common RunCommand args set as higher levels expect.""" return cros_build_lib.RunCommand(cmd, error_code_ok=True, print_cmd=debug, debug_level=logging.NOTICE, **kwargs)
a48355f692b9c75d8ad14bf899f2e9a305bd25a2
3,659,449
def plotTSNE(Xdata, target = None, useMulti=True, num=2500, savename=None, njobs=4, size=4, cmap=None, dim=(12,8)): """ Plot TSNE for training data Inputs: > Xdata: The training feature data (DataFrame) > target: The training target data (Series) > num (2500 by default): The number o...
9751f861df2d67516e93218000d23e23ba0ad4fe
3,659,450
import os def _get_distance(captcha_url): """ 获取缺口距离 :param captcha_url: 验证码 url :return: """ save_path = os.path.abspath('...') + '\\' + 'images' if not os.path.exists(save_path): os.mkdir(save_path) img_path = _pic_download(captcha_url, 'captcha') img1 = cv2.imread(img_p...
a1e79e775bf2c298992b1a0f986318b2ca70edd8
3,659,451
def adjust_contrast(img, contrast_factor): """Adjust contrast of an Image. Args: img (PIL Image): PIL Image to be adjusted. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original image while 2 increases the contr...
aedd8bb489df64138189626585228ffc086e2428
3,659,452
def matplotlib_view(gviz: Digraph): """ Views the diagram using Matplotlib Parameters --------------- gviz Graphviz """ return gview.matplotlib_view(gviz)
9eb0a686c6d01a7d24273bbbc6ddb9b4ee7cb9ac
3,659,453
def shuf_repeat(lst, count): """ Xiaolong's code expects LMDBs with the train list shuffled and repeated, so creating that here to avoid multiple steps. """ final_list = [] ordering = range(len(lst)) for _ in range(count): np.random.shuffle(ordering) final_list += [lst[i] for i in or...
fea9478aaa37f5b1c58d4a41126055d9cfa4b035
3,659,454
def create_query(table_name, schema_dict): """ see datatypes documentation here: https://www.postgresql.org/docs/11/datatype.html """ columns = db_schema[table_name] return ( f"goodbooks_{table_name}", [f"{column} {value}" for column, value in columns.items()], )
3b330d57f45ca053cfbe90952adc7aa1658ab76d
3,659,455
from typing import Any from typing import Tuple def new_document( source_path: str, settings: Any = None ) -> Tuple[nodes.document, JSONReporter]: """Return a new empty document object. Replicates ``docutils.utils.new_document``, but uses JSONReporter, which is also returned Parameters -----...
9ec26dd8f8b9c7a2e3a4bc56520b7872e7b53a7a
3,659,456
import requests def delete_repleciation(zfssrcfs, repel_uuid): """ZFS repleciation action status accepts: An exsistng ZFS action uuid (id). returns: the ZFS return status code. """ r = requests.delete( "%s/api/storage/v1/replication/actions/%s" % (url, repel_uuid), auth=zfsauth, ve...
f62ad1ec3e31ac7c54cf749982690631bb7b72d2
3,659,457
from pathlib import Path import random import torch import sys def load_checkpoint( neox_args, model, optimizer, lr_scheduler, inference=False, iteration=None ): """Load a model checkpoint and return the iteration.""" if neox_args.deepspeed: load_optim_and_scheduler = ( not neox_ar...
7395cc48a1be6c86cf15cd4576257d7f3b5c0f19
3,659,458
import aiohttp def get_logged_in_session(websession: aiohttp.ClientSession) -> RenaultSession: """Get initialised RenaultSession.""" return RenaultSession( websession=websession, country=TEST_COUNTRY, locale_details=TEST_LOCALE_DETAILS, credential_store=get_logged_in_credential...
87a5a439c5ca583c01151f340ce79f2f4a79558c
3,659,459
def __getStationName(name, id): """Construct a station name.""" name = name.replace("Meetstation", "") name = name.strip() name += " (%s)" % id return name
daab36ed8020536c8dd2c073c352634696a63f3e
3,659,460
import io import os import torch def load_hist(path): """ load spatial histogram """ # load all hist properties logpYX = io.loadmat(os.path.join(path, 'logpYX'))['value'] xlab = io.loadmat(os.path.join(path, 'xlab'))['value'] ylab = io.loadmat(os.path.join(path, 'ylab'))['value'] rg_bi...
e494f5e351c8c098b26bd0e7f417ec634a15d9c3
3,659,461
def post_url(url): """Post url argument type :param str url: the post url :rtype: str :returns: the post url """ url = url.strip() if len(url) == 0: raise ArgumentTypeError("A url is required") elif len(url) > Url.URL_LENGTH: raise ArgumentTypeError("The url length is o...
65d3c670580d6abfcfefcc8bcff35ca4e7d51f5c
3,659,462
def create_planner(request): """Create a new planner and redirect to new planner page.""" user = request.user plan = Plan.objects.create(author=user) plan.save() return HttpResponseRedirect(reverse('planner:edit_plan', args=[plan.id], ))
ab22dfa950208b44c308690dcff6e0f228faa406
3,659,463
def rule_matching_evaluation(df, model, seed_num, rein_num, eval_num, label_map, refer_label, lime_flag=True, scan_flag=False , content_direction='forward', xcol_name='text', n_cores=20): """A integrated rule extraction, refinement and validation process. On the dataset, sample base...
9ed0d5653797544de384c41ef6d9e402d2a57403
3,659,464
def login(): """ Typical login page """ # if current user is already logged in, then don't log in again if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first...
e4114979a6b5b5845f32442bb66ee0798357f4e7
3,659,465
def create_timeperiod_map( start: spec.Timestamp = None, end: spec.Timestamp = None, length: spec.Timelength = None, ) -> spec.TimeperiodMap: """create Timeperiod with representation TimeperiodMap ## Inputs - start: Timestamp - end: Timestamp - length: Timelength ## Returns - T...
c8087ea252e86b97c55376bfb21b93c2b50e3b19
3,659,466
import requests async def patched_send_async(self, *args, **kwargs): """Patched send function that push to queue idx of server to which request is routed.""" buf = args[0] if buf and len(buf) >= 6: op_code = int.from_bytes(buf[4:6], byteorder=PROTOCOL_BYTE_ORDER) # Filter only caches opera...
c78c9b437547266b4bfa82627c45e3c7c6450049
3,659,467
from datetime import datetime def add_event_records(df, event_type, event_date): """Add event records for the event type.""" log(f'Adding {DATASET_ID} event records for {event_type}') this_year = datetime.now().year df = df.loc[df[event_date].notnull(), :].copy() df['event_id'] = db.create_ids(df,...
d3e804d9b24274e5a87e1e470f1f758214e1f805
3,659,468
def _renderPath(path,drawFuncs,countOnly=False,forceClose=False): """Helper function for renderers.""" # this could be a method of Path... points = path.points i = 0 hadClosePath = 0 hadMoveTo = 0 active = not countOnly for op in path.operators: if op == _MOVETO: if f...
17a2fc3224b2ba80de9dee0110468c4d934281b7
3,659,469
def _search_focus(s, code=None): """ Search for a particular module / presentation. The search should return only a single item. """ if not code: code = input("Module code (e.g. TM129-17J): ") results = _search_by_code(s, code) if not len(results): print('Nothing found for "{}"...
8eec36dbe48c1825d742c9834776a7a0705429b6
3,659,470
def parse_line(sample): """Parse an ndjson line and return ink (as np array) and classname.""" class_name = sample["word"] inkarray = sample["drawing"] stroke_lengths = [len(stroke[0]) for stroke in inkarray] total_points = sum(stroke_lengths) np_ink = np.zeros((total_points, 3), dtype=np.float3...
19d20f7e67b58d699c0aea47f1f03095a957f757
3,659,471
def evalRPN(self, tokens): # ! 求解逆波兰式,主要利用栈 """ :type tokens: List[str] :rtype: int """ stack = [] for item in tokens: # print(stack) if item.isdigit(): stack.append(int(item)) if item[0] == '-' and len(item) > 1 and item[1:].isdigit(): stack...
6b2050f6f635324878116371cd81a6d25ea31240
3,659,472
def _validate_flags(): """Returns True if flag values are valid or prints error and returns False.""" if FLAGS.list_ports: print("Input ports: '%s'" % ( "', '".join(midi_hub.get_available_input_ports()))) print("Ouput ports: '%s'" % ( "', '".join(midi_hub.get_available_output_ports()))) ...
812791a8c71cc354a1ebe32f3fa9a3cc0f1c0182
3,659,473
def proto_test(test): """ If test is a ProtoTest, I just return it. Otherwise I create a ProtoTest out of test and return it. """ if isinstance(test, ProtoTest): return test else: return ProtoTest(test)
3326ea07ae5e4f90d3ae49cedee7b16aa97a3c65
3,659,474
def get_frames(): """Get frames for an episode Params: episode: int The episode for which the frames shall be returned Returns: frames: dict The frames for an episode per timestep """ episode = int(request.args.get('user')) frames = data_preprocessor.get_f...
1180c38175ef07f5e58ce8b77d748f6c1c1ab17b
3,659,475
def remove(s1,s2): """ Returns a copy of s, with all characters in s2 removed. Examples: remove('abc','ab') returns 'c' remove('abc','xy') returns 'abc' remove('hello world','ol') returns 'he wrd' Parameter s1: the string to copy Precondition: s1 is a string Parameter ...
089107767063309d1cc34360ae290e7fa74133e7
3,659,476
import re import os def get_firebase_db_url(): """Grabs the databaseURL from the Firebase config snippet. Regex looks scary, but all it is doing is pulling the 'databaseURL' field from the Firebase javascript snippet""" regex = re.compile(r'\bdatabaseURL\b.*?["\']([^"\']+)') cwd = os.path.dirname(...
aafc688c20adc060046ebd96b047741bedae600f
3,659,477
def get_issuer_plan_ids(issuer): """Given an issuer id, return all of the plan ids registered to that issuer.""" df = pd.read_csv(PATH_TO_PLANS) df = df[df.IssuerId.astype(str) == issuer] return set(df.StandardComponentId.unique())
b41b36b70000736acde63673961f92231a62f9a4
3,659,478
def add_args(parser): """ parser : argparse.ArgumentParser return a parser added with args required by fit """ # Training settings parser.add_argument('--model', type=str, default='mobilenet', metavar='N', help='neural network used in training') parser.add_argument('...
e1e2d1e61976b8f2dea6d6ab5f928b72bcdd15a5
3,659,479
def parse_coords(lines): """Parse skbio's ordination results file into coords, labels, eigvals, pct_explained. Returns: - list of sample labels in order - array of coords (rows = samples, cols = axes in descending order) - list of eigenvalues - list of percent variance explained F...
fec53839f5f995f94f07120cac5bab1ba66f7b4c
3,659,480
def run_ann(model, train, test, params_save_path, iteration, optimizer, loss, callbacks=None, valid=None, shuffle_training=True, batch_size=16, num_epochs=30): """ Run analog network with cross-validation :param batch_size: batch size during training :param model: ref...
9df68d8c6cdf6df08177bd1cc5d3116c10ae073e
3,659,481
def get_sector(session, sector_name=None, sector_id=None): """ Get a sector by it's name or id. """ return get_by_name_or_id(session, Sector, model_id=sector_id, name=sector_name)
69de99bbdd630fb0cc5412c2b3124dff819287ed
3,659,482
def is_valid_pre_6_2_version(xml): """Returns whether the given XML object corresponds to an XML output file of Quantum ESPRESSO pw.x pre v6.2 :param xml: a parsed XML output file :return: boolean, True when the XML was produced by Quantum ESPRESSO with the old XML format """ element_header = xml.f...
80bda73addc68a88b2a1dc5828c0553cbaf7e6f2
3,659,483
import warnings def exportdf (df =None, refout:str =None, to:str =None, savepath:str =None, modname:str ='_wexported_', reset_index:bool =True): """ Export dataframe ``df`` to `refout` files. `refout` file can be Excell sheet file or '.json' file. To get more details about the `wr...
0bc6d2750f236c5f3e529b2489be47658ddbf2d9
3,659,484
def clean_bpoa_seniority_list(csv): """Clean a digitized BPOA seniority list.""" dirty = pd.read_csv(csv) clean = pd.DataFrame() clean["job_title"] = dirty["Rank"] clean["last_name"] = dirty["Last name"] clean["first_name"] = dirty["First Name"] clean = clean.apply(correct_name, axis=1) ...
b1af748d92c4cdced4a77fd3799dada318c0f57e
3,659,485
def topk(table, metric, dimensions, is_asc, k, **kwargs): """ This function returns both the results according to the intent as well as the debiasing suggestions. Some of the oversights considered in this intent are- 1. Regression to the mean 2. Looking at tails to find causes - TODO Args: ...
be8387b349da558d07fdb86fc8261f9153869028
3,659,486
def addMovieElement(findings, data): """ Helper Function which handles unavailable information for each movie""" if len(findings) != 0: data.append(findings[0]) else: data.append("") return data
af3c45c8b8d4c0cb7ba1cac4925d0f5998affe93
3,659,487
from typing import Optional def get_bst_using_min_and_max_value(preorder: list) -> Node: """ time complexity: O(n) space complexity: O(n) """ def construct_tree(min_: int, max_: int) -> Optional[Node]: nonlocal pre_index nonlocal l if pre_index >= l: return No...
809c74967e73c82a428f317d8551432bb392d5ea
3,659,488
import math def qwtStepSize(intervalSize, maxSteps, base): """this version often doesn't find the best ticks: f.e for 15: 5, 10""" minStep = divideInterval(intervalSize, maxSteps, base) if minStep != 0.0: # # ticks per interval numTicks = math.ceil(abs(intervalSize / minStep)) - 1 ...
57d1c4140e32dbf4a8bd0e306b9c10d4e9dae9bd
3,659,489
def get_trimmed_glyph_name(gname, num): """ Glyph names cannot have more than 31 characters. See https://docs.microsoft.com/en-us/typography/opentype/spec/... recom#39post39-table Trims an input string and appends a number to it. """ suffix = '_{}'.format(num) return gname[:31...
a5e90163d15bd4fc0b315414fffd2ac227768ab0
3,659,490
def vmatrix(ddir, file_prefix): """ generate vmatrix DataFile """ name = autofile.name.vmatrix(file_prefix) writer_ = autofile.write.vmatrix reader_ = autofile.read.vmatrix return factory.DataFile(ddir=ddir, name=name, writer_=writer_, reader_=reader_)
b9303e08f10e0604fde7b40116b74e66aac553dc
3,659,491
import os def fetch_precision_overlay(precision): """ Returns the overlay for the given precision value as cv2 image. """ overlay_folder = os.path.join( os.path.dirname(os.path.realpath(__file__)), '../assets/precision_overlays' ) img_path = os.path.join( overlay_fold...
7d8e8c82676bc4686f9b08b171a6deb60fb60a9e
3,659,492
import ast from typing import Callable from typing import MutableMapping from typing import Union import inspect def get_argument_sources( source: Source, node: ast.Call, func: Callable, vars_only: bool, pos_only: bool ) -> MutableMapping[str, Union[ast.AST, str]]: """Get t...
1ab344b5ccf9754ade06210e74540db51fe8c671
3,659,493
def _register_dataset(service, dataset, compression): """Registers a dataset with the tf.data service. This transformation is similar to `register_dataset`, but supports additional parameters which we do not yet want to add to the public Python API. Args: service: A string or a tuple indicating how to con...
e95edfeaccc324bf7d732658846a3ef25c1a371c
3,659,494
def rivers_by_station_number(stations,N): """function that uses stations_by_rivers to return a dictionary that it then itterates each river for, summing the number of stations on the river into tuples""" stationsOfRivers = stations_by_rivers(stations) listOfNumberStations = [] for river in stationsO...
ca159843f10cbadf5a35529c45656121672972e0
3,659,495
import itertools def generate_itoa_dict( bucket_values=[-0.33, 0, 0.33], valid_movement_direction=[1, 1, 1, 1]): """ Set cartesian product to generate action combination spaces for the fetch environments valid_movement_direction: To set """ action_space_extended = [bucket_values if...
b8264174857aeb9d64226cce1cd1625f7e65b726
3,659,496
import dateutil from datetime import datetime def try_convert(value, datetime_to_ms=False, precise=False): """Convert a str into more useful python type (datetime, float, int, bool), if possible Some precision may be lost (e.g. Decimal converted to a float) >>> try_convert('false') False >>> try...
59f8a16310e4ac6604a145dcff1ff390df259da9
3,659,497
def signin(request, auth_form=AuthenticationForm, template_name='accounts/signin_form.html', redirect_field_name=REDIRECT_FIELD_NAME, redirect_signin_function=signin_redirect, extra_context=None): """ Signin using email or username with password. Signs a user in by combinin...
6a8536fb3a0c551ae4cdb7f01de622c012d0734c
3,659,498
import random def run_syncdb(database_info): """Make sure that the database tables are created. database_info -- a dictionary specifying the database info as dictated by Django; if None then the default database is used Return the identifier the import process should use. """ ...
19da3e97226363fbee885ff8ee24c7abe0489d3c
3,659,499