content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/usr/bin/env python3 """UrsaLeo LEDdebug board LED demo Turn the LED's on one at a time, then all off""" import time ON = 1 OFF = 0 DELAY = 0.5 # seconds try: from LEDdebug import LEDdebug except ImportError: try: import sys import os sys.path.append("..") sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'LEDdebug')) from LEDdebug import LEDdebug except ImportError: print('LEDdebug import failed') exit(0) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 52, 3808, 64, 3123, 78, 12365, 24442, 3096, 12365, 13605, 198, 220, 220, 6756, 262, 12365, 338, 319, 530, 379, 257, 640, 11, 788, 477, 572, 37811, 198, 198, 11748, 640, 19...
2.211765
255
#!/usr/bin/env python ################################################################################### ## ## Project: COVID -19 xDNN Classifier 2020 ## Version: 1.0.0 ## Module: Server ## Desription: The COVID -19 xDNN Classifier 2020 server. ## License: MIT ## Copyright: 2021, Asociacion De Investigacion En Inteligencia Artificial Para ## La Leucemia Peter Moss. ## Author: Nitin Mane ## Maintainer: Nitin Mane ## ## Modified: 2021-2-19 ## ################################################################################### ## ## 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 cv2 import json import jsonpickle import os import requests import time import numpy as np import tensorflow as tf from modules.AbstractServer import AbstractServer from flask import Flask, request, Response from io import BytesIO from PIL import Image from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.vgg16 import preprocess_input
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 29113, 29113, 14468, 21017, 198, 2235, 198, 2235, 4935, 25, 220, 220, 220, 7375, 11008, 532, 1129, 2124, 35, 6144, 5016, 7483, 12131, 198, 2235, 10628, 25, 220, 220, 220, 352, 13, 15, ...
3.867647
544
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 3.0.0.11832 on 2017-03-22. # 2017, SMART Health IT. import io import json import os import unittest from . import allergyintolerance from .fhirdate import FHIRDate
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 220, 2980, 515, 422, 376, 39, 4663, 513, 13, 15, 13, 15, 13, 16817, 2624, 319, 2177, 12, 3070, 12, 182...
2.536842
95
import time import random import requests from lxml import etree import pymongo from .url_file import mjx_weibo, mjx_dy, mjx_ks, mjx_xhs if __name__ == '__main__': mjx = MJX() mjx.run()
[ 11748, 640, 198, 11748, 4738, 198, 11748, 7007, 198, 6738, 300, 19875, 1330, 2123, 631, 198, 11748, 279, 4948, 25162, 198, 6738, 764, 6371, 62, 7753, 1330, 285, 73, 87, 62, 732, 26762, 11, 285, 73, 87, 62, 9892, 11, 285, 73, 87, 6...
2.275862
87
import numpy as np from keras.utils import np_utils import pandas as pd import sys from sklearn.preprocessing import LabelEncoder from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA from sklearn.decomposition import PCA import os from sklearn.externals import joblib from sklearn.metrics import f1_score trainName = sys.argv[1] testName = sys.argv[2] # Create an object called iris with the iris Data dftrain = pd.read_csv(filepath_or_buffer=trainName, header=None, sep=',') dftest = pd.read_csv(filepath_or_buffer=testName, header=None, sep=',') cols = ['Proto'] for i in range(1,dftrain.shape[1]): cols.append('Byte' + str(i)) dftrain.columns=cols dftrain.dropna(how="all", inplace=True) dftrain.tail() dftest.columns=cols dftest.dropna(how="all", inplace=True) dftest.tail() Xtrain = dftrain.ix[:,1:dftrain.shape[1]].values Ytrain = dftrain.ix[:,0].values Xtest = dftest.ix[:,1:dftrain.shape[1]].values Ytest = dftest.ix[:,0].values encoder = LabelEncoder() encoder.fit(Ytrain) encYtrain = encoder.transform(Ytrain) encoder = LabelEncoder() encoder.fit(Ytest) encYtest = encoder.transform(Ytest) directory = "models/ABD/QDA/" if not os.path.exists(directory): os.makedirs(directory) logfile = directory + "log-0.csv" with open(logfile, "w") as file: file.write("PCAlevel,acc,val_acc,f1\n") fscores = [] accs = [] for q in xrange(1,151): pca = PCA(n_components=q) Xtrain_pca = pca.fit_transform(Xtrain) Xtest_pca = pca.transform(Xtest) clf = QDA(priors=None, reg_param=0.0) clf.fit(Xtrain_pca, encYtrain) trainPred = clf.predict(Xtrain_pca) testPred = clf.predict(Xtest_pca) score = 0.0 for i in xrange(0, len(trainPred)): if trainPred[i] == encYtrain[i]: score += 1 trainAcc = float(score) / len(trainPred) score = 0.0 for i in xrange(0, len(testPred)): if testPred[i] == encYtest[i]: score += 1 testAcc = float(score) / len(testPred) f1 = f1_score(encYtest, testPred) accs.append(testAcc) fscores.append(f1) print("Train " + str(trainAcc)) print("Test " + str(testAcc)) print("F1 " + str(f1)) with open(logfile, "a") as file: file.write(str(q) + "," + str(trainAcc) + "," + str(testAcc) + "," + str(f1) + "\n") if q == 2: joblib.dump(clf, 'QDA2.pkl') print("Val Acc max" + str(max(accs))) print("FMAX " + str(max(fscores))) # print(str(q) + ":" + str((float(score)/len(classesPred)*100)) + "%") # # preds = classesPred # if(len(preds) > 0): # preds = np.array(list(encoder.inverse_transform(preds))) # # df = pd.crosstab(dftest['Proto'], preds, rownames=['Actual Protocol'], colnames=['Predicted Protocol']) # df.to_csv('ConfusionMatrixLDA.csv')
[ 11748, 299, 32152, 355, 45941, 198, 6738, 41927, 292, 13, 26791, 1330, 45941, 62, 26791, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 25064, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 36052, 27195, 12342, 198, 6738, 1341, 35720, ...
2.302423
1,197
import struct import json from collections import OrderedDict file_path = "data0002.bin" show_offset = True show_hash = False loaded_data = 0 file = open(file_path, mode='rb') data = file.read() data_set = OrderedDict() if len(data) > 0x40 and data[0:4] == b'ggdL': file.seek(0x0c, 0) numOfData = int.from_bytes(file.read(4), byteorder='little') while loaded_data < numOfData: unpack(data_set) print() print(data_set) print() print("Complete with %i/%i data" % (loaded_data, numOfData)) with open(r"%s.txt" % (file_path.split('.')[0]), 'w', encoding='utf-8') as json_file: json.dump(data_set, json_file, indent=4, ensure_ascii=False) else: print("File Incorrect")
[ 11748, 2878, 201, 198, 11748, 33918, 201, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 201, 198, 201, 198, 7753, 62, 6978, 796, 366, 7890, 34215, 13, 8800, 1, 201, 198, 12860, 62, 28968, 796, 6407, 201, 198, 12860, 62, 17831, 796, ...
2.292308
325
## to change recursion limit import sys print(sys.getrecursionlimit()) #Return the current value of the recursion limit #1000 ## change the limit sys.setrecursionlimit(2000) # change value of the recursion limit #2000 i=0 greet() # hellow 1996 then error
[ 2235, 284, 1487, 220, 664, 24197, 4179, 220, 198, 11748, 25064, 198, 198, 4798, 7, 17597, 13, 1136, 8344, 24197, 32374, 28955, 220, 1303, 13615, 262, 1459, 1988, 286, 262, 664, 24197, 4179, 198, 2, 12825, 198, 198, 2235, 1487, 262, 41...
3
91
from django.test import TestCase, override_settings from django.urls import reverse from pages.models import Article, HomePage
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 11, 20957, 62, 33692, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 198, 6738, 5468, 13, 27530, 1330, 10172, 11, 5995, 9876, 628 ]
3.909091
33
#!/usr/bin/env python import logging import sys sys.path.append("../../") sys.path.append("pylib") import time import datetime import pymongo import uuid import os import subprocess import os.path import settings from common.utils import getSiteDBCollection sys.path.insert(0, "../../") logging_manager = LoggingManager() connection = getConnection() # TODO: removed items' similarities should also be removed. begin_flow = BeginFlow() preprocessing_flow = PreprocessingFlow() preprocessing_flow.dependOn(begin_flow) hive_based_statistics_flow = HiveBasedStatisticsFlow() hive_based_statistics_flow.dependOn(preprocessing_flow) v_similarity_calc_flow = VSimiliarityCalcFlow() v_similarity_calc_flow.dependOn(preprocessing_flow) plo_similarity_calc_flow = PLOSimilarityCalcFlow() plo_similarity_calc_flow.dependOn(preprocessing_flow) buy_together_similarity_flow = BuyTogetherSimilarityFlow() buy_together_similarity_flow.dependOn(preprocessing_flow) viewed_ultimately_buy_flow = ViewedUltimatelyBuyFlow() viewed_ultimately_buy_flow.dependOn(preprocessing_flow) #edm_related_preprocessing_flow = EDMRelatedPreprocessingFlow() # edm_related_preprocessing_flow.dependOn(preprocessing_flow) if __name__ == "__main__": os.environ["PATH"] = "%s:%s" % (getattr(settings, "extra_shell_path", ""), os.environ["PATH"]) while True: #site_ids = ["test_with_gdian_data"] for site in loadSites(connection): for site in getManualCalculationSites(): workOnSiteWithRetries(site, is_manual_calculation=True) workOnSiteWithRetries(site) sleep_seconds = 1 time.sleep(sleep_seconds)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 18931, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7203, 40720, 40720, 4943, 198, 17597, 13, 6978, 13, 33295, 7203, 79, 2645, 571, 4943, 198, 11748, 640, 198, 11748, 4818,...
2.762684
611
from decimal import Decimal as D from django.test import TestCase from oscar.apps.basket.models import Basket from oscar.apps.partner import strategy from oscar.test import factories from oscar.apps.catalogue.models import Option
[ 6738, 32465, 1330, 4280, 4402, 355, 360, 198, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 198, 6738, 267, 13034, 13, 18211, 13, 65, 11715, 13, 27530, 1330, 347, 11715, 198, 6738, 267, 13034, 13, 18211, 13, 3911, 1008, 1...
3.522388
67
import pytest import os import sqlalchemy import contextlib
[ 11748, 12972, 9288, 198, 11748, 28686, 198, 11748, 44161, 282, 26599, 198, 11748, 4732, 8019, 628 ]
3.8125
16
#!/usr/bin/env python3 import json import os from pathlib import Path import numpy as np from natsort import natsorted try: from docopt import docopt from marko.ext.gfm import gfm import pygal from pygal.style import Style, DefaultStyle except ImportError as e: raise Exception('Some external dependencies not found, install them using: pip install -r requirements.txt') from e FIGURE_FUNCS = [] def figure(func): """Simple decorator to mark a function as a figure generator.""" FIGURE_FUNCS.append(func) return func def latency_vs_connections_figure(percentile, names, suites, config): all_vals = [[s[f'latency_{percentile}p_ms_avg'] for s in suites[name]['stats'][0:]] for name in names] mx = np.max(all_vals) mn = np.min(all_vals) config.range = (mn - mn * .5, mx + mx * .5) chart = pygal.Line(config, logarithmic=True, value_formatter=lambda x: "{:0.0f}".format(x)) chart.title = f'{percentile}. centyl czasu odpowiedzi wzgldem liczby pocze (ms)' connections_x_labels(chart, suites, skip=0) for name in names: chart.add(name, [s[f'latency_{percentile}p_ms_avg'] for s in suites[name]['stats'][0:]]) return chart def connections_x_labels(chart, suites, skip=0): chart.x_labels = [f"{s['connections']} conn's" if s['connections'] else s['message'] for s in next(iter(suites.values()))['stats']][skip:] chart.x_label_rotation = -30 def div_or_none(numerator, denominator, scale=1): if not denominator: return None return scale * numerator / denominator HTML_PREFIX = '''<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Benchmark Report</title> </head> <body> ''' HTML_SUFFIX = ''' </body> </html> ''' if __name__ == '__main__': # args = docopt(__doc__) render()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 33918, 198, 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 299, 1381, 419, 1330, 299, 1381, 9741, 198, 198, 28311, ...
2.444301
772
# # This file is part of LiteX. # # Copyright (c) 2014-2019 Florent Kermarrec <florent@enjoy-digital.fr> # Copyright (c) 2019 msloniewski <marcin.sloniewski@gmail.com> # Copyright (c) 2019 vytautasb <v.buitvydas@limemicro.com> # SPDX-License-Identifier: BSD-2-Clause import os import subprocess import sys import math from shutil import which from migen.fhdl.structure import _Fragment from litex.build.generic_platform import Pins, IOStandard, Misc from litex.build import tools # IO/Placement Constraints (.qsf) ------------------------------------------------------------------ # Timing Constraints (.sdc) ------------------------------------------------------------------------ # Project (.qsf) ----------------------------------------------------------------------------------- # Script ------------------------------------------------------------------------------------------- # AlteraQuartusToolchain ---------------------------------------------------------------------------
[ 2, 198, 2, 770, 2393, 318, 636, 286, 27395, 55, 13, 198, 2, 198, 2, 15069, 357, 66, 8, 1946, 12, 23344, 23347, 429, 17337, 3876, 8344, 1279, 2704, 382, 429, 31, 268, 2633, 12, 34725, 13, 8310, 29, 198, 2, 15069, 357, 66, 8, 13...
4.24359
234
"""Various helpers and utilities that don't belong anywhere else.""" from typing import Dict, Generic, TypeVar KeyType = TypeVar('KeyType') ValueType = TypeVar('ValueType')
[ 37811, 40009, 49385, 290, 20081, 326, 836, 470, 5594, 6609, 2073, 526, 15931, 198, 198, 6738, 19720, 1330, 360, 713, 11, 42044, 11, 5994, 19852, 198, 198, 9218, 6030, 796, 5994, 19852, 10786, 9218, 6030, 11537, 198, 11395, 6030, 796, 59...
3.723404
47
from rest_framework.routers import DefaultRouter from records.views import RecordViewSet router = DefaultRouter() router.register('', RecordViewSet, basename='records') urlpatterns = router.urls
[ 6738, 1334, 62, 30604, 13, 472, 1010, 1330, 15161, 49, 39605, 198, 198, 6738, 4406, 13, 33571, 1330, 13266, 7680, 7248, 198, 198, 472, 353, 796, 15161, 49, 39605, 3419, 198, 472, 353, 13, 30238, 10786, 3256, 13266, 7680, 7248, 11, 161...
3.413793
58
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import os from rhea import RheaError from rhea import parser as rhea_parser from azure.common import AzureHttpError from azure.storage.blob.models import BlobPrefix from polystores.clients.azure_client import get_blob_service_connection from polystores.exceptions import PolyaxonStoresException from polystores.stores.base_store import BaseStore from polystores.utils import append_basename, check_dirname_exists, get_files_in_current_directory # pylint:disable=arguments-differ
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 198, 11748, 28686, 198, 198, 6738, 374, 21632, 1330, 371, 21632, 12331, 198, 6738, 374...
3.337209
172
""" Copyright (c) 2016 Jet Propulsion Laboratory, California Institute of Technology. All rights reserved """ import sys import numpy as np import logging import time import types from datetime import datetime from netCDF4 import Dataset from nexustiles.nexustiles import NexusTileService from webservice.webmodel import NexusProcessingException AVAILABLE_HANDLERS = [] AVAILABLE_INITIALIZERS = [] DEFAULT_PARAMETERS_SPEC = { "ds": { "name": "Dataset", "type": "string", "description": "One or more comma-separated dataset shortnames" }, "minLat": { "name": "Minimum Latitude", "type": "float", "description": "Minimum (Southern) bounding box Latitude" }, "maxLat": { "name": "Maximum Latitude", "type": "float", "description": "Maximum (Northern) bounding box Latitude" }, "minLon": { "name": "Minimum Longitude", "type": "float", "description": "Minimum (Western) bounding box Longitude" }, "maxLon": { "name": "Maximum Longitude", "type": "float", "description": "Maximum (Eastern) bounding box Longitude" }, "startTime": { "name": "Start Time", "type": "long integer", "description": "Starting time in milliseconds since midnight Jan. 1st, 1970 UTC" }, "endTime": { "name": "End Time", "type": "long integer", "description": "Ending time in milliseconds since midnight Jan. 1st, 1970 UTC" }, "lowPassFilter": { "name": "Apply Low Pass Filter", "type": "boolean", "description": "Specifies whether to apply a low pass filter on the analytics results" }, "seasonalFilter": { "name": "Apply Seasonal Filter", "type": "boolean", "description": "Specified whether to apply a seasonal cycle filter on the analytics results" } } def _lon2ind(self,lon): return int((lon-self._minLonCent)/self._lonRes) def _ind2lat(self,y): return self._minLatCent+y*self._latRes def _ind2lon(self,x): return self._minLonCent+x*self._lonRes def _create_nc_file_time1d(self, a, fname, varname, varunits=None, fill=None): self.log.debug('a={0}'.format(a)) self.log.debug('shape a = {0}'.format(a.shape)) assert len(a.shape) == 1 time_dim = len(a) rootgrp = Dataset(fname, "w", format="NETCDF4") rootgrp.createDimension("time", time_dim) vals = rootgrp.createVariable(varname, "f4", dimensions=("time",), fill_value=fill) times = rootgrp.createVariable("time", "f4", dimensions=("time",)) vals[:] = [d['mean'] for d in a] times[:] = [d['time'] for d in a] if varunits is not None: vals.units = varunits times.units = 'seconds since 1970-01-01 00:00:00' rootgrp.close() def _create_nc_file_latlon2d(self, a, fname, varname, varunits=None, fill=None): self.log.debug('a={0}'.format(a)) self.log.debug('shape a = {0}'.format(a.shape)) assert len(a.shape) == 2 lat_dim, lon_dim = a.shape rootgrp = Dataset(fname, "w", format="NETCDF4") rootgrp.createDimension("lat", lat_dim) rootgrp.createDimension("lon", lon_dim) vals = rootgrp.createVariable(varname, "f4", dimensions=("lat","lon",), fill_value=fill) lats = rootgrp.createVariable("lat", "f4", dimensions=("lat",)) lons = rootgrp.createVariable("lon", "f4", dimensions=("lon",)) vals[:,:] = a lats[:] = np.linspace(self._minLatCent, self._maxLatCent, lat_dim) lons[:] = np.linspace(self._minLonCent, self._maxLonCent, lon_dim) if varunits is not None: vals.units = varunits lats.units = "degrees north" lons.units = "degrees east" rootgrp.close() def _create_nc_file(self, a, fname, varname, **kwargs): self._create_nc_file_latlon2d(a, fname, varname, **kwargs) def executeInitializers(config): [wrapper.init(config) for wrapper in AVAILABLE_INITIALIZERS]
[ 37811, 198, 15269, 357, 66, 8, 1584, 19013, 8772, 15204, 18643, 11, 198, 25284, 5136, 286, 8987, 13, 220, 1439, 2489, 10395, 198, 37811, 198, 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 18931, 198, 11748, 640, 198, 117...
2.159801
2,015
import numpy as np from collections import defaultdict, Counter from .rbbox_np import rbbox_iou
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 17268, 1330, 4277, 11600, 11, 15034, 198, 198, 6738, 764, 26145, 3524, 62, 37659, 1330, 374, 65, 3524, 62, 72, 280, 628, 628 ]
3.258065
31
import logging import pygame from app import * from pygame.locals import * from werkzeug.serving import run_simple from web import webapp as w import data_access as da logging.basicConfig(filename='setlistmanager.log', level=logging.DEBUG) SCREEN_WIDTH = 160 SCREEN_HEIGHT = 128
[ 198, 11748, 18931, 198, 11748, 12972, 6057, 198, 6738, 598, 1330, 1635, 198, 6738, 12972, 6057, 13, 17946, 874, 1330, 1635, 198, 6738, 266, 9587, 2736, 1018, 13, 31293, 1330, 1057, 62, 36439, 198, 198, 6738, 3992, 1330, 3992, 1324, 355,...
3.053763
93
import json import pandas as pd import numpy as np from matplotlib import pyplot as plt import simulation from eval_functions import oks_score_multi import utils
[ 11748, 33918, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 198, 11748, 18640, 198, 6738, 5418, 62, 12543, 2733, 1330, 267, 591, 62, 26675, 62, ...
3.5
46
import requests import time import os import sys import json import threading from getpass import getpass import schedule import event as e import configuration as c import RPi.GPIO as GPIO #SERVER_URL = "https://home-automation-289621.uc.r.appspot.com" #SERVER_URL = "http://127.0.0.1:4747" SERVER_URL = "http://192.168.11.117:4747" pins = [2, 3, 4, 7, 8, 9, 10, 11, 14, 15, 17, 18, 22, 23, 24, 27] if __name__ == "__main__": main()
[ 11748, 7007, 198, 11748, 640, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 33918, 198, 11748, 4704, 278, 198, 6738, 651, 6603, 1330, 651, 6603, 198, 11748, 7269, 198, 11748, 1785, 355, 304, 198, 11748, 8398, 355, 269, 198, 11748, 2...
2.513812
181
from typing import Dict, Union from graphql import ( GraphQLBoolean, GraphQLFloat, GraphQLInputField, GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLString, ) from sqlalchemy import ARRAY, Boolean, Float, Integer from sqlalchemy.dialects.postgresql import ARRAY as PGARRAY from sqlalchemy.types import TypeEngine
[ 6738, 19720, 1330, 360, 713, 11, 4479, 198, 198, 6738, 4823, 13976, 1330, 357, 198, 220, 220, 220, 29681, 9711, 46120, 13087, 11, 198, 220, 220, 220, 29681, 9711, 43879, 11, 198, 220, 220, 220, 29681, 9711, 20560, 15878, 11, 198, 220,...
2.774436
133
import Crypto.Random.random as rand import itertools import math #for log import sys if len(sys.argv) > 2: kk = 2 parts = 7 kk = rand.randint(1, int(parts / 4)) #how many sends to demand fuzz = 1 decideAmounts(float(sys.argv[1]), float(sys.argv[2]), parts, kk, fuzz)
[ 11748, 36579, 13, 29531, 13, 25120, 355, 43720, 198, 11748, 340, 861, 10141, 198, 11748, 10688, 1303, 1640, 2604, 198, 11748, 25064, 628, 628, 198, 361, 18896, 7, 17597, 13, 853, 85, 8, 1875, 362, 25, 198, 220, 220, 220, 479, 74, 79...
2.466102
118
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from .shared import Conv_Block from ..utils.utils import zeros, mean_cube, last_frame, ENS
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 304, 259, 2840, 1330, 37825, 858, 198, 6738, 764, 28710, 1330, 34872, 62, 12235,...
3.322581
62
# Copyright (C) 2017 O.S. Systems Software LTDA. # This software is released under the MIT License import unittest from hydra import Hydra, Client
[ 2, 15069, 357, 34, 8, 2177, 440, 13, 50, 13, 11998, 10442, 34146, 5631, 13, 198, 2, 770, 3788, 318, 2716, 739, 262, 17168, 13789, 198, 198, 11748, 555, 715, 395, 198, 198, 6738, 25039, 1330, 31613, 11, 20985, 628 ]
3.75
40
# Copyright 2020 The FastEstimator 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. # ============================================================================== import unittest import numpy as np import tensorflow as tf import torch import fastestimator as fe
[ 2, 15069, 12131, 383, 12549, 22362, 320, 1352, 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, ...
4.135417
192
#!/usr/bin/env python from scTools import interval, primeForm from scTools.rowData import ats from scTools.scData import * count = 1 for w in ats: prime = primeForm(w[0:6]) print '%3d\t' % count, for x in w: print '%X' % x, print ' ', intervals = interval(w) for y in intervals: print '%X' % y, print '\t%2d\t' % sc6.index(prime), if prime == sc6[1] or prime == sc6[7] or prime == sc6[8] or \ prime == sc6[20] or prime == sc6[32] or prime == sc6[35]: print 'AC' elif prime == sc6[17]: print 'AT' else: print count += 1
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 629, 33637, 1330, 16654, 11, 6994, 8479, 198, 6738, 629, 33637, 13, 808, 6601, 1330, 379, 82, 198, 6738, 629, 33637, 13, 1416, 6601, 1330, 1635, 198, 198, 9127, 796, 352, 198, ...
2.134483
290
import asyncio import click from precon.devices_handlers.distance_sensor import show_distance as show_distance_func from precon.remote_control import steer_vehicle, Screen try: import RPi.GPIO as GPIO except (RuntimeError, ModuleNotFoundError): import fake_rpi GPIO = fake_rpi.RPi.GPIO
[ 11748, 30351, 952, 198, 198, 11748, 3904, 198, 198, 6738, 49394, 13, 42034, 62, 4993, 8116, 13, 30246, 62, 82, 22854, 1330, 905, 62, 30246, 355, 905, 62, 30246, 62, 20786, 198, 6738, 49394, 13, 47960, 62, 13716, 1330, 27401, 62, 33892...
3.070707
99
import csv import string import ftplib import math import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import sqlite3 from lxml import html import requests import sys import midwords import facebook import hd_images import adwords_feeds import sheets import random import sales_specials import scrape from pprint import pprint from pyvirtualdisplay import Display import locale locale.setlocale(locale.LC_ALL, 'en_US.utf8') # Misc stuff # FMC Dealer Scrapes # Data stuff if __name__ == '__main__': main()
[ 11748, 269, 21370, 198, 11748, 4731, 198, 11748, 10117, 489, 571, 198, 11748, 10688, 198, 11748, 640, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 13083, 1330, 26363, 198, ...
3.263158
228
# -*- coding: utf-8 -*- # # Copyright (c) 2015, Alcatel-Lucent 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 the copyright holder 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 HOLDER 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. from __future__ import unicode_literals import os import shutil from monolithe.lib import Printer from monolithe.generators.lib import Generator from monolithe.generators.managers import MainManager, CLIManager, VanillaManager from .sdkapiversiongenerator import SDKAPIVersionGenerator
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 66, 8, 1853, 11, 43757, 25791, 12, 25596, 1087, 3457, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2297, 396, 3890, 290, 779, 287, 2723, 2...
3.424682
551
import atexit import sys if sys.version_info[0] == 2: from Queue import Empty else: from queue import Empty from multiprocessing import Process, Queue from rllab.sampler.utils import rollout import numpy as np __all__ = [ 'init_worker', 'init_plot', 'update_plot' ] process = None queue = None
[ 11748, 379, 37023, 198, 11748, 25064, 198, 361, 25064, 13, 9641, 62, 10951, 58, 15, 60, 6624, 362, 25, 198, 220, 220, 220, 422, 4670, 518, 1330, 33523, 198, 17772, 25, 198, 220, 220, 220, 422, 16834, 1330, 33523, 198, 6738, 18540, 3...
2.767241
116
''' Livro-Introduo-a-Viso-Computacional-com-Python-e-OpenCV-3 Repositrio de imagens https://github.com/opencv/opencv/tree/master/samples/data ''' import cv2 import numpy as np from matplotlib import pyplot as plt #import mahotas VERMELHO = (0, 0, 255) VERDE = (0, 255, 0) AZUL = (255, 0, 0) AMARELO = (0, 255, 255) BRANCO = (255,255,255) CIANO = (255, 255, 0) PRETO = (0, 0, 0) img = cv2.imread('ponte2.jpg') # Flag 1 = Color, 0 = Gray, -1 = Unchanged img = img[::2,::2] # Diminui a imagem #Binarizao com limiar img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) suave = cv2.GaussianBlur(img, (7, 7), 0) # aplica blur (T, bin) = cv2.threshold(suave, 160, 255, cv2.THRESH_BINARY) (T, binI) = cv2.threshold(suave, 160, 255, cv2.THRESH_BINARY_INV) ''' resultado = np.vstack([ np.hstack([suave, bin]), np.hstack([binI, cv2.bitwise_and(img, img, mask = binI)]) ]) ''' resultado = np.vstack([ np.hstack([img, suave]), np.hstack([bin, binI]) ]) cv2.imshow("Binarizao da imagem", resultado) cv2.waitKey(0) #Threshold adaptativo bin1 = cv2.adaptiveThreshold(suave, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 21, 5) bin2 = cv2.adaptiveThreshold(suave, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 21, 5) resultado = np.vstack([ np.hstack([img, suave]), np.hstack([bin1, bin2]) ]) cv2.imshow("Binarizao adaptativa da imagem", resultado) cv2.waitKey(0) #Threshold com Otsu e Riddler-Calvard ''' T = mahotas.thresholding.otsu(suave) temp = img.copy() temp[temp > T] = 255 temp[temp < 255] = 0 temp = cv2.bitwise_not(temp) T = mahotas.thresholding.rc(suave) temp2 = img.copy() temp2[temp2 > T] = 255 temp2[temp2 < 255] = 0 temp2 = cv2.bitwise_not(temp2) resultado = np.vstack([ np.hstack([img, suave]), np.hstack([temp, temp2]) ]) cv2.imshow("Binarizao com mtodo Otsu e Riddler-Calvard", resultado) cv2.waitKey(0) '''
[ 7061, 6, 628, 220, 32020, 305, 12, 15005, 78, 12, 64, 12, 15854, 78, 12, 5377, 1996, 330, 1538, 12, 785, 12, 37906, 12, 68, 12, 11505, 33538, 12, 18, 198, 198, 6207, 7434, 27250, 390, 3590, 641, 198, 5450, 1378, 12567, 13, 785, ...
2.08269
907
import base64 import json import jwt import requests from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend USER_MODEL = get_user_model()
[ 11748, 2779, 2414, 198, 11748, 33918, 198, 198, 11748, 474, 46569, 198, 11748, 7007, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 4262...
3.264706
68
import json import os import sys import re import copy import numpy as np from data_profiler.labelers.base_model import BaseModel from data_profiler.labelers.base_model import AutoSubRegistrationMeta _file_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(_file_dir)
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 302, 198, 11748, 4866, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 1366, 62, 5577, 5329, 13, 18242, 364, 13, 8692, 62, 19849, 1330, 7308, 17633, 198, 6738, 136...
3.042553
94
# Desarrolle un un programa que reciba la fecha de nacimiento # de una persona, y como salida, indique el nombre del signo del # zodiaco correspondiente, ademas de su edad fecha_str = input("Ingrese la fecha de nacimiento (DD/MM/AAAA): ") fecha = fecha_str.split("/") fecha_int = [] for elemento in fecha: fecha_int.append(int(elemento)) dia = fecha_int[0] mes = fecha_int[1] ano = fecha_int[2] signo = zodiaco(dia, mes) print(f"Siendo que su fecha de nacimiento es {fecha_str}, su signo zodiacal corresponde a {signo} y tiene {abs(ano - 2021)} aos")
[ 2, 2935, 283, 3225, 293, 555, 555, 1430, 64, 8358, 664, 23718, 8591, 730, 11693, 390, 299, 330, 320, 1153, 78, 198, 2, 390, 555, 64, 27822, 11, 331, 401, 78, 3664, 3755, 11, 773, 2350, 1288, 299, 2381, 260, 1619, 1051, 78, 1619, ...
2.386266
233
import re, scrapy from crawler.items import *
[ 11748, 302, 11, 15881, 88, 198, 6738, 27784, 1754, 13, 23814, 1330, 1635 ]
3.461538
13
# Copyright 2017 GoDaddy # # 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 oslo_serialization import jsonutils from tempest import config from octavia_tempest_plugin.services.load_balancer.v2 import base_client CONF = config.CONF Unset = base_client.Unset
[ 2, 220, 220, 15069, 2177, 1514, 48280, 198, 2, 198, 2, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 137...
3.383621
232
import re import logging import httplib import view_base from models import rt_proxy LOG = logging.getLogger('ryu.gui')
[ 11748, 302, 198, 11748, 18931, 198, 11748, 1841, 489, 571, 198, 198, 11748, 1570, 62, 8692, 198, 6738, 4981, 1330, 374, 83, 62, 36436, 198, 198, 25294, 796, 18931, 13, 1136, 11187, 1362, 10786, 49056, 13, 48317, 11537 ]
3.184211
38
"""This module contains tests for the helper module. """ from pywrangler.util.helper import get_param_names
[ 37811, 1212, 8265, 4909, 5254, 329, 262, 31904, 8265, 13, 198, 198, 37811, 198, 198, 6738, 12972, 18351, 49910, 13, 22602, 13, 2978, 525, 1330, 651, 62, 17143, 62, 14933, 628 ]
3.580645
31
# ============================================================================= # Created By : Giannis Kostas Georgiou # Project : Machine Learning for Fish Recognition (Individual Project) # ============================================================================= # Description : File in order to convert saved models to .tflite instances. # To be used after the desired model are trained and saved # How to use : Replace variables in CAPS according to needs of the dataset # ============================================================================= import tensorflow as tf model_path='PATH TO SAVED MODEL' tflite_model_name='NAME OF THE NEWLY CREATED TFLITE MODEL' #convert the model by loading the saved model to the converter converter = tf.lite.TFLiteConverter.from_saved_model(model_path) tflite_model = converter.convert() #save the tflite model with open(tflite_model_name+'.tflite', 'wb') as f: f.write(tflite_model)
[ 2, 38093, 25609, 198, 2, 15622, 2750, 220, 1058, 30851, 21361, 509, 455, 292, 6850, 72, 280, 198, 2, 4935, 220, 220, 220, 220, 1058, 10850, 18252, 329, 13388, 31517, 653, 357, 35392, 4935, 8, 198, 2, 38093, 25609, 198, 2, 12489, 105...
3.825397
252
from .test_utils import PySparkTestCase from sparkts.datetimeindex import * import pandas as pd
[ 6738, 764, 9288, 62, 26791, 1330, 9485, 4561, 668, 14402, 20448, 198, 6738, 9009, 912, 13, 19608, 8079, 9630, 1330, 1635, 198, 11748, 19798, 292, 355, 279, 67, 628 ]
3.344828
29
# Definition for singly-linked list.
[ 2, 30396, 329, 1702, 306, 12, 25614, 1351, 13, 628 ]
3.8
10
import numpy as np import photon_stream as ps import photon_stream_production as psp import pkg_resources import os runinfo_path = pkg_resources.resource_filename( 'photon_stream_production', os.path.join('tests', 'resources', 'runinfo_20161115_to_20170103.csv') ) drs_fRunID_for_obs_run = psp.drs_run._drs_fRunID_for_obs_run
[ 11748, 299, 32152, 355, 45941, 198, 11748, 48190, 62, 5532, 355, 26692, 198, 11748, 48190, 62, 5532, 62, 25493, 355, 279, 2777, 198, 11748, 279, 10025, 62, 37540, 198, 11748, 28686, 198, 198, 5143, 10951, 62, 6978, 796, 279, 10025, 62, ...
2.632813
128
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-04-18 05:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 1238, 319, 13130, 12, 3023, 12, 1507, 8870, 25, 3980, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198...
2.753623
69
import http import logging from typing import List, Tuple, MutableMapping from datetime import datetime import re from requests.packages.urllib3 import Retry import autoscaler.utils as utils from autoscaler.autoscaling_groups import AutoScalingGroup from autoscaler.azure_api import AzureApi, AzureScaleSet, AzureScaleSetInstance from autoscaler.utils import TransformingFuture, AllCompletedFuture, CompletedFuture logger = logging.getLogger(__name__) _RETRY_TIME_LIMIT = 30 _CLASS_PAT = re.compile(r'\w+_(?P<class>[A-Z]+).+') _SCALE_SET_SIZE_LIMIT = 100 # Appears as an unbounded scale set. Currently, Azure Scale Sets have a limit of 100 hosts.
[ 11748, 2638, 198, 11748, 18931, 198, 6738, 19720, 1330, 7343, 11, 309, 29291, 11, 13859, 540, 44, 5912, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 302, 198, 6738, 7007, 13, 43789, 13, 333, 297, 571, 18, 1330, 4990, 563,...
3.147619
210
""" Insertion Sort Approach: Loop Complexity: O(n2) """ if __name__ == '__main__': arr = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14] sort_insertion(arr)
[ 37811, 198, 44402, 295, 33947, 198, 198, 4677, 28562, 25, 26304, 198, 5377, 11141, 414, 25, 440, 7, 77, 17, 8, 198, 37811, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 5240, 796, 685, ...
2.093333
75
""" NAME tarea_7.py VERSION [1.0] AUTHOR Ignacio Emmanuel Ramirez Bernabe CONTACT iramirez@lcg.unam.mx GITHUB https://github.com/eveiramirez/python_class/blob/master/Python2/tareas/tarea_7.py DESCRIPTION Este programa contiene arrays estructurados para los arrays creados en el ejercicio 1, los cuales son: Produccion Costos Costos por g/L CATEGORY Numpy """ import numpy as np # Crear array con la produccion de cada gen para cada temperatura production = np.array([("Gen1", 5, 3), ("Gen2", 11, 7), ("Gen3", 4, 9), ("Gen4", 2, 6)], dtype=[("name", (np.str_, 10)), ("production_cond1", np.int32), ("production_cond2", np.int32)]) # Crear array con los costos de induccion costs = np.array([("Gen1", 3.5), ("Gen2", 5), ("Gen3", 7), ("Gen4", 4.3)], dtype=[("name", (np.str_, 10)), ("cost", np.float64)]) # Crear array con los costos por g/L para condicion 1 pc_cond1 = production["production_cond1"]/costs["cost"] # Crear array con los costos por g/L para temperatura 2 pc_cond2 = production["production_cond2"]/costs["cost"] # Crear lista con los costos por g/L para cada gene guardados en una # tupla gene_list = [] for gene in range(0, 4): gene_list.append((f"Gen{gene+1}", pc_cond1[gene], pc_cond2[gene])) # Crear array con los costos por g/L prod_costs = np.array(gene_list, dtype=[("name", (np.str_, 10)), ("pc_cond1", np.float64), ("pc_cond2", np.float64)]) # Imprimir array de los costos por g/L print(prod_costs)
[ 37811, 198, 198, 20608, 198, 220, 220, 220, 220, 220, 220, 220, 256, 20337, 62, 22, 13, 9078, 198, 198, 43717, 198, 220, 220, 220, 220, 220, 220, 220, 685, 16, 13, 15, 60, 198, 198, 32, 24318, 1581, 198, 220, 220, 220, 220, 220,...
1.958196
909
""" Base pipeline class. Main rule generator classes inherit from this one. """ from copy import deepcopy from typing import List, Tuple, Union, Dict from iguanas.pipeline.class_accessor import ClassAccessor from iguanas.utils.typing import PandasDataFrameType, PandasSeriesType import iguanas.utils.utils as utils from iguanas.exceptions import DataFrameSizeError
[ 37811, 198, 14881, 11523, 1398, 13, 8774, 3896, 17301, 6097, 16955, 422, 428, 530, 13, 198, 37811, 198, 6738, 4866, 1330, 2769, 30073, 198, 6738, 19720, 1330, 7343, 11, 309, 29291, 11, 4479, 11, 360, 713, 198, 6738, 45329, 7258, 292, ...
3.623762
101
import unittest import datetime from parameterized import parameterized from activity_merger import Interval from aw_core.models import Event from typing import List, Tuple def build_intervals_linked_list(data: List[Tuple[int, bool, int]]) -> Interval: """ Builds intervals linked list from the list of tuples. Doesn't check parameters. :param data: List of tuples (day of start, flag to return `Interval` from the function, duration). :return: Chosen interval. """ result = None previous = None for (seed, is_target, duration) in data: if not previous: previous = Interval(_build_datetime(seed), _build_datetime(seed + duration)) else: tmp = Interval(_build_datetime(seed), _build_datetime(seed + duration), previous) previous.next = tmp previous = tmp if is_target: assert result is None, f"Wrong parameters - '{seed}' interval is marked as result but is not first." result = previous return result if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 4818, 8079, 198, 6738, 11507, 1143, 1330, 11507, 1143, 198, 6738, 3842, 62, 647, 1362, 1330, 4225, 2100, 198, 6738, 3253, 62, 7295, 13, 27530, 1330, 8558, 198, 6738, 19720, 1330, 7343, 11, 309, 29291, ...
2.758883
394
""" NOTE: There are a few minor complications to fluid human control which make this code a little more involved than trivial. 1. Key press-release cycles can be, and often are, faster than one tick of the game/simulation, but the player still wants that cycle to count, i.e. to lay a bomb! 2. When holding down a key, the player expects that action to be repeated, at least after a slight delay. 3. But when holding a key down (say, move left) and simultaneously doing a quick press-release cycle (put a bomb), we want the held-down key to keep being executed, but the cycle should have happened in-between. The way we solve this problem is by separating key-state and actions-to-do. We hold the actions that need be executed in a queue (`self._action_q`) and a state for all considered keys. 1. When a key is pressed down, we note the time and mark it as down. 2. If it is released quickly thereafter, before a game tick could happen, we add its action into the queue. This often happens when putting bombs. 3. If it's still pressed down as we enter a game tick, we do some math to see if it's time for a "repeat" event and, if so, push an action to the queue. 4. Just work off one item from the queue each tick. This way, the input is "natural" and things like dropping a bomb while doing a diagonal walk from one end to the other "just work". """ from time import time from . import BaseAgent from .. import characters REPEAT_DELAY = 0.2 # seconds REPEAT_INTERVAL = 0.1
[ 37811, 198, 16580, 25, 198, 198, 1858, 389, 257, 1178, 4159, 19481, 284, 11711, 1692, 1630, 543, 787, 428, 198, 8189, 257, 1310, 517, 2950, 621, 20861, 13, 198, 198, 16, 13, 7383, 1803, 12, 20979, 16006, 460, 307, 11, 290, 1690, 389...
3.628916
415
# Copyright 2015 Cisco Systems, 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 __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import str from builtins import range from builtins import object import http.client import os import pytest import random import string import time import xml.etree.ElementTree as ET import logging from cobra.internal.codec.jsoncodec import toJSONStr, fromJSONStr from cobra.internal.codec.xmlcodec import toXMLStr, fromXMLStr import cobra.mit.access import cobra.mit.request import cobra.mit.session cobra = pytest.importorskip("cobra") cobra.model = pytest.importorskip("cobra.model") cobra.model.fv = pytest.importorskip("cobra.model.fv") import cobra.model.pol import cobra.model.infra import cobra.services pytestmark = pytest.mark.skipif(pytest.config.getvalue('apic') == [], reason="You must specify at least one --apic " + "option on the CLI") slow = pytest.mark.slow http.client.HTTPConnection.debuglevel = 1 logging.basicConfig(level=logging.DEBUG) fakeDevicePackageZip = 'Archive.zip' realDevicePackageZip = 'asa-device-pkg.zip'
[ 2, 15069, 1853, 28289, 11998, 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, 13789, 13, 198, 2,...
3.008681
576
""" fixtures that return an sql statement with a list of values to be inserted.""" def load_language(): """ return the sql and values of the insert queuery.""" sql = """ INSERT INTO Spanglish_Test.Language ( `name`, `iso-639-1` ) VALUES (%s, %s) """ values = [ ( 'English', 'EN' ), ( 'Spanish', 'ES' ), ( 'Dutch', 'NL' ) ] return { 'sql': sql, 'values': values }
[ 37811, 34609, 326, 1441, 281, 44161, 2643, 351, 257, 1351, 286, 3815, 284, 307, 18846, 526, 15931, 198, 198, 4299, 3440, 62, 16129, 33529, 198, 220, 220, 220, 37227, 1441, 262, 44161, 290, 3815, 286, 262, 7550, 8358, 84, 1924, 526, 15...
1.831683
303
import datetime as dt from os.path import dirname, join import numpy as np import pandas as pd import pyarrow as pa import pyarrow.parquet as pq from bokeh.io import curdoc from bokeh.layouts import column, gridplot, row from bokeh.models import ColumnDataSource, DataRange1d, Select, HoverTool, Panel, Tabs, LinearColorMapper, Range1d from bokeh.models import NumeralTickFormatter, Title, Label, Paragraph, Div, CustomJSHover, BoxAnnotation from bokeh.models import ColorBar from bokeh.palettes import brewer, Spectral6 from bokeh.plotting import figure from bokeh.embed import server_document from bokeh.transform import factor_cmap ################################################################################# # This just loads in the data... # Alot of this was built of this "cross-fire demo" # https://github.com/bokeh/bokeh/blob/branch-2.3/examples/app/crossfilter/main.py start_date = dt.datetime(2017,7,1) end_date = dt.datetime(2022,1,1) background = "#ffffff" file = "./data"+ "/data.parquet" df = pq.read_table(file).to_pandas() df.sort_index(inplace=True) options = df.index.unique(0).to_list() #print(options) product = "HS CODE 72, IRON AND STEEL" level = "US Dollars" ################################################################################# #These are functions used in the plot... ################################################################################# # Then this makes the simple plots: # This part is still not clear to me. but it tells it what to update and where to put it # so it updates the layout and [0] is the first option (see below there is a row with the # first entry the plot, then the controls) level_select = Select(value=level, title='Tranformations', options=['US Dollars', 'Year over Year % Change', "Cumulative Purchases 2020 vs 2017"]) level_select.on_change('value', update_plot) #print(sorted(options)) product_select = Select(value=product, title='Product', options=sorted(options), width=400) # This is the key thing that creates teh selection object product_select.on_change('value', update_plot) # Change the value upone selection via the update plot div0 = Div(text = """Categories are at both the HS2 and HS4 level. Only Phase One covered products as defined in Annex 6-1 of The Agreement within that HS Code are shown. Red marks the period of Section 301 tariffs and retaliation. Blue is period of agreement.\n \n \n """, width=400, background = background, style={"justify-content": "space-between", "display": "flex"} ) div1 = Div(text = """Transformations: US Dollars, year over year growth rate and cumulative purchases in 2017 vs 2020.\n The later transformation cumulates Chinese purchases over each month in 2017 and 2020 and compares each. Because 2017 is the benchmark year for The Agreement, this measure provides a sense, for each product category, China's progress towards meeting their purchase commitments.\n """, width=400, background = background, style={"justify-content": "space-between", "display": "flex"} ) controls = column(product_select, div0, level_select, div1) height = int(1.95*533) width = int(1.95*675) layout = row(make_plot(), controls, sizing_mode = "scale_height", max_height = height, max_width = width, min_height = int(0.25*height), min_width = int(0.25*width)) curdoc().add_root(layout) curdoc().title = "us-china-products"
[ 11748, 4818, 8079, 355, 288, 83, 198, 6738, 28686, 13, 6978, 1330, 26672, 3672, 11, 4654, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 11748, 12972, 6018, 355, 14187, 198, 11748, 12972, ...
3.387226
1,002
""" ================ HTTPS Middleware ================ Change scheme for current request when aiohttp application deployed behind reverse proxy with HTTPS enabled. Usage ===== .. code-block:: python from aiohttp import web from aiohttp_middlewares import https_middleware # Basic usage app = web.Application(middlewares=[https_middleware()]) # Specify custom headers to match, not `X-Forwarded-Proto: https` app = web.Application( middlewares=https_middleware({"Forwarded": "https"}) ) """ import logging from aiohttp import web from aiohttp.web_middlewares import _Handler, _Middleware from .annotations import DictStrStr DEFAULT_MATCH_HEADERS = {"X-Forwarded-Proto": "https"} logger = logging.getLogger(__name__) def https_middleware(match_headers: DictStrStr = None) -> _Middleware: """ Change scheme for current request when aiohttp application deployed behind reverse proxy with HTTPS enabled. This middleware is required to use, when your aiohttp app deployed behind nginx with HTTPS enabled, after aiohttp discounted ``secure_proxy_ssl_header`` keyword argument in https://github.com/aio-libs/aiohttp/pull/2299. :param match_headers: Dict of header(s) from reverse proxy to specify that aiohttp run behind HTTPS. By default: .. code-block:: python {"X-Forwarded-Proto": "https"} """ return middleware
[ 37811, 198, 4770, 198, 6535, 28820, 6046, 1574, 198, 4770, 198, 198, 19400, 7791, 329, 1459, 2581, 618, 257, 952, 4023, 3586, 12380, 2157, 198, 50188, 15741, 351, 38288, 9343, 13, 198, 198, 28350, 198, 1421, 28, 198, 198, 492, 2438, 1...
3.027311
476
import cv2 import numpy as np
[ 11748, 269, 85, 17, 201, 198, 11748, 299, 32152, 355, 45941, 201 ]
2.583333
12
import pandas_datareader.data as pdr import yfinance as fix import numpy as np fix.pdr_override() def back_test(strategy, seq_len, ticker, start_date, end_date, dim): """ A simple back test for a given date period :param strategy: the chosen strategy. Note to have already formed the model, and fitted with training data. :param seq_len: length of the days used for prediction :param ticker: company ticker :param start_date: starting date :type start_date: "YYYY-mm-dd" :param end_date: ending date :type end_date: "YYYY-mm-dd" :param dim: dimension required for strategy: 3dim for LSTM and 2dim for MLP :type dim: tuple :return: Percentage errors array that gives the errors for every test in the given date range """ data = pdr.get_data_yahoo(ticker, start_date, end_date) stock_data = data["Adj Close"] errors = [] for i in range((len(stock_data) // 10) * 10 - seq_len - 1): x = np.array(stock_data.iloc[i: i + seq_len, 1]).reshape(dim) / 200 y = np.array(stock_data.iloc[i + seq_len + 1, 1]) / 200 predict = strategy.predict(x) while predict == 0: predict = strategy.predict(x) error = (predict - y) / 100 errors.append(error) total_error = np.array(errors) print(f"Average error = {total_error.mean()}") # If you want to see the full error list then print the following statement # print(errors)
[ 11748, 19798, 292, 62, 19608, 533, 5067, 13, 7890, 355, 279, 7109, 198, 11748, 331, 69, 14149, 355, 4259, 198, 11748, 299, 32152, 355, 45941, 198, 13049, 13, 79, 7109, 62, 2502, 13154, 3419, 628, 198, 4299, 736, 62, 9288, 7, 2536, 4...
2.64
550
# -*- coding: utf-8 """Module for custom component groups. It is possible to create subsystems of component groups in tespy. The subsystem class is the base class for custom subsystems. This file is part of project TESPy (github.com/oemof/tespy). It's copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/components/subsystems.py SPDX-License-Identifier: MIT """ import logging # %%
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 26796, 329, 2183, 7515, 2628, 13, 198, 198, 1026, 318, 1744, 284, 2251, 39335, 82, 286, 7515, 2628, 287, 256, 274, 9078, 13, 383, 39335, 198, 4871, 318, 262, 2779, 1398,...
3.612403
129
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. import copy import logging from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type import torch import torch.distributed as dist from torch.optim import SGD, Optimizer from .utils import broadcast_object, recursive_copy_to_device if TYPE_CHECKING: from torch.optim.optimizer import _params_t else: _params_t = Any
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 347, 10305, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, ...
3.546053
152
from setuptools import setup, find_packages setup( name="raytracing-one-weekend", version="0.0.0", author="Andy Palmer", author_email="contactninezerozeronine@gmail.com", description="A raytracer achievable in a weekend.", url="https://github.com/ninezerozeronine/raytracing-one-weekend", install_requires=[ "Pillow", "numpy", ], packages=find_packages('src'), package_dir={'': 'src'}, )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 2433, 2213, 4092, 12, 505, 12, 10464, 437, 1600, 198, 220, 220, 220, 2196, 2625, 15, 13, 15, 13, 15, 1600, 198, 220, 220...
2.472222
180
""" URLconf of the homepage """ from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), path('auth', views.auth, name='auth'), path('auth/public', views.auth_public, name='auth-public'), path('auth/full', views.auth_full, name='auth-full'), path('auth/invite', views.auth_invite, name='auth-invite'), path('callback/sni', views.sni_callback, name='sni_callback'), path('logout', views.logout, name='logout'), path('403', views.no_perm, name='no-permission'), path('404', views.not_found, name='not-found'), ]
[ 37811, 198, 21886, 10414, 286, 262, 34940, 198, 37811, 628, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 11, 2291, 198, 198, 6738, 764, 1330, 5009, 628, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 3256, 5009...
2.716216
222
""" Notification email machinery, for tasks to send credentials and instructions to users. Email templates placed inside the `templates` directory of this module should: - extend from `layout` - provide `subject` and `body` blocks """ from enum import Enum import os.path from jinja2 import Environment, FileSystemLoader from sqlalchemy.orm import Session as SQLASession from srcf.database import Member, Society from srcf.mail import send_mail from ..plumbing import Owner, owner_desc, owner_name, owner_website ENV = Environment(loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), "templates")), trim_blocks=True, lstrip_blocks=True) ENV.filters.update({"is_member": lambda mem: isinstance(mem, Member), "is_society": lambda soc: isinstance(soc, Society), "owner_name": owner_name, "owner_desc": owner_desc, "owner_website": owner_website}) CURRENT_WRAPPER = None DEFAULT_WRAPPER = EmailWrapper(subject="[SRCF] {}") def send(target: Owner, template: str, context: dict = None, session: SQLASession = None): """ Render and send an email to the target member or society. """ wrapper = CURRENT_WRAPPER or DEFAULT_WRAPPER subject = wrapper.render(template, Layout.SUBJECT, target, context) body = wrapper.render(template, Layout.BODY, target, context) recipient = (owner_desc(target, True), target.email) send_mail(recipient, subject, body, copy_sysadmins=False, session=session)
[ 37811, 198, 3673, 2649, 3053, 20230, 11, 329, 8861, 284, 3758, 18031, 290, 7729, 284, 2985, 13, 198, 198, 15333, 24019, 4624, 2641, 262, 4600, 11498, 17041, 63, 8619, 286, 428, 8265, 815, 25, 198, 198, 12, 9117, 422, 4600, 39786, 63, ...
2.8117
547
from .operations import Multiply, Add, Substract
[ 6738, 764, 3575, 602, 1330, 7854, 541, 306, 11, 3060, 11, 3834, 8709, 628 ]
3.571429
14
import os from typing import Union import tensorflow as tf import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split, KFold import utility as ut from variables import * # Read the data. train_data = pd.read_csv(os.path.join(DATA_PATH, ".".join([DATA_TRAIN, DATA_EXT])), header = 0) # Get the labels. Y = train_data.pop(LABEL) sample_weights = np.ones(Y.shape[0]) for i in range(10, 24): sample_weights[train_data["_".join(("hour", str(i)))] == 1] = 1.5 # -- For classification -- # # CLASSES = np.unique(Y) # N_CLASSES = len(CLASSES) # Y = Y.replace(dict(zip(CLASSES, range(0, len(CLASSES))))) # Data shape parameters. N_FEATURES = train_data.shape[1] N_SAMPLES = train_data.shape[0] # Split the training data. X_train, X_val, Y_train, Y_val = train_test_split(train_data, Y, shuffle = True, random_state = 7919) def build_and_compile(input_: tuple = (WB_SIZE, N_FEATURES), loss_func: str = "mae") -> tf.keras.Model: """ Build and compile a TensorFLow LSTM network. Parameters ---------- input_ : Shape of the trainining data. Should specify `(batch_size` or `window_size, n_features)` loss_func : Loss function to use for training. Returns ------- `tf.keras.Model` : A compiled TensorFlow model. """ # Seqential keras model. model = tf.keras.models.Sequential([ tf.keras.layers.LSTM(50, input_shape = input_, return_sequences = True), tf.keras.layers.LSTM(50, return_sequences = False), tf.keras.layers.GaussianNoise(1.0), tf.keras.layers.Dense(1024, activation = "relu"), tf.keras.layers.Dropout(0.7), tf.keras.layers.Dense(128, activation = "relu"), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(64, activation = "relu"), tf.keras.layers.GaussianNoise(0.2), # tf.keras.layers.Dense(32, activation = "relu"), # tf.keras.layers.GaussianNoise(0.7), tf.keras.layers.Dense(1, activation = "relu") ]) # Compile the model. model.compile( loss = loss_func, optimizer = "adam" ) return model def train(model: tf.keras.Model, train_data: np.ndarray, train_labels: np.ndarray, val_data: np.ndarray, val_labels: np.ndarray, epochs: int = 200, sample_weights: np.array = None, cross_val = False) -> pd.DataFrame: """ Trains the TensorFlow `model`. Parameters ---------- model : A TensorFlow compiled model. train_data : The data to be trained. Shape must be consistent with what is passed during model compilation. train_labels : The ground truth predictions. val_data : The data to be used as validation. val_labels : The ground truth validation predictions. epochs : Total number of epochs to train. sample_weights : Weights for `train_data` to use during training. Returns ------- pd.DataFrame: Training information. """ # Check for overfitting. early_stopping = tf.keras.callbacks.EarlyStopping( monitor = "val_loss", min_delta = 0.001, patience = 100, restore_best_weights = False) history = model.fit( train_data.reshape(-1, WB_SIZE, N_FEATURES), train_labels, sample_weight = sample_weights, validation_data = (val_data.reshape(-1, WB_SIZE, N_FEATURES), val_labels), verbose = 1, epochs = epochs, callbacks = early_stopping) return pd.DataFrame(history.history) # def cross_validate(train_data: pd.DataFrame, # train_labels: pd.DataFrame, # epochs: int = 50, # sample_weights: np.array = None, # folds: int = 2) -> pd.DataFrame: # splits = KFold(n_splits = folds, shuffle = True) # print("Starting cross validation.") # accuracy = list() # val_loss = list() # models = list() # for i, (train_index, test_index) in enumerate(splits.split(train_data, train_labels)): # print(f"Iteration {i}\n") # X_train, X_val, Y_train, Y_val = train_data[train_index], train_data[test_index], train_data[train_index], train_labels[test_index] # model = build_and_compile((WB_SIZE, N_FEATURES), "mae") # history_df = train(model, X_train, Y_train, epochs) # # train_stats(history_df, i) # scores = model.evaluate(X_val.reshape(-1, WB_SIZE, N_FEATURES), Y_val) # print(f"Validation loss: {scores}\n") # #of {scores[0]} {model.metrics_names[1]} of {scores[1] * 100:.2f}%") # # accuracy.append(scores[1] * 100) # val_loss.append(scores) # models.append(model) # return models[np.argmin(val_loss)] def train_stats(history_df: pd.DataFrame, it: int = None) -> None: """ Produces training statistics once training has run its course. Parameters ---------- history_df : The history as returned by Keras `fit` method. it : To be used with cross validation. Specifies the name of the learning curve based on the cross validation itertation `it`. Returns ------- `None` """ # Learning curve. plt.rcParams["figure.dpi"] = 160 history_df.loc[:, ["loss", "val_loss"]].plot() plt.title("Model Loss") plt.ylabel("Loss") plt.xlabel("Epoch") name = TRAIN_FIG_SAVE_NAME if it is not None: name = "_".join([name, str(it)]) plt.savefig(os.path.join(TRAIN_FIG_SAVE_PATH, ".".join([name, FIG_EXT]))) # Stats print(f"Minimum validation loss: {history_df['val_loss'].min()}") # plt.plot(f"Accuracy: {history_df['train_accuracy']}") # plt.plot(f"Validation Accuracy: {history_df['val_accuracy']}") return None if __name__ == "__main__": main()
[ 11748, 28686, 198, 6738, 19720, 1330, 4479, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198...
2.391361
2,292
import base64 import random import string import netbyte import numpy as np try: import simplejson as json except ImportError: import json kinds = {}
[ 11748, 2779, 2414, 198, 11748, 4738, 198, 11748, 4731, 198, 11748, 2010, 26327, 198, 11748, 299, 32152, 355, 45941, 198, 198, 28311, 25, 198, 220, 220, 220, 1330, 2829, 17752, 355, 33918, 198, 220, 220, 220, 220, 198, 16341, 17267, 1233...
2.864407
59
import unittest from players import Player, Quarterback from possible_values import * from game import Game from random import randint, uniform, sample from season import * # TODO - some things you can add... if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 1938, 1330, 7853, 11, 17264, 1891, 198, 6738, 1744, 62, 27160, 1330, 1635, 198, 6738, 983, 1330, 3776, 198, 6738, 4738, 1330, 43720, 600, 11, 8187, 11, 6291, 198, 6738, 1622, 1330, 1635, 198, 198, 2, ...
3.48
75
import os import logging import numpy as np from tqdm import tqdm from functools import partial from multiprocessing.pool import ThreadPool import pyworld as pw from util.dsp import Dsp logger = logging.getLogger(__name__)
[ 11748, 28686, 198, 11748, 18931, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 18540, 305, 919, 278, 13, 7742, 1330, 14122, 27201, 198, 11748, 1...
3.228571
70
#!/usr/bin/python import sys from subprocess import call print "divsum_count.py ListOfDivsumFiles\n" try: files = sys.argv[1] except: files = raw_input("Introduce RepeatMasker's list of Divsum files with library size (tab separated): ") files = open(files).readlines() to_join = [] header = "Coverage for each repeat class and divergence (Kimura)\n" results = {} for line in files: line = line.split("\t") file = line[0] size = int(line[1]) data = open(file).readlines() matrix_start = data.index(header) matrix = data[matrix_start+1:] li= [] names_line = matrix[0] info = names_line.split() for fam in info: li.append([fam]) info_len = len(li) for line in matrix[1:]: info = line.split() for i in range(0,info_len): li[i].append(info[i]) out = open(file+".counts","w") out.write("Sequence\tAbundance\n") stats = open(file+".stats","w") stats.write("Sequence\tDivergence\tTotalAbundance\tMaxAbundance\tMaxPeak\tRPS\tDIVPEAK\n") for el in li[1:]: numbers = el[1:] numbers = [int(x) for x in numbers] numbers_prop = [1.0*x/size for x in numbers] prop_dict = {} prop_li = [] for prop in range(0,len(numbers_prop)): prop_dict[prop] = numbers_prop[prop] prop_li.append(numbers_prop[prop]) prop_dict_sorted = sorted(prop_dict.items(), key=lambda x: x[1], reverse=True) total = sum(numbers_prop) top = prop_dict_sorted[0] top_div = top[0] top_ab = top[1] peak = [] if top_div >= 2: for div in range(top_div-2,top_div+3): peak.append(prop_dict[div]) else: for div in range(0,5): peak.append(prop_dict[div]) sum_peak = sum(peak) rps = sum_peak/total divpeak = top_div out.write(el[0]+"\t"+str(sum(numbers))+"\n") all_divs = [] for d in li[0][1:]: all_divs.append(int(d)+0.5) div_sumproduct = 0 for x,y in zip(all_divs,prop_li): div_sumproduct += x * y divergence = div_sumproduct/total data = "%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (el[0],str(divergence),str(total),str(top_ab),str(sum_peak),str(rps),str(divpeak)) stats.write(data) data2 = "%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (file, str(divergence),str(total),str(top_ab),str(sum_peak),str(rps),str(divpeak)) if el[0] in results: results[el[0]].append(data2) else: results[el[0]] = [data2] out.close() stats.close() to_join.append(file+".counts") out = open("results.txt", "w") for el in sorted(results): info = results[el] out.write("%s\tDivergence\tTotalAbundance\tMaxAbundance\tMaxPeak\tRPS\tDIVPEAK\n" % (el)) for i in info: out.write(i) out.write("\n\n\n") out.close() call("join_multiple_lists.py %s" % (" ".join(to_join)), shell=True)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 25064, 198, 6738, 850, 14681, 1330, 869, 198, 198, 4798, 366, 7146, 16345, 62, 9127, 13, 9078, 7343, 5189, 24095, 16345, 25876, 59, 77, 1, 198, 198, 28311, 25, 198, 220, 220, 22...
1.994067
1,517
#!/usr/bin/env python from agatecharts.charts.bars import Bars from agatecharts.charts.columns import Columns from agatecharts.charts.lines import Lines from agatecharts.charts.scatter import Scatter
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 556, 40340, 5889, 13, 354, 5889, 13, 34046, 1330, 39924, 198, 6738, 556, 40340, 5889, 13, 354, 5889, 13, 28665, 82, 1330, 29201, 82, 198, 6738, 556, 40340, 5889, 13, 354, ...
3.241935
62
from django.contrib.auth import update_session_auth_hash from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from django.contrib.auth.views import (LoginView, PasswordResetConfirmView, PasswordResetView) from django.http import HttpResponse, HttpResponseNotAllowed from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView, DeleteView, UpdateView from users.forms import (SignInForm, SignUpForm, UserPasswordResetForm, UserProfileForm, UserSetPasswordForm) from users.mixins import LockDuringEditMixin from users.models import Lock, UserSession def unlock(request, pk): if request.method == "POST": lock = Lock.objects.filter(pk=pk).delete() return HttpResponse('') return HttpResponseNotAllowed(["POST"])
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 4296, 62, 29891, 62, 18439, 62, 17831, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 19816, 1040, 1330, 23093, 37374, 35608, 259, 198, 6738, 42625, 14208, 13, 3642, 822, 13, ...
2.785933
327
import os from test.core.emr_system_unit_test_base import EMRSystemUnitTestBase from test.core.tconx_helper import TconxHelper
[ 11748, 28686, 198, 198, 6738, 1332, 13, 7295, 13, 368, 81, 62, 10057, 62, 20850, 62, 9288, 62, 8692, 1330, 17228, 6998, 6781, 26453, 14402, 14881, 198, 6738, 1332, 13, 7295, 13, 83, 1102, 87, 62, 2978, 525, 1330, 309, 1102, 87, 4742...
2.931818
44
from rest_framework import serializers from metrics.models import Metrics_Cpu, Metrics_PingServer, Metrics_MountPoint, \ Metrics_CpuLoad, Metrics_PingDb
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 6738, 20731, 13, 27530, 1330, 3395, 10466, 62, 34, 19944, 11, 3395, 10466, 62, 49806, 10697, 11, 3395, 10466, 62, 35452, 12727, 11, 3467, 198, 220, 220, 220, 3395, 10466, 62, 34, 19944, ...
3.204082
49
# Copyright 2020 Plezentek, 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. load( "//sqlc/private:providers.bzl", "SQLCRelease", ) load( "//sqlc/private/rules_go/lib:platforms.bzl", "PLATFORMS", ) sqlc_toolchain = rule( _sqlc_toolchain_impl, attrs = { "goos": attr.string( mandatory = True, doc = "Default target OS", ), "goarch": attr.string( mandatory = True, doc = "Default target architecture", ), "release": attr.label( mandatory = True, providers = [SQLCRelease], cfg = "exec", doc = "The SQLC release this toolchain is based on", ), }, doc = "Defines a SQLC toolchain based on a release", provides = [platform_common.ToolchainInfo], )
[ 2, 15069, 12131, 18063, 89, 298, 988, 11, 3457, 13, 1439, 2489, 10395, 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...
2.56381
525
root = { "general" : { "display_viewer" : False, #The visible GPUS will be restricted to the numbers listed here. The pytorch (cuda:0) numeration will start at 0 #This is a trick to get everything onto the wanted gpus because just setting cuda:4 in the function calls will #not work for mmdetection. There will still be things on gpu cuda:0. "cuda_visible_devices" : "1", "save_track_results" : True }, "data" : { # To increase the speed while developing an specific interval of all frames can be set. "selection_interval" : [0,10000], "source" : { "base_folder" : "/u40/zhanr110/MTA_ext_short/test", # "base_folder" : "/Users/nolanzhang/Projects/mtmct/data/MTA_ext_short/test", "cam_ids" : [1] } }, "detector" : { # "mmdetection_config" : "detectors/mmdetection/configs/faster_rcnn_r50_fpn_1x_gta.py", "mmdetection_config" : "detectors/mmdetection/configs/mta/faster_rcnn_r50_mta.py", # "mmdetection_checkpoint_file" : "work_dirs/detector/faster_rcnn_gta22.07_epoch_5.pth", "mmdetection_checkpoint_file" : "detectors/mmdetection/work_dirs/GtaDataset_30e/epoch_20.pth", "device" : "cuda:0", #Remove all detections with a confidence less than min_confidence "min_confidence" : 0.8, }, "feature_extractor" : { "feature_extractor_name" : "abd_net_extractor" ,"reid_strong_extractor": { "reid_strong_baseline_config": "feature_extractors/reid_strong_baseline/configs/softmax_triplet.yml", "checkpoint_file": "work_dirs/feature_extractor/strong_reid_baseline/resnet50_model_reid_GTA_softmax_triplet.pth", "device": "cuda:0,1" ,"visible_device" : "0,1"} ,"abd_net_extractor" : dict(abd_dan=['cam', 'pam'], abd_dan_no_head=False, abd_dim=1024, abd_np=2, adam_beta1=0.9, adam_beta2=0.999, arch='resnet50', branches=['global', 'abd'], compatibility=False, criterion='htri', cuhk03_classic_split=False, cuhk03_labeled=False, dan_dan=[], dan_dan_no_head=False, dan_dim=1024, data_augment=['crop,random-erase'], day_only=False, dropout=0.5, eval_freq=5, evaluate=False, fixbase=False, fixbase_epoch=10, flip_eval=False, gamma=0.1, global_dim=1024, global_max_pooling=False, gpu_devices='1', height=384, htri_only=False, label_smooth=True, lambda_htri=0.1, lambda_xent=1, lr=0.0003, margin=1.2, max_epoch=80, min_height=-1, momentum=0.9, night_only=False, np_dim=1024, np_max_pooling=False, np_np=2, np_with_global=False, num_instances=4, of_beta=1e-06, of_position=['before', 'after', 'cam', 'pam', 'intermediate'], of_start_epoch=23, open_layers=['classifier'], optim='adam', ow_beta=0.001, pool_tracklet_features='avg', print_freq=10, resume='', rmsprop_alpha=0.99 , load_weights='work_dirs/feature_extractor/abd-net/checkpoint_ep30_non_clean.pth.tar' # , load_weights='work_dirs/feature_extractor/abd-net/resnet50-19c8e357.pth' , root='work_dirs/datasets' , sample_method='evenly' , save_dir='work_dirs/feature_extractor/abd-net/log/eval-resnet50' , seed=1, seq_len=15, sgd_dampening=0, sgd_nesterov=False, shallow_cam=True, source_names=['mta_ext'], split_id=0, start_epoch=0, start_eval=0, stepsize=[20, 40], target_names=['market1501'], test_batch_size=100, train_batch_size=64, train_sampler='', use_avai_gpus=False, use_cpu=False, use_metric_cuhk03=False, use_of=True, use_ow=True, visualize_ranks=False, weight_decay=0.0005, width=128, workers=4) }, "tracker" : { "type" : "DeepSort", "nn_budget" : 100 } }
[ 15763, 796, 1391, 628, 220, 220, 220, 366, 24622, 1, 1058, 1391, 628, 220, 220, 220, 220, 220, 220, 220, 366, 13812, 62, 1177, 263, 1, 1058, 10352, 11, 198, 220, 220, 220, 220, 220, 220, 220, 1303, 464, 7424, 14714, 2937, 481, 307...
2.001486
2,019
from ..utils import TranspileTestCase
[ 6738, 11485, 26791, 1330, 3602, 79, 576, 14402, 20448, 628 ]
3.9
10
''' ------------------------------------------------------------------------ Functions for taxes in the steady state and along the transition path. ------------------------------------------------------------------------ ''' # Packages import numpy as np from ogusa import utils ''' ------------------------------------------------------------------------ Functions ------------------------------------------------------------------------ ''' def replacement_rate_vals(nssmat, wss, factor_ss, j, p): ''' Calculates replacement rate values for the social security system. Args: nssmat (Numpy array): initial guess at labor supply, size = SxJ new_w (scalar): steady state real wage rate factor_ss (scalar): scaling factor converting model units to dollars j (int): index of lifetime income group p (OG-USA Specifications object): model parameters Returns: theta (Numpy array): social security replacement rate value for lifetime income group j ''' if j is not None: e = p.e[:, j] else: e = p.e # adjust number of calendar years AIME computed from int model periods equiv_periods = int(round((p.S / 80.0) * p.AIME_num_years)) - 1 if e.ndim == 2: dim2 = e.shape[1] else: dim2 = 1 earnings = (e * (wss * nssmat * factor_ss)).reshape(p.S, dim2) # get highest earning years for number of years AIME computed from highest_earn =\ (-1.0 * np.sort(-1.0 * earnings[:p.retire[-1], :], axis=0))[:equiv_periods] AIME = highest_earn.sum(0) / ((12.0 * (p.S / 80.0)) * equiv_periods) PIA = np.zeros(dim2) # Compute level of replacement using AIME brackets and PIA rates for j in range(dim2): if AIME[j] < p.AIME_bkt_1: PIA[j] = p.PIA_rate_bkt_1 * AIME[j] elif AIME[j] < p.AIME_bkt_2: PIA[j] = (p.PIA_rate_bkt_1 * p.AIME_bkt_1 + p.PIA_rate_bkt_2 * (AIME[j] - p.AIME_bkt_1)) else: PIA[j] = (p.PIA_rate_bkt_1 * p.AIME_bkt_1 + p.PIA_rate_bkt_2 * (p.AIME_bkt_2 - p.AIME_bkt_1) + p.PIA_rate_bkt_3 * (AIME[j] - p.AIME_bkt_2)) # Set the maximum monthly replacment rate from SS benefits tables PIA[PIA > p.PIA_maxpayment] = p.PIA_maxpayment if p.PIA_minpayment != 0.0: PIA[PIA < p.PIA_minpayment] = p.PIA_minpayment theta = (PIA * (12.0 * p.S / 80.0)) / (factor_ss * wss) return theta def ETR_wealth(b, h_wealth, m_wealth, p_wealth): r''' Calculates the effective tax rate on wealth. .. math:: T_{j,s,t}^{w} = \frac{h^{w}p_{w}b_{j,s,t}}{h^{w}b_{j,s,t} + m^{w}} Args: b (Numpy array): savings h_wealth (scalar): parameter of wealth tax function p_wealth (scalar): parameter of wealth tax function m_wealth (scalar): parameter of wealth tax function Returns: tau_w (Numpy array): effective tax rate on wealth, size = SxJ ''' tau_w = (p_wealth * h_wealth * b) / (h_wealth * b + m_wealth) return tau_w def MTR_wealth(b, h_wealth, m_wealth, p_wealth): r''' Calculates the marginal tax rate on wealth from the wealth tax. .. math:: \frac{\partial T_{j,s,t}^{w}}{\partial b_{j,s,t}} = \frac{h^{w}m^{w}p_{w}}{(b_{j,s,t}h^{w}m^{w})^{2}} Args: b (Numpy array): savings h_wealth (scalar): parameter of wealth tax function p_wealth (scalar): parameter of wealth tax function m_wealth (scalar): parameter of wealth tax function Returns: tau_prime (Numpy array): marginal tax rate on wealth, size = SxJ ''' tau_prime = ((b * h_wealth * m_wealth * p_wealth) / ((b * h_wealth + m_wealth) ** 2) + ETR_wealth(b, h_wealth, m_wealth, p_wealth)) return tau_prime def ETR_income(r, w, b, n, factor, e, etr_params, p): ''' Calculates effective personal income tax rate. Args: r (array_like): real interest rate w (array_like): real wage rate b (Numpy array): savings n (Numpy array): labor supply factor (scalar): scaling factor converting model units to dollars e (Numpy array): effective labor units etr_params (Numpy array): effective tax rate function parameters p (OG-USA Specifications object): model parameters Returns: tau (Numpy array): effective tax rate on total income ''' X = (w * e * n) * factor Y = (r * b) * factor X2 = X ** 2 Y2 = Y ** 2 income = X + Y income2 = income ** 2 if p.tax_func_type == 'GS': phi0 = np.squeeze(etr_params[..., 0]) phi1 = np.squeeze(etr_params[..., 1]) phi2 = np.squeeze(etr_params[..., 2]) tau = ((phi0 * (income - ((income ** -phi1) + phi2) ** (-1 / phi1))) / income) elif p.tax_func_type == 'DEP_totalinc': A = np.squeeze(etr_params[..., 0]) B = np.squeeze(etr_params[..., 1]) max_income = np.squeeze(etr_params[..., 4]) min_income = np.squeeze(etr_params[..., 5]) shift_income = np.squeeze(etr_params[..., 8]) shift = np.squeeze(etr_params[..., 10]) tau_income = (((max_income - min_income) * (A * income2 + B * income) / (A * income2 + B * income + 1)) + min_income) tau = tau_income + shift_income + shift else: # DEP or linear A = np.squeeze(etr_params[..., 0]) B = np.squeeze(etr_params[..., 1]) C = np.squeeze(etr_params[..., 2]) D = np.squeeze(etr_params[..., 3]) max_x = np.squeeze(etr_params[..., 4]) min_x = np.squeeze(etr_params[..., 5]) max_y = np.squeeze(etr_params[..., 6]) min_y = np.squeeze(etr_params[..., 7]) shift_x = np.squeeze(etr_params[..., 8]) shift_y = np.squeeze(etr_params[..., 9]) shift = np.squeeze(etr_params[..., 10]) share = np.squeeze(etr_params[..., 11]) tau_x = ((max_x - min_x) * (A * X2 + B * X) / (A * X2 + B * X + 1) + min_x) tau_y = ((max_y - min_y) * (C * Y2 + D * Y) / (C * Y2 + D * Y + 1) + min_y) tau = (((tau_x + shift_x) ** share) * ((tau_y + shift_y) ** (1 - share))) + shift return tau def MTR_income(r, w, b, n, factor, mtr_capital, e, etr_params, mtr_params, p): r''' Generates the marginal tax rate on labor income for households. Args: r (array_like): real interest rate w (array_like): real wage rate b (Numpy array): savings n (Numpy array): labor supply factor (scalar): scaling factor converting model units to dollars mtr_capital (bool): whether to compute the marginal tax rate on capital income or labor income e (Numpy array): effective labor units etr_params (Numpy array): effective tax rate function parameters p (OG-USA Specifications object): model parameters Returns: tau (Numpy array): marginal tax rate on income source ''' X = (w * e * n) * factor Y = (r * b) * factor X2 = X ** 2 Y2 = Y ** 2 income = X + Y income2 = income ** 2 if p.tax_func_type == 'GS': if p.analytical_mtrs: phi0 = np.squeeze(etr_params[..., 0]) phi1 = np.squeeze(etr_params[..., 1]) phi2 = np.squeeze(etr_params[..., 2]) else: phi0 = np.squeeze(mtr_params[..., 0]) phi1 = np.squeeze(mtr_params[..., 1]) phi2 = np.squeeze(mtr_params[..., 2]) tau = (phi0*(1 - (income ** (-phi1 - 1) * ((income ** -phi1) + phi2) ** ((-1 - phi1) / phi1)))) elif p.tax_func_type == 'DEP_totalinc': if p.analytical_mtrs: A = np.squeeze(etr_params[..., 0]) B = np.squeeze(etr_params[..., 1]) max_income = np.squeeze(etr_params[..., 4]) min_income = np.squeeze(etr_params[..., 5]) shift_income = np.squeeze(etr_params[..., 8]) shift = np.squeeze(etr_params[..., 10]) d_etr = ((max_income - min_income) * ((2 * A * income + B) / ((A * income2 + B * income + 1) ** 2))) etr = (((max_income - min_income) * ((A * income2 + B * income) / (A * income2 + B * income + 1)) + min_income) + shift_income + shift) tau = (d_etr * income) + (etr) else: A = np.squeeze(mtr_params[..., 0]) B = np.squeeze(mtr_params[..., 1]) max_income = np.squeeze(mtr_params[..., 4]) min_income = np.squeeze(mtr_params[..., 5]) shift_income = np.squeeze(mtr_params[..., 8]) shift = np.squeeze(mtr_params[..., 10]) tau_income = (((max_income - min_income) * (A * income2 + B * income) / (A * income2 + B * income + 1)) + min_income) tau = tau_income + shift_income + shift else: # DEP or linear if p.analytical_mtrs: A = np.squeeze(etr_params[..., 0]) B = np.squeeze(etr_params[..., 1]) C = np.squeeze(etr_params[..., 2]) D = np.squeeze(etr_params[..., 3]) max_x = np.squeeze(etr_params[..., 4]) min_x = np.squeeze(etr_params[..., 5]) max_y = np.squeeze(etr_params[..., 6]) min_y = np.squeeze(etr_params[..., 7]) shift_x = np.squeeze(etr_params[..., 8]) shift_y = np.squeeze(etr_params[..., 9]) shift = np.squeeze(etr_params[..., 10]) share = np.squeeze(etr_params[..., 11]) tau_x = ((max_x - min_x) * (A * X2 + B * X) / (A * X2 + B * X + 1) + min_x) tau_y = ((max_y - min_y) * (C * Y2 + D * Y) / (C * Y2 + D * Y + 1) + min_y) etr = (((tau_x + shift_x) ** share) * ((tau_y + shift_y) ** (1 - share))) + shift if mtr_capital: d_etr = ((1-share) * ((tau_y + shift_y) ** (-share)) * (max_y - min_y) * ((2 * C * Y + D) / ((C * Y2 + D * Y + 1) ** 2)) * ((tau_x + shift_x) ** share)) tau = d_etr * income + etr else: d_etr = (share * ((tau_x + shift_x) ** (share - 1)) * (max_x - min_x) * ((2 * A * X + B) / ((A * X2 + B * X + 1) ** 2)) * ((tau_y + shift_y) ** (1 - share))) tau = d_etr * income + etr else: A = np.squeeze(mtr_params[..., 0]) B = np.squeeze(mtr_params[..., 1]) C = np.squeeze(mtr_params[..., 2]) D = np.squeeze(mtr_params[..., 3]) max_x = np.squeeze(mtr_params[..., 4]) min_x = np.squeeze(mtr_params[..., 5]) max_y = np.squeeze(mtr_params[..., 6]) min_y = np.squeeze(mtr_params[..., 7]) shift_x = np.squeeze(mtr_params[..., 8]) shift_y = np.squeeze(mtr_params[..., 9]) shift = np.squeeze(mtr_params[..., 10]) share = np.squeeze(mtr_params[..., 11]) tau_x = ((max_x - min_x) * (A * X2 + B * X) / (A * X2 + B * X + 1) + min_x) tau_y = ((max_y - min_y) * (C * Y2 + D * Y) / (C * Y2 + D * Y + 1) + min_y) tau = (((tau_x + shift_x) ** share) * ((tau_y + shift_y) ** (1 - share))) + shift return tau def get_biz_tax(w, Y, L, K, p, method): r''' Finds total business income tax revenue. .. math:: R_{t}^{b} = \tau_{t}^{b}(Y_{t} - w_{t}L_{t}) - \tau_{t}^{b}\delta_{t}^{\tau}K_{t}^{\tau} Args: r (array_like): real interest rate Y (array_like): aggregate output L (array_like): aggregate labor demand K (array_like): aggregate capital demand Returns: business_revenue (array_like): aggregate business tax revenue ''' if method == 'SS': delta_tau = p.delta_tau[-1] tau_b = p.tau_b[-1] else: delta_tau = p.delta_tau[:p.T] tau_b = p.tau_b[:p.T] business_revenue = tau_b * (Y - w * L) - tau_b * delta_tau * K return business_revenue def net_taxes(r, w, b, n, bq, factor, tr, theta, t, j, shift, method, e, etr_params, p): ''' Calculate net taxes paid for each household. Args: r (array_like): real interest rate w (array_like): real wage rate b (Numpy array): savings n (Numpy array): labor supply bq (Numpy array): bequests received factor (scalar): scaling factor converting model units to dollars tr (Numpy array): government transfers to the household theta (Numpy array): social security replacement rate value for lifetime income group j t (int): time period j (int): index of lifetime income group shift (bool): whether computing for periods 0--s or 1--(s+1), =True for 1--(s+1) method (str): adjusts calculation dimensions based on 'SS' or 'TPI' e (Numpy array): effective labor units etr_params (Numpy array): effective tax rate function parameters p (OG-USA Specifications object): model parameters Returns: net_tax (Numpy array): net taxes paid for each household ''' T_I = income_tax_liab(r, w, b, n, factor, t, j, method, e, etr_params, p) pension = pension_amount(w, n, theta, t, j, shift, method, e, p) T_BQ = bequest_tax_liab(r, b, bq, t, j, method, p) T_W = wealth_tax_liab(r, b, t, j, method, p) net_tax = T_I - pension + T_BQ + T_W - tr return net_tax def income_tax_liab(r, w, b, n, factor, t, j, method, e, etr_params, p): ''' Calculate income and payroll tax liability for each household Args: r (array_like): real interest rate w (array_like): real wage rate b (Numpy array): savings n (Numpy array): labor supply factor (scalar): scaling factor converting model units to dollars t (int): time period j (int): index of lifetime income group method (str): adjusts calculation dimensions based on 'SS' or 'TPI' e (Numpy array): effective labor units etr_params (Numpy array): effective tax rate function parameters p (OG-USA Specifications object): model parameters Returns: T_I (Numpy array): total income and payroll taxes paid for each household ''' if j is not None: if method == 'TPI': if b.ndim == 2: r = r.reshape(r.shape[0], 1) w = w.reshape(w.shape[0], 1) else: if method == 'TPI': r = utils.to_timepath_shape(r) w = utils.to_timepath_shape(w) income = r * b + w * e * n labor_income = w * e * n T_I = ETR_income(r, w, b, n, factor, e, etr_params, p) * income if method == 'SS': T_P = p.tau_payroll[-1] * labor_income elif method == 'TPI': length = w.shape[0] if len(b.shape) == 1: T_P = p.tau_payroll[t: t + length] * labor_income elif len(b.shape) == 2: T_P = (p.tau_payroll[t: t + length].reshape(length, 1) * labor_income) else: T_P = (p.tau_payroll[t:t + length].reshape(length, 1, 1) * labor_income) elif method == 'TPI_scalar': T_P = p.tau_payroll[0] * labor_income income_payroll_tax_liab = T_I + T_P return income_payroll_tax_liab def pension_amount(w, n, theta, t, j, shift, method, e, p): ''' Calculate public pension benefit amounts for each household. Args: w (array_like): real wage rate n (Numpy array): labor supply theta (Numpy array): social security replacement rate value for lifetime income group j t (int): time period j (int): index of lifetime income group shift (bool): whether computing for periods 0--s or 1--(s+1), =True for 1--(s+1) method (str): adjusts calculation dimensions based on 'SS' or 'TPI' e (Numpy array): effective labor units p (OG-USA Specifications object): model parameters Returns: pension (Numpy array): pension amount for each household ''' if j is not None: if method == 'TPI': if n.ndim == 2: w = w.reshape(w.shape[0], 1) else: if method == 'TPI': w = utils.to_timepath_shape(w) pension = np.zeros_like(n) if method == 'SS': # Depending on if we are looking at b_s or b_s+1, the # entry for retirement will change (it shifts back one). # The shift boolean makes sure we start replacement rates # at the correct age. if shift is False: pension[p.retire[-1]:] = theta * w else: pension[p.retire[-1] - 1:] = theta * w elif method == 'TPI': length = w.shape[0] if not shift: # retireTPI is different from retire, because in TP income # we are counting backwards with different length lists. # This will always be the correct location of retirement, # depending on the shape of the lists. retireTPI = (p.retire[t: t + length] - p.S) else: retireTPI = (p.retire[t: t + length] - 1 - p.S) if len(n.shape) == 1: if not shift: retireTPI = p.retire[t] - p.S else: retireTPI = p.retire[t] - 1 - p.S pension[retireTPI:] = ( theta[j] * p.replacement_rate_adjust[t] * w[retireTPI:]) elif len(n.shape) == 2: for tt in range(pension.shape[0]): pension[tt, retireTPI[tt]:] = ( theta * p.replacement_rate_adjust[t + tt] * w[tt]) else: for tt in range(pension.shape[0]): pension[tt, retireTPI[tt]:, :] = ( theta.reshape(1, p.J) * p.replacement_rate_adjust[t + tt] * w[tt]) elif method == 'TPI_scalar': # The above methods won't work if scalars are used. This option # is only called by the SS_TPI_firstdoughnutring function in TPI. pension = theta * p.replacement_rate_adjust[0] * w return pension def wealth_tax_liab(r, b, t, j, method, p): ''' Calculate wealth tax liability for each household. Args: r (array_like): real interest rate b (Numpy array): savings t (int): time period j (int): index of lifetime income group method (str): adjusts calculation dimensions based on 'SS' or 'TPI' p (OG-USA Specifications object): model parameters Returns: T_W (Numpy array): wealth tax liability for each household ''' if j is not None: if method == 'TPI': if b.ndim == 2: r = r.reshape(r.shape[0], 1) else: if method == 'TPI': r = utils.to_timepath_shape(r) if method == 'SS': T_W = (ETR_wealth(b, p.h_wealth[-1], p.m_wealth[-1], p.p_wealth[-1]) * b) elif method == 'TPI': length = r.shape[0] if len(b.shape) == 1: T_W = (ETR_wealth(b, p.h_wealth[t:t + length], p.m_wealth[t:t + length], p.p_wealth[t:t + length]) * b) elif len(b.shape) == 2: T_W = (ETR_wealth(b, p.h_wealth[t:t + length], p.m_wealth[t:t + length], p.p_wealth[t:t + length]) * b) else: T_W = (ETR_wealth( b, p.h_wealth[t:t + length].reshape(length, 1, 1), p.m_wealth[t:t + length].reshape(length, 1, 1), p.p_wealth[t:t + length].reshape(length, 1, 1)) * b) elif method == 'TPI_scalar': T_W = (ETR_wealth(b, p.h_wealth[0], p.m_wealth[0], p.p_wealth[0]) * b) return T_W def bequest_tax_liab(r, b, bq, t, j, method, p): ''' Calculate liability due from taxes on bequests for each household. Args: r (array_like): real interest rate b (Numpy array): savings bq (Numpy array): bequests received t (int): time period j (int): index of lifetime income group method (str): adjusts calculation dimensions based on 'SS' or 'TPI' p (OG-USA Specifications object): model parameters Returns: T_BQ (Numpy array): bequest tax liability for each household ''' if j is not None: lambdas = p.lambdas[j] if method == 'TPI': if b.ndim == 2: r = r.reshape(r.shape[0], 1) else: lambdas = np.transpose(p.lambdas) if method == 'TPI': r = utils.to_timepath_shape(r) if method == 'SS': T_BQ = p.tau_bq[-1] * bq elif method == 'TPI': length = r.shape[0] if len(b.shape) == 1: T_BQ = p.tau_bq[t:t + length] * bq elif len(b.shape) == 2: T_BQ = p.tau_bq[t:t + length].reshape(length, 1) * bq / lambdas else: T_BQ = p.tau_bq[t:t + length].reshape(length, 1, 1) * bq elif method == 'TPI_scalar': # The above methods won't work if scalars are used. This option # is only called by the SS_TPI_firstdoughnutring function in TPI. T_BQ = p.tau_bq[0] * bq return T_BQ
[ 7061, 6, 198, 10097, 982, 198, 24629, 2733, 329, 5704, 287, 262, 11831, 1181, 290, 1863, 262, 6801, 3108, 13, 198, 10097, 982, 198, 7061, 6, 198, 198, 2, 6400, 1095, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 267, 70, 22064, 133...
1.972898
11,180
"""Module containing the taxonomy items API endpoints of the v1 API.""" from datetime import datetime from sqlalchemy.sql.schema import Sequence from muse_for_anything.db.models.taxonomies import ( Taxonomy, TaxonomyItem, TaxonomyItemRelation, TaxonomyItemVersion, ) from marshmallow.utils import INCLUDE from flask_babel import gettext from muse_for_anything.api.util import template_url_for from typing import Any, Callable, Dict, List, Optional, Union, cast from flask.helpers import url_for from flask.views import MethodView from sqlalchemy.sql.expression import asc, desc, literal from sqlalchemy.orm.query import Query from sqlalchemy.orm import selectinload from flask_smorest import abort from http import HTTPStatus from .root import API_V1 from ..base_models import ( ApiLink, ApiResponse, ChangedApiObject, ChangedApiObjectSchema, CursorPage, CursorPageArgumentsSchema, CursorPageSchema, DynamicApiResponseSchema, NewApiObject, NewApiObjectSchema, ) from ...db.db import DB from ...db.pagination import get_page_info from ...db.models.namespace import Namespace from ...db.models.ontology_objects import OntologyObjectType, OntologyObjectTypeVersion from .models.ontology import ( TaxonomyItemRelationPostSchema, TaxonomyItemRelationSchema, TaxonomyItemSchema, TaxonomySchema, ) from .namespace_helpers import ( query_params_to_api_key, ) from .taxonomy_helpers import ( action_links_for_taxonomy_item, action_links_for_taxonomy_item_relation, create_action_link_for_taxonomy_item_relation_page, nav_links_for_taxonomy_item, nav_links_for_taxonomy_item_relation, taxonomy_item_relation_to_api_link, taxonomy_item_relation_to_api_response, taxonomy_item_relation_to_taxonomy_item_relation_data, taxonomy_item_to_api_link, taxonomy_item_to_api_response, taxonomy_item_to_taxonomy_item_data, taxonomy_to_api_response, taxonomy_to_items_links, taxonomy_to_taxonomy_data, )
[ 37811, 26796, 7268, 262, 1687, 30565, 3709, 7824, 886, 13033, 286, 262, 410, 16, 7824, 526, 15931, 198, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 44161, 282, 26599, 13, 25410, 13, 15952, 2611, 1330, 45835, 198, 6738, 2681...
2.816412
719
import matplotlib.pyplot as plt import numpy as np import pandas as pd df = pd.read_csv('transcount.csv') df = df.groupby('year').aggregate(np.mean) gpu = pd.read_csv('gpu_transcount.csv') gpu = gpu.groupby('year').aggregate(np.mean) df = pd.merge(df, gpu, how='outer', left_index=True, right_index=True) df = df.replace(np.nan, 0) df.plot() df.plot(logy=True) df[df['gpu_trans_count'] > 0].plot(kind='scatter', x='trans_count', y='gpu_trans_count', loglog=True) plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 628, 198, 7568, 796, 279, 67, 13, 961, 62, 40664, 10786, 7645, 9127, 13, 40664, 11537, 198, 7568, 796, ...
2.414141
198
# Generated by Django 2.0.5 on 2018-07-02 19:46 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 20, 319, 2864, 12, 2998, 12, 2999, 678, 25, 3510, 201, 198, 201, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 201, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 293...
2.58
50
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) n = int(readline()) h = int(readline()) w = int(readline()) print((n - h + 1) * (n - w + 1))
[ 11748, 25064, 198, 961, 796, 25064, 13, 19282, 259, 13, 22252, 13, 961, 198, 961, 1370, 796, 25064, 13, 19282, 259, 13, 22252, 13, 961, 1370, 198, 961, 6615, 796, 25064, 13, 19282, 259, 13, 22252, 13, 961, 6615, 198, 17597, 13, 2617...
2.56383
94
import pygame from NetworkBroadcast import Broadcast, AnimatedSprite, DeleteSpriteCommand from Textures import HALO_SPRITE12, HALO_SPRITE14, HALO_SPRITE13 __author__ = "Yoann Berenguer" __credits__ = ["Yoann Berenguer"] __version__ = "1.0.0" __maintainer__ = "Yoann Berenguer" __email__ = "yoyoberenguer@hotmail.com"
[ 201, 198, 11748, 12972, 6057, 201, 198, 6738, 7311, 30507, 2701, 1330, 44244, 11, 36492, 38454, 578, 11, 23520, 38454, 578, 21575, 201, 198, 6738, 8255, 942, 1330, 42968, 46, 62, 4303, 49, 12709, 1065, 11, 42968, 46, 62, 4303, 49, 127...
2.459854
137
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import logging import os.path import subprocess from collections import OrderedDict from itertools import izip import numpy as np import pandas as pd from django.conf import settings from django.core.cache import cache from django.db import connection from sqlalchemy import create_engine from dataops.formula_evaluation import evaluate_node_sql from ontask import fix_pctg_in_name SITE_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) table_prefix = '__ONTASK_WORKFLOW_TABLE_' df_table_prefix = table_prefix + '{0}' upload_table_prefix = table_prefix + 'UPLOAD_{0}' # Query to count the number of rows in a table query_count_rows = 'SELECT count(*) from "{0}"' logger = logging.getLogger(__name__) # Translation between pandas data type names, and those handled in OnTask pandas_datatype_names = { 'object': 'string', 'int64': 'integer', 'float64': 'double', 'bool': 'boolean', 'datetime64[ns]': 'datetime' } # Translation between SQL data type names, and those handled in OnTask sql_datatype_names = { 'text': 'string', 'bigint': 'integer', 'double precision': 'double', 'boolean': 'boolean', 'timestamp without time zone': 'datetime' } # DB Engine to use with Pandas (required by to_sql, from_sql engine = None def create_db_connection(dialect, driver, username, password, host, dbname): """ Function that creates the engine object to connect to the database. The object is required by the pandas functions to_sql and from_sql :param dialect: Dialect for the engine (oracle, mysql, postgresql, etc) :param driver: DBAPI driver (psycopg2, ...) :param username: Username to connect with the database :param password: Password to connect with the database :param host: Host to connect with the database :param dbname: database name :return: the engine """ # DB engine database_url = \ '{dialect}{driver}://{user}:{password}@{host}/{database_name}'.format( dialect=dialect, driver=driver, user=username, password=password, host=host, database_name=dbname, ) return create_engine(database_url, echo=False, paramstyle='format') def create_db_engine(dialect, driver, username, password, host, dbname): """ Function that creates the engine object to connect to the database. The object is required by the pandas functions to_sql and from_sql :param dialect: Dialect for the engine (oracle, mysql, postgresql, etc) :param driver: DBAPI driver (psycopg2, ...) :param username: Username to connect with the database :param password: Password to connect with the database :param host: Host to connect with the database :param dbname: database name :return: the engine """ # DB engine database_url = \ '{dialect}{driver}://{user}:{password}@{host}/{database_name}'.format( dialect=dialect, driver=driver, user=username, password=password, host=host, database_name=dbname, ) engine = create_db_connection(dialect, driver, username, password, host, dbname) if settings.DEBUG: print('Creating engine with ', database_url) return engine def destroy_db_engine(db_engine): """ Method that disposes of the given engine (to guarantee there are no connections available :param db_engine: Engine to destroy :return: Nothing """ db_engine.dispose() def pg_restore_table(filename): """ Function that given a file produced with a pg_dump, it uploads its content to the existing database :param filename: File in pg_dump format to restore :return: """ process = subprocess.Popen(['psql', '-d', settings.DATABASES['default']['NAME'], '-q', '-f', filename]) process.wait() def delete_all_tables(): """ Delete all tables related to existing workflows :return: """ cursor = connection.cursor() table_list = connection.introspection.get_table_list(cursor) for tinfo in table_list: if not tinfo.name.startswith(table_prefix): continue cursor.execute('DROP TABLE "{0}";'.format(tinfo.name)) # To make sure the table is dropped. connection.commit() return def create_table_name(pk): """ :param pk: Primary Key of a workflow :return: The unique table name to use to store a workflow data frame """ return df_table_prefix.format(pk) def create_upload_table_name(pk): """ :param pk: Primary key of a workflow :return: The unique table to use to upload a new data frame """ return upload_table_prefix.format(pk) def load_from_db(pk, columns=None, filter_exp=None): """ Load the data frame stored for the workflow with the pk :param pk: Primary key of the workflow :param columns: Optional list of columns to load (all if NOne is given) :param filter_exp: JSON expression to filter a subset of rows :return: data frame """ return load_table(create_table_name(pk), columns=columns, filter_exp=filter_exp) def load_table(table_name, columns=None, filter_exp=None): """ Load a data frame from the SQL DB. FUTURE WORK: Consider to store the dataframes in Redis to reduce load/store time. The trick is to use a compressed format: SET: redisConn.set("key", df.to_msgpack(compress='zlib')) GET: pd.read_msgpack(redisConn.get("key")) Need to agree on a sensible item name that does not collide with anything else and a policy to detect a cached dataframe and remove it when the data changes (difficult to detect? Perhaps df_new.equals(df_current)) If feasible, a write-through system could be easily implemented. :param table_name: Table name to read from the db in to data frame :param view: Optional view object to restrict access to the DB :return: data_frame or None if it does not exist. """ if table_name not in connection.introspection.table_names(): return None if settings.DEBUG: print('Loading table ', table_name) if columns or filter_exp: # A list of columns or a filter exp is given query, params = get_filter_query(table_name, columns, filter_exp) result = pd.read_sql_query(query, engine, params=params) else: # No view given, so simply get the whole table result = pd.read_sql(table_name, engine) # After reading from the DB, turn all None into NaN result.fillna(value=np.nan, inplace=True) return result def load_query(query): """ Load a data frame from the SQL DB running the given query. :param query: Query to run in the DB :return: data_frame or None if it does not exist. """ if settings.DEBUG: print('Loading query ', query) result = pd.read_sql_query(query, engine) # After reading from the DB, turn all None into NaN result.fillna(value=np.nan, inplace=True) return result def load_df_from_csvfile(file, skiprows=0, skipfooter=0): """ Given a file object, try to read the content as a CSV file and transform into a data frame. The skiprows and skipfooter are number of lines to skip from the top and bottom of the file (see read_csv in pandas). It also tries to convert as many columns as possible to date/time format (testing the conversion on every string column). :param filename: File object to read the CSV content :param skiprows: Number of lines to skip at the top of the document :param skipfooter: Number of lines to skip at the bottom of the document :return: Resulting data frame, or an Exception. """ data_frame = pd.read_csv( file, index_col=False, infer_datetime_format=True, quotechar='"', skiprows=skiprows, skipfooter=skipfooter ) # Strip white space from all string columns and try to convert to # datetime just in case for x in list(data_frame.columns): if data_frame[x].dtype.name == 'object': # Column is a string! Remove the leading and trailing white # space data_frame[x] = data_frame[x].str.strip().fillna(data_frame[x]) # Try the datetime conversion try: series = pd.to_datetime(data_frame[x], infer_datetime_format=True) # Datetime conversion worked! Update the data_frame data_frame[x] = series except (ValueError, TypeError): pass return data_frame def load_df_from_sqlconnection(conn_item, pwd=None): """ Load a DF from a SQL connection open with the parameters given in conn_item. :param conn_item: SQLConnection object with the connection parameters. :return: Data frame or raise an exception. """ # Get the connection db_connection = create_db_connection(conn_item.conn_type, conn_item.conn_driver, conn_item.db_user, pwd, conn_item.db_host, conn_item.db_name) # Try to fetch the data result = pd.read_sql(conn_item.db_table, db_connection) # After reading from the DB, turn all None into NaN result.fillna(value=np.nan, inplace=True) return result def store_table(data_frame, table_name): """ Store a data frame in the DB :param data_frame: The data frame to store :param table_name: The name of the table in the DB :return: Nothing. Side effect in the DB """ with cache.lock(table_name): # We ovewrite the content and do not create an index data_frame.to_sql(table_name, engine, if_exists='replace', index=False) return def delete_table(pk): """Delete the table representing the workflow with the given PK. Due to the dual use of the database, the command has to be executed directly on the DB. """ try: cursor = connection.cursor() cursor.execute('DROP TABLE "{0}";'.format(create_table_name(pk))) connection.commit() except Exception: logger.error( 'Error while dropping table {0}'.format(create_table_name(pk)) ) def delete_upload_table(pk): """Delete the table used to merge data into the workflow with the given PK. Due to the dual use of the database, the command has to be executed directly on the DB. """ cursor = connection.cursor() cursor.execute('DROP TABLE "{0}"'.format(create_upload_table_name(pk))) connection.commit() def get_table_column_types(table_name): """ :param table_name: Table name :return: List of pairs (column name, SQL type) """ cursor = connection.cursor() cursor.execute("""select column_name, data_type from INFORMATION_SCHEMA.COLUMNS where table_name = '{0}'""".format(table_name)) return cursor.fetchall() def df_column_types_rename(table_name): """ :param table_name: Primary key of the workflow containing this data frame (table) :return: List of data type strings translated to the proper values """ column_types = get_table_column_types(table_name) # result = [table_name[x].dtype.name for x in list(table_name.columns)] # for tname, ntname in pandas_datatype_names.items(): # result[:] = [x if x != tname else ntname for x in result] return [sql_datatype_names[x] for __, x in get_table_column_types(table_name)] def df_drop_column(pk, column_name): """ Drop a column from the DB table storing a data frame :param pk: Workflow primary key to obtain table name :param column_name: Column name :return: Drops the column from the corresponding DB table """ query = 'ALTER TABLE "{0}" DROP COLUMN "{1}"'.format( create_table_name(pk), column_name ) cursor = connection.cursor() cursor.execute(query) def get_subframe(pk, cond_filter, column_names=None): """ Execute a select query to extract a subset of the dataframe and turn the resulting query set into a data frame. :param pk: Workflow primary key :param cond_filter: Condition object to filter the data (or None) :param column_names: [list of column names], QuerySet with the data rows :return: """ # Get the cursor cursor = get_table_cursor(pk, cond_filter, column_names) # Create the DataFrame and set the column names result = pd.DataFrame.from_records(cursor.fetchall(), coerce_float=True) result.columns = [c.name for c in cursor.description] return result def get_table_cursor(pk, cond_filter, column_names=None): """ Execute a select query in the database with an optional filter obtained from the jquery QueryBuilder. :param pk: Primary key of the workflow storing the data :param cond_filter: Condition object to filter the data (or None) :param column_names: optional list of columns to select :return: ([list of column names], QuerySet with the data rows) """ # Create the query if column_names: safe_column_names = [fix_pctg_in_name(x) for x in column_names] query = 'SELECT "{0}" from "{1}"'.format( '", "'.join(safe_column_names), create_table_name(pk) ) else: query = 'SELECT * from "{0}"'.format(create_table_name(pk)) # See if the action has a filter or not fields = [] if cond_filter is not None: cond_filter, fields = evaluate_node_sql(cond_filter.formula) if cond_filter: # The condition may be empty, in which case, nothing is needed. query += ' WHERE ' + cond_filter # Execute the query cursor = connection.cursor() cursor.execute(query, fields) return cursor def execute_select_on_table(pk, fields, values, column_names=None): """ Execute a select query in the database with an optional filter obtained from the jquery QueryBuilder. :param pk: Primary key of the workflow storing the data :param fields: List of fields to add to the WHERE clause :param values: parameters to match the previous fields :param column_names: optional list of columns to select :return: QuerySet with the data rows """ # Create the query if column_names: safe_column_names = ['"' + fix_pctg_in_name(x) + '"' for x in column_names] query = 'SELECT {0}'.format(','.join(safe_column_names)) else: query = 'SELECT *' # Add the table query += ' FROM "{0}"'.format(create_table_name(pk)) # See if the action has a filter or not cursor = connection.cursor() if fields: query += ' WHERE ' + \ ' AND '.join(['"{0}" = %s'.format(fix_pctg_in_name(x)) for x in fields]) cursor.execute(query, values) else: # Execute the query cursor.execute(query) # Get the data return cursor.fetchall() def update_row(pk, set_fields, set_values, where_fields, where_values): """ Given a primary key, pairs (set_field, set_value), and pairs (where_field, where_value), it updates the row in the table selected with the list of (where field = where value) with the values in the assignments in the list of (set_fields, set_values) :param pk: Primary key to detect workflow :param set_fields: List of field names to be updated :param set_values: List of values to update the fields of the previous list :param where_fields: List of fields used to filter the row in the table :param where_values: List of values of the previous fields to filter the row :return: The table in the workflow pointed by PK is modified. """ # First part of the query with the table name query = 'UPDATE "{0}"'.format(create_table_name(pk)) # Add the SET field = value clauses query += ' SET ' + ', '.join(['"{0}" = %s'.format(fix_pctg_in_name(x)) for x in set_fields]) # And finally add the WHERE clause query += ' WHERE ' + ' AND '.join(['"{0}" = %s'.format(fix_pctg_in_name(x)) for x in where_fields]) # Concatenate the values as parameters to the query parameters = set_values + where_values # Execute the query cursor = connection.cursor() cursor.execute(query, parameters) connection.commit() def increase_row_integer(pk, set_field, where_field, where_value): """ Given a primary key, a field set_field, and a pair (where_field, where_value), it increases the field in the appropriate row :param pk: Primary key to detect workflow :param set_field: name of the field to be increased :param where_field: Field used to filter the row in the table :param where_value: Value of the previous field to filter the row :return: The table in the workflow pointed by PK is modified. """ # First part of the query with the table name query = 'UPDATE "{0}" SET "{1}" = "{1}" + 1 WHERE "{2}" = %s'.format( create_table_name(pk), set_field, where_field ) # Execute the query cursor = connection.cursor() cursor.execute(query, [where_value]) connection.commit() def get_table_row_by_key(workflow, cond_filter, kv_pair, column_names=None): """ Select the set of elements after filtering and with the key=value pair :param workflow: workflow object to get to the table :param cond_filter: Condition object to filter the data (or None) :param kv_pair: A key=value pair to identify the row. Key is suppose to be unique. :param column_names: Optional list of column names to select :return: A dictionary with the (column_name, value) data or None if the row has not been found """ # Create the query if column_names: safe_column_names = [fix_pctg_in_name(x) for x in column_names] query = 'SELECT "{0}"'.format('", "'.join(safe_column_names)) else: query = 'SELECT *' # Add the table query += ' FROM "{0}"'.format(create_table_name(workflow.id)) # Create the second part of the query setting key=value query += ' WHERE ("{0}" = %s)'.format(fix_pctg_in_name(kv_pair[0])) fields = [kv_pair[1]] # See if the action has a filter or not if cond_filter is not None: cond_filter, filter_fields = \ evaluate_node_sql(cond_filter.formula) query += ' AND (' + cond_filter + ')' fields = fields + filter_fields # Execute the query cursor = connection.cursor() cursor.execute(query, fields) # Get the data qs = cursor.fetchall() # If there is anything different than one element, return None if len(qs) != 1: return None # Get the only element qs = qs[0] # ZIP the values to create a dictionary return OrderedDict(zip(workflow.get_column_names(), qs)) def get_column_stats_from_df(df_column): """ Given a data frame with a single column, return a set of statistics depending on its type. :param df_column: data frame with a single column :return: A dictionary with keys depending on the type of column {'min': minimum value (integer, double an datetime), 'q1': Q1 value (0.25) (integer, double), 'mean': mean value (integer, double), 'median': median value (integer, double), 'mean': mean value (integer, double), 'q3': Q3 value (0.75) (integer, double), 'max': maximum value (integer, double an datetime), 'std': standard deviation (integer, double), 'counts': (integer, double, string, datetime, Boolean', 'mode': (integer, double, string, datetime, Boolean, or None if the column has all its values to NaN """ if len(df_column.loc[df_column.notnull()]) == 0: # The column has no data return None # Dictionary to return result = { 'min': 0, 'q1': 0, 'mean': 0, 'median': 0, 'q3': 0, 'max': 0, 'std': 0, 'mode': None, 'counts': {}, } data_type = pandas_datatype_names[df_column.dtype.name] if data_type == 'integer' or data_type == 'double': quantiles = df_column.quantile([0, .25, .5, .75, 1]) result['min'] = '{0:g}'.format(quantiles[0]) result['q1'] = '{0:g}'.format(quantiles[.25]) result['mean'] = '{0:g}'.format(df_column.mean()) result['median'] = '{0:g}'.format(quantiles[.5]) result['q3'] = '{0:g}'.format(quantiles[.75]) result['max'] = '{0:g}'.format(quantiles[1]) result['std'] = '{0:g}'.format(df_column.std()) result['counts'] = df_column.value_counts().to_dict() mode = df_column.mode() if len(mode) == 0: mode = '--' result['mode'] = mode[0] return result def get_filter_query(table_name, column_names, filter_exp): """ Given a set of columns and a filter expression, return a pair of SQL query and params to be executed :param table_name: Table to query :param column_names: list of columns to consider or None to consider all :param filter_exp: Text filter expression :return: (sql query, sql params) """ # Create the query if column_names: safe_column_names = [fix_pctg_in_name(x) for x in column_names] query = 'SELECT "{0}"'.format('", "'.join(safe_column_names)) else: query = 'SELECT *' # Add the table query += ' FROM "{0}"'.format(table_name) # Calculate the first suffix to add to the query filter_txt = '' filter_fields = [] if filter_exp: filter_txt, filter_fields = evaluate_node_sql(filter_exp) # Build the query so far appending the filter and/or the cv_tuples if filter_txt: query += ' WHERE ' fields = [] # If there has been a suffix from the filter, add it. if filter_txt: query += filter_txt if filter_fields: fields.extend(filter_fields) return (query, fields) def search_table_rows(workflow_id, cv_tuples=None, any_join=True, order_col_name=None, order_asc=True, column_names=None, pre_filter=None): """ Select rows where for every (column, value) pair, column contains value ( as in LIKE %value%, these are combined with OR if any is TRUE, or AND if any is false, and the result is ordered by the given column and type (if given) :param workflow_id: workflow object to get to the table :param cv_tuples: A column, value, type tuple to search the value in the column :param any_join: Boolean encoding if values should be combined with OR (or AND) :param order_col_name: Order results by this column :param order_asc: Order results in ascending values (or descending) :param column_names: Optional list of column names to select :param pre_filter: Optional filter condition to pre filter the query set. the query is built with these terms as requirement AND the cv_tuples. :return: The resulting query set """ # Create the query if column_names: safe_column_names = [fix_pctg_in_name(x) for x in column_names] query = 'SELECT "{0}"'.format('", "'.join(safe_column_names)) else: query = 'SELECT *' # Add the table query += ' FROM "{0}"'.format(create_table_name(workflow_id)) # Calculate the first suffix to add to the query filter_txt = '' filter_fields = [] if pre_filter: filter_txt, filter_fields = evaluate_node_sql(pre_filter) if cv_tuples: likes = [] tuple_fields = [] for name, value, data_type in cv_tuples: # Make sure we escape the name and search as text name = fix_pctg_in_name(name) mod_name = '(CAST("{0}" AS TEXT) LIKE %s)'.format(name) # Create the second part of the query setting column LIKE '%value%' likes.append(mod_name) tuple_fields.append('%' + value + '%') # Combine the search subqueries if any_join: tuple_txt = '(' + ' OR '.join(likes) + ')' else: tuple_txt = '(' + ' AND '.join(likes) + ')' # Build the query so far appending the filter and/or the cv_tuples if filter_txt or cv_tuples: query += ' WHERE ' fields = [] # If there has been a suffix from the filter, add it. if filter_txt: query += filter_txt fields.extend(filter_fields) # If there is a pre-filter, the suffix needs to be "AND" with the ones # just calculated if filter_txt and cv_tuples: query += ' AND ' if cv_tuples: query += tuple_txt fields.extend(tuple_fields) # Add the order if needed if order_col_name: query += ' ORDER BY "{0}"'.format(fix_pctg_in_name(order_col_name)) if not order_asc: query += ' DESC' # Execute the query cursor = connection.cursor() cursor.execute(query, fields) # Get the data return cursor.fetchall() def delete_table_row_by_key(workflow_id, kv_pair): """ Delete the row in the table attached to a workflow with the given key, value pairs :param workflow_id: workflow object to get to the table :param kv_pair: A key=value pair to identify the row. Key is suppose to be unique. :return: Drops that row from the table in the DB """ # Create the query query = 'DELETE FROM "{0}"'.format(create_table_name(workflow_id)) # Create the second part of the query setting key=value query += ' WHERE ("{0}" = %s)'.format(fix_pctg_in_name(kv_pair[0])) fields = [kv_pair[1]] # Execute the query cursor = connection.cursor() cursor.execute(query, fields) def num_rows(pk, cond_filter=None): """ Obtain the number of rows of the table storing workflow with given pk :param pk: Primary key of the table storing the data frame :param cond_filter: Condition element to filter the query :return: """ return num_rows_by_name(create_table_name(pk), cond_filter) def num_rows_by_name(table_name, cond_filter=None): """ Given a table name, get its number of rows :param table_name: Table name :param cond_filter: Condition element used to filter the query :return: integer """ # Initial query with the table name query = query_count_rows.format(table_name) fields = [] if cond_filter is not None: cond_filter, fields = evaluate_node_sql(cond_filter) query += ' WHERE ' + cond_filter cursor = connection.cursor() cursor.execute(query, fields) return cursor.fetchone()[0] def check_wf_df(workflow): """ Check the consistency between the information stored in the workflow and the structure of the underlying dataframe :param workflow: Workflow object :return: Boolean stating the result of the check. True: Correct. """ # Get the df df = load_from_db(workflow.id) # Set values in case there is no df if df is not None: dfnrows = df.shape[0] dfncols = df.shape[1] df_col_names = list(df.columns) else: dfnrows = 0 dfncols = 0 df_col_names = [] # Check 1: Number of rows and columns if workflow.nrows != dfnrows: return False if workflow.ncols != dfncols: return False # Identical sets of columns wf_cols = workflow.columns.all() if [x.name for x in wf_cols] != df_col_names: return False # Identical data types for n1, n2 in zip(wf_cols, df_col_names): df_dt = pandas_datatype_names[df[n2].dtype.name] if n1.data_type == 'boolean' and df_dt == 'string': # This is the case of a column with Boolean and Nulls continue if n1.data_type != df_dt: return False return True
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 11, 3601, 62, 8818, 198, 198, 11748, 18931, 198, 11748, 28686, 13, 6978, 198, 11748, 850, 14681, 198, 6738, 1...
2.550324
11,257
from typing import Any, Dict, KeysView import attr from config.auth import OAuth2 from config.cfenv import CFenv from config.spring import ConfigClient
[ 6738, 19720, 1330, 4377, 11, 360, 713, 11, 26363, 7680, 198, 198, 11748, 708, 81, 198, 198, 6738, 4566, 13, 18439, 1330, 440, 30515, 17, 198, 6738, 4566, 13, 12993, 24330, 1330, 18551, 24330, 198, 6738, 4566, 13, 16469, 1330, 17056, 1...
3.604651
43
# Copyright 2015 Confluent 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 ducktape.utils.util import package_is_installed from jinja2 import Template, FileSystemLoader, PackageLoader, ChoiceLoader, Environment import os.path import inspect
[ 2, 15069, 1853, 7326, 28216, 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, 13789, 13, 198, 2, 921,...
3.91623
191
i=input("Enter a string: ") list = i.split() list.sort() for i in list: print(i,end=' ')
[ 72, 28, 15414, 7203, 17469, 257, 4731, 25, 366, 8, 198, 4868, 796, 1312, 13, 35312, 3419, 198, 4868, 13, 30619, 3419, 198, 1640, 1312, 287, 1351, 25, 198, 220, 220, 220, 3601, 7, 72, 11, 437, 11639, 705, 8, 198 ]
2.268293
41
"""Config repositories use case.""" from __future__ import annotations import git_portfolio.config_manager as cm import git_portfolio.domain.gh_connection_settings as cs import git_portfolio.responses as res
[ 37811, 16934, 38072, 779, 1339, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 17606, 62, 634, 13652, 13, 11250, 62, 37153, 355, 12067, 198, 11748, 17606, 62, 634, 13652, 13, 27830, 13, 456, 62, 38659, 62, 33692...
3.818182
55
import pytest from ..logic import Board, empty_board, example_board, solved_board
[ 11748, 12972, 9288, 198, 6738, 11485, 6404, 291, 1330, 5926, 11, 6565, 62, 3526, 11, 1672, 62, 3526, 11, 16019, 62, 3526, 628 ]
3.608696
23
from __future__ import print_function from __future__ import absolute_import from __future__ import division import ast import rhinoscriptsyntax as rs __all__ = [ 'mesh_select_vertex', 'mesh_select_vertices', 'mesh_select_face', 'mesh_select_faces', 'mesh_select_edge', 'mesh_select_edges', 'network_select_node', 'network_select_nodes', 'network_select_edge', 'network_select_edges', ] def mesh_select_vertex(mesh, message="Select a vertex."): """Select a single vertex of a mesh. Parameters ---------- mesh: :class:`compas.datastructures.Mesh` message: str, optional Returns ------- int or None """ guid = rs.GetObject(message, preselect=True, filter=rs.filter.point | rs.filter.textdot) if guid: prefix = mesh.attributes['name'] name = rs.ObjectName(guid).split('.') if 'vertex' in name: if not prefix or prefix in name: key = name[-1] return ast.literal_eval(key) return None def mesh_select_vertices(mesh, message="Select vertices."): """Select multiple vertices of a mesh. Parameters ---------- mesh: :class:`compas.datastructures.Mesh` message: str, optional Returns ------- list of int """ keys = [] guids = rs.GetObjects(message, preselect=True, filter=rs.filter.point | rs.filter.textdot) if guids: prefix = mesh.attributes['name'] seen = set() for guid in guids: name = rs.ObjectName(guid).split('.') if 'vertex' in name: if not prefix or prefix in name: key = name[-1] if not seen.add(key): key = ast.literal_eval(key) keys.append(key) return keys def mesh_select_face(mesh, message="Select a face."): """Select a single face of a mesh. Parameters ---------- mesh: :class:`compas.datastructures.Mesh` message: str, optional Returns ------- int or None """ guid = rs.GetObject(message, preselect=True, filter=rs.filter.mesh | rs.filter.textdot) if guid: prefix = mesh.attributes['name'] name = rs.ObjectName(guid).split('.') if 'face' in name: if not prefix or prefix in name: key = name[-1] key = ast.literal_eval(key) return key return None def mesh_select_faces(mesh, message="Select faces."): """Select multiple faces of a mesh. Parameters ---------- mesh: :class:`compas.datastructures.Mesh` message: str, optional Returns ------- list of int """ keys = [] guids = rs.GetObjects(message, preselect=True, filter=rs.filter.mesh | rs.filter.textdot) if guids: prefix = mesh.attributes['name'] seen = set() for guid in guids: name = rs.ObjectName(guid).split('.') if 'face' in name: if not prefix or prefix in name: key = name[-1] if not seen.add(key): key = ast.literal_eval(key) keys.append(key) return keys def mesh_select_edge(mesh, message="Select an edge."): """Select a single edge of a mesh. Parameters ---------- mesh: :class:`compas.datastructures.Mesh` message: str, optional Returns ------- tuple of int, or None """ guid = rs.GetObject(message, preselect=True, filter=rs.filter.curve | rs.filter.textdot) if guid: prefix = mesh.attributes['name'] name = rs.ObjectName(guid).split('.') if 'edge' in name: if not prefix or prefix in name: key = name[-1] u, v = key.split('-') u = ast.literal_eval(u) v = ast.literal_eval(v) return u, v return None def mesh_select_edges(mesh, message="Select edges."): """Select multiple edges of a mesh. Parameters ---------- mesh: :class:`compas.datastructures.Mesh` message: str, optional Returns ------- list of tuple of int """ keys = [] guids = rs.GetObjects(message, preselect=True, filter=rs.filter.curve | rs.filter.textdot) if guids: prefix = mesh.attributes['name'] seen = set() for guid in guids: name = rs.ObjectName(guid).split('.') if 'edge' in name: if not prefix or prefix in name: key = name[-1] if not seen.add(key): u, v = key.split('-') u = ast.literal_eval(u) v = ast.literal_eval(v) keys.append((u, v)) return keys def network_select_node(network, message="Select a node."): """Select a single node of a network. Parameters ---------- network: :class:`compas.datastructures.Network` message: str, optional Returns ------- hashable or None """ guid = rs.GetObject(message, preselect=True, filter=rs.filter.point | rs.filter.textdot) if guid: prefix = network.attributes['name'] name = rs.ObjectName(guid).split('.') if 'node' in name: if not prefix or prefix in name: key = name[-1] return ast.literal_eval(key) return None def network_select_nodes(network, message="Select nodes."): """Select multiple nodes of a network. Parameters ---------- network: :class:`compas.datastructures.Network` message: str, optional Returns ------- list of hashable """ keys = [] guids = rs.GetObjects(message, preselect=True, filter=rs.filter.point | rs.filter.textdot) if guids: prefix = network.attributes['name'] seen = set() for guid in guids: name = rs.ObjectName(guid).split('.') if 'node' in name: if not prefix or prefix in name: key = name[-1] if not seen.add(key): key = ast.literal_eval(key) keys.append(key) return keys def network_select_edge(network, message="Select an edge."): """Select a single edge of a network. Parameters ---------- network: :class:`compas.datastructures.Network` message: str, optional Returns ------- tuple of hashable, or None """ guid = rs.GetObject(message, preselect=True, filter=rs.filter.curve | rs.filter.textdot) if guid: prefix = network.attributes['name'] name = rs.ObjectName(guid).split('.') if 'edge' in name: if not prefix or prefix in name: key = name[-1] u, v = key.split('-') u = ast.literal_eval(u) v = ast.literal_eval(v) return u, v return None def network_select_edges(network, message="Select edges."): """Select multiple edges of a network. Parameters ---------- network: :class:`compas.datastructures.Network` message: str, optional Returns ------- list of tuple of hashable """ keys = [] guids = rs.GetObjects(message, preselect=True, filter=rs.filter.curve | rs.filter.textdot) if guids: prefix = network.attributes['name'] seen = set() for guid in guids: name = rs.ObjectName(guid).split('.') if 'edge' in name: if not prefix or prefix in name: key = name[-1] if not seen.add(key): u, v = key.split('-') u = ast.literal_eval(u) v = ast.literal_eval(v) keys.append((u, v)) return keys # ============================================================================== # Main # ============================================================================== if __name__ == '__main__': pass
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 11748, 6468, 198, 11748, 9529, 11996, 6519, 1837, 41641, 355, 44608, 628, 198, 834, ...
2.164088
3,748
from telegram import Update from telegram.ext import Updater, CallbackContext, ConversationHandler, CommandHandler, MessageHandler, Filters from db import DBConnector import re str_matcher = r"\"(?P<name>.+)\"\s*(?P<fat>\d+)\s*/\s*(?P<protein>\d+)\s*/\s*(?P<carbohydrates>\d+)\s*(?P<kcal>\d+)" ADD_1 = 0 def add_handler(updater: Updater): """/product_add - Add product to list known products""" updater.dispatcher.add_handler(ConversationHandler( entry_points=[CommandHandler('product_add', add_0)], states={ ADD_1: [MessageHandler(Filters.text & ~Filters.command, add_1)] }, fallbacks=[] ))
[ 6738, 573, 30536, 1330, 10133, 198, 6738, 573, 30536, 13, 2302, 1330, 3205, 67, 729, 11, 4889, 1891, 21947, 11, 42427, 25060, 11, 9455, 25060, 11, 16000, 25060, 11, 7066, 1010, 198, 198, 6738, 20613, 1330, 360, 2749, 261, 1606, 273, 1...
2.368231
277
from mock import patch import numpy as np
[ 6738, 15290, 1330, 8529, 198, 11748, 299, 32152, 355, 45941, 628, 628, 198 ]
3.538462
13
import Cipher.tk from Cipher.tk import EncryptDecryptCoord, GetChiSquared, Mode ''' # testing do write it here a = " abcdefghijklmnopqrstuvwxyz" p=[] for c in a: p.append (c) print ("starting...") print (MultiDecrypt ("dtyktckcxlbd", p)) # original 231 '''
[ 11748, 44334, 13, 30488, 220, 220, 201, 198, 6738, 44334, 13, 30488, 1330, 14711, 6012, 10707, 6012, 7222, 585, 11, 3497, 1925, 72, 22266, 1144, 11, 10363, 201, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 2...
2.148148
135
#!/usr/bin/env python import sys import argparse import pkg_resources import vcf from vcf.parser import _Filter parser = argparse.ArgumentParser(description='Filter a VCF file', formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument('input', metavar='input', type=str, nargs=1, help='File to process (use - for STDIN)') parser.add_argument('filters', metavar='filter', type=str, nargs='+', help='Filters to use') parser.add_argument('--no-short-circuit', action='store_true', help='Do not stop filter processing on a site if a single filter fails.') parser.add_argument('--output', action='store', default=sys.stdout, help='Filename to output (default stdout)') parser.add_argument('--no-filtered', action='store_true', help='Remove failed sites') if __name__ == '__main__': # TODO: allow filter specification by short name # TODO: flag that writes filter output into INFO column # TODO: argument use implies filter use # TODO: parallelize # TODO: prevent plugins raising an exception from crashing the script # dynamically build the list of available filters filters = {} filter_help = '\n\navailable filters:' for p in pkg_resources.iter_entry_points('vcf.filters'): filt = p.load() filters[filt.name] = filt filt.customize_parser(parser) filter_help += '\n %s:\t%s' % (filt.name, filt.description) parser.description += filter_help # parse command line args args = parser.parse_args() inp = vcf.Reader(file(args.input[0])) # build filter chain chain = [] for name in args.filters: f = filters[name](args) chain.append(f) inp.filters[f.filter_name()] = _Filter(f.filter_name(), f.description) oup = vcf.Writer(args.output, inp) # apply filters short_circuit = not args.no_short_circuit for record in inp: for filt in chain: result = filt(record) if result: record.add_filter(filt.filter_name()) if short_circuit: break if (not args.no_filtered) or (record.FILTER == '.'): oup.write_record(record)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 25064, 198, 11748, 1822, 29572, 198, 11748, 279, 10025, 62, 37540, 198, 198, 11748, 410, 12993, 198, 6738, 410, 12993, 13, 48610, 1330, 4808, 22417, 198, 198, 48610, 796, 1822, 29...
2.515766
888
import os from flask import Blueprint, render_template
[ 11748, 28686, 198, 6738, 42903, 1330, 39932, 11, 8543, 62, 28243 ]
4.909091
11
# from aiohttp.client_exceptions import ClientError from lxml import html from pathlib import Path from asyncio import create_task from functools import wraps def download_search(client, keyword, page): safe_keyword = keyword.replace(" ", "+") # url = f"https://mobile.alphacoders.com/by-resolution/5?search={safe_keyword}&page={page}" url = f"https://wall.alphacoders.com/search.php?search={safe_keyword}&page={page}" return download_page(client, url) class SingleTask: def __init__(self, keyword, limit=None): self.keyword = keyword self.limit = limit self.complete_count = 0 self.triggered = False
[ 2, 198, 198, 6738, 257, 952, 4023, 13, 16366, 62, 1069, 11755, 1330, 20985, 12331, 198, 6738, 300, 19875, 1330, 27711, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 30351, 952, 1330, 2251, 62, 35943, 198, 6738, 1257, 310, 10141, 1330, ...
2.752066
242
# SQL output is imported as a pandas dataframe variable called "df" # Source: https://stackoverflow.com/questions/19441730/trimmed-mean-with-percentage-limit-in-python import pandas as pd import matplotlib.pyplot as plt from scipy.stats import tmean, scoreatpercentile import numpy as np my_result = trimmean(df["amt_paid"].values,10)
[ 2, 16363, 5072, 318, 17392, 355, 257, 19798, 292, 1366, 14535, 7885, 1444, 366, 7568, 1, 198, 198, 2, 8090, 25, 220, 3740, 1378, 25558, 2502, 11125, 13, 785, 14, 6138, 507, 14, 1129, 2598, 1558, 1270, 14, 2213, 320, 1150, 12, 32604,...
2.95614
114
import os import cv2 import random import numpy as np from tensorflow.keras.utils import to_categorical from scripts.consts import class_dict
[ 11748, 28686, 198, 11748, 269, 85, 17, 198, 11748, 4738, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 26791, 1330, 284, 62, 66, 2397, 12409, 198, 6738, 14750, 13, 1102, 6448, 1330, 1398, 62, 116...
3.325581
43
# Copyright 2014 Cisco Systems, 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. import json import mock from ironic.common import exception from ironic.common import raid from ironic.common import states from ironic.drivers import base as driver_base from ironic.drivers.modules import fake from ironic.tests import base class PassthruDecoratorTestCase(base.TestCase): def test_passthru_shared_task_metadata(self): self.assertIn('require_exclusive_lock', self.fvi.shared_task._vendor_metadata[1]) self.assertFalse( self.fvi.shared_task._vendor_metadata[1]['require_exclusive_lock']) def test_passthru_exclusive_task_metadata(self): self.assertIn('require_exclusive_lock', self.fvi.noexception._vendor_metadata[1]) self.assertTrue( self.fvi.noexception._vendor_metadata[1]['require_exclusive_lock']) def test_passthru_check_func_references(self): inst1 = FakeVendorInterface() inst2 = FakeVendorInterface() self.assertNotEqual(inst1.vendor_routes['noexception']['func'], inst2.vendor_routes['noexception']['func']) self.assertNotEqual(inst1.driver_routes['driver_noexception']['func'], inst2.driver_routes['driver_noexception']['func']) class CleanStepDecoratorTestCase(base.TestCase): obj = TestClass() obj2 = TestClass2() obj3 = TestClass3() self.assertEqual(2, len(obj.get_clean_steps(task_mock))) # Ensure the steps look correct self.assertEqual(10, obj.get_clean_steps(task_mock)[0]['priority']) self.assertTrue(obj.get_clean_steps(task_mock)[0]['abortable']) self.assertEqual('test', obj.get_clean_steps( task_mock)[0]['interface']) self.assertEqual('automated_method', obj.get_clean_steps( task_mock)[0]['step']) self.assertEqual(0, obj.get_clean_steps(task_mock)[1]['priority']) self.assertFalse(obj.get_clean_steps(task_mock)[1]['abortable']) self.assertEqual('test', obj.get_clean_steps( task_mock)[1]['interface']) self.assertEqual('manual_method', obj.get_clean_steps( task_mock)[1]['step']) # Ensure the second obj get different clean steps self.assertEqual(2, len(obj2.get_clean_steps(task_mock))) # Ensure the steps look correct self.assertEqual(20, obj2.get_clean_steps(task_mock)[0]['priority']) self.assertTrue(obj2.get_clean_steps(task_mock)[0]['abortable']) self.assertEqual('test2', obj2.get_clean_steps( task_mock)[0]['interface']) self.assertEqual('automated_method2', obj2.get_clean_steps( task_mock)[0]['step']) self.assertEqual(0, obj2.get_clean_steps(task_mock)[1]['priority']) self.assertFalse(obj2.get_clean_steps(task_mock)[1]['abortable']) self.assertEqual('test2', obj2.get_clean_steps( task_mock)[1]['interface']) self.assertEqual('manual_method2', obj2.get_clean_steps( task_mock)[1]['step']) self.assertIsNone(obj2.get_clean_steps(task_mock)[0]['argsinfo']) # Ensure the third obj has different clean steps self.assertEqual(2, len(obj3.get_clean_steps(task_mock))) self.assertEqual(15, obj3.get_clean_steps(task_mock)[0]['priority']) self.assertFalse(obj3.get_clean_steps(task_mock)[0]['abortable']) self.assertEqual('test3', obj3.get_clean_steps( task_mock)[0]['interface']) self.assertEqual('automated_method3', obj3.get_clean_steps( task_mock)[0]['step']) self.assertEqual({'arg10': {'description': 'desc10'}}, obj3.get_clean_steps(task_mock)[0]['argsinfo']) self.assertEqual(0, obj3.get_clean_steps(task_mock)[1]['priority']) self.assertTrue(obj3.get_clean_steps(task_mock)[1]['abortable']) self.assertEqual(obj3.interface_type, obj3.get_clean_steps( task_mock)[1]['interface']) self.assertEqual('manual_method3', obj3.get_clean_steps( task_mock)[1]['step']) self.assertEqual({'arg1': {'description': 'desc1', 'required': True}}, obj3.get_clean_steps(task_mock)[1]['argsinfo']) # Ensure we can execute the function. obj.execute_clean_step(task_mock, obj.get_clean_steps(task_mock)[0]) method_mock.assert_called_once_with(task_mock) args = {'arg1': 'val1'} clean_step = {'interface': 'test3', 'step': 'manual_method3', 'args': args} obj3.execute_clean_step(task_mock, clean_step) method_args_mock.assert_called_once_with(task_mock, **args) class DeployStepDecoratorTestCase(base.TestCase): obj = TestClass() obj2 = TestClass2() obj3 = TestClass3() self.assertEqual(2, len(obj.get_deploy_steps(task_mock))) # Ensure the steps look correct self.assertEqual(10, obj.get_deploy_steps(task_mock)[0]['priority']) self.assertEqual('test', obj.get_deploy_steps( task_mock)[0]['interface']) self.assertEqual('deploy_ten', obj.get_deploy_steps( task_mock)[0]['step']) self.assertEqual(0, obj.get_deploy_steps(task_mock)[1]['priority']) self.assertEqual('test', obj.get_deploy_steps( task_mock)[1]['interface']) self.assertEqual('deploy_zero', obj.get_deploy_steps( task_mock)[1]['step']) # Ensure the second obj has different deploy steps self.assertEqual(2, len(obj2.get_deploy_steps(task_mock))) # Ensure the steps look correct self.assertEqual(20, obj2.get_deploy_steps(task_mock)[0]['priority']) self.assertEqual('test2', obj2.get_deploy_steps( task_mock)[0]['interface']) self.assertEqual('deploy_twenty', obj2.get_deploy_steps( task_mock)[0]['step']) self.assertEqual(0, obj2.get_deploy_steps(task_mock)[1]['priority']) self.assertEqual('test2', obj2.get_deploy_steps( task_mock)[1]['interface']) self.assertEqual('deploy_zero2', obj2.get_deploy_steps( task_mock)[1]['step']) self.assertIsNone(obj2.get_deploy_steps(task_mock)[0]['argsinfo']) # Ensure the third obj has different deploy steps self.assertEqual(2, len(obj3.get_deploy_steps(task_mock))) self.assertEqual(15, obj3.get_deploy_steps(task_mock)[0]['priority']) self.assertEqual('test3', obj3.get_deploy_steps( task_mock)[0]['interface']) self.assertEqual('deploy_fifteen', obj3.get_deploy_steps( task_mock)[0]['step']) self.assertEqual({'arg10': {'description': 'desc10'}}, obj3.get_deploy_steps(task_mock)[0]['argsinfo']) self.assertEqual(0, obj3.get_deploy_steps(task_mock)[1]['priority']) self.assertEqual(obj3.interface_type, obj3.get_deploy_steps( task_mock)[1]['interface']) self.assertEqual('deploy_zero3', obj3.get_deploy_steps( task_mock)[1]['step']) self.assertEqual({'arg1': {'description': 'desc1', 'required': True}}, obj3.get_deploy_steps(task_mock)[1]['argsinfo']) # Ensure we can execute the function. obj.execute_deploy_step(task_mock, obj.get_deploy_steps(task_mock)[0]) method_mock.assert_called_once_with(task_mock) args = {'arg1': 'val1'} deploy_step = {'interface': 'test3', 'step': 'deploy_zero3', 'args': args} obj3.execute_deploy_step(task_mock, deploy_step) method_args_mock.assert_called_once_with(task_mock, **args) class MyRAIDInterface(driver_base.RAIDInterface): class RAIDInterfaceTestCase(base.TestCase): class TestBIOSInterface(base.TestCase):
[ 2, 15069, 1946, 28289, 11998, 11, 3457, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, ...
2.183062
3,873
import pytest from opentimesheet.core.tests import TenantTestCase
[ 11748, 12972, 9288, 198, 198, 6738, 1034, 43598, 25473, 13, 7295, 13, 41989, 1330, 9368, 415, 14402, 20448, 628 ]
3.578947
19
from ami.flowchart.library.DisplayWidgets import ScalarWidget, ScatterWidget, WaveformWidget, \ ImageWidget, ObjectWidget, LineWidget, TimeWidget, HistogramWidget, \ Histogram2DWidget from ami.flowchart.library.common import CtrlNode from amitypes import Array1d, Array2d from typing import Any import ami.graph_nodes as gn
[ 6738, 716, 72, 13, 11125, 40926, 13, 32016, 13, 23114, 54, 312, 11407, 1330, 34529, 283, 38300, 11, 1446, 1436, 38300, 11, 17084, 687, 38300, 11, 3467, 198, 220, 220, 220, 7412, 38300, 11, 9515, 38300, 11, 6910, 38300, 11, 3862, 38300...
3.226415
106
'''OpenGL extension ARB.transform_feedback_instanced This module customises the behaviour of the OpenGL.raw.GL.ARB.transform_feedback_instanced to provide a more Python-friendly API Overview (from the spec) Multiple instances of geometry may be specified to the GL by calling functions such as DrawArraysInstanced and DrawElementsInstanced. Further, the results of a transform feedback operation may be returned to the GL by calling DrawTransformFeedback, or DrawTransformFeedbackStream. However, it is not presently possible to draw multiple instances of data transform feedback without using a query and the resulting round trip from server to client. This extension adds functionality to draw multiple instances of the result of a transform feedback operation. The official definition of this extension is available here: http://www.opengl.org/registry/specs/ARB/transform_feedback_instanced.txt ''' from OpenGL import platform, constant, arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GL import _types, _glgets from OpenGL.raw.GL.ARB.transform_feedback_instanced import * from OpenGL.raw.GL.ARB.transform_feedback_instanced import _EXTENSION_NAME def glInitTransformFeedbackInstancedARB(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME ) ### END AUTOGENERATED SECTION
[ 7061, 6, 11505, 8763, 7552, 5923, 33, 13, 35636, 62, 12363, 1891, 62, 8625, 2903, 198, 198, 1212, 8265, 2183, 2696, 262, 9172, 286, 262, 220, 198, 11505, 8763, 13, 1831, 13, 8763, 13, 37304, 13, 35636, 62, 12363, 1891, 62, 8625, 290...
3.857527
372
from regression_tests import *
[ 6738, 20683, 62, 41989, 1330, 1635, 198 ]
4.428571
7