content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# Copyright 2021 Research Institute of Systems Planning, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List, Optional from abc import ABCMeta, abstractmethod from trace_analysis.callback import CallbackBase from trace_analysis.communication import VariablePassing, Communication from trace_analysis.node import Node UNDEFINED_STR = "UNDEFINED"
[ 2, 15069, 33448, 4992, 5136, 286, 11998, 21913, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, ...
3.919643
224
from thkc_disrank import *
[ 6738, 294, 74, 66, 62, 6381, 43027, 1330, 1635, 201, 198 ]
2.545455
11
import torch import torch.nn as nn import torch.nn.functional as F import dgl.function as fn """ GIN: Graph Isomorphism Networks HOW POWERFUL ARE GRAPH NEURAL NETWORKS? (Keyulu Xu, Weihua Hu, Jure Leskovec and Stefanie Jegelka, ICLR 2019) https://arxiv.org/pdf/1810.00826.pdf """
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 288, 4743, 13, 8818, 355, 24714, 198, 198, 37811, 198, 220, 220, 220, 402, 1268, 25, 29681, 1148, 25831, 1042, 27...
2.568966
116
""" *mus . it . dia* The simple diatonic intervals. """ from .second import MinorSecond from .second import MajorSecond from .third import MinorThird from .third import MajorThird from .fourth import PerfectFourth from .fifth import Tritone from .fifth import PerfectFifth from .sixth import MinorSixth from .sixth import MajorSixth from .seventh import MinorSeventh from .seventh import MajorSeventh from .eighth import Octave __all__ = [ "MinorSecond", "MajorSecond", "MinorThird", "MajorThird", "PerfectFourth", "Tritone", "PerfectFifth", "MinorSixth", "MajorSixth", "MinorSeventh", "MajorSeventh", "Octave", ]
[ 37811, 628, 220, 220, 220, 1635, 14664, 764, 340, 764, 288, 544, 9, 628, 220, 383, 2829, 2566, 265, 9229, 20016, 13, 198, 198, 37811, 198, 198, 6738, 764, 12227, 1330, 15367, 12211, 198, 6738, 764, 12227, 1330, 8386, 12211, 198, 6738,...
2.888412
233
# this file holds some common testing functions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By depurl = "localhost:3000"
[ 2, 428, 2393, 6622, 617, 2219, 4856, 5499, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11284, 13, 17077, 1330, 5313, 32103, 21321, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11284, 1330, 2938, 62, 17561, 1756, 355, 13182,...
3.707692
65
#-- coding: utf-8 -- import sys reload(sys) sys.setdefaultencoding('utf-8') import os import time import collections from PIL import Image, ImageOps, ImageDraw, ImageFont code_2_icono = collections.defaultdict(lambda : '38') kor_2_eng = collections.defaultdict(lambda : 'UNKNOWN') code_2_icono['SKY_O00'] = ['38'] code_2_icono['SKY_O01'] = ['01', '08'] code_2_icono['SKY_O02'] = ['02', '09'] code_2_icono['SKY_O03'] = ['03', '10'] code_2_icono['SKY_O04'] = ['12', '40'] code_2_icono['SKY_O05'] = ['13', '41'] code_2_icono['SKY_O06'] = ['14', '42'] code_2_icono['SKY_O07'] = ['18'] code_2_icono['SKY_O08'] = ['21'] code_2_icono['SKY_O09'] = ['32'] code_2_icono['SKY_O10'] = ['04'] code_2_icono['SKY_O11'] = ['29'] code_2_icono['SKY_O12'] = ['26'] code_2_icono['SKY_O13'] = ['27'] code_2_icono['SKY_O14'] = ['28'] code_2_icono['SKY_W00'] = ['38'] code_2_icono['SKY_W01'] = ['01', '08'] code_2_icono['SKY_W02'] = ['02', '09'] code_2_icono['SKY_W03'] = ['03', '10'] code_2_icono['SKY_W04'] = ['18'] code_2_icono['SKY_W07'] = ['21'] code_2_icono['SKY_W09'] = ['12', '40'] code_2_icono['SKY_W10'] = ['21'] code_2_icono['SKY_W11'] = ['04'] code_2_icono['SKY_W12'] = ['13', '41'] code_2_icono['SKY_W13'] = ['32'] kor_2_eng[u''] = ['GOOD'] kor_2_eng[u''] = ['NORMAL'] kor_2_eng[u''] = ['BAD'] kor_2_eng[u' '] = ['V BAD'] BLACK = 0 WHITE = 1
[ 2, 438, 19617, 25, 3384, 69, 12, 23, 1377, 198, 198, 11748, 25064, 198, 260, 2220, 7, 17597, 8, 198, 17597, 13, 2617, 12286, 12685, 7656, 10786, 40477, 12, 23, 11537, 198, 198, 11748, 28686, 198, 11748, 640, 198, 198, 11748, 17268, ...
1.985251
678
from .catchment import regime, flow_duration_curve from . import indices
[ 6738, 764, 40198, 434, 1330, 7142, 11, 5202, 62, 32257, 62, 22019, 303, 198, 6738, 764, 1330, 36525 ]
4
18
# # (C) Copyright 1996- ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation # nor does it submit to any jurisdiction. # import os import numpy as np import argparse import keras import keras2onnx if __name__ == "__main__": """ Lightweight script to convert a keras model into a TFlite model """ parser = argparse.ArgumentParser("Data Augmentation") parser.add_argument('keras_model_path', help="Path of the input keras model") parser.add_argument('onnx_model_path', help="Path of the output onnx model") parser.add_argument("--verify_with", help="Check the model by passing an input numpy path") args = parser.parse_args() # load the keras model model = keras.models.load_model(args.keras_model_path) model.summary() # do the conversion onnx_model = keras2onnx.convert_keras(model, model.name) # write to file file = open(args.onnx_model_path, "wb") file.write(onnx_model.SerializeToString()) file.close()
[ 2, 198, 2, 357, 34, 8, 15069, 8235, 12, 13182, 14326, 37, 13, 198, 2, 198, 2, 770, 3788, 318, 11971, 739, 262, 2846, 286, 262, 24843, 10483, 594, 10628, 362, 13, 15, 198, 2, 543, 460, 307, 6492, 379, 2638, 1378, 2503, 13, 43073,...
2.880734
436
# Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause """Assistant utility for automatically load network from network description.""" import torch
[ 2, 15069, 357, 34, 8, 33160, 8180, 10501, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 220, 347, 10305, 12, 18, 12, 2601, 682, 198, 198, 37811, 48902, 10361, 329, 6338, 3440, 3127, 422, 3127, 198, 11213, 526, 15931, 198, 198, ...
3.847826
46
""" Inspired by example from https://github.com/Vict0rSch/deep_learning/tree/master/keras/recurrent Uses the TensorFlow backend The basic idea is to detect anomalies in a time-series. """ import matplotlib.pyplot as plt import numpy as np import time from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential from numpy import arange, sin, pi, random np.random.seed(1234) # Global hyper-parameters sequence_length = 100 random_data_dup = 10 # each sample randomly duplicated between 0 and 9 times, see dropin function epochs = 1 batch_size = 50 def dropin(X, y): """ The name suggests the inverse of dropout, i.e. adding more samples. See Data Augmentation section at http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/ :param X: Each row is a training sequence :param y: Tne target we train and will later predict :return: new augmented X, y """ print("X shape:", X.shape) print("y shape:", y.shape) X_hat = [] y_hat = [] for i in range(0, len(X)): for j in range(0, np.random.random_integers(0, random_data_dup)): X_hat.append(X[i, :]) y_hat.append(y[i]) return np.asarray(X_hat), np.asarray(y_hat) def gen_wave(): """ Generate a synthetic wave by adding up a few sine waves and some noise :return: the final wave """ t = np.arange(0.0, 10.0, 0.01) wave1 = sin(2 * 2 * pi * t) noise = random.normal(0, 0.1, len(t)) wave1 = wave1 + noise print("wave1", len(wave1)) wave2 = sin(2 * pi * t) print("wave2", len(wave2)) t_rider = arange(0.0, 0.5, 0.01) wave3 = sin(10 * pi * t_rider) print("wave3", len(wave3)) insert = round(0.8 * len(t)) wave1[insert:insert + 50] = wave1[insert:insert + 50] + wave3 return wave1 + wave2 run_network()
[ 37811, 45827, 416, 1672, 422, 198, 5450, 1378, 12567, 13, 785, 14, 21944, 15, 81, 14874, 14, 22089, 62, 40684, 14, 21048, 14, 9866, 14, 6122, 292, 14, 8344, 6657, 198, 5842, 274, 262, 309, 22854, 37535, 30203, 198, 464, 4096, 2126, ...
2.544371
755
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, 15720, 602, 198, 11748, 4818, 8079, 628 ]
3
41
__title__ = 'har2case' __description__ = 'Convert HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner.' __url__ = 'https://github.com/HttpRunner/har2case' __version__ = '0.2.0' __author__ = 'debugtalk' __author_email__ = 'mail@debugtalk.com' __license__ = 'Apache-2.0' __copyright__ = 'Copyright 2017 debugtalk'
[ 834, 7839, 834, 796, 705, 9869, 17, 7442, 6, 198, 834, 11213, 834, 796, 705, 3103, 1851, 43638, 7, 40717, 20816, 8, 284, 575, 2390, 43, 14, 40386, 1332, 33964, 329, 367, 29281, 49493, 2637, 198, 834, 6371, 834, 796, 705, 5450, 1378,...
2.73913
115
import os from pathlib import Path from data_utils import get_data_path, get_image_data_path, get_image_extension
[ 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 1366, 62, 26791, 1330, 651, 62, 7890, 62, 6978, 11, 651, 62, 9060, 62, 7890, 62, 6978, 11, 651, 62, 9060, 62, 2302, 3004, 628, 628, 628, 628 ]
3.128205
39
#!/usr/bin/env python import boto3 import random import os BUCKET=os.environ.get('EXPORT_S3_BUCKET_URL') if (BUCKET != None): s3 = boto3.client('s3') with open("maze.txt", "rb") as f: s3.upload_fileobj(f, BUCKET, "maze"+str(random.randrange(100000))+".txt") else: print("EXPORT_S3_BUCKET_URL was not set so not uploading file")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 275, 2069, 18, 198, 11748, 4738, 198, 11748, 28686, 198, 33, 16696, 2767, 28, 418, 13, 268, 2268, 13, 1136, 10786, 6369, 15490, 62, 50, 18, 62, 33, 16696, 2767, 62, 21886, 115...
2.230769
156
import sys from typing import Any from argparse import ArgumentParser from zerver.models import Realm from zerver.lib.management import ZulipBaseCommand
[ 198, 11748, 25064, 198, 198, 6738, 19720, 1330, 4377, 198, 6738, 1822, 29572, 1330, 45751, 46677, 198, 198, 6738, 1976, 18497, 13, 27530, 1330, 23651, 198, 6738, 1976, 18497, 13, 8019, 13, 27604, 1330, 1168, 377, 541, 14881, 21575, 198 ]
3.9
40
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2009, Eucalyptus Systems, Inc. # All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. """ Some unit tests for the EC2Connection """ import unittest import time import telnetlib import socket from nose.plugins.attrib import attr from boto.ec2.connection import EC2Connection from boto.exception import EC2ResponseError
[ 2, 15069, 357, 66, 8, 4793, 12, 10333, 20472, 402, 28610, 265, 2638, 1378, 70, 28610, 265, 13, 2398, 14, 198, 2, 15069, 357, 66, 8, 3717, 11, 412, 1229, 3400, 457, 385, 11998, 11, 3457, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2,...
3.650259
386
# coding: utf-8 """ DocuSign REST API The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501 OpenAPI spec version: v2.1 Contact: devcenter@docusign.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from docusign_esign.client.configuration import Configuration def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ConditionalRecipientRuleFilter): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, ConditionalRecipientRuleFilter): return True return self.to_dict() != other.to_dict()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 14432, 84, 11712, 30617, 7824, 628, 220, 220, 220, 383, 14432, 84, 11712, 30617, 7824, 3769, 345, 351, 257, 3665, 11, 11282, 11, 290, 2829, 5313, 2594, 7824, 329, ...
2.657143
420
from django.apps import AppConfig from django.core.checks import register from . import checks
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 198, 6738, 42625, 14208, 13, 7295, 13, 42116, 1330, 7881, 198, 198, 6738, 764, 1330, 8794, 628 ]
3.88
25
""" Get all TM1 transactions for all cubes starting to a specific date. """ import configparser config = configparser.ConfigParser() config.read('..\config.ini') from datetime import datetime from TM1py.Services import TM1Service with TM1Service(**config['tm1srv01']) as tm1: # Timestamp for Message-Log parsing timestamp = datetime(year=2018, month=2, day=15, hour=16, minute=2, second=0) # Get all entries since timestamp entries = tm1.server.get_transaction_log_entries(since=timestamp) # loop through entries for entry in entries: # Do stuff print(entry['TimeStamp'], entry)
[ 37811, 198, 3855, 477, 21232, 16, 8945, 329, 477, 34896, 3599, 284, 257, 2176, 3128, 13, 198, 37811, 198, 198, 11748, 4566, 48610, 198, 11250, 796, 4566, 48610, 13, 16934, 46677, 3419, 198, 11250, 13, 961, 10786, 492, 59, 11250, 13, 5...
2.916279
215
import logging import numpy as np from scipy.stats import entropy from patteRNA.Transcript import Transcript from patteRNA import filelib logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 34242, 1330, 40709, 198, 6738, 1458, 660, 27204, 13, 8291, 6519, 1330, 42978, 198, 6738, 1458, 660, 27204, 1330, 2393, 8019, 198, 198, 6404, 1362, 796, 18931...
3.470588
51
import library import json def updateModel(model, list_weights): """ list_weights : 3D list of shape : (clientNumber,modelOuter, modelInner) It contains all the models for each client """ # this part will change developer to developer # one can just take avg # or one can discard smallest and largest than take average # this example just takes avg without use of external library alpha = library.get("alpha") # getting shape of 3D array number_clients = len(list_weights) size_outer = len(list_weights[0]) size_inner = len(list_weights[0][0]) # constructing a new 2D array of zeros of same size newModel = [ [0 for j in range(size_inner)] for i in range(size_outer)] # validate new created shape assert(len(newModel) == size_outer) assert(len(newModel[0]) == size_inner) # sum for all the clients for weights in list_weights: for outerIndex, outerList in enumerate(weights): for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] += innerVal # average it by number of clients for outerIndex, outerList in enumerate(newModel): for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] /= number_clients # now update the model using the learning rate using below formula # model = (1-a) * model + a * new_model # Prev. part and next part could be merged for efficiency but readability they implemented with two loops # Iterate over model for outerIndex, outerList in enumerate(newModel): for innerIndex, innerVal in enumerate(outerList): model[outerIndex][innerIndex] *= 1-alpha model[outerIndex][innerIndex] += alpha * newModel[outerIndex][innerIndex] # Finally update round number return model
[ 11748, 5888, 198, 11748, 33918, 198, 198, 4299, 4296, 17633, 7, 19849, 11, 1351, 62, 43775, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 220, 220, 220, 220, 1351, 62, 43775, 1058, 513, 35, 1351, 286, 5485, 1058, 357, 16366, ...
2.944969
636
from molecule import api
[ 6738, 27756, 1330, 40391, 628 ]
5.2
5
import numpy as np from coffeine.covariance_transformers import ( Diag, LogDiag, ExpandFeatures, Riemann, RiemannSnp, NaiveVec) from coffeine.spatial_filters import ( ProjIdentitySpace, ProjCommonSpace, ProjLWSpace, ProjRandomSpace, ProjSPoCSpace) from sklearn.compose import make_column_transformer from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import RidgeCV, LogisticRegression def make_filter_bank_transformer(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None): """Generate pipeline for filterbank models. Prepare filter bank models as used in [1]_. These models take as input sensor-space covariance matrices computed from M/EEG signals in different frequency bands. Then transformations are applied to improve the applicability of linear regression techniques by reducing the impact of field spread. In terms of implementation, this involves 1) projection (e.g. spatial filters) and 2) vectorization (e.g. taking the log on the diagonal). .. note:: The resulting model expects as inputs data frames in which different covarances (e.g. for different frequencies) are stored inside columns indexed by ``names``. Other columns will be passed through by the underlying column transformers. The pipeline also supports fitting categorical interaction effects after projection and vectorization steps are performed. .. note:: All essential methods from [1]_ are implemented here. In practice, we recommend comparing `riemann', `spoc' and `diag' as a baseline. Parameters ---------- names : list of str The column names of the data frame corresponding to different covariances. method : str The method used for extracting features from covariances. Defaults to ``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict | None The parameters for the projection step. vectorization_params : dict | None The parameters for the vectorization step. categorical_interaction : str The column in the input data frame containing a binary descriptor used to fit 2-way interaction effects. References ---------- [1] D. Sabbagh, P. Ablin, G. Varoquaux, A. Gramfort, and D.A. Engemann. Predictive regression modeling with MEG/EEG: from source power to signals and cognitive states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 """ # put defaults here for projection and vectorization step projection_defaults = { 'riemann': dict(scale=1, n_compo='full', reg=1.e-05), 'lw_riemann': dict(shrink=1), 'diag': dict(), 'log_diag': dict(), 'random': dict(n_compo='full'), 'naive': dict(), 'spoc': dict(n_compo='full', scale='auto', reg=1.e-05, shrink=1), 'riemann_wasserstein': dict() } vectorization_defaults = { 'riemann': dict(metric='riemann'), 'lw_riemann': dict(metric='riemann'), 'diag': dict(), 'log_diag': dict(), 'random': dict(), 'naive': dict(method='upper'), 'spoc': dict(), 'riemann_wasserstein': dict(rank='full') } assert set(projection_defaults) == set(vectorization_defaults) if method not in projection_defaults: raise ValueError( f"The `method` ('{method}') you specified is unknown.") # update defaults projection_params_ = projection_defaults[method] if projection_params is not None: projection_params_.update(**projection_params) vectorization_params_ = vectorization_defaults[method] if vectorization_params is not None: vectorization_params_.update(**vectorization_params) # setup pipelines (projection + vectorization step) steps = tuple() if method == 'riemann': steps = (ProjCommonSpace, Riemann) elif method == 'lw_riemann': steps = (ProjLWSpace, Riemann) elif method == 'diag': steps = (ProjIdentitySpace, Diag) elif method == 'log_diag': steps = (ProjIdentitySpace, LogDiag) elif method == 'random': steps = (ProjRandomSpace, LogDiag) elif method == 'naive': steps = (ProjIdentitySpace, NaiveVec) elif method == 'spoc': steps = (ProjSPoCSpace, LogDiag) elif method == 'riemann_wasserstein': steps = (ProjIdentitySpace, RiemannSnp) filter_bank_transformer = make_column_transformer( *_get_projector_vectorizer(*steps), remainder='passthrough') if categorical_interaction is not None: filter_bank_transformer = ExpandFeatures( filter_bank_transformer, expander_column=categorical_interaction) return filter_bank_transformer def make_filter_bank_regressor(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): """Generate pipeline for regression with filter bank model. Prepare filter bank models as used in [1]_. These models take as input sensor-space covariance matrices computed from M/EEG signals in different frequency bands. Then transformations are applied to improve the applicability of linear regression techniques by reducing the impact of field spread. In terms of implementation, this involves 1) projection (e.g. spatial filters) and 2) vectorization (e.g. taking the log on the diagonal). .. note:: The resulting model expects as inputs data frames in which different covarances (e.g. for different frequencies) are stored inside columns indexed by ``names``. Other columns will be passed through by the underlying column transformers. The pipeline also supports fitting categorical interaction effects after projection and vectorization steps are performed. .. note:: All essential methods from [1]_ are implemented here. In practice, we recommend comparing `riemann', `spoc' and `diag' as a baseline. Parameters ---------- names : list of str The column names of the data frame corresponding to different covariances. method : str The method used for extracting features from covariances. Defaults to ``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict | None The parameters for the projection step. vectorization_params : dict | None The parameters for the vectorization step. categorical_interaction : str The column in the input data frame containing a binary descriptor used to fit 2-way interaction effects. scaling : scikit-learn Transformer object | None Method for re-rescaling the features. Defaults to None. If None, StandardScaler is used. estimator : scikit-learn Estimator object. The estimator object. Defaults to None. If None, RidgeCV is performed with default values. References ---------- [1] D. Sabbagh, P. Ablin, G. Varoquaux, A. Gramfort, and D.A. Engemann. Predictive regression modeling with MEG/EEG: from source power to signals and cognitive states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 """ filter_bank_transformer = make_filter_bank_transformer( names=names, method=method, projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction ) scaling_ = scaling if scaling_ is None: scaling_ = StandardScaler() estimator_ = estimator if estimator_ is None: estimator_ = RidgeCV(alphas=np.logspace(-3, 5, 100)) filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_ ) return filter_bank_regressor def make_filter_bank_classifier(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): """Generate pipeline for classification with filter bank model. Prepare filter bank models as used in [1]_. These models take as input sensor-space covariance matrices computed from M/EEG signals in different frequency bands. Then transformations are applied to improve the applicability of linear regression techniques by reducing the impact of field spread. In terms of implementation, this involves 1) projection (e.g. spatial filters) and 2) vectorization (e.g. taking the log on the diagonal). .. note:: The resulting model expects as inputs data frames in which different covarances (e.g. for different frequencies) are stored inside columns indexed by ``names``. Other columns will be passed through by the underlying column transformers. The pipeline also supports fitting categorical interaction effects after projection and vectorization steps are performed. .. note:: All essential methods from [1]_ are implemented here. In practice, we recommend comparing `riemann', `spoc' and `diag' as a baseline. Parameters ---------- names : list of str The column names of the data frame corresponding to different covariances. method : str The method used for extracting features from covariances. Defaults to ``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict | None The parameters for the projection step. vectorization_params : dict | None The parameters for the vectorization step. categorical_interaction : str The column in the input data frame containing a binary descriptor used to fit 2-way interaction effects. scaling : scikit-learn Transformer object | None Method for re-rescaling the features. Defaults to None. If None, StandardScaler is used. estimator : scikit-learn Estimator object. The estimator object. Defaults to None. If None, LogisticRegression is performed with default values. References ---------- [1] D. Sabbagh, P. Ablin, G. Varoquaux, A. Gramfort, and D.A. Engemann. Predictive regression modeling with MEG/EEG: from source power to signals and cognitive states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 """ filter_bank_transformer = make_filter_bank_transformer( names=names, method=method, projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction ) scaling_ = scaling if scaling_ is None: scaling_ = StandardScaler() estimator_ = estimator if estimator_ is None: estimator_ = LogisticRegression(solver='liblinear') filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_ ) return filter_bank_regressor
[ 11748, 299, 32152, 355, 45941, 198, 6738, 763, 16658, 500, 13, 66, 709, 2743, 590, 62, 35636, 364, 1330, 357, 198, 220, 220, 220, 6031, 363, 11, 198, 220, 220, 220, 5972, 18683, 363, 11, 198, 220, 220, 220, 49368, 23595, 11, 198, ...
2.627882
4,598
from games import Game from math import nan, isnan from queue import PriorityQueue from copy import deepcopy from utils import isnumber from grading.util import print_table def q2list(mq): list = [] while not mq.empty(): list.append(mq.get(1).rcv()) return list def movesInRow(board, r): mQueue = PriorityQueue() row = board[r] for c in range(len(row)): if isnan(row[c]): continue v = row[c] move = Move(r, c, v) mQueue.put(move) return q2list(mQueue) def movesInCol(board, c): mQueue = PriorityQueue() for r in range(len(board)): if isnan(board[r][c]): continue v = board[r][c] move = Move(r, c, v) mQueue.put(move) return q2list(mQueue) won = GameState( to_move='H', position=(0, 1), board=[[nan, nan], [9, nan]], label='won' ) won.scores = {'H': 9, 'V': 0} lost = GameState( to_move='V', position=(0, 1), board=[[nan, nan], [9, nan]], label='lost' ) lost.scores = {'H': 0, 'V': 9} winin1 = GameState( to_move='H', position=(1, 1), board=[[nan, nan], [9, nan]], label='winin1' ) losein1 = GameState( to_move='V', position=(0, 0), board=[[nan, nan], [9, nan]], label='losein1' ) winin2 = GameState( to_move='H', position=(0, 0), board=[[nan, 3, 2], [nan, 9, nan], [nan, nan, 1]], label='winin2' ) losein2 = GameState( to_move='V', position=(0, 0), board=[[nan, nan, nan], [3, 9, nan], [2, nan, 1]], label='losein2' ) losein2.maxDepth = 3 # http://www.kongregate.com/games/zolli/thinkahead-brain-trainer stolen = GameState( to_move='H', position=(3, 1), board=[[3, 8, 9, 5], [9, 1, 3, 2], [8, 6, 4, 4], [9, nan, 1, 5]], label='stolen' ) choose1 = GameState( to_move='H', position=(1, 0), board=[[3, 8, 9, 5], [nan, 1, 3, 2], [8, 6, 4, 4], [nan, nan, 1, 5]], label='choose1' ) winby10 = GameState( to_move='H', position=(2, 0), board=[[nan, nan, nan, nan], [nan, nan, nan, nan], [nan, 6, 4, 5], [nan, nan, 1, 3]], label='winby10' ) thinkA = ThinkAhead(stolen) board = ''' *** *** *** ''' ''' Board represents the squares, whether the top, bottom, left, and right have been filled, and which player owns the square. ''' dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] won = DotLineState(board=dotLineBoard, to_move='A', label='Won', scores={'A': 3, 'B': 1}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] lost = DotLineState(board=dotLineBoard, to_move='A', label='Lost', scores={'A': 1, 'B': 3}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] tied = DotLineState(board=dotLineBoard, to_move='A', label='Tied', scores={'A': 2, 'B': 2}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': '', 'lines': ['T', 'L']}]] winin1Dots = DotLineState(board=dotLineBoard, to_move='A', label='Win in 1', scores={'A': 2, 'B': 1}) dotLineBoard = [[{'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['T', 'L']}, {'winner': '', 'lines': ['R']}], [{'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['L', 'R']}], [{'winner': '', 'lines': ['B', 'L', 'R']}, {'winner': '', 'lines': ['L', 'B']}, {'winner': '', 'lines': ['B', 'R']}], ] winIn5_3x3 = DotLineState(board=dotLineBoard, to_move='A', label='Win in 5', scores={'A': 0, 'B': 0}) play = DotLineState( board=[[{'winner': '', 'lines': []}, {'winner': '', 'lines': []}], [{'winner': '', 'lines': []}, {'winner': '', 'lines': []}]], to_move='A', label='Start') #amended by whh dotLine = DotsAndLines(play) #dotLine = DotsAndLines(winIn5_3x3) myGames = { dotLine: [ won, lost, tied, winin1Dots, winIn5_3x3, play ] }
[ 6738, 1830, 1330, 3776, 198, 6738, 10688, 1330, 15709, 11, 2125, 272, 198, 6738, 16834, 1330, 34416, 34991, 198, 6738, 4866, 1330, 2769, 30073, 198, 6738, 3384, 4487, 1330, 2125, 4494, 198, 6738, 43165, 13, 22602, 1330, 3601, 62, 11487, ...
1.979857
2,383
import os import df2img import disnake import numpy as np import pandas as pd from menus.menu import Menu from PIL import Image import discordbot.config_discordbot as cfg from discordbot.config_discordbot import gst_imgur, logger from discordbot.helpers import autocrop_image from gamestonk_terminal.stocks.options import yfinance_model
[ 11748, 28686, 198, 198, 11748, 47764, 17, 9600, 198, 11748, 595, 77, 539, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 26798, 13, 26272, 1330, 21860, 198, 6738, 350, 4146, 1330, 7412, 198, 198, ...
3.333333
102
#%% import packages import numpy as np import pandas as pd import multiprocessing from time import time import json from premiumFinance.constants import ( MORTALITY_TABLE_CLEANED_PATH, PROCESSED_PROFITABILITY_PATH, ) from premiumFinance.financing import calculate_lender_profit, yield_curve mortality_experience = pd.read_excel(MORTALITY_TABLE_CLEANED_PATH) #%% calculate profit rate lender_coc_value = np.arange(start=0.01, stop=0.2, step=0.01) #%% tbd if __name__ == "__main__": pool = multiprocessing.Pool() start_time = time() foo = [] for tempfunc in (tempfunc_t, tempfunc_f): foo.append( pool.map( tempfunc, lender_coc_value, ) ) print(f"it took {time() - start_time}") lender_profitability = { "lender_coc": lender_coc_value.tolist(), "profitability": foo, } with open(PROCESSED_PROFITABILITY_PATH, "w") as outfile: json.dump(lender_profitability, outfile)
[ 2, 16626, 1330, 10392, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 18540, 305, 919, 278, 198, 6738, 640, 1330, 640, 198, 11748, 33918, 198, 198, 6738, 8683, 37, 14149, 13, 9979, 1187, 133...
2.25167
449
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Caches processed query results in memcache and datastore. Memcache is not very reliable for the perf dashboard. Prometheus team explained that memcache is LRU and shared between multiple applications, so their activity may result in our data being evicted. To prevent this, we cache processed query results in the data store. Using NDB, the values are also cached in memcache if possible. This improves performance because doing a get() for a key which has a single BlobProperty is much quicker than a complex query over a large dataset. (Background: http://g/prometheus-discuss/othVtufGIyM/wjAS5djyG8kJ) When an item is cached, layered_cache does the following: 1) Namespaces the key based on whether datastore_hooks says the request is internal_only. 2) Pickles the value (memcache does this internally), and adds a data store entity with the key and a BlobProperty with the pickled value. Retrieving values checks memcache via NDB first, and if datastore is used it unpickles. When an item is removed from the the cache, it is removed from both internal and external caches, since removals are usually caused by large changes that affect both caches. Although this module contains ndb.Model classes, these are not intended to be used directly by other modules. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import import six.moves.cPickle as cPickle import datetime import logging from google.appengine.api import datastore_errors from google.appengine.runtime import apiproxy_errors from google.appengine.ext import ndb from dashboard.common import datastore_hooks from dashboard.common import namespaced_stored_object from dashboard.common import stored_object def Get(key): """Gets the value from the datastore.""" if key is None: return None namespaced_key = namespaced_stored_object.NamespaceKey(key) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value) return stored_object.Get(key) def GetExternal(key): """Gets the value from the datastore for the externally namespaced key.""" if key is None: return None namespaced_key = namespaced_stored_object.NamespaceKey( key, datastore_hooks.EXTERNAL) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value) return stored_object.Get(key) def Set(key, value, days_to_keep=None, namespace=None): """Sets the value in the datastore. Args: key: The key name, which will be namespaced. value: The value to set. days_to_keep: Number of days to keep entity in datastore, default is None. Entity will not expire when this value is 0 or None. namespace: Optional namespace, otherwise namespace will be retrieved using datastore_hooks.GetNamespace(). """ # When number of days to keep is given, calculate expiration time for # the entity and store it in datastore. # Once the entity expires, it will be deleted from the datastore. expire_time = None if days_to_keep: expire_time = datetime.datetime.now() + datetime.timedelta( days=days_to_keep) namespaced_key = namespaced_stored_object.NamespaceKey(key, namespace) try: CachedPickledString( id=namespaced_key, value=cPickle.dumps(value), expire_time=expire_time).put() except datastore_errors.BadRequestError as e: logging.warning('BadRequestError for key %s: %s', key, e) except apiproxy_errors.RequestTooLargeError as e: stored_object.Set(key, value) def SetExternal(key, value, days_to_keep=None): """Sets the value in the datastore for the externally namespaced key. Needed for things like /add_point that update internal/external data at the same time. Args: key: The key name, which will be namespaced as externally_visible. value: The value to set. days_to_keep: Number of days to keep entity in datastore, default is None. Entity will not expire when this value is 0 or None. """ Set(key, value, days_to_keep, datastore_hooks.EXTERNAL) def DeleteAllExpiredEntities(): """Deletes all expired entities from the datastore.""" ndb.delete_multi(CachedPickledString.GetExpiredKeys())
[ 2, 15069, 2864, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 198, 37811, 34,...
3.21322
1,407
# -*- coding:utf-8 -*- """ """ import cudf from hypergbm import make_experiment from hypernets.tabular import get_tool_box from hypernets.tabular.datasets import dsutils if __name__ == '__main__': main(target='y', reward_metric='auc', ensemble_size=10, pos_label='yes', log_level='info', max_trials=10) # main(target='y', max_trials=10, cv=False, ensemble_size=0, verbose=0, pos_label='yes', ) # main(target='day', reward_metric='f1', ensemble_size=10, log_level='info', max_trials=5) # main(target='day', dtype='str', reward_metric='f1', ensemble_size=0, log_level='info', max_trials=6) # main(target='age', dtype='float', ensemble_size=10, log_level='info', max_trials=8)
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 37811, 198, 198, 37811, 198, 198, 11748, 269, 463, 69, 198, 198, 6738, 8718, 70, 20475, 1330, 787, 62, 23100, 3681, 198, 6738, 8718, 45938, 13, 8658, 934, 1330, 651, 62, ...
2.534296
277
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import concurrent.futures import numpy as np import os from PIL import Image import torchvision from datasets import base from platforms.platform import get_platform DataLoader = base.DataLoader
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, 198, ...
3.968421
95
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : sm4.py @Description : sm4 @Date : 2021/10/28 15:59:51 @Author : ZelKnow @Github : https://github.com/ZelKnow """ __author__ = "ZelKnow" from argparse import ArgumentParser, ArgumentError from binascii import hexlify, unhexlify from utils import S_BOX, BLOCK_BYTE, FK, CK, BLOCK_HEX from utils import rotl, num2hex, bytes_to_list, list_to_bytes, padding, unpadding ENCRYPT = 0 # DECRYPT = 1 # if __name__ == '__main__': parser = ArgumentParser(description="SM4") parser.add_argument('crypt', choices=['encrypt', 'decrypt'], help='') parser.add_argument('mode', choices=['ecb', 'cbc'], help='') parser.add_argument('source', help='/') parser.add_argument('key', help='') parser.add_argument('--iv', help='cbc') parser.add_argument('--source_type', choices=['input', 'bin_file', 'image'], help='', default='input') parser.add_argument('--output', help='') args = parser.parse_args() c = CryptSM4() c.set_key(args.key) if args.mode == 'cbc' and args.iv is None: raise ArgumentError("") if args.source_type == 'input': input = args.source if input[:2].lower() == '0x': input = int(input[2:], 16) elif args.source_type == 'bin_file': with open(args.source, 'rb') as f: input = f.read() else: from PIL import Image import numpy as np source = Image.open(args.source) img = np.array(source.convert('RGBA')) shape = img.shape size = img.size input = unhexlify(''.join([num2hex(i, width=2) for i in img.flatten()])) if args.crypt == 'encrypt': output = c.encrypt_ECB(input) if args.mode == 'ecb' else c.encrypt_CBC( input, args.iv) else: output = c.decrypt_ECB(input) if args.mode == 'ecb' else c.decrypt_CBC( input, args.iv) if args.source_type == 'image': output = hexlify(output).decode() output = output[:size * 2] output = [[int(output[i + j:i + j + 2], 16) for j in range(0, 8, 2)] for i in range(0, len(output), 8)] output = np.array(output) output = Image.fromarray(output.reshape(shape).astype('uint8')) output.save(args.output) elif args.output: with open(args.output, "wb") as f: f.write(output) else: try: print(output.decode()) except: print(hexlify(output).decode())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 31, 8979, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1058, 895, 19, 13, 9078, 198, 31, 11828, 220, 22...
2.084385
1,268
import json import requests from random import randint
[ 11748, 33918, 198, 11748, 7007, 198, 6738, 4738, 1330, 43720, 600, 628 ]
4.666667
12
if __name__ == '__main__': # s = '(()())(())' # s = '(()())(())(()(()))' s = '()()' ret = Solution().removeOuterParentheses(s) print(ret)
[ 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1303, 264, 796, 29513, 3419, 3419, 5769, 28955, 6, 198, 220, 220, 220, 1303, 264, 796, 29513, 3419, 3419, 5769, 3419, 5769, 3419, 7, 3419, 4008, ...
2.051282
78
n = int(input('Digite um nmero para ver sua tabuada: ')) for c in range(0, 11): print(f'{n} * {c} = {n * c}')
[ 77, 796, 493, 7, 15414, 10786, 19511, 578, 23781, 299, 647, 78, 31215, 3326, 424, 64, 7400, 84, 4763, 25, 705, 4008, 198, 1640, 269, 287, 2837, 7, 15, 11, 1367, 2599, 198, 220, 220, 220, 3601, 7, 69, 6, 90, 77, 92, 1635, 1391, ...
2.072727
55
# coding=utf-8 from .translators import translate_js, DEFAULT_HEADER from .es6 import js6_to_js5 import sys import time import json import six import os import hashlib import codecs __all__ = [ 'EvalJs', 'translate_js', 'import_js', 'eval_js', 'translate_file', 'eval_js6', 'translate_js6', 'run_file', 'disable_pyimport', 'get_file_contents', 'write_file_contents' ] DEBUG = False def import_js(path, lib_name, globals): """Imports from javascript source file. globals is your globals()""" with codecs.open(path_as_local(path), "r", "utf-8") as f: js = f.read() e = EvalJs() e.execute(js) var = e.context['var'] globals[lib_name] = var.to_python() def translate_file(input_path, output_path): ''' Translates input JS file to python and saves the it to the output path. It appends some convenience code at the end so that it is easy to import JS objects. For example we have a file 'example.js' with: var a = function(x) {return x} translate_file('example.js', 'example.py') Now example.py can be easily importend and used: >>> from example import example >>> example.a(30) 30 ''' js = get_file_contents(input_path) py_code = translate_js(js) lib_name = os.path.basename(output_path).split('.')[0] head = '__all__ = [%s]\n\n# Don\'t look below, you will not understand this Python code :) I don\'t.\n\n' % repr( lib_name) tail = '\n\n# Add lib to the module scope\n%s = var.to_python()' % lib_name out = head + py_code + tail write_file_contents(output_path, out) def run_file(path_or_file, context=None): ''' Context must be EvalJS object. Runs given path as a JS program. Returns (eval_value, context). ''' if context is None: context = EvalJs() if not isinstance(context, EvalJs): raise TypeError('context must be the instance of EvalJs') eval_value = context.eval(get_file_contents(path_or_file)) return eval_value, context def eval_js(js): """Just like javascript eval. Translates javascript to python, executes and returns python object. js is javascript source code EXAMPLE: >>> import js2py >>> add = js2py.eval_js('function add(a, b) {return a + b}') >>> add(1, 2) + 3 6 >>> add('1', 2, 3) u'12' >>> add.constructor function Function() { [python code] } NOTE: For Js Number, String, Boolean and other base types returns appropriate python BUILTIN type. For Js functions and objects, returns Python wrapper - basically behaves like normal python object. If you really want to convert object to python dict you can use to_dict method. """ e = EvalJs() return e.eval(js) def eval_js6(js): """Just like eval_js but with experimental support for js6 via babel.""" return eval_js(js6_to_js5(js)) def translate_js6(js): """Just like translate_js but with experimental support for js6 via babel.""" return translate_js(js6_to_js5(js)) #print x if __name__ == '__main__': #with open('C:\Users\Piotrek\Desktop\esprima.js', 'rb') as f: # x = f.read() e = EvalJs() e.execute('square(x)') #e.execute(x) e.console()
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 764, 7645, 75, 2024, 1330, 15772, 62, 8457, 11, 5550, 38865, 62, 37682, 1137, 198, 6738, 764, 274, 21, 1330, 44804, 21, 62, 1462, 62, 8457, 20, 198, 11748, 25064, 198, 11748, 640, 198, 11748, ...
2.567059
1,275
#!/usr/bin/python3 from setuptools import setup, find_packages setup( package_dir = { '': 'src' }, packages = find_packages( where='src' ), )
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 40406, 7, 198, 220, 220, 220, 5301, 62, 15908, 796, 1391, 10148, 25, 705, 10677, 6, 8964, 198, 220, 220, 220, ...
2.666667
57
#!/usr/bin/env python # # Copyright (C) 2018 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import logging import os.path import shlex import struct import common import sparse_img from rangelib import RangeSet logger = logging.getLogger(__name__) OPTIONS = common.OPTIONS BLOCK_SIZE = common.BLOCK_SIZE FIXED_SALT = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7" def Append2Simg(sparse_image_path, unsparse_image_path, error_message): """Appends the unsparse image to the given sparse image. Args: sparse_image_path: the path to the (sparse) image unsparse_image_path: the path to the (unsparse) image Raises: BuildVerityImageError: On error. """ cmd = ["append2simg", sparse_image_path, unsparse_image_path] try: common.RunAndCheckOutput(cmd) except: logger.exception(error_message) raise BuildVerityImageError(error_message) def Append(target, file_to_append, error_message): """Appends file_to_append to target. Raises: BuildVerityImageError: On error. """ try: with open(target, 'ab') as out_file, \ open(file_to_append, 'rb') as input_file: for line in input_file: out_file.write(line) except IOError: logger.exception(error_message) raise BuildVerityImageError(error_message) def CreateVerityImageBuilder(prop_dict): """Returns a verity image builder based on the given build properties. Args: prop_dict: A dict that contains the build properties. In particular, it will look for verity-related property values. Returns: A VerityImageBuilder instance for Verified Boot 1.0 or Verified Boot 2.0; or None if the given build doesn't support Verified Boot. """ partition_size = prop_dict.get("partition_size") # partition_size could be None at this point, if using dynamic partitions. if partition_size: partition_size = int(partition_size) # Verified Boot 1.0 verity_supported = prop_dict.get("verity") == "true" is_verity_partition = "verity_block_device" in prop_dict if verity_supported and is_verity_partition: if OPTIONS.verity_signer_path is not None: signer_path = OPTIONS.verity_signer_path else: signer_path = prop_dict["verity_signer_cmd"] return Version1VerityImageBuilder( partition_size, prop_dict["verity_block_device"], prop_dict.get("verity_fec") == "true", signer_path, prop_dict["verity_key"] + ".pk8", OPTIONS.verity_signer_args, "verity_disable" in prop_dict) # Verified Boot 2.0 if (prop_dict.get("avb_hash_enable") == "true" or prop_dict.get("avb_hashtree_enable") == "true"): # key_path and algorithm are only available when chain partition is used. key_path = prop_dict.get("avb_key_path") algorithm = prop_dict.get("avb_algorithm") # Image uses hash footer. if prop_dict.get("avb_hash_enable") == "true": return VerifiedBootVersion2VerityImageBuilder( prop_dict["partition_name"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER, prop_dict["avb_avbtool"], key_path, algorithm, prop_dict.get("avb_salt"), prop_dict["avb_add_hash_footer_args"]) # Image uses hashtree footer. return VerifiedBootVersion2VerityImageBuilder( prop_dict["partition_name"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, prop_dict["avb_avbtool"], key_path, algorithm, prop_dict.get("avb_salt"), prop_dict["avb_add_hashtree_footer_args"]) return None def CreateHashtreeInfoGenerator(partition_name, block_size, info_dict): generator = None if (info_dict.get("verity") == "true" and info_dict.get("{}_verity_block_device".format(partition_name))): partition_size = info_dict["{}_size".format(partition_name)] fec_supported = info_dict.get("verity_fec") == "true" generator = VerifiedBootVersion1HashtreeInfoGenerator( partition_size, block_size, fec_supported) return generator def CreateCustomImageBuilder(info_dict, partition_name, partition_size, key_path, algorithm, signing_args): builder = None if info_dict.get("avb_enable") == "true": builder = VerifiedBootVersion2VerityImageBuilder( partition_name, partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, info_dict.get("avb_avbtool"), key_path, algorithm, # Salt is None because custom images have no fingerprint property to be # used as the salt. None, signing_args) return builder
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 357, 34, 8, 2864, 383, 5565, 4946, 8090, 4935, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, ...
2.622036
2,024
#!/usr/bin/env python """org archive to html table converter""" import os import datetime import itertools from .utils.date import minutestr, total_minutes def rootname_from_archive_olpath(node): """ Find rootname from ARCHIVE_OLPATH property. Return None if not found. """ olpath = node.get_property('ARCHIVE_OLPATH') if olpath: olpathlist = olpath.split('/', 1) if len(olpathlist) > 1: (rootname, dummy) = olpathlist else: rootname = olpath return rootname return None def find_rootname(node): """ Find rootname given node """ rootname = rootname_from_archive_olpath(node) if not rootname: n = node p = node.parent while not p.is_root(): n = p p = p.parent # n is root node rootname = rootname_from_archive_olpath(n) or n.heading return rootname def key_row_from_node(node): """ Return three tuple (key, row) whose elemens are key object for sorting table and dictionary which has following keywords: heading, closed, scheduled, effort, clocksum, rootname. """ heading = node.heading # find rootname rootname = find_rootname(node) if heading == rootname: rootname = "" # calc clocksum if CLOCK exists clocksum = '' clocklist = node.clock if clocklist: clocksum = sum([total_minutes(c.duration) for c in clocklist]) closed = node.closed scheduled = node.scheduled effort = node.get_property('Effort') row = dict( heading=heading, closed=closed and closed.start.strftime('%a %d %b %H:%M'), scheduled=scheduled and scheduled.start.strftime('%a %d %b %H:%M'), effort=effort and minutestr(effort), clocksum=clocksum and minutestr(clocksum), rootname=rootname, ) return (closed.start if closed else None, row) def table_add_oddday(key_table): """ Add oddday key in each rows of key_table *IN PLACE*. Note that key should be a ``datetime.date`` object. """ previous = None odd = True for (key, row) in key_table: this = key if not sameday(this, previous): odd = not odd row['oddday'] = odd previous = this def get_data(orgnodes_list, orgpath_list, done, num=100): """ Get data for rendering jinja2 template. Data is dictionary like this: table: list of `row` list of row generated by ``row_from_node`` orgpathname_list: list of `orgpathname` orgpathname: dict contains `orgpath` and `orgname`. `orgname` is short and unique name for `orgpath`. title: str a title """ key_table = [] orgname_list = unique_name_from_paths(orgpath_list) for (nodelist, orgname) in zip(orgnodes_list, orgname_list): for node in nodelist: if node.todo == done: (key, row) = key_row_from_node(node) if key: row['orgname'] = orgname key_table.append((key, row)) orgpathname_list = [ dict(orgpath=orgpath, orgname=orgname) for (orgpath, orgname) in zip(orgpath_list, orgname_list)] key_table.sort(reverse=True) table_add_oddday(key_table) table = list(itertools.islice((row for (key, row) in key_table), num)) return dict(table=table, orgpathname_list=orgpathname_list, title='Recently archived tasks')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 2398, 15424, 284, 27711, 3084, 38394, 37811, 198, 198, 11748, 28686, 198, 11748, 4818, 8079, 198, 11748, 340, 861, 10141, 198, 198, 6738, 764, 26791, 13, 4475, 1330, 949, 315, 395...
2.31659
1,513
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json import tvm if __name__ == "__main__": test_with() test_decorator() test_nested()
[ 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 220, 383, 7054,...
3.736402
239
""" MIT License Copyright (c) 2019 Simon Olofsson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import numpy as np from scipy.integrate import odeint from ..continuous_time import MSFB2014 """ A. Mesbah, S. Streif, R. Findeisen and R. D. Braatz (2014) "Active fault diagnosis for nonlinear systems with probabilistic uncertainties" IFAC Proceedings (2014): 7079-7084 """ def get (): return DataGen(), [M1(), M2(), M3()]
[ 37811, 198, 36393, 13789, 198, 198, 15269, 357, 66, 8, 13130, 11288, 6544, 1659, 16528, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 1659, 428, 3788, 290, 3917, 10314, 3696, 3...
3.586294
394
#!/usr/bin/env python """ The pozyx ranging demo (c) Pozyx Labs please check out https://www.pozyx.io/Documentation/Tutorials/getting_started/Python This demo requires one (or two) pozyx shields. It demonstrates the 3D orientation and the functionality to remotely read register data from a pozyx device. Connect one of the Pozyx devices with USB and run this script. This demo reads the following sensor data: - pressure - acceleration - magnetic field strength - angular velocity - the heading, roll and pitch - the quaternion rotation describing the 3D orientation of the device. This can be used to transform from the body coordinate system to the world coordinate system. - the linear acceleration (the acceleration excluding gravity) - the gravitational vector The data can be viewed in the Processing sketch orientation_3D.pde """ from time import time from time import sleep from pypozyx import * from pypozyx.definitions.bitmasks import POZYX_INT_MASK_IMU from pythonosc.osc_message_builder import OscMessageBuilder from pythonosc.udp_client import SimpleUDPClient from modules.user_input_config_functions import UserInputConfigFunctions as UserInput from modules.file_writing import SensorAndPositionFileWriting as FileWriting from modules.console_logging_functions import ConsoleLoggingFunctions as ConsoleLogging import time as t if __name__ == '__main__': # shortcut to not have to find out the port yourself serial_port = get_serial_ports()[0].device remote_id = 0x6110 # remote device network ID remote = True # whether to use a remote device # if not remote: # remote_id = None index = 0 previous_cycle_time = 0 current_cycle_time = 0 attributes_to_log = ["acceleration"] to_use_file = False filename = None """User input configuration section, comment out to use above settings""" remote = UserInput.use_remote() remote_id = UserInput.get_remote_id(remote) to_use_file = UserInput.use_file() filename = UserInput.get_filename(to_use_file) attributes_to_log = UserInput.get_multiple_attributes_to_log() use_processing = True ip = "127.0.0.1" network_port = 8888 anchors = [DeviceCoordinates(0x6863, 1, Coordinates(0, 0, 2000)), DeviceCoordinates(0x615a, 1, Coordinates(0, 18288, 1000)), DeviceCoordinates(0x607c, 1, Coordinates(18288, 0, 1000)), DeviceCoordinates(0x6134, 1, Coordinates(18288, 18288, 2000))] # algorithm = POZYX_POS_ALG_UWB_ONLY # positioning algorithm to use algorithm = POZYX_POS_ALG_TRACKING # tracking positioning algorithm dimension = POZYX_3D # positioning dimension height = 1000 # height of device, required in 2.5D positioning pozyx = PozyxSerial(serial_port) osc_udp_client = SimpleUDPClient(ip, network_port) o = Orientation3D(pozyx, osc_udp_client, anchors, algorithm, dimension, height, remote_id) o.setup() logfile = None if to_use_file: logfile = open(filename, 'a') FileWriting.write_sensor_and_position_header_to_file(logfile) start = ConsoleLogging.get_time() try: while True: # updates elapsed time and time difference elapsed = ConsoleLogging.get_elapsed_time(ConsoleLogging, start) previous_cycle_time = current_cycle_time current_cycle_time = elapsed time_difference = current_cycle_time - previous_cycle_time # store iterate_file returns as a tuple or an error message loop_results = o.loop() if type(loop_results) == tuple: one_cycle_sensor_data, one_cycle_position = loop_results formatted_data_dictionary = ConsoleLogging.format_sensor_data( one_cycle_sensor_data, attributes_to_log) if type(formatted_data_dictionary) == dict: formatted_data_dictionary["Position"] = [ "x:", one_cycle_position.x, "y:", one_cycle_position.y, "z:", one_cycle_position.z] ConsoleLogging.log_sensor_data_to_console(index, elapsed, formatted_data_dictionary) if to_use_file: FileWriting.write_sensor_and_position_data_to_file( index, elapsed, time_difference, logfile, one_cycle_sensor_data, one_cycle_position) # if the iterate_file didn't return a tuple, it returned an error string else: error_string = loop_results ConsoleLogging.print_data_error_message(index, elapsed, error_string) index += 1 # increment data index # this allows Windows users to exit the while iterate_file by pressing ctrl+c except KeyboardInterrupt: pass if to_use_file: logfile.close()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 464, 745, 7357, 87, 12897, 13605, 357, 66, 8, 7695, 7357, 87, 23500, 198, 29688, 2198, 503, 3740, 1378, 2503, 13, 7501, 7357, 87, 13, 952, 14, 24941, 341, 14, 51, 44917, ...
2.580882
1,904
#!/usr/bin/env python # -*- coding=utf-8 -*- # # Author: huangnj # Time: 2019/09/27 import traceback from functools import wraps from hdfs_kernel.constants import EXPECTED_ERROR_MSG, INTERNAL_ERROR_MSG from hdfs.util import HdfsError # == EXCEPTIONS == # option parse Error # == DECORATORS FOR EXCEPTION HANDLING == EXPECTED_EXCEPTIONS = [HdfsError, SessionManagementException, CommandNotAllowedException, CommandExecuteException, OptionParsingExit, OptionParsingError] def handle_expected_exceptions(f): """A decorator that handles expected exceptions. Self can be any object with an "ipython_display" attribute. Usage: @handle_expected_exceptions def fn(self, ...): etc...""" exceptions_to_handle = tuple(EXPECTED_EXCEPTIONS) # Notice that we're NOT handling e.DataFrameParseException here. That's because DataFrameParseException # is an internal error that suggests something is wrong with LivyClientLib's implementation. return wrapped def wrap_unexpected_exceptions(f, execute_if_error=None): """A decorator that catches all exceptions from the function f and alerts the user about them. Self can be any object with a "logger" attribute and a "ipython_display" attribute. All exceptions are logged as "unexpected" exceptions, and a request is made to the user to file an issue at the Github repository. If there is an error, returns None if execute_if_error is None, or else returns the output of the function execute_if_error. Usage: @wrap_unexpected_exceptions def fn(self, ...): ..etc """ return wrapped
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 28, 40477, 12, 23, 532, 9, 12, 198, 2, 198, 2, 6434, 25, 289, 84, 648, 77, 73, 198, 2, 3862, 25, 13130, 14, 2931, 14, 1983, 198, 198, 11748, 12854, 1891, ...
3.050373
536
# Copyright 2017 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from mock import patch from fixture import DjangoFixture from fixture.style import NamedDataStyle from fixture.django_testcase import FixtureTestCase from dashboard.managers.inventory import InventoryManager from dashboard.models import Product from dashboard.tests.testdata.db_fixtures import ( LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData ) db_fixture = DjangoFixture(style=NamedDataStyle())
[ 2, 15069, 2177, 2297, 10983, 11, 3457, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846...
3.90458
262
# Copyright 2020 The FedLearner Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8 # pylint: disable=broad-except, cyclic-import import logging import threading from concurrent import futures import grpc from fedlearner_webconsole.proto import ( service_pb2, service_pb2_grpc, common_pb2 ) from fedlearner_webconsole.db import db from fedlearner_webconsole.project.models import Project from fedlearner_webconsole.workflow.models import ( Workflow, WorkflowState, TransactionState ) from fedlearner_webconsole.exceptions import ( UnauthorizedException ) rpc_server = RpcServer()
[ 2, 15069, 12131, 383, 10169, 14961, 1008, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846...
3.471125
329
""" aiohttpHTTP """ import asyncio import time import aiohttp from asyncrates import get_rates SYMBOLS = ('USD', 'EUR', 'PLN', 'NOK', 'CZK') BASES = ('USD', 'EUR', 'PLN', 'NOK', 'CZK') if __name__ == "__main__": started = time.time() loop = asyncio.get_event_loop() loop.run_until_complete(main()) elapsed = time.time() - started print() print(f": {elapsed:.2f}s")
[ 37811, 198, 198, 64, 952, 4023, 40717, 198, 198, 37811, 198, 11748, 30351, 952, 198, 11748, 640, 198, 198, 11748, 257, 952, 4023, 198, 198, 6738, 355, 2047, 6098, 689, 1330, 651, 62, 9700, 198, 198, 23060, 10744, 3535, 50, 796, 19203,...
2.272727
176
#!/usr/bin/env python from __future__ import print_function import logging import os import signal from time import sleep from subprocess import Popen, PIPE import socket from core.common_functions import * from core.run import Runner
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 6737, 198, 6738, 640, 1330, 3993, 198, 6738, 850, 14681, 1330, 8099, 268, 11, 350, ...
3.621212
66
# -*- coding: utf-8 -*- import unittest from tavi.base.documents import BaseDocument
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 555, 715, 395, 198, 6738, 256, 15820, 13, 8692, 13, 15390, 2886, 1330, 7308, 24941, 628 ]
2.774194
31
"""Test file sequence discovery on disk.""" # "Future" Libraries from __future__ import print_function # Standard Libraries import os import unittest # Third Party Libraries import mock from builtins import range from future.utils import lrange from . import (DirEntry, generate_entries, initialise_mock_scandir_data, mock_scandir_deep) from .. import (__version__, get_parser, get_sequence, get_version, invert, validate_frame_sequence) from ..sequences import FileSequence, FrameChunk, FrameSequence ############################################################################### # class: TestSeqparseModule def test_add_file_sequence(self): """Seqparse: Test file sequence addition via seqparse.add_file.""" input_file = ".".join((self._test_file_name, "0005", self._test_ext)) input_file = os.path.join(self._test_root, input_file) # Expected outputs ... input_frame_seq = "0000-0004" output_frame_seq = "0000-0005" input_file_seq = ".".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) output_file_seq = ".".join( (self._test_file_name, output_frame_seq, self._test_ext)) output_file_seq = os.path.join(self._test_root, output_file_seq) print("\n\n INPUT FILES\n -----------") print(" o", input_file_seq) print(" o", input_file) parser = get_parser() parser.add_file(input_file_seq) parser.add_file(input_file) output = list(parser.output()) print("\n OUTPUT FILES\n ------------") for line in output: print(" o", line) print("\n EXPECTED OUTPUT\n ---------------") print(" o", output_file_seq) print("") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) input_frame_seq = "0000-0002,,0003-0005" input_file_seq = ".".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) print("\n INPUT FILES\n -----------") print(" o", input_file_seq) print(" o", input_file) parser = get_parser() parser.add_file(input_file_seq) parser.add_file(input_file) output = list(parser.output()) print("\n OUTPUT FILES\n ------------") for line in output: print(" o", line) print("\n EXPECTED OUTPUT\n ---------------") print(" o", output_file_seq) print("") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) def test_api_calls(self): """Seqparse: Test API calls at root of module.""" chunk = FrameChunk(first=1, last=7, step=2, pad=4) seq = get_sequence(lrange(1, 8, 2), pad=4) self.assertTrue(isinstance(seq, FrameSequence)) self.assertEqual(str(seq), "0001-0007x2") expected = FrameChunk(first=2, last=6, step=2, pad=4) inverted = invert(chunk) self.assertEqual(str(inverted), str(expected)) inverted = invert(seq) self.assertEqual(str(inverted), str(expected)) with self.assertRaises(TypeError): invert(get_parser()) self.assertEqual(get_version(), __version__)
[ 37811, 14402, 2393, 8379, 9412, 319, 11898, 526, 15931, 198, 198, 2, 366, 29783, 1, 46267, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 2, 8997, 46267, 198, 11748, 28686, 198, 11748, 555, 715, 395, 198, 198, 2, 10467,...
2.298398
1,498
import urllib.request import pandas as pd import sqlite3 import re from bs4 import BeautifulSoup # Parameters postcodes_list = ["W1F7EY"] db_name = "scraped.db" # This is so that Deliveroo think the scraper is Google Chrome # as opposed to a web scraper hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11' + '(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*' + ';q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} if __name__ == "__main__": postcodes_df = pd.DataFrame({ 'post_code': postcodes_list }) process_all_restaurants(postcodes_df, db_name)
[ 11748, 2956, 297, 571, 13, 25927, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 44161, 578, 18, 198, 11748, 302, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 628, 198, 2, 40117, 198, 7353, 40148, 62, 4868, 796, 14631, 54, 16,...
2.217158
373
from django.contrib import admin from wouso.core.security.models import Report admin.site.register(Report)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 266, 516, 78, 13, 7295, 13, 12961, 13, 27530, 1330, 6358, 198, 198, 28482, 13, 15654, 13, 30238, 7, 19100, 8, 198 ]
3.375
32
#### Reading Data from The Things Network Data and Automatically Storing it to a Google Spreadsheet # Author: Dilip Rajkumar # Email: d.rajkumar@hbksaar.de # Date: 19/01/2018 # Revision: version#1 # License: MIT License import pandas as pd import requests from df2gspread import df2gspread as d2g import time ## Set Initial Time Duration in mins to query TTN Data: time_duration = 5 # Insert spreadsheet file id of Google Spreadsheet spreadsheet = '1ftXlebCTDp5tTxvlm5K3Sv1oNttDHR7s1xTi-i-ZR_o' ## Google SpreadSheet Title: TTN_Live_DataLogger # Insert Sheet Name wks_name = 'Sheet1' def queryttndata(time_duration): ''' This function queries data from TTN Swagger API based on a time duration which is given as an input ''' headers = {'Accept': 'application/json','Authorization': 'key ttn-account-v2.P4kRaEqenNGbIdFSgSLDJGMav5K9YrekkMm_F1lOVrw'} ## Set query duration in minutes querytime = str(time_duration) + 'm' params = (('last', querytime),) response = requests.get('https://vehiclecounter.data.thethingsnetwork.org/api/v2/query', headers=headers, params=params).json() df_raw = pd.DataFrame.from_dict(response) return df_raw def cleandf(df): ''' In this function we pass as input the raw dataframe from TTN in JSON format to clean and optimize the data. This function is customized and unique to every dataset ''' df.rename(columns={'time': 'TTNTimeStamp'}, inplace=True) df['TTNTimeStamp'] = pd.to_datetime(df['TTNTimeStamp']) df['TTNTimeStamp'] = df['TTNTimeStamp'] + pd.Timedelta(hours=1) ## Offset Time by 1 hour to fix TimeZone Error of Swagger API TimeStamps df['TTNTimeStamp'] = df['TTNTimeStamp'].values.astype('datetime64[s]') drop_cols = ['raw','device_id'] df = df.drop(drop_cols, 1) df.reset_index() df = df.reindex(['TTNTimeStamp','Count'], axis=1) print("Latest Data:") print(df.tail(1),'\n') return df while True: #begin your infinite loop df_raw = queryttndata(time_duration) df_clean = cleandf(df_raw) d2g.upload(df_clean, spreadsheet,wks_name,col_names=True,clean=True) # Write dataframe to Google Spreadsheet df_clean.to_csv('TTN_VehicleCountData.csv', date_format="%d/%m/%Y %H:%M:%S",index=True) # Save DataFrame locally time.sleep(60) # Call function every 60 seconds time_duration += 1 ## Increment query duration by 1 mins at the end of every function call
[ 4242, 11725, 6060, 422, 383, 11597, 7311, 6060, 290, 17406, 4142, 520, 3255, 340, 284, 257, 3012, 31843, 21760, 198, 198, 2, 6434, 25, 29328, 541, 13308, 74, 44844, 198, 2, 9570, 25, 288, 13, 430, 73, 74, 44844, 31, 71, 65, 591, 6...
2.617271
938
import xmltodict from share.transform.chain import * # noqa EXAMPLE = ''' <entry> <id>http://arxiv.org/abs/cond-mat/0102536v1</id> <updated>2001-02-28T20:12:09Z</updated> <published>2001-02-28T20:12:09Z</published> <title>Impact of Electron-Electron Cusp on Configuration Interaction Energies</title> <summary> The effect of the electron-electron cusp on the convergence of configuration interaction (CI) wave functions is examined. By analogy with the pseudopotential approach for electron-ion interactions, an effective electron-electron interaction is developed which closely reproduces the scattering of the Coulomb interaction but is smooth and finite at zero electron-electron separation. The exact many-electron wave function for this smooth effective interaction has no cusp at zero electron-electron separation. We perform CI and quantum Monte Carlo calculations for He and Be atoms, both with the Coulomb electron-electron interaction and with the smooth effective electron-electron interaction. We find that convergence of the CI expansion of the wave function for the smooth electron-electron interaction is not significantly improved compared with that for the divergent Coulomb interaction for energy differences on the order of 1 mHartree. This shows that, contrary to popular belief, description of the electron-electron cusp is not a limiting factor, to within chemical accuracy, for CI calculations. </summary> <author> <name>David Prendergast</name> <arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">Department of Physics</arxiv:affiliation> </author> <author> <name>M. Nolan</name> <arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">NMRC, University College, Cork, Ireland</arxiv:affiliation> </author> <author> <name>Claudia Filippi</name> <arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">Department of Physics</arxiv:affiliation> </author> <author> <name>Stephen Fahy</name> <arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">Department of Physics</arxiv:affiliation> </author> <author> <name>J. C. Greer</name> <arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">NMRC, University College, Cork, Ireland</arxiv:affiliation> </author> <arxiv:doi xmlns:arxiv="http://arxiv.org/schemas/atom">10.1063/1.1383585</arxiv:doi> <link title="doi" href="http://dx.doi.org/10.1063/1.1383585" rel="related"/> <arxiv:comment xmlns:arxiv="http://arxiv.org/schemas/atom">11 pages, 6 figures, 3 tables, LaTeX209, submitted to The Journal of Chemical Physics</arxiv:comment> <arxiv:journal_ref xmlns:arxiv="http://arxiv.org/schemas/atom">J. Chem. Phys. 115, 1626 (2001)</arxiv:journal_ref> <link href="http://arxiv.org/abs/cond-mat/0102536v1" rel="alternate" type="text/html"/> <link title="pdf" href="http://arxiv.org/pdf/cond-mat/0102536v1" rel="related" type="application/pdf"/> <arxiv:primary_category xmlns:arxiv="http://arxiv.org/schemas/atom" term="cond-mat.str-el" scheme="http://arxiv.org/schemas/atom"/> <category term="cond-mat.str-el" scheme="http://arxiv.org/schemas/atom"/> </entry> '''
[ 11748, 2124, 76, 2528, 375, 713, 198, 198, 6738, 2648, 13, 35636, 13, 7983, 1330, 1635, 220, 1303, 645, 20402, 628, 198, 6369, 2390, 16437, 796, 705, 7061, 198, 1279, 13000, 29, 198, 220, 220, 220, 1279, 312, 29, 4023, 1378, 283, 87...
2.814075
1,151
from __future__ import annotations from typing import TypeVar, Generic, Callable, Optional, Any, cast, Tuple import rx from returns import pipeline from returns.functions import identity from returns.maybe import Maybe, Nothing from rx import Observable from rx.subject import BehaviorSubject from . import ReactiveValue, ReactiveView from .value import Modifier T = TypeVar("T")
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 5994, 19852, 11, 42044, 11, 4889, 540, 11, 32233, 11, 4377, 11, 3350, 11, 309, 29291, 198, 198, 11748, 374, 87, 198, 6738, 5860, 1330, 11523, 198, 6738, 5860, 13, 1254...
3.888889
99
""" Argo Server API You can get examples of requests and responses by using the CLI with `--gloglevel=9`, e.g. `argo list --gloglevel=9` # noqa: E501 The version of the OpenAPI document: VERSION Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from openapi_client.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) from ..model_utils import OpenApiModel from openapi_client.exceptions import ApiAttributeError
[ 37811, 198, 220, 220, 220, 943, 2188, 9652, 7824, 628, 220, 220, 220, 921, 460, 651, 6096, 286, 7007, 290, 9109, 416, 1262, 262, 43749, 351, 4600, 438, 4743, 2467, 626, 28, 24, 47671, 304, 13, 70, 13, 4600, 9448, 1351, 1377, 4743, ...
2.650558
269
#!/usr/bin/env python # # Copyright (C) 2018 Intel Corporation # # SPDX-License-Identifier: MIT from __future__ import absolute_import, division, print_function import argparse import os import glog as log import numpy as np import cv2 from lxml import etree from tqdm import tqdm def parse_args(): """Parse arguments of command line""" parser = argparse.ArgumentParser( fromfile_prefix_chars='@', description='Convert CVAT XML annotations to masks' ) parser.add_argument( '--cvat-xml', metavar='FILE', required=True, help='input file with CVAT annotation in xml format' ) parser.add_argument( '--background-color', metavar='COLOR_BGR', default="0,0,0", help='specify background color (by default: 0,0,0)' ) parser.add_argument( '--label-color', metavar='LABEL:COLOR_BGR', action='append', default=[], help="specify a label's color (e.g. 255 or 255,0,0). The color will " + "be interpreted in accordance with the mask format." ) parser.add_argument( '--mask-bitness', type=int, choices=[8, 24], default=8, help='choose bitness for masks' ) parser.add_argument( '--output-dir', metavar='DIRECTORY', required=True, help='directory for output masks' ) return parser.parse_args() if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 357, 34, 8, 2864, 8180, 10501, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 17168, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 729...
2.532609
552
""" ========================== Callosal bundles using AFQ API ========================== An example using the AFQ API to find callosal bundles using the templates from: http://hdl.handle.net/1773/34926 """ import os.path as op import plotly from AFQ import api from AFQ.mask import RoiMask import AFQ.data as afd ########################################################################## # Get some example data # --------------------- # # Retrieves `Stanford HARDI dataset <https://purl.stanford.edu/ng782rw8378>`_. # afd.organize_stanford_data(clear_previous_afq=True) ########################################################################## # Set tractography parameters (optional) # --------------------- # We make this tracking_params which we will pass to the AFQ object # which specifies that we want 100,000 seeds randomly distributed # in the ROIs of every bundle. # # We only do this to make this example faster and consume less space. tracking_params = dict(seed_mask=RoiMask(), n_seeds=10000, random_seeds=True, rng_seed=42) ########################################################################## # Initialize an AFQ object: # ------------------------- # # We specify bundle_info as the default bundles list (api.BUNDLES) plus the # callosal bundle list. This tells the AFQ object to use bundles from both # the standard and callosal templates. myafq = api.AFQ(bids_path=op.join(afd.afq_home, 'stanford_hardi'), dmriprep='vistasoft', bundle_info=api.BUNDLES + api.CALLOSUM_BUNDLES, tracking_params=tracking_params) ########################################################################## # Visualizing bundles and tract profiles: # --------------------------------------- # This would run the script and visualize the bundles using the plotly # interactive visualization, which should automatically open in a # new browser window. bundle_html = myafq.viz_bundles(export=True, n_points=50) plotly.io.show(bundle_html[0])
[ 37811, 198, 4770, 2559, 855, 198, 14134, 40725, 36344, 1262, 12341, 48, 7824, 198, 4770, 2559, 855, 198, 2025, 1672, 1262, 262, 12341, 48, 7824, 284, 1064, 869, 40725, 36344, 1262, 262, 24019, 422, 25, 198, 4023, 1378, 71, 25404, 13, ...
3.137519
669
import time import Queue import random import socket import struct import logging import threading from convert import * from protocol import ethernet, ip, tcp, udp ETH_P_IP = 0x0800 # IP protocol ETH_P_ALL = 0x0003 # Every packet NSCRIPT_PATH = 'nscript' # NSCRIPT PATH PAYLOAD = { 53:('\x5d\x0d\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x06' 'google\x03com\x00\x00\x01\x00\x01'), # 'google.com' DNS Lookup 161:('\x30\x26\x02\x01\x01\x04\x06public\xa1\x19\x02' '\x04\x56\x9f\x5a\xdd\x02\x01\x00\x02\x01\x00\x30\x0b\x30\x09\x06' '\x05\x2b\x06\x01\x02\x01\x05\x00'), # SNMP GetNextRequest|public|2c version|1.3.6.1.2.1 123:('\x17\x00\x02\x05'), # NTP systats commands lacks 38 null bytes (just to save bandwidth) 1900:('M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\n' 'MAN: "ssdp:discover"\r\nMX: 2\r\nST: ssdp:all\r\n\r\n') } def Extract(packet): src = socket.inet_ntoa(packet[12:16]) srcp = struct.unpack('!H', packet[20:22])[0] return src, srcp def Alive(thread_list): ''' check if thread is alive ''' alive = False for t in thread_list: if t.isAlive(): alive = True break return alive
[ 11748, 640, 198, 11748, 4670, 518, 198, 11748, 4738, 198, 11748, 17802, 198, 11748, 2878, 198, 11748, 18931, 198, 11748, 4704, 278, 198, 6738, 10385, 1330, 1635, 198, 6738, 8435, 1330, 28475, 3262, 11, 20966, 11, 48265, 11, 334, 26059, ...
2.041742
551
import sys from flask import Blueprint, request, jsonify from flaskApp import db from flaskApp.assignment.utils import * from flaskApp.error.error_handlers import * import json from flaskApp.helpers import getAssignmentData assignment = Blueprint('assignment', __name__) '''Test method, keep just in case. Will prob be moved to seperate API designed to interact with just the MySQL database that the data pipeline will drop stuff into'''
[ 11748, 25064, 198, 6738, 42903, 1330, 39932, 11, 2581, 11, 33918, 1958, 198, 6738, 42903, 4677, 1330, 20613, 198, 6738, 42903, 4677, 13, 562, 16747, 13, 26791, 1330, 1635, 198, 6738, 42903, 4677, 13, 18224, 13, 18224, 62, 4993, 8116, 13...
3.928571
112
####################################################################################################################### # Given a string, find the length of the longest substring which has no repeating characters. # # Input: String="aabccbb" # Output: 3 # Explanation: The longest substring without any repeating characters is "abc". # # Input: String="abbbb" # Output: 2 # Explanation: The longest substring without any repeating characters is "ab". # # Input: String="abccde" # Output: 3 # Explanation: Longest substrings without any repeating characters are "abc" & "cde". ####################################################################################################################### print(longest_substring_no_repeating_char('aabccbb')) print(longest_substring_no_repeating_char('abbbb')) print(longest_substring_no_repeating_char('abccde')) print(longest_substring_no_repeating_char('abcabcbb')) print(longest_substring_no_repeating_char('bbbbb')) print(longest_substring_no_repeating_char('pwwkew'))
[ 29113, 29113, 29113, 14468, 4242, 21017, 198, 2, 11259, 257, 4731, 11, 1064, 262, 4129, 286, 262, 14069, 3293, 1806, 543, 468, 645, 20394, 3435, 13, 198, 2, 198, 2, 23412, 25, 10903, 2625, 64, 397, 535, 11848, 1, 198, 2, 25235, 25, ...
3.780669
269
import sys sys.path.insert(0, '.') from pyspark import SparkContext, SparkConf from commons.Utils import Utils if __name__ == "__main__": ''' Create a Spark program to read the airport data from in/airports.text; generate a pair RDD with airport name being the key and country name being the value. Then remove all the airports which are located in United States and output the pair RDD to out/airports_not_in_usa_pair_rdd.text Each row of the input file contains the following columns: Airport ID, Name of airport, Main city served by airport, Country where airport is located, IATA/FAA code, ICAO Code, Latitude, Longitude, Altitude, Timezone, DST, Timezone in Olson format Sample output: ("Kamloops", "Canada") ("Wewak Intl", "Papua New Guinea") ... ''' conf = SparkConf().setAppName("airports").setMaster("local[*]") sc = SparkContext(conf=conf) airportsRDD = sc.textFile("inputs/airports.text") airportPairRDD = airportsRDD.map(lambda line: (Utils.COMMA_DELIMITER.split(line)[1], Utils.COMMA_DELIMITER.split(line)[3])) airportsNotInUSA = airportPairRDD.filter( lambda keyValue: keyValue[1] != "\"United States\"") airportsNotInUSA.saveAsTextFile( "outputs/airports_not_in_usa_pair_rdd.text")
[ 11748, 25064, 201, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 705, 2637, 8, 201, 198, 201, 198, 201, 198, 6738, 279, 893, 20928, 1330, 17732, 21947, 11, 17732, 18546, 201, 198, 6738, 36523, 13, 18274, 4487, 1330, 7273, 4487, 201, 1...
2.428571
581
#!/usr/bin/python3 # Keyboard details window import logging import json from os import path import qrcode import tempfile import gi from gi.repository import Gtk from keyman_config import KeymanComUrl, _, secure_lookup from keyman_config.accelerators import init_accel from keyman_config.kmpmetadata import parsemetadata gi.require_version('Gtk', '3.0') # basics: keyboard name, package version, description # other things: filename (of kmx), , # OSK availability, documentation availability, package copyright # also: supported languages, fonts # from kmx?: keyboard version, encoding, layout type # there is data in kmp.inf/kmp.json # there is possibly data in kbid.json (downloaded from api)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 2, 31973, 3307, 4324, 198, 198, 11748, 18931, 198, 11748, 33918, 198, 6738, 28686, 1330, 3108, 198, 11748, 10662, 6015, 1098, 198, 11748, 20218, 7753, 198, 198, 11748, 308, 72, 198, ...
3.410628
207
import os import shutil SOURCE_DIR = '../deploy/runtime' TARGET_DIR = 'SAM.app/Contents/runtime' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/solar_resource' TARGET_DIR = 'SAM.app/Contents/solar_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/wind_resource' TARGET_DIR = 'SAM.app/Contents/wind_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/libraries' TARGET_DIR = 'SAM.app/Contents/libraries' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git'))
[ 11748, 28686, 198, 11748, 4423, 346, 198, 198, 47690, 62, 34720, 796, 705, 40720, 2934, 1420, 14, 43282, 6, 198, 51, 46095, 62, 34720, 796, 705, 49302, 13, 1324, 14, 15842, 14, 43282, 6, 198, 198, 361, 28686, 13, 6978, 13, 1069, 102...
2.422164
379
""" path_util contains helpers for working with local filesystem paths. There are a few classes of methods provided here: Functions to normalize paths and check that they are in normal form: normalize, check_isvalid, check_isdir, check_isfile, path_is_url Functions to list directories and to deal with subpaths of paths: safe_join, get_relative_path, ls, recursive_ls Functions to read files to compute hashes, write results to stdout, etc: getmtime, get_size, hash_directory, hash_file_contents Functions that modify that filesystem in controlled ways: copy, make_directory, set_write_permissions, rename, remove """ import errno import hashlib import itertools import os import shutil import subprocess import sys from typing import Optional from codalab.common import precondition, UsageError, parse_linked_bundle_url from codalab.lib import file_util from codalab.worker.file_util import get_path_size # Block sizes and canonical strings used when hashing files. BLOCK_SIZE = 0x40000 FILE_PREFIX = 'file' LINK_PREFIX = 'link' def path_error(message, path): """ Raised when a user-supplied path causes an exception. """ return UsageError(message + ': ' + path) ################################################################################ # Functions to normalize paths and check that they are in normal form. ################################################################################ def normalize(path): """ Return the absolute path of the location specified by the given path. This path is returned in a "canonical form", without ~'s, .'s, ..'s. """ if path == '-': return '/dev/stdin' elif path_is_url(path): return path else: return os.path.abspath(os.path.expanduser(path)) def check_isvalid(path, fn_name): """ Raise a PreconditionViolation if the path is not absolute or normalized. Raise a UsageError if the file at that path does not exist. """ precondition(os.path.isabs(path), '%s got relative path: %s' % (fn_name, path)) # Broken symbolic links are valid paths, so we use lexists instead of exists. if not os.path.lexists(path): raise path_error('%s got non-existent path:' % (fn_name,), path) def check_isdir(path, fn_name): """ Check that the path is valid, then raise UsageError if the path is a file. """ check_isvalid(path, fn_name) if not os.path.isdir(path): raise path_error('%s got non-directory:' % (fn_name,), path) def check_isfile(path, fn_name): """ Check that the path is valid, then raise UsageError if the path is a file. """ check_isvalid(path, fn_name) if os.path.isdir(path): raise path_error('%s got directory:' % (fn_name,), path) ################################################################################ # Functions to list directories and to deal with subpaths of paths. ################################################################################ def safe_join(*paths): """ Join a sequence of paths but filter out any that are empty. Used for targets. Note that os.path.join has this functionality EXCEPT at the end of the list, which causes problems when a target subpath is empty. """ return os.path.join(*[_f for _f in paths if _f]) def get_relative_path(root, path): """ Return the relative path from root to path, which should be nested under root. """ precondition(path.startswith(root), '%s is not under %s' % (path, root)) return path[len(root) :] def ls(path): """ Return a (list of directories, list of files) in the given directory. """ check_isdir(path, 'ls') (directories, files) = ([], []) for file_name in os.listdir(path): if os.path.isfile(os.path.join(path, file_name)): files.append(file_name) else: directories.append(file_name) return (directories, files) def recursive_ls(path): """ Return a (list of directories, list of files) in the given directory and all of its nested subdirectories. All paths returned are absolute. Symlinks are returned in the list of files, even if they point to directories. This makes it possible to distinguish between real and symlinked directories when computing the hash of a directory. This function will NOT descend into symlinked directories. """ check_isdir(path, 'recursive_ls') (directories, files) = ([], []) for (root, _, file_names) in os.walk(path): assert os.path.isabs(root), 'Got relative root in os.walk: %s' % (root,) directories.append(root) for file_name in file_names: files.append(os.path.join(root, file_name)) # os.walk ignores symlinks to directories, but we should count them as files. # However, we can't used the followlinks parameter, because a) we don't want # to descend into directories and b) we could end up in an infinite loop if # we were to pass that flag. Instead, we handle symlinks here: for subpath in os.listdir(root): full_subpath = os.path.join(root, subpath) if os.path.islink(full_subpath) and os.path.isdir(full_subpath): files.append(full_subpath) return (directories, files) ################################################################################ # Functions to read files to compute hashes, write results to stdout, etc. ################################################################################ def getmtime(path): """ Like os.path.getmtime, but does not follow symlinks. """ return os.lstat(path).st_mtime def get_size(path, dirs_and_files=None): """ Get the size (in bytes) of the file or directory at or under the given path. Does not include symlinked files and directories. """ if parse_linked_bundle_url(path).uses_beam: return get_path_size(path) if os.path.islink(path) or not os.path.isdir(path): return os.lstat(path).st_size dirs_and_files = dirs_and_files or recursive_ls(path) return sum(os.lstat(path).st_size for path in itertools.chain(*dirs_and_files)) def hash_directory(path, dirs_and_files=None): """ Return the hash of the contents of the folder at the given path. This hash is independent of the path itself - if you were to move the directory and call get_hash again, you would get the same result. """ if parse_linked_bundle_url(path).uses_beam: # On Azure Blob Storage, we just use the directory size for the hashed contents. return get_size(path) (directories, files) = dirs_and_files or recursive_ls(path) # Sort and then hash all directories and then compute a hash of the hashes. # This two-level hash is necessary so that the overall hash is unambiguous - # if we updated directory_hash with the directory names themselves, then # we'd be hashing the concatenation of these names, which could be generated # in multiple ways. directory_hash = hashlib.sha1() for directory in sorted(directories): relative_path = get_relative_path(path, directory) directory_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) # Use a similar two-level hashing scheme for all files, but incorporate a # hash of both the file name and contents. file_hash = hashlib.sha1() for file_name in sorted(files): relative_path = get_relative_path(path, file_name) file_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) file_hash.update(hash_file_contents(file_name).encode()) # Return a hash of the two hashes. overall_hash = hashlib.sha1(directory_hash.hexdigest().encode()) overall_hash.update(file_hash.hexdigest().encode()) return overall_hash.hexdigest() def hash_file_contents(path): """ Return the hash of the file's contents, read in blocks of size BLOCK_SIZE. """ message = 'hash_file called with relative path: %s' % (path,) precondition(os.path.isabs(path), message) if os.path.islink(path): contents_hash = hashlib.sha1(LINK_PREFIX.encode()) contents_hash.update(os.readlink(path).encode()) else: contents_hash = hashlib.sha1(FILE_PREFIX.encode()) with open(path, 'rb') as file_handle: while True: data = file_handle.read(BLOCK_SIZE) if not data: break contents_hash.update(data) return contents_hash.hexdigest() ################################################################################ # Functions that modify that filesystem in controlled ways. ################################################################################ def copy(source_path: str, dest_path: str, follow_symlinks: Optional[bool] = False): """ Copy |source_path| to |dest_path|. Assume dest_path doesn't exist. |follow_symlinks|: whether to follow symlinks Note: this only works in Linux. """ if os.path.exists(dest_path): raise path_error('already exists', dest_path) if source_path == '/dev/stdin': with open(dest_path, 'wb') as dest: file_util.copy( sys.stdin, dest, autoflush=False, print_status='Copying %s to %s' % (source_path, dest_path), ) else: if not follow_symlinks and os.path.islink(source_path): raise path_error('not following symlinks', source_path) if not os.path.exists(source_path): raise path_error('does not exist', source_path) command = [ 'rsync', '-pr%s' % ('L' if follow_symlinks else 'l'), source_path + ('/' if not os.path.islink(source_path) and os.path.isdir(source_path) else ''), dest_path, ] if subprocess.call(command) != 0: raise path_error('Unable to copy %s to' % source_path, dest_path) def make_directory(path): """ Create the directory at the given path. """ try: os.mkdir(path) except OSError as e: if e.errno != errno.EEXIST: raise check_isdir(path, 'make_directory') def remove(path): """ Remove the given path, whether it is a directory, file, or link. """ if parse_linked_bundle_url(path).uses_beam: from apache_beam.io.filesystems import FileSystems if not FileSystems.exists(path): FileSystems.delete([path]) return check_isvalid(path, 'remove') set_write_permissions(path) # Allow permissions if os.path.islink(path): os.unlink(path) elif os.path.isdir(path): try: shutil.rmtree(path) except shutil.Error: pass else: os.remove(path) if os.path.exists(path): print('Failed to remove %s' % path) def soft_link(source, path): """ Create a symbolic link to source at path. This is basically the same as doing "ln -s $source $path" """ check_isvalid(source, 'soft_link') os.symlink(source, path)
[ 37811, 198, 6978, 62, 22602, 4909, 49385, 329, 1762, 351, 1957, 29905, 13532, 13, 198, 1858, 389, 257, 1178, 6097, 286, 5050, 2810, 994, 25, 628, 220, 40480, 284, 3487, 1096, 13532, 290, 2198, 326, 484, 389, 287, 3487, 1296, 25, 198, ...
2.745285
4,083
# -*- coding: utf-8 -*- """Tests of GLSAR and diagnostics against Gretl Created on Thu Feb 02 21:15:47 2012 Author: Josef Perktold License: BSD-3 """ import os import numpy as np from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose, assert_array_less) from statsmodels.regression.linear_model import OLS, GLSAR from statsmodels.tools.tools import add_constant from statsmodels.datasets import macrodata import statsmodels.stats.sandwich_covariance as sw import statsmodels.stats.diagnostic as smsdia import statsmodels.stats.outliers_influence as oi if __name__ == '__main__': t = TestGLSARGretl() t.test_all() ''' Model 5: OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable: ds_l_realinv HAC standard errors, bandwidth 4 (Bartlett kernel) coefficient std. error t-ratio p-value ------------------------------------------------------------- const -9.48167 1.17709 -8.055 7.17e-014 *** ds_l_realgdp 4.37422 0.328787 13.30 2.62e-029 *** realint_1 -0.613997 0.293619 -2.091 0.0378 ** Mean dependent var 3.257395 S.D. dependent var 18.73915 Sum squared resid 22799.68 S.E. of regression 10.70380 R-squared 0.676978 Adjusted R-squared 0.673731 F(2, 199) 90.79971 P-value(F) 9.53e-29 Log-likelihood -763.9752 Akaike criterion 1533.950 Schwarz criterion 1543.875 Hannan-Quinn 1537.966 rho -0.107341 Durbin-Watson 2.213805 QLR test for structural break - Null hypothesis: no structural break Test statistic: max F(3, 196) = 3.01985 at observation 2001:4 (10 percent critical value = 4.09) Non-linearity test (logs) - Null hypothesis: relationship is linear Test statistic: LM = 1.68351 with p-value = P(Chi-square(2) > 1.68351) = 0.430953 Non-linearity test (squares) - Null hypothesis: relationship is linear Test statistic: LM = 7.52477 with p-value = P(Chi-square(2) > 7.52477) = 0.0232283 LM test for autocorrelation up to order 4 - Null hypothesis: no autocorrelation Test statistic: LMF = 1.17928 with p-value = P(F(4,195) > 1.17928) = 0.321197 CUSUM test for parameter stability - Null hypothesis: no change in parameters Test statistic: Harvey-Collier t(198) = 0.494432 with p-value = P(t(198) > 0.494432) = 0.621549 Chow test for structural break at observation 1984:1 - Null hypothesis: no structural break Asymptotic test statistic: Chi-square(3) = 13.1897 with p-value = 0.00424384 Test for ARCH of order 4 - Null hypothesis: no ARCH effect is present Test statistic: LM = 3.43473 with p-value = P(Chi-square(4) > 3.43473) = 0.487871: #ANOVA Analysis of Variance: Sum of squares df Mean square Regression 47782.7 2 23891.3 Residual 22799.7 199 114.571 Total 70582.3 201 351.156 R^2 = 47782.7 / 70582.3 = 0.676978 F(2, 199) = 23891.3 / 114.571 = 208.528 [p-value 1.47e-049] #LM-test autocorrelation Breusch-Godfrey test for autocorrelation up to order 4 OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable: uhat coefficient std. error t-ratio p-value ------------------------------------------------------------ const 0.0640964 1.06719 0.06006 0.9522 ds_l_realgdp -0.0456010 0.217377 -0.2098 0.8341 realint_1 0.0511769 0.293136 0.1746 0.8616 uhat_1 -0.104707 0.0719948 -1.454 0.1475 uhat_2 -0.00898483 0.0742817 -0.1210 0.9039 uhat_3 0.0837332 0.0735015 1.139 0.2560 uhat_4 -0.0636242 0.0737363 -0.8629 0.3893 Unadjusted R-squared = 0.023619 Test statistic: LMF = 1.179281, with p-value = P(F(4,195) > 1.17928) = 0.321 Alternative statistic: TR^2 = 4.771043, with p-value = P(Chi-square(4) > 4.77104) = 0.312 Ljung-Box Q' = 5.23587, with p-value = P(Chi-square(4) > 5.23587) = 0.264: RESET test for specification (squares and cubes) Test statistic: F = 5.219019, with p-value = P(F(2,197) > 5.21902) = 0.00619 RESET test for specification (squares only) Test statistic: F = 7.268492, with p-value = P(F(1,198) > 7.26849) = 0.00762 RESET test for specification (cubes only) Test statistic: F = 5.248951, with p-value = P(F(1,198) > 5.24895) = 0.023 #heteroscedasticity White White's test for heteroskedasticity OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable: uhat^2 coefficient std. error t-ratio p-value ------------------------------------------------------------- const 104.920 21.5848 4.861 2.39e-06 *** ds_l_realgdp -29.7040 6.24983 -4.753 3.88e-06 *** realint_1 -6.93102 6.95607 -0.9964 0.3203 sq_ds_l_realg 4.12054 0.684920 6.016 8.62e-09 *** X2_X3 2.89685 1.38571 2.091 0.0379 ** sq_realint_1 0.662135 1.10919 0.5970 0.5512 Unadjusted R-squared = 0.165860 Test statistic: TR^2 = 33.503723, with p-value = P(Chi-square(5) > 33.503723) = 0.000003: #heteroscedasticity Breusch-Pagan (original) Breusch-Pagan test for heteroskedasticity OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable: scaled uhat^2 coefficient std. error t-ratio p-value ------------------------------------------------------------- const 1.09468 0.192281 5.693 4.43e-08 *** ds_l_realgdp -0.0323119 0.0386353 -0.8363 0.4040 realint_1 0.00410778 0.0512274 0.08019 0.9362 Explained sum of squares = 2.60403 Test statistic: LM = 1.302014, with p-value = P(Chi-square(2) > 1.302014) = 0.521520 #heteroscedasticity Breusch-Pagan Koenker Breusch-Pagan test for heteroskedasticity OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable: scaled uhat^2 (Koenker robust variant) coefficient std. error t-ratio p-value ------------------------------------------------------------ const 10.6870 21.7027 0.4924 0.6230 ds_l_realgdp -3.64704 4.36075 -0.8363 0.4040 realint_1 0.463643 5.78202 0.08019 0.9362 Explained sum of squares = 33174.2 Test statistic: LM = 0.709924, with p-value = P(Chi-square(2) > 0.709924) = 0.701200 ########## forecast #forecast mean y For 95% confidence intervals, t(199, 0.025) = 1.972 Obs ds_l_realinv prediction std. error 95% interval 2008:3 -7.134492 -17.177905 2.946312 -22.987904 - -11.367905 2008:4 -27.665860 -36.294434 3.036851 -42.282972 - -30.305896 2009:1 -70.239280 -44.018178 4.007017 -51.919841 - -36.116516 2009:2 -27.024588 -12.284842 1.427414 -15.099640 - -9.470044 2009:3 8.078897 4.483669 1.315876 1.888819 - 7.078520 Forecast evaluation statistics Mean Error -3.7387 Mean Squared Error 218.61 Root Mean Squared Error 14.785 Mean Absolute Error 12.646 Mean Percentage Error -7.1173 Mean Absolute Percentage Error -43.867 Theil's U 0.4365 Bias proportion, UM 0.06394 Regression proportion, UR 0.13557 Disturbance proportion, UD 0.80049 #forecast actual y For 95% confidence intervals, t(199, 0.025) = 1.972 Obs ds_l_realinv prediction std. error 95% interval 2008:3 -7.134492 -17.177905 11.101892 -39.070353 - 4.714544 2008:4 -27.665860 -36.294434 11.126262 -58.234939 - -14.353928 2009:1 -70.239280 -44.018178 11.429236 -66.556135 - -21.480222 2009:2 -27.024588 -12.284842 10.798554 -33.579120 - 9.009436 2009:3 8.078897 4.483669 10.784377 -16.782652 - 25.749991 Forecast evaluation statistics Mean Error -3.7387 Mean Squared Error 218.61 Root Mean Squared Error 14.785 Mean Absolute Error 12.646 Mean Percentage Error -7.1173 Mean Absolute Percentage Error -43.867 Theil's U 0.4365 Bias proportion, UM 0.06394 Regression proportion, UR 0.13557 Disturbance proportion, UD 0.80049 '''
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 51, 3558, 286, 402, 6561, 1503, 290, 6689, 34558, 1028, 35877, 75, 198, 198, 41972, 319, 26223, 3158, 7816, 2310, 25, 1314, 25, 2857, 2321, 198, 198, 13838, 25, ...
2.11004
4,044
import requests import django.contrib.auth as auth from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, JsonResponse, Http404 from django.contrib.auth.decorators import login_required from django.core.serializers import serialize from core.serializers import * from core.models import * from core.secrets import API_TOKEN, STRIPE_API_KEY import json from django.views.decorators.csrf import csrf_exempt from django.shortcuts import get_object_or_404
[ 11748, 7007, 198, 11748, 42625, 14208, 13, 3642, 822, 13, 18439, 355, 6284, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 18941, 11, 651, 62, 15252, 62, 273, 62, 26429, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, ...
3.317881
151
from __future__ import absolute_import __author__ = 'kaizhuang' """ Package implementing features for simulating bioreactor operation. """ from .base import Organism, Bioreactor from .bioreactors import ANAEROBIC, AEROBIC, MICROAEROBIC from .bioreactors import Bioreactor_ox, IdealBatch, IdealFedbatch from framed.bioreactor.dfba import *
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 834, 9800, 834, 796, 705, 4914, 528, 13415, 648, 6, 198, 37811, 198, 27813, 15427, 3033, 329, 985, 8306, 3182, 382, 11218, 4905, 13, 198, 37811, 198, 198, 6738, 764, 8692, 1330, 722...
3.196262
107
from ssg.utils import parse_template_boolean_value
[ 6738, 37786, 70, 13, 26791, 1330, 21136, 62, 28243, 62, 2127, 21052, 62, 8367, 628 ]
3.466667
15
# -*- coding: UTF-8 -*- """ This file is part of Pondus, a personal weight manager. Copyright (C) 2011 Eike Nicklas <eike@ephys.de> This program is free software licensed under the MIT license. For details see LICENSE or http://www.opensource.org/licenses/mit-license.php """ __all__ = ['csv_backend', 'sportstracker_backend', 'xml_backend', 'xml_backend_old']
[ 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 1212, 2393, 318, 636, 286, 41598, 385, 11, 257, 2614, 3463, 4706, 13, 198, 15269, 357, 34, 8, 2813, 220, 412, 522, 8047, 21921, 1279, 68, 522, 31, 27446,...
2.772059
136
import pathlib from setuptools import find_packages, setup # The directory containing this file HERE = pathlib.Path(__file__).parent # The text of the README file README = (HERE / "README.md").read_text() # This call to setup() does all the work setup( name="chpy", version="0.1.1", description="Build networks from the Companies House API", long_description=README, long_description_content_type="text/markdown", url="https://github.com/specialprocedures/chpy", author="Ian Goodrich", # author_email="office@realpython.com", license="MIT", classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", ], packages=find_packages(exclude=["collections", "time", "math", "re", "os"]), include_package_data=True, # install_requires=["networkx", "pandas", "progressbar", "fuzzywuzzy", # "os", "requests", "math", "time", "collections", "re"] )
[ 11748, 3108, 8019, 201, 198, 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 201, 198, 201, 198, 2, 383, 8619, 7268, 428, 2393, 201, 198, 39, 9338, 796, 3108, 8019, 13, 15235, 7, 834, 7753, 834, 737, 8000, 201, 198, 201, ...
2.537349
415
from __future__ import absolute_import import six from sentry.utils.safe import get_path, trim from sentry.utils.strings import truncatechars from .base import BaseEvent
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 2237, 198, 198, 6738, 1908, 563, 13, 26791, 13, 21230, 1330, 651, 62, 6978, 11, 15797, 198, 6738, 1908, 563, 13, 26791, 13, 37336, 1330, 40122, 40340, 945, 198, 198, 673...
3.571429
49
from unittest import TestCase from datetime import date from keras_en_parser_and_analyzer.library.pipmp_my_cv_classify import detect_date
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 4818, 8079, 1330, 3128, 198, 6738, 41927, 292, 62, 268, 62, 48610, 62, 392, 62, 38200, 9107, 13, 32016, 13, 79, 541, 3149, 62, 1820, 62, 33967, 62, 4871, 1958, 1330, 4886, 62, 4475,...
3.111111
45
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Ipset iptables generator. This is a subclass of Iptables generator. ipset is a system inside the Linux kernel, which can very efficiently store and match IPv4 and IPv6 addresses. This can be used to dramatically increase performace of iptables firewall. """ import string from capirca.lib import iptables from capirca.lib import nacaddr
[ 2, 15069, 1853, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.768924
251
import warnings import numba import numpy as np import strax import straxen DEFAULT_MAX_SAMPLES = 20_000
[ 11748, 14601, 198, 198, 11748, 997, 7012, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 3534, 87, 198, 11748, 3534, 87, 268, 198, 198, 7206, 38865, 62, 22921, 62, 49302, 6489, 1546, 796, 1160, 62, 830, 628, 628 ]
2.846154
39
from collections import namedtuple from cryptoconditions import crypto CryptoKeypair = namedtuple('CryptoKeypair', ('signing_key', 'verifying_key')) def generate_keypair(): """Generates a cryptographic key pair. Returns: :class:`~bigchaindb_driver.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with named fields :attr:`~bigchaindb_driver.crypto.CryptoKeypair.signing_key` and :attr:`~bigchaindb_driver.crypto.CryptoKeypair.verifying_key`. """ return CryptoKeypair( *(k.decode() for k in crypto.ed25519_generate_key_pair()))
[ 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 6738, 15149, 623, 1756, 1330, 21473, 628, 198, 23919, 78, 9218, 24874, 796, 3706, 83, 29291, 10786, 23919, 78, 9218, 24874, 3256, 19203, 12683, 278, 62, 2539, 3256, 705, 332, 4035, 62, 2539,...
2.568966
232
from __future__ import unicode_literals from django.utils import six from djblets.util.decorators import augment_method_from from reviewboard.changedescs.models import ChangeDescription from reviewboard.reviews.fields import get_review_request_field from reviewboard.webapi.base import WebAPIResource from reviewboard.webapi.decorators import webapi_check_local_site from reviewboard.webapi.mixins import MarkdownFieldsMixin from reviewboard.webapi.resources import resources change_resource = ChangeResource()
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 26791, 1330, 2237, 198, 6738, 42625, 903, 912, 13, 22602, 13, 12501, 273, 2024, 1330, 35016, 62, 24396, 62, 6738, 198, 198, 6738, 2423, 3526, ...
3.659574
141
# Dependencies from aurora import Controller, View, Forms from models import Users, Notes from aurora.security import login_required, get_session from flask import request from datetime import datetime # The controller class
[ 2, 37947, 3976, 198, 6738, 45714, 5799, 1330, 22741, 11, 3582, 11, 39196, 198, 6738, 4981, 1330, 18987, 11, 11822, 198, 6738, 45714, 5799, 13, 12961, 1330, 17594, 62, 35827, 11, 651, 62, 29891, 198, 6738, 42903, 1330, 2581, 198, 6738, ...
4.283019
53
# -------------- #Importing header files import pandas as pd import matplotlib.pyplot as plt import seaborn as sns #Code starts here data = pd.read_csv(path) data['Rating'].hist() data = data[data['Rating']<=5] data['Rating'].hist() #Code ends here # -------------- # code starts here total_null = data.isnull().sum() percent_null = (total_null/data.isnull().count())*100 missing_data = pd.concat([total_null,percent_null],axis=1,keys=['Total','Percentage']) print(missing_data) data = data.dropna() total_null_1 = data.isnull().sum() percent_null_1 = (total_null_1/data.isnull().count())*100 missing_data_1 = pd.concat([total_null_1,percent_null_1],axis=1,keys=['Total','Percentage']) print(missing_data_1) # code ends here # -------------- #Code starts here a = sns.catplot(x='Category',y='Rating',data=data, kind="box", height = 10) a.set_xticklabels(rotation=90) a.set_titles('Rating vs Category [BoxPlot]') #Code ends here # -------------- #Importing header files from sklearn.preprocessing import MinMaxScaler, LabelEncoder #Code starts here le = LabelEncoder() #data['Installs'] = data['Installs'].str.replace(',','').str.replace('+','') data['Installs'] = data['Installs'].apply(lambda x : x.replace(',','')).apply(lambda x : x.replace('+','')) data['Installs'] =data['Installs'].astype(int) print(data['Installs']) data['Installs'] = le.fit_transform(data['Installs']) a = sns.regplot(x="Installs", y="Rating" , data=data) a.set_title('Rating vs Installs [RegPlot]') #Code ends here # -------------- #Code starts here from sklearn.preprocessing import MinMaxScaler, LabelEncoder import seaborn as sns #Code starts here d=data['Price'].value_counts() print(d) data['Price']=data['Price'].apply(lambda x : x.replace('$','')) d=data['Price'].value_counts() print(d) data['Price']=data['Price'].astype(float) #le=LabelEncoder() #data['Installs'] = le.fit_transform(data['Installs']) y=sns.regplot(data=data,x='Price',y='Rating') y.set_title('Rating vs Installs [RegPlot]') #Code ends here # -------------- #Code starts here data['Genres']=data['Genres'].str.split(';').str[0] #print(data['Genres']) df=data[['Genres','Rating']] gr_mean=df.groupby(['Genres'],as_index=False).mean() gr_mean=gr_mean.sort_values(by=['Rating']) gr_mean=pd.DataFrame(gr_mean) print(gr_mean)#,gr_mean[-1,:]) #Code ends heree # -------------- #Code starts here import seaborn as sns data['Last Updated'] = pd.to_datetime(data['Last Updated']) print(data['Last Updated'].max()) max_date=data['Last Updated'].max() data['Last Updated Days']=max_date-data['Last Updated'] data['Last Updated Days']=data['Last Updated Days'].dt.days sns.regplot(data=data,x='Last Updated Days',y='Rating').set_title('Rating vs Last Updated [RegPlot]') #Code ends here
[ 2, 220, 26171, 198, 2, 20939, 278, 13639, 3696, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 384, 397, 1211, 355, 3013, 82, 628, 198, 2, 10669, 4940, 994, 198, 7890,...
2.731949
1,011
import numpy as np from openpnm.algorithms import ReactiveTransport from openpnm.models.physics import generic_source_term as gst from openpnm.utils import logging logger = logging.getLogger(__name__)
[ 11748, 299, 32152, 355, 45941, 198, 6738, 1280, 79, 21533, 13, 282, 7727, 907, 1330, 797, 5275, 8291, 634, 198, 6738, 1280, 79, 21533, 13, 27530, 13, 746, 23154, 1330, 14276, 62, 10459, 62, 4354, 355, 308, 301, 198, 6738, 1280, 79, ...
3.258065
62
from jno.util import interpret_configs from jno.util import run_arduino_process from jno.util import create_build_directory from jno.util import get_common_parameters from jno.util import verify_arduino_dir from jno.util import verify_and_get_port from jno.util import JnoException from jno.commands.command import Command import getopt from colorama import Fore
[ 6738, 474, 3919, 13, 22602, 1330, 6179, 62, 11250, 82, 198, 6738, 474, 3919, 13, 22602, 1330, 1057, 62, 446, 84, 2879, 62, 14681, 198, 6738, 474, 3919, 13, 22602, 1330, 2251, 62, 11249, 62, 34945, 198, 6738, 474, 3919, 13, 22602, 13...
3.309091
110
import argparse import json import logging import os import torch from transformers.file_utils import ModelOutput from typing import Dict, Optional, Tuple from torch.utils.data import DataLoader, SequentialSampler from transformers.modeling_outputs import Seq2SeqLMOutput import train_seq2seq_utils import single_head_utils import multi_head_utils from torch import nn from generation_utils_multi_attribute import GenerationMixinCustomCombined from transformers import ( PreTrainedModel, PreTrainedTokenizer, BartConfig, BartTokenizer ) logger = logging.getLogger(__name__) MODEL_CLASSES = {"bart_mult_heads_2": (BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads, BartTokenizer), } def load_model(path): args = json.load(open(path)) config_class, model_class = BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads config = config_class.from_pretrained(args['path']) model = model_class.from_pretrained( args['path'], from_tf=bool(".ckpt" in args['path']), config=config) return model, args, config def evaluate(args, eval_dataset, model: PreTrainedModel, args1, args2, tokenizer: PreTrainedTokenizer, suffix="") -> Dict: eval_output_dir = args.output_dir if not os.path.exists(eval_output_dir): os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size) # Eval! logger.info("***** Running evaluation *****") logger.info(" Num examples = %d", len(eval_dataset)) logger.info(" Batch size = %d", args.eval_batch_size) if args.generate: f_out = open(os.path.join(eval_output_dir, 'test_out%s.txt' % suffix), 'w') print(eval_output_dir) k = 0 with torch.no_grad(): model.eval() for batch in eval_dataloader: batch = tuple(t.to(args.device) for t in batch) input_ids, input_attention_mask, decoder_ids = batch[0], batch[1], batch[2] for j in range(input_ids.shape[0]): gold = tokenizer.decode(decoder_ids[j], skip_special_tokens=True) input = tokenizer.decode(input_ids[j], skip_special_tokens=True) input_args = {'input_ids': input_ids[j].unsqueeze(0), 'attention_mask': input_attention_mask[j].unsqueeze(0), 'num_beams': 6, 'length_penalty': 2, 'no_repeat_ngram_size': 3, 'max_length': 200, 'min_length': 12, 'top_k': 30, 'top_p': 0.5, 'do_sample': True, 'decoder_start_token_id': tokenizer.bos_token_id, 'num_return_sequences': 1, 'gate_prob': args.gate_probability, 'use_head_1': args1['use_head'], 'use_head_2': args2['use_head']} gen = model.generate(**input_args) gen = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True) for g in gen] # gen = gen[0] print(gen[0].strip()) f_out.write(input + '\n') f_out.write(gold + '\n') for g in gen: f_out.write(g.strip() + '\n') f_out.write('\n') k += 1 if k > 1000: break f_out.close() if __name__ == "__main__": main()
[ 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 28034, 198, 6738, 6121, 364, 13, 7753, 62, 26791, 1330, 9104, 26410, 198, 6738, 19720, 1330, 360, 713, 11, 32233, 11, 309, 29291, 198, 6738, 28034, ...
2.014301
1,888
import logging
[ 11748, 18931, 628, 628, 198 ]
3.8
5
# you just need to add some informations here
[ 2, 345, 655, 761, 284, 751, 617, 4175, 602, 994, 201, 198 ]
3.916667
12
from .IFileConverter import IFileConverter
[ 6738, 764, 5064, 576, 3103, 332, 353, 1330, 314, 8979, 3103, 332, 353, 198 ]
3.071429
14
from functools import wraps from agave.blueprints.decorators import copy_attributes
[ 6738, 1257, 310, 10141, 1330, 27521, 198, 198, 6738, 556, 1015, 13, 17585, 17190, 13, 12501, 273, 2024, 1330, 4866, 62, 1078, 7657, 628, 628 ]
3.52
25
# Copyright 2019 The MACE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import re import os import copy import yaml from enum import Enum from utils.util import mace_check from utils.util import MaceLogger from py_proto import mace_pb2 CPP_KEYWORDS = [ 'alignas', 'alignof', 'and', 'and_eq', 'asm', 'atomic_cancel', 'atomic_commit', 'atomic_noexcept', 'auto', 'bitand', 'bitor', 'bool', 'break', 'case', 'catch', 'char', 'char16_t', 'char32_t', 'class', 'compl', 'concept', 'const', 'constexpr', 'const_cast', 'continue', 'co_await', 'co_return', 'co_yield', 'decltype', 'default', 'delete', 'do', 'double', 'dynamic_cast', 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float', 'for', 'friend', 'goto', 'if', 'import', 'inline', 'int', 'long', 'module', 'mutable', 'namespace', 'new', 'noexcept', 'not', 'not_eq', 'nullptr', 'operator', 'or', 'or_eq', 'private', 'protected', 'public', 'register', 'reinterpret_cast', 'requires', 'return', 'short', 'signed', 'sizeof', 'static', 'static_assert', 'static_cast', 'struct', 'switch', 'synchronized', 'template', 'this', 'thread_local', 'throw', 'true', 'try', 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', 'virtual', 'void', 'volatile', 'wchar_t', 'while', 'xor', 'xor_eq', 'override', 'final', 'transaction_safe', 'transaction_safe_dynamic', 'if', 'elif', 'else', 'endif', 'defined', 'ifdef', 'ifndef', 'define', 'undef', 'include', 'line', 'error', 'pragma', ] def parse_data_format(str): str = str.upper() mace_check(str in [e.name for e in DataFormat], "unknown data format %s" % str) return DataFormat[str] DEVICE_MAP = { "cpu": DeviceType.CPU, "gpu": DeviceType.GPU, "hexagon": DeviceType.HEXAGON, "dsp": DeviceType.HEXAGON, "hta": DeviceType.HTA, "apu": DeviceType.APU, "cpu+gpu": DeviceType.CPU_GPU } DATA_TYPE_MAP = { 'float32': mace_pb2.DT_FLOAT, 'int32': mace_pb2.DT_INT32, }
[ 2, 15069, 13130, 383, 337, 11598, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
2.694332
988
# -*- coding: utf-8 -*- # Copyright 2019 Pierre-Luc Delisle. All Rights Reserved. # # Licensed under the MIT License; # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/MIT # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import logging import multiprocessing import numpy as np import os import random import torch import torch.backends.cudnn as cudnn from kerosene.configs.configs import RunConfiguration, DatasetConfiguration from kerosene.configs.parsers import YamlConfigurationParser from kerosene.loggers.visdom import PlotType, PlotFrequency from kerosene.loggers.visdom.config import VisdomConfiguration from kerosene.loggers.visdom.visdom import VisdomLogger, VisdomData from kerosene.training.trainers import ModelTrainerFactory from samitorch.inputs.utils import augmented_sample_collate from torch.utils.data import DataLoader from torch.utils.data.dataloader import DataLoader from deepNormalize.config.parsers import ArgsParserFactory, ArgsParserType from deepNormalize.factories.customModelFactory import CustomModelFactory from deepNormalize.factories.customTrainerFactory import TrainerFactory from deepNormalize.inputs.datasets import iSEGSliceDatasetFactory, MRBrainSSliceDatasetFactory, ABIDESliceDatasetFactory from deepNormalize.nn.criterions import CustomCriterionFactory from deepNormalize.utils.constants import * from deepNormalize.utils.image_slicer import ImageReconstructor cudnn.benchmark = True cudnn.enabled = True np.random.seed(42) random.seed(42) if __name__ == '__main__': # Basic settings logging.basicConfig(level=logging.INFO) torch.set_num_threads(multiprocessing.cpu_count()) torch.set_num_interop_threads(multiprocessing.cpu_count()) args = ArgsParserFactory.create_parser(ArgsParserType.MODEL_TRAINING).parse_args() # Create configurations. run_config = RunConfiguration(use_amp=args.use_amp, local_rank=args.local_rank, amp_opt_level=args.amp_opt_level) model_trainer_configs, training_config = YamlConfigurationParser.parse(args.config_file) if not isinstance(model_trainer_configs, list): model_trainer_configs = [model_trainer_configs] dataset_configs = YamlConfigurationParser.parse_section(args.config_file, "dataset") dataset_configs = {k: DatasetConfiguration(v) for k, v, in dataset_configs.items()} data_augmentation_config = YamlConfigurationParser.parse_section(args.config_file, "data_augmentation") config_html = [training_config.to_html(), list(map(lambda config: config.to_html(), dataset_configs.values())), list(map(lambda config: config.to_html(), model_trainer_configs))] # Prepare the data. train_datasets = list() valid_datasets = list() test_datasets = list() reconstruction_datasets = list() iSEG_train = None iSEG_CSV = None MRBrainS_train = None MRBrainS_CSV = None ABIDE_train = None ABIDE_CSV = None iSEG_augmentation_strategy = None MRBrainS_augmentation_strategy = None ABIDE_augmentation_strategy = None # Initialize the model trainers model_trainer_factory = ModelTrainerFactory(model_factory=CustomModelFactory(), criterion_factory=CustomCriterionFactory()) model_trainers = model_trainer_factory.create(model_trainer_configs) if not isinstance(model_trainers, list): model_trainers = [model_trainers] # Create datasets if dataset_configs.get("iSEG", None) is not None: iSEG_train, iSEG_valid, iSEG_test, iSEG_reconstruction = iSEGSliceDatasetFactory.create_train_valid_test( source_dir=dataset_configs["iSEG"].path, modalities=dataset_configs["iSEG"].modalities, dataset_id=ISEG_ID, test_size=dataset_configs["iSEG"].validation_split, max_subjects=dataset_configs["iSEG"].max_subjects, max_num_patches=dataset_configs["iSEG"].max_num_patches, augment=dataset_configs["iSEG"].augment, patch_size=dataset_configs["iSEG"].patch_size, step=dataset_configs["iSEG"].step, test_patch_size=dataset_configs["iSEG"].test_patch_size, test_step=dataset_configs["iSEG"].test_step, data_augmentation_config=data_augmentation_config) train_datasets.append(iSEG_train) valid_datasets.append(iSEG_valid) reconstruction_datasets.append(iSEG_reconstruction) if dataset_configs.get("MRBrainS", None) is not None: MRBrainS_train, MRBrainS_valid, MRBrainS_test, MRBrainS_reconstruction = MRBrainSSliceDatasetFactory.create_train_valid_test( source_dir=dataset_configs["MRBrainS"].path, modalities=dataset_configs["MRBrainS"].modalities, dataset_id=MRBRAINS_ID, test_size=dataset_configs["MRBrainS"].validation_split, max_subjects=dataset_configs["MRBrainS"].max_subjects, max_num_patches=dataset_configs["MRBrainS"].max_num_patches, augment=dataset_configs["MRBrainS"].augment, patch_size=dataset_configs["MRBrainS"].patch_size, step=dataset_configs["MRBrainS"].step, test_patch_size=dataset_configs["MRBrainS"].test_patch_size, test_step=dataset_configs["MRBrainS"].test_step, data_augmentation_config=data_augmentation_config) test_datasets.append(MRBrainS_test) reconstruction_datasets.append(MRBrainS_reconstruction) if dataset_configs.get("ABIDE", None) is not None: ABIDE_train, ABIDE_valid, ABIDE_test, ABIDE_reconstruction = ABIDESliceDatasetFactory.create_train_valid_test( source_dir=dataset_configs["ABIDE"].path, modalities=dataset_configs["ABIDE"].modalities, dataset_id=ABIDE_ID, sites=dataset_configs["ABIDE"].sites, max_subjects=dataset_configs["ABIDE"].max_subjects, test_size=dataset_configs["ABIDE"].validation_split, max_num_patches=dataset_configs["ABIDE"].max_num_patches, augment=dataset_configs["ABIDE"].augment, patch_size=dataset_configs["ABIDE"].patch_size, step=dataset_configs["ABIDE"].step, test_patch_size=dataset_configs["ABIDE"].test_patch_size, test_step=dataset_configs["ABIDE"].test_step, data_augmentation_config=data_augmentation_config) train_datasets.append(ABIDE_train) valid_datasets.append(ABIDE_valid) test_datasets.append(ABIDE_test) reconstruction_datasets.append(ABIDE_reconstruction) if len(list(dataset_configs.keys())) == 2: segmentation_reconstructor = ImageReconstructor( [iSEG_reconstruction._source_images[0], MRBrainS_reconstruction._source_images[0]], patch_size=dataset_configs["iSEG"].test_patch_size, reconstructed_image_size=(1, 256, 256, 192), step=dataset_configs["iSEG"].test_step, models=[model_trainers[0]], segment=True, batch_size=8) input_reconstructor = ImageReconstructor( [iSEG_reconstruction._source_images[0], MRBrainS_reconstruction._source_images[0]], patch_size=dataset_configs["iSEG"].test_patch_size, reconstructed_image_size=(1, 256, 256, 192), step=dataset_configs["iSEG"].test_step, batch_size=50) gt_reconstructor = ImageReconstructor( [iSEG_reconstruction._target_images[0], MRBrainS_reconstruction._target_images[0]], patch_size=dataset_configs["iSEG"].test_patch_size, reconstructed_image_size=(1, 256, 256, 192), step=dataset_configs["iSEG"].test_step, is_ground_truth=True, batch_size=50) if dataset_configs["iSEG"].augment: augmented_input_reconstructor = ImageReconstructor( [iSEG_reconstruction._source_images[0], MRBrainS_reconstruction._source_images[0]], patch_size=dataset_configs["iSEG"].test_patch_size, reconstructed_image_size=(1, 256, 256, 192), step=dataset_configs["iSEG"].test_step, batch_size=50, alpha=data_augmentation_config["test"]["bias_field"]["alpha"][0], prob_bias=data_augmentation_config["test"]["bias_field"]["prob_bias"], snr=data_augmentation_config["test"]["noise"]["snr"], prob_noise=data_augmentation_config["test"]["noise"]["prob_noise"]) else: augmented_input_reconstructor = None augmented_normalized_input_reconstructor = None else: segmentation_reconstructor = ImageReconstructor( [iSEG_reconstruction._source_images[0], MRBrainS_reconstruction._source_images[0], ABIDE_reconstruction._source_images[0]], patch_size=(1, 32, 32, 32), reconstructed_image_size=(1, 256, 256, 192), step=dataset_configs["iSEG"].test_step, models=[model_trainers[0]], normalize_and_segment=True, batch_size=4) input_reconstructor = ImageReconstructor( [iSEG_reconstruction._source_images[0], MRBrainS_reconstruction._source_images[0], ABIDE_reconstruction._source_images[0]], patch_size=(1, 32, 32, 32), reconstructed_image_size=(1, 256, 256, 192), step=dataset_configs["iSEG"].test_step, batch_size=50) gt_reconstructor = ImageReconstructor( [iSEG_reconstruction._target_images[0], MRBrainS_reconstruction._target_images[0], ABIDE_reconstruction._target_images[0]], patch_size=(1, 32, 32, 32), reconstructed_image_size=(1, 256, 256, 192), step=dataset_configs["iSEG"].test_step, batch_size=50, is_ground_truth=True) if dataset_configs["iSEG"].augment: augmented_input_reconstructor = ImageReconstructor( [iSEG_reconstruction._source_images[0], MRBrainS_reconstruction._source_images[0], ABIDE_reconstruction._source_images[0]], patch_size=(1, 32, 32, 32), reconstructed_image_size=(1, 256, 256, 192), step=dataset_configs["iSEG"].test_step, batch_size=50, alpha=data_augmentation_config["test"]["bias_field"]["alpha"][0], prob_bias=data_augmentation_config["test"]["bias_field"]["prob_bias"], snr=data_augmentation_config["test"]["noise"]["snr"], prob_noise=data_augmentation_config["test"]["noise"]["prob_noise"]) else: augmented_input_reconstructor = None augmented_normalized_input_reconstructor = None # Concat datasets. if len(dataset_configs) > 1: train_dataset = torch.utils.data.ConcatDataset(train_datasets) valid_dataset = torch.utils.data.ConcatDataset(valid_datasets) test_dataset = torch.utils.data.ConcatDataset(test_datasets) else: train_dataset = train_datasets[0] valid_dataset = valid_datasets[0] test_dataset = test_datasets[0] # Create loaders. dataloaders = list(map(lambda dataset: DataLoader(dataset, training_config.batch_size, sampler=None, shuffle=True, num_workers=args.num_workers, collate_fn=augmented_sample_collate, drop_last=True, pin_memory=True), [train_dataset, valid_dataset, test_dataset])) # Initialize the loggers. visdom_config = VisdomConfiguration.from_yml(args.config_file, "visdom") exp = args.config_file.split("/")[-3:] if visdom_config.save_destination is not None: save_folder = visdom_config.save_destination + os.path.join(exp[0], exp[1], os.path.basename( os.path.normpath(visdom_config.env))) else: save_folder = "saves/{}".format(os.path.basename(os.path.normpath(visdom_config.env))) [os.makedirs("{}/{}".format(save_folder, model), exist_ok=True) for model in ["Discriminator", "Generator", "Segmenter"]] visdom_logger = VisdomLogger(visdom_config) visdom_logger(VisdomData("Experiment", "Experiment Config", PlotType.TEXT_PLOT, PlotFrequency.EVERY_EPOCH, None, config_html)) visdom_logger(VisdomData("Experiment", "Patch count", PlotType.BAR_PLOT, PlotFrequency.EVERY_EPOCH, x=[len(iSEG_train) if iSEG_train is not None else 0, len(MRBrainS_train) if MRBrainS_train is not None else 0, len(ABIDE_train) if ABIDE_train is not None else 0], y=["iSEG", "MRBrainS", "ABIDE"], params={"opts": {"title": "Patch count"}})) trainer = TrainerFactory(training_config.trainer).create(training_config, model_trainers, dataloaders, reconstruction_datasets, None, input_reconstructor, segmentation_reconstructor, augmented_input_reconstructor, None, gt_reconstructor, run_config, dataset_configs, save_folder, visdom_logger) trainer.train(training_config.nb_epochs)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 13130, 21204, 12, 22946, 4216, 20919, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 17168, 13789, 26, 198, 2, 345, 743, 407, 779, 428, 2393, ...
2.03955
7,282
#!/usr/bin/env python # -*- coding: utf-8 -*- # ClientOpenCV # Server: Jetson TX2 # Client: Jetson TX2/Raspberry Pi3 Docker # 1. FFMPEG UDP StreamingClientAWS10FPS,Jetson TX21FPS # 2. Server # 3. Client # # lib/camera.py: vid = cv2.VideoCapture() # lib/object_detection.py: /home/ubuntu/notebooks/github/SSD-Tensorflow/ ''' Python 3.6 message.encode('ascii').encode('utf-8') ClientOpenCV BGR'ascii''ascii' ''' print("wait. launching...") import socket, select import time import cv2 import numpy as np import time import os import sys import logging import threading import numpy as np from lib.functions import * from lib.object_detection import ObjectDetection from lib.opencv_lane_detection import LaneDetection from lib.webcam import WebcamVideoStream # logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] time:%(created).8f pid:%(process)d pn:%(processName)-10s tid:%(thread)d tn:%(threadName)-10s fn:%(funcName)-10s %(message)s', ) # is_analyze_running = False sock = None out = None # IPMx,y() X_METER=1.5 Y_METER=1 # ld = None # od = None if __name__ == '__main__': main() print("end server")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 20985, 11505, 33538, 198, 2, 9652, 25, 14728, 261, 15326, 17, 198, 2, 20985, 25, 14728, 261, 15326, 17, 14, 49, ...
2.458774
473
from collections import defaultdict import json import re import redis import threading import time import traceback import uuid import base64 import binascii TTL = 2 hash_keys = ('cmd', 'user') cmd_hash_keys = { 'comment': ('addr',), 'extra_comment': ('addr',), 'area_comment': ('addr',), 'rename': ('addr',), 'stackvar_renamed': ('addr', 'offset', 'name',), 'struc_created': ('struc_name', 'is_union',), 'struc_deleted': ('struc_name',), 'struc_renamed': ('old_name', 'new_name',), 'struc_member_created': ('struc_name', 'offset', 'member_name', 'size', 'flag',), 'struc_member_deleted': ('struc_name', 'offset',), 'struc_member_renamed': ('struc_name', 'offset', 'member_name',), 'struc_member_changed': ('struc_name', 'offset', 'size',), } key_dec = { 'c': 'cmd', 'a': 'addr', 'u': 'user', 't': 'text', 'i': 'uuid', 'b': 'blocks' } key_enc = dict((v, k) for k, v in key_dec.items()) nick_filter = re.compile(r'[^a-zA-Z0-9_\-]')
[ 6738, 17268, 1330, 4277, 11600, 198, 11748, 33918, 198, 11748, 302, 198, 11748, 2266, 271, 198, 11748, 4704, 278, 198, 11748, 640, 198, 11748, 12854, 1891, 198, 11748, 334, 27112, 198, 11748, 2779, 2414, 198, 11748, 9874, 292, 979, 72, ...
2.350467
428
# -*- coding: utf-8 -*- """URLs to manipulate columns.""" from django.urls import path from ontask.condition import views app_name = 'condition' urlpatterns = [ # # FILTERS # path( '<int:pk>/create_filter/', views.FilterCreateView.as_view(), name='create_filter'), path('<int:pk>/edit_filter/', views.edit_filter, name='edit_filter'), path('<int:pk>/delete_filter/', views.delete_filter, name='delete_filter'), # # CONDITIONS # path( '<int:pk>/create_condition/', views.ConditionCreateView.as_view(), name='create_condition'), path( '<int:pk>/edit_condition/', views.edit_condition, name='edit_condition'), path( '<int:pk>/delete_condition/', views.delete_condition, name='delete_condition'), # Clone the condition path( '<int:pk>/clone_condition/', views.clone_condition, name='clone_condition'), path( '<int:pk>/<int:action_pk>/clone_condition/', views.clone_condition, name='clone_condition'), ]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 21886, 82, 284, 18510, 15180, 526, 15931, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 198, 6738, 319, 35943, 13, 31448, 1330, 5009, 198, 198, 132...
2.170254
511
"""Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Defines the architecture of the Video Classifier. """ import math import tensorflow as tf
[ 37811, 15269, 12131, 3012, 11419, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 1639, 743, 7330, ...
3.993789
161
""" Collection of Jax math functions, wrapped to fit Ivy syntax and signature. """ # global import jax as _jax import jax.numpy as _jnp tan = _jnp.tan acos = _jnp.arccos atan = _jnp.arctan atan2 = _jnp.arctan2 cosh = _jnp.cosh atanh = _jnp.arctanh log = _jnp.log exp = _jnp.exp erf = _jax.scipy.special.erf
[ 37811, 198, 36307, 286, 449, 897, 10688, 5499, 11, 12908, 284, 4197, 27386, 15582, 290, 9877, 13, 198, 37811, 198, 198, 2, 3298, 198, 11748, 474, 897, 355, 4808, 73, 897, 198, 11748, 474, 897, 13, 77, 32152, 355, 4808, 73, 37659, 62...
2.230216
139
from pymongo import MongoClient from pyltp import Segmentor if __name__ == '__main__': # insert_questions_from_answered_question() # insert_questions_from_followed_question() # insert_questions_from_asked_question() # insert_questions_from_collected_question() #delete_noise_question() #remove_enger_inline() # insert_user_list() insert_user_follow_user_list() # insert_user_follow_question_list() # insert_user_ask_question_list() # insert_user_collect_question_list() # insert_user_answer_question_list()
[ 6738, 279, 4948, 25162, 1330, 42591, 11792, 198, 6738, 12972, 2528, 79, 1330, 1001, 5154, 273, 628, 628, 628, 628, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1303, 7550, 62, 6138,...
2.709524
210
import sys import unittest import os import tempfile from netCDF4 import Dataset import numpy as np from numpy.testing import assert_array_equal FILE_NAME = tempfile.NamedTemporaryFile(suffix='.nc', delete=False).name VL_NAME = 'vlen_type' VL_BASETYPE = np.int16 DIM1_NAME = 'lon' DIM2_NAME = 'lat' nlons = 5; nlats = 5 VAR1_NAME = 'ragged' VAR2_NAME = 'strings' VAR3_NAME = 'strings_alt' VAR4_NAME = 'string_scalar' VAR5_NAME = 'vlen_scalar' data = np.empty(nlats*nlons,object) datas = np.empty(nlats*nlons,object) nn = 0 for n in range(nlats*nlons): nn = nn + 1 data[n] = np.arange(nn,dtype=VL_BASETYPE) datas[n] = ''.join([chr(i) for i in range(97,97+nn+1)]) data = np.reshape(data,(nlats,nlons)) datas = np.reshape(datas,(nlats,nlons)) if __name__ == '__main__': unittest.main()
[ 11748, 25064, 198, 11748, 555, 715, 395, 198, 11748, 28686, 198, 11748, 20218, 7753, 198, 6738, 2010, 34, 8068, 19, 1330, 16092, 292, 316, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 299, 32152, 13, 33407, 1330, 6818, 62, 18747, 62, ...
2.218232
362
# Copyright 2019 The Sonnet Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Utility to run functions and methods once.""" import uuid from sonnet.src import utils _ONCE_PROPERTY = "_snt_once" def once(f): """Decorator which ensures a wrapped method is only ever run once. >>> @snt.once ... def f(): ... print('Hello, world!') >>> f() Hello, world! >>> f() >>> f() If `f` is a method then it will be evaluated once per instance: >>> class MyObject: ... @snt.once ... def f(self): ... print('Hello, world!') >>> o = MyObject() >>> o.f() Hello, world! >>> o.f() >>> o2 = MyObject() >>> o2.f() Hello, world! >>> o.f() >>> o2.f() If an error is raised during execution of `f` it will be raised to the user. Next time the method is run, it will be treated as not having run before. Args: f: A function to wrap which should only be called once. Returns: Wrapped version of `f` which will only evaluate `f` the first time it is called. """ # TODO(tomhennigan) Perhaps some more human friendly identifier? once_id = uuid.uuid4() wrapper.seen_none = False decorated = wrapper(f) # pylint: disable=no-value-for-parameter,assignment-from-none decorated.__snt_once_wrapped__ = f return decorated
[ 2, 15069, 13130, 383, 6295, 3262, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
2.962575
668
import piarm import time import numpy as np import cv2 import random
[ 11748, 31028, 1670, 198, 11748, 640, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 4738, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220 ]
2.454545
33
# Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Test of the GRPC-backed ForeLink and RearLink.""" import threading import unittest from grpc._adapter import _proto_scenarios from grpc._adapter import _test_links from grpc._adapter import fore from grpc._adapter import rear from grpc.framework.base import interfaces from grpc.framework.base.packets import packets as tickets from grpc.framework.foundation import logging_pool _IDENTITY = lambda x: x _TIMEOUT = 2 if __name__ == '__main__': unittest.main()
[ 2, 15069, 1853, 11, 3012, 3457, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2297, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 351, 393, 1231, 198, 2, 17613, 11, 389, 10431, 2810, 326, 262, 1708, 3403, 389, 198, ...
3.494755
572
import os, glob import subprocess from subprocess import DEVNULL, STDOUT abspath = os.path.abspath(__file__) dir_ = os.path.dirname(abspath) files = glob.glob(dir_ + "/_progress_board_tests/_test_progress_board_*.py") for file_path in files: file_name = str(file_path.rsplit("/", maxsplit=1)[1]) try: print("\033[0;33;40m Testing", file_name, end="...\r") subprocess.check_call(["pytest", file_path], stdout=DEVNULL, stderr=STDOUT) except subprocess.CalledProcessError: print("\033[0;31;40m Error in", file_name) else: print("\033[0;32;40m", file_name, "is correct")
[ 11748, 28686, 11, 15095, 198, 11748, 850, 14681, 198, 6738, 850, 14681, 1330, 5550, 53, 33991, 11, 48571, 12425, 628, 198, 397, 2777, 776, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 8, 198, 15908, 62, 796, 28686, 1...
2.357414
263
import csv import datetime from collections import defaultdict from django.contrib import messages from django.http.response import FileResponse from django.shortcuts import redirect, render from django.utils import timezone from django.views.decorators.http import require_GET, require_http_methods, require_POST from authentication.admin_authentication import (authenticate_admin, authenticate_researcher_study_access, forest_enabled) from constants.data_access_api_constants import CHUNK_FIELDS from constants.forest_constants import ForestTaskStatus, ForestTree from database.data_access_models import ChunkRegistry from database.study_models import Study from database.tableau_api_models import ForestTask from database.user_models import Participant from forms.django_forms import CreateTasksForm from libs.http_utils import easy_url from libs.internal_types import ParticipantQuerySet, ResearcherRequest from libs.streaming_zip import zip_generator from libs.utils.date_utils import daterange from middleware.abort_middleware import abort from serializers.forest_serializers import ForestTaskCsvSerializer, ForestTaskSerializer def stream_forest_task_log_csv(forest_tasks): buffer = CSVBuffer() writer = csv.DictWriter(buffer, fieldnames=ForestTaskCsvSerializer.Meta.fields) writer.writeheader() yield buffer.read() for forest_task in forest_tasks: writer.writerow(ForestTaskCsvSerializer(forest_task).data) yield buffer.read()
[ 11748, 269, 21370, 198, 11748, 4818, 8079, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 6218, 198, 6738, 42625, 14208, 13, 4023, 13, 26209, 1330, 9220, 31077, 198, 6738, 42625, 14208, 13, 19509, ...
3.422018
436
from __future__ import division from .transformation import Transformation from pyparsing import (Literal, CaselessLiteral, Word, Combine, Group, Optional, ZeroOrMore, Forward, nums, alphas, oneOf) import math import re import operator __author__ = 'Paul McGuire' __version__ = '$Revision: 0.0 $' __date__ = '$Date: 2009-03-20 $' __source__ = '''http://pyparsing.wikispaces.com/file/view/fourFn.py http://pyparsing.wikispaces.com/message/view/home/15549426 ''' __note__ = ''' All I've done is rewrap Paul McGuire's fourFn.py as a class, so I can use it more easily in other places. '''
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 6738, 764, 7645, 1161, 1330, 49127, 198, 6738, 279, 4464, 945, 278, 1330, 357, 43, 270, 1691, 11, 11294, 5321, 43, 270, 1691, 11, 9678, 11, 29176, 11, 4912, 11, 32233, 11, 198, 220, 220...
2.684211
228
# # this manager stores directly into the db wit Database update from cloudmesh.mongo.DataBaseDecorator import DatabaseUpdate from cloudmesh.mongo.CmDatabase import CmDatabase from cloudmesh.common.console import Console from cloudmesh.storage.Provider import Provider import os from datetime import datetime
[ 2, 198, 2, 428, 4706, 7000, 3264, 656, 262, 20613, 20868, 24047, 4296, 198, 198, 6738, 6279, 76, 5069, 13, 76, 25162, 13, 6601, 14881, 10707, 273, 1352, 1330, 24047, 10260, 198, 6738, 6279, 76, 5069, 13, 76, 25162, 13, 34, 76, 38105...
3.8875
80
import json import logging from redash.query_runner import * from redash.utils import JSONEncoder logger = logging.getLogger(__name__) try: from influxdb import InfluxDBClusterClient enabled = True except ImportError: enabled = False register(InfluxDB)
[ 11748, 33918, 198, 11748, 18931, 198, 198, 6738, 2266, 1077, 13, 22766, 62, 16737, 1330, 1635, 198, 6738, 2266, 1077, 13, 26791, 1330, 19449, 27195, 12342, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, ...
3.067416
89