content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
"""Drop-in replacement for collections.OrderedDict by Raymond Hettinger http://code.activestate.com/recipes/576693/ """ try: all except NameError:
[ 37811, 26932, 12, 259, 9014, 329, 17268, 13, 35422, 1068, 35, 713, 416, 24238, 367, 35463, 263, 198, 4023, 1378, 8189, 13, 15791, 44146, 13, 785, 14, 8344, 18636, 14, 3553, 2791, 6052, 14, 198, 37811, 198, 28311, 25, 198, 197, 439, ...
3.12766
47
from HardBlock import *
[ 6738, 6912, 12235, 1330, 1635, 198, 220, 220, 220, 220, 220, 220, 220, 220, 198, 220, 220, 220, 220, 198, 220, 220, 220, 220, 220, 220, 220, 220, 198, 220, 220, 220, 220, 220, 220, 220, 220, 198, 220, 220, 220, 220, 220, 220, 22...
1.372549
51
import dill import haiku as hk import jax from jax.experimental import optix import jax.numpy as jnp from dataset import load_data MINERL_ENV = 'MineRLTreechopVectorObf-v0' PARAMS_FILENAME = 'bc_params_treechop.pkl' def behavioral_cloning(batch): """ The full forward model definition """ x_0 = PovStack(name='pov_stack')(batch[0]) x_1 = VectorStack(name='vector_stack')(batch[1]) x = jnp.concatenate((x_0, x_1), axis=1) return jnp.tanh(hk.Linear(64)(x)) if __name__ == '__main__': main()
[ 11748, 288, 359, 198, 11748, 387, 28643, 355, 289, 74, 198, 11748, 474, 897, 198, 6738, 474, 897, 13, 23100, 9134, 1330, 2172, 844, 198, 11748, 474, 897, 13, 77, 32152, 355, 474, 37659, 198, 198, 6738, 27039, 1330, 3440, 62, 7890, 6...
2.386364
220
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ A library of template circuits. Templates are circuits that compute the identity. They find use in circuit optimization where matching part of the template allows the compiler to replace the match with the inverse of the remainder from the template. """ from .nct.template_nct_2a_1 import template_nct_2a_1 from .nct.template_nct_2a_2 import template_nct_2a_2 from .nct.template_nct_2a_3 import template_nct_2a_3 from .nct.template_nct_4a_1 import template_nct_4a_1 from .nct.template_nct_4a_2 import template_nct_4a_2 from .nct.template_nct_4a_3 import template_nct_4a_3 from .nct.template_nct_4b_1 import template_nct_4b_1 from .nct.template_nct_4b_2 import template_nct_4b_2 from .nct.template_nct_5a_1 import template_nct_5a_1 from .nct.template_nct_5a_2 import template_nct_5a_2 from .nct.template_nct_5a_3 import template_nct_5a_3 from .nct.template_nct_5a_4 import template_nct_5a_4 from .nct.template_nct_6a_1 import template_nct_6a_1 from .nct.template_nct_6a_2 import template_nct_6a_2 from .nct.template_nct_6a_3 import template_nct_6a_3 from .nct.template_nct_6a_4 import template_nct_6a_4 from .nct.template_nct_6b_1 import template_nct_6b_1 from .nct.template_nct_6b_2 import template_nct_6b_2 from .nct.template_nct_6c_1 import template_nct_6c_1 from .nct.template_nct_7a_1 import template_nct_7a_1 from .nct.template_nct_7b_1 import template_nct_7b_1 from .nct.template_nct_7c_1 import template_nct_7c_1 from .nct.template_nct_7d_1 import template_nct_7d_1 from .nct.template_nct_7e_1 import template_nct_7e_1 from .nct.template_nct_9a_1 import template_nct_9a_1 from .nct.template_nct_9c_1 import template_nct_9c_1 from .nct.template_nct_9c_2 import template_nct_9c_2 from .nct.template_nct_9c_3 import template_nct_9c_3 from .nct.template_nct_9c_4 import template_nct_9c_4 from .nct.template_nct_9c_5 import template_nct_9c_5 from .nct.template_nct_9c_6 import template_nct_9c_6 from .nct.template_nct_9c_7 import template_nct_9c_7 from .nct.template_nct_9c_8 import template_nct_9c_8 from .nct.template_nct_9c_9 import template_nct_9c_9 from .nct.template_nct_9c_10 import template_nct_9c_10 from .nct.template_nct_9c_11 import template_nct_9c_11 from .nct.template_nct_9c_12 import template_nct_9c_12 from .nct.template_nct_9d_1 import template_nct_9d_1 from .nct.template_nct_9d_2 import template_nct_9d_2 from .nct.template_nct_9d_3 import template_nct_9d_3 from .nct.template_nct_9d_4 import template_nct_9d_4 from .nct.template_nct_9d_5 import template_nct_9d_5 from .nct.template_nct_9d_6 import template_nct_9d_6 from .nct.template_nct_9d_7 import template_nct_9d_7 from .nct.template_nct_9d_8 import template_nct_9d_8 from .nct.template_nct_9d_9 import template_nct_9d_9 from .nct.template_nct_9d_10 import template_nct_9d_10
[ 2, 770, 2438, 318, 636, 286, 1195, 1984, 270, 13, 198, 2, 198, 2, 357, 34, 8, 15069, 19764, 12131, 13, 198, 2, 198, 2, 770, 2438, 318, 11971, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 13, 921, 743, 198, 2, 7330, 257, 486...
2.384672
1,357
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Apache License, Version 2.0, please send an email to # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # ##################################################################################### # # test Microsoft.Scripting.Math # from iptest.assert_util import * skiptest("win32") from System import * import clr #silverlight already has this if is_cli: math_assembly = (1).GetType().Assembly clr.AddReference(math_assembly) load_iron_python_test() import IronPythonTest if is_net40: from System.Numerics import BigInteger, Complex else: from Microsoft.Scripting.Math import BigInteger from Microsoft.Scripting.Math import Complex64 as Complex p = myFormatProvider() #complex run_test(__name__)
[ 29113, 29113, 14468, 4242, 2, 198, 2, 198, 2, 220, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 2426, 284, 2846, 290, 3403, 286, 262, 24843, 13789, 11, 10628, 362, 13, 15, 13, ...
3.717647
340
import matplotlib.pyplot as plt, numpy as np, pandas as pd,os from ..model import recall_powerlaw_fits_to_full_models from .. import compute_power_rmse from .bluf import * from ..measure.powerlaw import * from .gener_q_vs_w_for_result_folder import *
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 11, 299, 32152, 355, 45941, 11, 19798, 292, 355, 279, 67, 11, 418, 198, 6738, 11485, 19849, 1330, 10014, 62, 6477, 6270, 62, 21013, 62, 1462, 62, 12853, 62, 27530, 198, 6738, ...
2.885057
87
import sys import math import numpy as np from datetime import datetime import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable
[ 11748, 25064, 198, 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 67...
3.56
50
import torch.nn as nn import math import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import torch import numpy as np import cv2 import pdb def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) ###''' self-attention; relation-attention ''' ''' self-attention; relation-attention '''
[ 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 10688, 198, 11748, 28034, 13, 26791, 13, 19849, 62, 89, 2238, 355, 2746, 62, 89, 2238, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 28034, 198, 11748, 299, 32152, 35...
2.538889
180
"""Serves the single page app web ui.""" import json import tornado.gen from ndscheduler import settings from ndscheduler import utils from ndscheduler.server.handlers import base
[ 37811, 50, 11184, 262, 2060, 2443, 598, 3992, 334, 72, 526, 15931, 198, 198, 11748, 33918, 198, 11748, 33718, 13, 5235, 198, 198, 6738, 299, 67, 1416, 704, 18173, 1330, 6460, 198, 6738, 299, 67, 1416, 704, 18173, 1330, 3384, 4487, 198...
3.267857
56
#!/usr/bin/env python # Created: Wed Jun 21 13:46:35 2000 # Last changed: Time-stamp: <00/12/02 14:18:23 thomas> # Thomas.Sicheritz@molbio.uu.se, http://evolution.bmc.uu.se/~thomas # File: xbb_io.py import os, sys # os.system, sys.argv sys.path.insert(0, '.') sys.path.insert(0, os.path.expanduser('~thomas/cbs/python/biopython')) from Bio.ParserSupport import * from Bio import Fasta
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15622, 25, 3300, 7653, 2310, 1511, 25, 3510, 25, 2327, 4751, 198, 2, 4586, 3421, 25, 3862, 12, 301, 696, 25, 1279, 405, 14, 1065, 14, 2999, 1478, 25, 1507, 25, 1954, 294, 16911,...
2.254144
181
# Convert a Number to a String! # We need a function that can transform a number into a string. # What ways of achieving this do you know? print(number_to_string(123)) print(type(number_to_string(123)))
[ 2, 38240, 257, 7913, 284, 257, 10903, 0, 198, 198, 2, 775, 761, 257, 2163, 326, 460, 6121, 257, 1271, 656, 257, 4731, 13, 198, 2, 1867, 2842, 286, 16937, 428, 466, 345, 760, 30, 628, 198, 4798, 7, 17618, 62, 1462, 62, 8841, 7, ...
3.416667
60
import spacy from spacy.scorer import PRFScore import typer from pathlib import Path from wasabi import Printer, table import operator import benepar import clausecat_component import clausecat_model import clausecat_reader import clause_segmentation import clause_aggregation msg = Printer() def main(model_path: Path, eval_path: Path): """This script is used to evaluate the clausecat component""" nlp = spacy.load(model_path) reader = clausecat_reader.ClausecatCorpus(eval_path) examples = reader(nlp) clausecat = nlp.get_pipe("clausecat") scorer = { "POSITIVE": PRFScore(), "NEGATIVE": PRFScore(), "NEUTRAL": PRFScore(), "ANAMNESIS": PRFScore(), } for i, example in enumerate(examples): prediction = example.predicted reference = example.reference # Prediction prediction = clausecat(prediction) # Iterate through prediction and references for pred_clause, ref_clause in zip(prediction._.clauses, reference._.clauses): prediction_cats = pred_clause["cats"] reference_cats = ref_clause["cats"] prediction_class = max(prediction_cats.items(), key=operator.itemgetter(1))[ 0 ] # Add to matrix for label in prediction_cats: if label != prediction_class: prediction = 0 else: prediction = 1 if prediction == 0 and reference_cats[label] != 0: scorer[label].fn += 1 elif prediction == 1 and reference_cats[label] != 1: scorer[label].fp += 1 elif prediction == 1 and reference_cats[label] == 1: scorer[label].tp += 1 # Printing textcat_data = [] avg_fscore = 0 avg_recall = 0 avg_precision = 0 for label in scorer: textcat_data.append( ( label, round(scorer[label].fscore, 2), round(scorer[label].recall, 2), round(scorer[label].precision, 2), ) ) avg_fscore += scorer[label].fscore avg_recall += scorer[label].recall avg_precision += scorer[label].precision textcat_data.append( ( "AVERAGE", round(avg_fscore / len(scorer), 2), round(avg_recall / len(scorer), 2), round(avg_precision / len(scorer), 2), ) ) header = ("Label", "F-Score", "Recall", "Precision") print(table(textcat_data, header=header, divider=True)) if __name__ == "__main__": typer.run(main)
[ 11748, 599, 1590, 198, 6738, 599, 1590, 13, 1416, 11934, 1330, 4810, 37, 26595, 198, 11748, 1259, 525, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 373, 17914, 1330, 1736, 3849, 11, 3084, 198, 11748, 10088, 198, 11748, 1888, 538, 283,...
2.1544
1,250
import pathlib print(pathlib.Path(__file__).parent.resolve()) while True: next_cmd = input("> ") print(eval(next_cmd))
[ 11748, 3108, 8019, 198, 198, 4798, 7, 6978, 8019, 13, 15235, 7, 834, 7753, 834, 737, 8000, 13, 411, 6442, 28955, 198, 198, 4514, 6407, 25, 198, 220, 220, 220, 1306, 62, 28758, 796, 5128, 7, 5320, 366, 8, 198, 220, 220, 220, 3601, ...
2.5
52
import logging import os import aiohttp.web from connexion import AioHttpApp from nlp_annotator_api.config.config import conf from nlp_annotator_api.config.logging import setup_logging from nlp_annotator_api.server.middleware.statsd_middleware import StatsdMiddleware from nlp_annotator_api.server.signals.statsd_client import statsd_client_factory setup_logging() access_log = logging.getLogger("nlp_annotator_api.access") _file_dir = os.path.dirname(__file__) app = AioHttpApp( __name__, specification_dir=os.path.join(_file_dir, "..", "resources", "schemas"), server_args=dict( client_max_size=8 * 1024**2 ) ) app.add_api("openapi.yaml", pass_context_arg_name="request") aiohttp_app: aiohttp.web.Application = app.app aiohttp_app.cleanup_ctx.append(statsd_client_factory(conf.statsd)) aiohttp_app.middlewares.append(StatsdMiddleware()) if __name__ == "__main__": app.run(access_log=access_log)
[ 11748, 18931, 198, 11748, 28686, 198, 198, 11748, 257, 952, 4023, 13, 12384, 198, 6738, 369, 12413, 295, 1330, 317, 952, 43481, 4677, 198, 198, 6738, 299, 34431, 62, 34574, 1352, 62, 15042, 13, 11250, 13, 11250, 1330, 1013, 198, 6738, ...
2.623596
356
import tensorflow as tf from tensorflow import keras from tensorflow.keras import backend as K from keras_cv_attention_models.aotnet import AotNet from keras_cv_attention_models.download_and_load import reload_model_weights from keras_cv_attention_models.attention_layers import batchnorm_with_activation, conv2d_no_bias PRETRAINED_DICT = { "resnest101": {"imagenet": "63f9ebdcd32529cbc4b4fbbec3d1bb2f"}, "resnest200": {"imagenet": "8e211dcb089b588e18d36ba7cdf92ef0"}, "resnest269": {"imagenet": "4309ed1b0a8ae92f2b1143dc3512c5c7"}, "resnest50": {"imagenet": "eee7b20a229821f730ab205b6afeb369"}, }
[ 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 1330, 41927, 292, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 1330, 30203, 355, 509, 198, 6738, 41927, 292, 62, 33967, 62, 1078, 1463, 62, 27530, 13, 64, 313, 3262, ...
2.329588
267
"""replace FileRequest with FileGeneration Revision ID: 8692ab1298e1 Revises: 4bbc47f2b48d Create Date: 2018-10-24 14:54:39.278159 """ # revision identifiers, used by Alembic. revision = '8692ab1298e1' down_revision = '4bbc47f2b48d' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa
[ 37811, 33491, 9220, 18453, 351, 9220, 8645, 341, 198, 198, 18009, 1166, 4522, 25, 807, 46589, 397, 1065, 4089, 68, 16, 198, 18009, 2696, 25, 604, 11848, 66, 2857, 69, 17, 65, 2780, 67, 198, 16447, 7536, 25, 2864, 12, 940, 12, 1731, ...
2.526718
131
import numpy as np import random import sys chainlength = int(sys.argv[1]) dfname = sys.argv[2] outfl = 'result.data' cluster_size = int(sys.argv[3]) # This function will perform statistical analysis to the clustering results X, Xi = readdata(dfname, chainlength) size = readsize(dfname) boxl = np.array([size, size, size]) n = len(X) k = int(len(X)/cluster_size) # Set up the database of objects # X = readdata(dfname, chainlength) # Choose initial means with K-means means = initmeans(k) # Set up initial clusters distmat = SetDistMat(X, means) clusters = InitialAssignment(distmat) ## debug code #keys = sorted(clusters.keys()) #for key in keys: # print("cluster %i:"%key) # print(clusters[key]) ## end of debug # Iteration step for iter in range(100): active = 0 # indicate the number of transfers in the current iteration tranlst = (-1)*np.ones(k, dtype='int') # set up transfer list for each cluster # Compute the cluster means oldmeans = means.copy() means = CalcMeans(X, oldmeans, clusters) # Get statistics about the clustering #ClusterStat(X, means, clusters) ## debug code #print("old means:") #print(oldmeans) #print("new means:") #print(means) ## end of debug # For each object, compute the distances to the cluster means distmat = SetDistMat(X, means) # Sort objects based on the delta of the current assignment and the best # possible alternate assignment objlst = SortObj(X, clusters, means, distmat) ##debug code #print(objlst) ##return #end of debug # For each element by prioty: while (len(objlst)): (i, key, temp) = objlst.pop() obj2key = GetDist(X[i], means[key]) transferred = False #record if any transfering has occured to i if (key == distmat[i,0][0]): ##debug #print("%i is already the opt cluster for obj %i. no transfer"%(clu, i)) ##end of debug continue # For each other clusters by element gain: else: for j in range(k): clu = distmat[i,j][0] # the key of another cluster objgain = obj2key - distmat[i,j][1] # gain by transfering i from cluster key to clu if (clu==key): # already in the cluster continue if (len(clusters[clu]) < cluster_size): active += 1 transferred = True clusters = Transfer(i, key, clu, clusters) ##debug #print("cluster %i not full. transfer obj %i from cluster %i to it."%(clu, i, key)) ##end of debug break elif (tranlst[clu] != -1): # if the tranlst of another cluster is not empty # distance between the obj in the tranlst and the current cluster tran2key = GetDist(X[tranlst[clu]], means[key]) tran2clu = GetDist(X[tranlst[clu]], means[clu]) # gain by transfering the obj in tranlst from cluster clu to key trangain = tran2clu - tran2key if (objgain + trangain > 0): # transfer if the sum of gains are positive, ie net gain active += 2 transferred = True clusters = Transfer(i, key, clu, clusters) clusters = Transfer(tranlst[clu], clu, key, clusters) ##debug #print("obj %i is transfered from cluster %i to %i"%(i, key, clu)) #print("obj %i is transfered from cluster %i to %i"%(tranlst[clu], clu, key)) #print("objgain: %f, trangain: %f"%(objgain, trangain)) ##end of debug tranlst[clu] = -1 # reset the tranlst to empty break if (not transferred): tranlst[key] = i ##debug #print("add obj %i in cluster %i to the transfer list"%(i, key)) ##end of debug # nothing is transferred during this iteration, return the clustering result if (not active): break #debug code print("number of transfers in iter %i: %i\n"%(iter+1, active)) #end of debug print("K-means clustering converged in %d iterations!\n"%(iter+1)) # Output the clustering results WriteResult(outfl, X, means, clusters) ClusterStat(X, means, clusters) # print(X)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 198, 11748, 25064, 198, 198, 7983, 13664, 796, 493, 7, 17597, 13, 853, 85, 58, 16, 12962, 198, 7568, 3672, 796, 25064, 13, 853, 85, 58, 17, 60, 198, 448, 2704, 796, 705, 20274, 13, ...
2.149692
2,111
import numpy as np import quaternion sample_points = np.array([[-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-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, 0.1, 0.1], [0.1, 0.1, 0.1]]) q1 = np.array([[1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0]]) t1 = np.array([[0.1, 0.1, 0.1], [0.1, 0.1, 0.1], [0.4, 0.4, 0.4]]) cube_param_1 = {'z': z1, 'q': q1, 't': t1} z2 = np.array([[0.1, 0.1, 0.1], [0.2, 0.2, 0.2]]) q2 = np.array([[1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0]]) t2 = np.array([[0.2, 0.2, 0.2], [0.3, 0.3, 0.3]]) cube_param_2 = {'z': z2, 'q': q2, 't': t2} index = cube_inclusion(cube_param_1, cube_param_2) print(index) assert((index == np.array([0, 0, 1])).all())
[ 11748, 299, 32152, 355, 45941, 201, 198, 11748, 627, 9205, 295, 201, 198, 201, 198, 201, 198, 39873, 62, 13033, 796, 45941, 13, 18747, 26933, 58, 12, 16, 13, 15, 12095, 16, 13, 15, 12095, 16, 13, 15, 12095, 16, 13, 15, 12095, 16, ...
1.131016
16,540
from django.test import TestCase from django.utils import timezone from accounts.models import CustomUser, CustomUserManager
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 198, 6738, 5504, 13, 27530, 1330, 8562, 12982, 11, 8562, 12982, 13511, 628 ]
4.2
30
import os from typing import List import numpy as np from torchvision import datasets as torchdata from continuum.datasets import ImageFolderDataset from continuum import download from continuum.tasks import TaskType
[ 11748, 28686, 198, 6738, 19720, 1330, 7343, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 28034, 10178, 1330, 40522, 355, 28034, 7890, 198, 198, 6738, 44422, 13, 19608, 292, 1039, 1330, 7412, 41092, 27354, 292, 316, 198, 6738, 44422...
4.169811
53
from board import Direction # Tuples of input, action, expected output. moving_tests = [ ( [[0,0,0,0], [4,0,0,0], [0,0,0,0], [4,0,2,0]], Direction.UP, [[8,0,2,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]] ), ( [[0,0,0,0], [4,0,0,0], [0,0,0,0], [4,0,2,0]], Direction.DOWN, [[0,0,0,0], [0,0,0,0], [0,0,0,0], [8,0,2,0]] ), ( [[0,0,0,0], [4,0,0,0], [0,0,0,0], [4,0,2,0]], Direction.LEFT, [[0,0,0,0], [4,0,0,0], [0,0,0,0], [4,2,0,0]] ), ( [[0,0,0,0], [4,0,0,0], [0,0,0,0], [4,0,2,0]], Direction.RIGHT, [[0,0,0,0], [0,0,0,4], [0,0,0,0], [0,0,4,2]] ), ( [[4,4,4,4], [8,0,8,4], [32,16,0,16], [16,8,2,4]], Direction.RIGHT, [[0,0,8,8], [0,0,16,4], [0,0,32,32], [16,8,2,4]] ), ( [[4,4,4,4], [8,0,8,4], [32,16,0,16], [16,8,2,4]], Direction.LEFT, [[8,8,0,0], [16,4,0,0], [32,32,0,0], [16,8,2,4]] ), ( [[4,4,4,4], [8,0,8,4], [32,16,0,16], [16,8,2,4]], Direction.UP, [[4,4,4,8], [8,16,8,16], [32,8,2,4], [16,0,0,0]] ), ( [[4,4,4,4], [8,0,8,4], [32,16,0,16], [16,8,2,4]], Direction.DOWN, [[4,0,0,0], [8,4,4,8], [32,16,8,16], [16,8,2,4]] ) ]
[ 6738, 3096, 1330, 41837, 198, 198, 2, 16749, 2374, 286, 5128, 11, 2223, 11, 2938, 5072, 13, 198, 31462, 62, 41989, 796, 685, 198, 220, 220, 220, 357, 198, 220, 220, 220, 220, 220, 220, 220, 16410, 15, 11, 15, 11, 15, 11, 15, 435...
1.257807
1,377
import pytest from pji.utils import ValueProxy
[ 11748, 12972, 9288, 198, 198, 6738, 279, 7285, 13, 26791, 1330, 11052, 44148, 628 ]
3.5
14
#Intro Page from tkinter import * from PIL import Image, ImageTk import cv2 #----------------------------Start Function--------------------------# #------------------------Main Window---------------------------------#li main_window()
[ 2, 5317, 305, 7873, 198, 6738, 256, 74, 3849, 1330, 1635, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 51, 74, 198, 11748, 269, 85, 17, 628, 198, 2, 1783, 10541, 10434, 15553, 22369, 438, 2, 628, 198, 2, 22369, 13383, 26580, 3880, ...
4.528302
53
""" This module provides helper functions to support exercises during AM1 with outliers, robust regression and template regression in the CORE data analytics workshop series, week 4. """ import numpy as np import pandas as pd import math from collections import namedtuple def recovery_sulphur_dataframe_with_outliers(outlier_probability): """Return dataframe representing recovery as a function of sulphur. Parameters: ---------- outlier_probability: This floating point parameter should range between 0 and 1 and is probability of an observation being an outlier. Returns: ------- Pandas dataframe: A dataframe is returned with two series, the first being observed recovery, and the second being sulphur %. The data may be sampled from the true underlying relationship, plus gaussian noise, or may be an outlier value taken from a non-gaussian distribution. The proportion of outliers to non-outliers will depend on the outlier_probability parameter. """ # Check that the outlier_probability is an ordinary number. assert isinstance(outlier_probability, (float, int)) # As it's a probability, ensure that it ranges between 0 and 1. assert outlier_probability >= 0.0 assert outlier_probability <= 1.0 # If no exceptions have been thrown then we likely have a valid input. # Get 50 pairs of sulphur features and recovery labels sulphur_percent = _draw_sulphur_observations(50) recovery_percent = _observe_recovery(sulphur_percent, outlier_probability) return pd.DataFrame({'metal_recovery_percent': recovery_percent, 'feed_sulphur_percent': sulphur_percent}) def _initialise_randomstate(seed): """ Use RandomState object with seed set.""" return np.random.RandomState(seed) def _observe_recovery(sulphur_percent, outlier_probability): """Returns an array of metal recoveries. This method returns an array of metal recoveries given both an array of sulphur percentages and the probability of an outlier being observed. """ recovery_percent = np.zeros_like(sulphur_percent) is_outlier = _is_outlier(outlier_probability, len(sulphur_percent)) for index in range(0, len(recovery_percent)): if is_outlier[index]: recovery_percent [index]= _return_outlier_model_of_recovery(sulphur_percent[index]) else: recovery_percent [index]=_noise_free_model_of_recovery(sulphur_percent[index]) return recovery_percent def _noise_free_model_of_recovery(sulphur): """This method returns a metal recovery for a given sulphur %.""" return 74.81 - 6.81/sulphur def _is_outlier(outlier_probability, how_many): """Return true/false numpy array """ rs = _initialise_randomstate(5) uniformly_distributed = rs.uniform(0, 1, how_many) is_outlier = np.zeros_like(uniformly_distributed) for index in range(0, len(is_outlier)): is_outlier[index]=uniformly_distributed[index]>(1-outlier_probability) return is_outlier def add_gaussian_noise(noise_free_input, mean, sigma): """Adds gaussian noise to vector, given mean and sigma """ bins = len(noise_free_input) noise = np.random.normal(mean, sigma, bins) return noise_free_input + noise def gaussian_fwhm_pdf(X, height, x_position, fwhm): """Returns guassian probability distribution function, given FWHM This computes a gaussian probability density function (pdf) given a Full Width at Half Maximum (FWHM) instead of standard deviation, and scales it by the height parameters. If the height is one, then the area of the guassian will also be unity, as required for a pdf, and for preserving area when used as an impulse response function in convolution operations. Note, this returns the function, it does not sample from the distribution. """ return gaussian_pdf(X, height, x_position, fwhm / (2 * math.sqrt(2 * math.log(2)))) def gaussian_pdf(X, area, x_position, standard_deviation): """Returns gaussian probability distribution function multiplied by area. This computes a gaussian with unit area and multiplies it by the area parameter. It is translated to be centered on x_position and has the width specified by standard_deviation. Unit area gaussians are used as probability distributions functions, and are also important in convolutions, as area of the convolution of two functions is the product of their areas. If it is important for the convolution to preserve area of a function when convolved with a gaussian then that gaussian needs to have unit area. Preserving area also implies conservation of energy in many physical models. It can be shown that the integral of the gaussian function is unity when the guassian's height is scaled as a function of standard_deviation as: height_scaling = 1/(standard_deviation*sqrt(2*pi)) So this function multiplies the height of the guassian by this factor and then multiplies this result by the area parameter that is passed in. If area parameter is 1, then the height of this gaussian with also be 1 for all standard deviations, otherwise the area will be set by the area parameter. The relationship between height and area, and the scaling of height by the second parameter below, will be made clearer by also studying the guassian function. """ return gaussian(X, area / (standard_deviation * math.sqrt(2 * math.pi)), x_position, standard_deviation) def gaussian(X, height, x_position, standard_deviation): """Return standard gaussian function This is the unnormalised gaussian function f(x)=height*exp(-(x-x_position)^2/(2*standard_deviation^2)) Parameters ---------- height: This is the maximum of the gaussian peak. This function does not normalise to constant area, the caller must do this if this is what they want. x_position: This is the x position of the centre of the gaussian. If the guassian is being used to apply the impulse response of an instrument applied to an XRD reflection, then this will be the two-theta position of the peak. standard_deviation: The standard deviation of the guassian curve. If this function is being applied in spectroscopy, optics or electrical engineering, it is common for gaussians to be defined in terms of Full Width at Half Maximum (FWHM), which is the width of the peak when the height drops to half of the peak height, specified by the height parameter. If the x-axis represents frequency, and the function height is proportional to energy or power, then this will be the gaussian's bandwidth, that is, the width between the -3db points. To convert from FWHM to standard deviation use the relationship: FWHM = 2*sqrt(2*log(2)) * standard_deviation Returns ------- double: Evaluated gaussian function. """ return height * math.e**(-(X - x_position)**2 / 2 / standard_deviation**2) def _apply_convolution_kernals(x_axis_vector, intensity, two_theta_angle, instrument_broadening_fwhm, reflection_broadening_fwhm): """Apply gaussian kernel for instrument broadening only.""" fwhm = _add_gaussian_fwhms (instrument_broadening_fwhm, reflection_broadening_fwhm) return gaussian_fwhm_pdf(x_axis_vector, intensity, two_theta_angle, fwhm) def create_templates_matrix(): """Create templates for four test pure components. This creates templates for quartz, dilithium, kryptonite and unobtainium, in that order. The templates are returned in an array where the first column is quartz, and the last is unobtainium. If you plot them, you'll see gently varying squiggly lines. """ # Create a templates matrix containing space for four templates, plus # a column of ones. x_axis = MultichannelXAxis(5, 90, 0.2) template_count = 4 templates_matrix = np.zeros((x_axis.channel_count, template_count+1)) # set 4 two-theta units of instrument broadening instrument_broadening = 4 # create a tuple for each reflection, and add it to a list. The loop # then grabs each reflection from the list and then adds it to the # template. The first value in the tuple is intensity, the second # two-theta angle and the third is how much broadening to apply. Reflection = namedtuple('Reflection', ('intensity', 'two_theta', 'broadening')) quartz_reflections = [] quartz_reflections.append (Reflection(intensity=10.0, two_theta=25.0, broadening=3.0)) quartz_reflections.append (Reflection(13.0, 38.0, 6.0)) quartz_reflections.append (Reflection(10.0, 43.0, 2.0)) quartz_reflections.append (Reflection(25.0, 60, 2.0)) dilithium_reflections = [] dilithium_reflections.append (Reflection(25.0, 80, 1.0)) kryptonite_reflections = [] #kryptonite_reflections.append (Reflection(intensity=12.0, two_theta=25.0, broadening=9.0)) kryptonite_reflections.append (Reflection(17.0, 12.0, 1.0)) kryptonite_reflections.append (Reflection(19.0, 43.0, 12.0)) #kryptonite_reflections.append (Reflection(4.0, 70, 2.0)) #kryptonite_reflections.append (Reflection(32.0, 74, 2.0)) unobtainium_reflections = [] #unobtainium_reflections.append (Reflection(intensity=4.0, two_theta=25.0, broadening=12.0)) unobtainium_reflections.append (Reflection(5.0, 18.0, 6.0)) unobtainium_reflections.append (Reflection(1.0, 23.0, 1.0)) unobtainium_reflections.append (Reflection(5.0, 31.0, 2.0)) unobtainium_reflections.append (Reflection(3.0, 55.0, 6.0)) unobtainium_reflections.append (Reflection(7.0, 58.0, 1.0)) #unobtainium_reflections.append (Reflection(5.0, 80, 2.0)) phases=[] # create four phases phases.append(quartz_reflections) phases.append(dilithium_reflections) phases.append(kryptonite_reflections) phases.append(unobtainium_reflections) for phase_idx in range(0, template_count): for a_reflection in phases[phase_idx]: contribution_of_this_reflection = \ _apply_convolution_kernals( x_axis.as_vector, a_reflection.intensity, a_reflection.two_theta, instrument_broadening, a_reflection.broadening) templates_matrix[:, phase_idx] += \ contribution_of_this_reflection # set the last column to be all ones templates_matrix[:, template_count] = \ np.ones(x_axis.channel_count) return templates_matrix def create_composition_dataframe(observations_count): """Create a dataframe of observations of drilling samples Returns: Pandas DataFrame with observations_count observations. The dataframe has four columns representing the amount of quartz, dilithium, kryptonite and unobtainium present. These values are drawn from uniform distributions.""" unobtainium = _draw_unobtainium_observations (observations_count) dilithium = _draw_dilithium_observations(observations_count) kryptonite = _draw_kryptonite_observations(observations_count) quartz = _draw_quartz_observations(observations_count) # Create clusters by imposing a relationship between quartz # and dilithium. for observation_idx in range(0, observations_count): if quartz[observation_idx] > 30: dilithium[observation_idx] = 5 if dilithium[observation_idx] > 30: quartz[observation_idx] = 5 return pd.DataFrame({'Quartz': quartz, 'Dilithium': dilithium, 'Kryptonite': kryptonite, 'Unobtainium': unobtainium}) def create_observations(compositions_dataframe, templates): """Create a new array containing synthetic observations""" observations_count = len(compositions_dataframe) channels_count = len(templates[:,0]) observations_matrix = np.zeros((channels_count, observations_count)) for observation_idx in range (0, observations_count): observations_matrix[:, observation_idx] = \ templates[:,0]*compositions_dataframe['Quartz'][observation_idx] + \ templates[:,1]*compositions_dataframe['Dilithium'][observation_idx] + \ templates[:,2]*compositions_dataframe['Kryptonite'][observation_idx] + \ templates[:,3]*compositions_dataframe['Unobtainium'][observation_idx] # add gaussian noise. If you have time, try increasing this and watch # prediction performance fall over. observations_matrix[:, observation_idx] = \ add_gaussian_noise(observations_matrix[:, observation_idx], 10, 3) return observations_matrix
[ 37811, 201, 198, 1212, 8265, 3769, 31904, 5499, 284, 1104, 13565, 1141, 3001, 16, 201, 198, 4480, 41528, 3183, 11, 12373, 20683, 290, 11055, 20683, 287, 262, 327, 6965, 201, 198, 7890, 23696, 20243, 2168, 11, 1285, 604, 13, 201, 198, ...
2.590123
5,204
from radixlib.actions import CreateTokenDefinition from typing import Dict, Any import unittest
[ 6738, 2511, 844, 8019, 13, 4658, 1330, 13610, 30642, 36621, 198, 6738, 19720, 1330, 360, 713, 11, 4377, 198, 11748, 555, 715, 395 ]
4.130435
23
floatVar = 1.0 listVar = [3, "hello"] dictVar = { "myField": "value" } aotVar = [dictVar, dictVar] intVar = 1
[ 22468, 19852, 796, 352, 13, 15, 198, 4868, 19852, 796, 685, 18, 11, 366, 31373, 8973, 198, 11600, 19852, 796, 1391, 198, 220, 220, 220, 366, 1820, 15878, 1298, 366, 8367, 1, 198, 92, 198, 64, 313, 19852, 796, 685, 11600, 19852, 11, ...
2.215686
51
"""Recipes for xTB"""
[ 37811, 6690, 18636, 329, 2124, 22737, 37811, 198 ]
2.75
8
# coding=utf-8 # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os from pants.backend.native.config.environment import Assembler, CCompiler, CppCompiler, Linker from pants.engine.rules import rule from pants.engine.selectors import Select from pants.subsystem.subsystem import Subsystem from pants.util.dirutil import is_readable_dir from pants.util.memo import memoized_method, memoized_property MIN_OSX_SUPPORTED_VERSION = '10.11' MIN_OSX_VERSION_ARG = '-mmacosx-version-min={}'.format(MIN_OSX_SUPPORTED_VERSION) def create_xcode_cli_tools_rules(): return [ get_assembler, get_ld, get_clang, get_clang_plusplus, ]
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 2864, 41689, 1628, 20420, 357, 3826, 27342, 9865, 3843, 20673, 13, 9132, 737, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 3826, 38559, 24290, 737, 198, 198, 6738, 1...
2.978261
276
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2021 Met Office. # 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. """Unit tests for the RegridWithLandSeaMask class""" # set up a special data set and corresponding land-sea mask info # set up target grid and its land-sea mask info # it is designed to cover different scenarios for regridding with land-sea # the regridding reference results are manually checked for different methods # not using "set_up_variable_cube" because of different spacing at lat/lon import numpy as np from improver.regrid.bilinear import basic_indexes from improver.regrid.grid import calculate_input_grid_spacing, latlon_from_cube from improver.regrid.landsea import RegridLandSea from improver.synthetic_data.set_up_test_cubes import set_up_variable_cube def modify_cube_coordinate_value(cube, coord_x, coord_y): """modify x(longitude) & y(latitude) andcoordinates for a cube""" cube.coord(axis="x").points = coord_x cube.coord(axis="x").bounds = None cube.coord(axis="x").guess_bounds() cube.coord(axis="y").points = coord_y cube.coord(axis="y").bounds = None cube.coord(axis="y").guess_bounds() return cube def define_source_target_grid_data(): """ define cube_in, cube_in_mask,cube_out_mask using assumed data """ # source (input) grid in_lats = np.linspace(0, 15, 4) in_lons = np.linspace(0, 40, 5) # target (output) grid out_lats = np.linspace(0, 14, 8) out_lons = np.linspace(5, 35, 11) # assume a set of nwp data data = np.arange(20).reshape(4, 5).astype(np.float32) # input grid mask info in_mask = np.empty((4, 5), dtype=np.int) in_mask[:, :] = 1 in_mask[0, 2] = 0 in_mask[2, 2:4] = 0 in_mask[3, 2:4] = 0 # output grid mask info out_mask = np.empty((8, 11), dtype=np.int) out_mask[:, :] = 1 out_mask[0, 4:7] = 0 out_mask[1, 5] = 0 out_mask[5:9, 4:10] = 0 out_mask[6, 6] = 1 out_mask[7, 6] = 1 out_mask[1, 0] = 0 # create cube with default spacing cube_in = set_up_variable_cube(data, "air_temperature", "Celsius") cube_in_mask = set_up_variable_cube(in_mask, "Land_Binary_Mask", "1") cube_out_mask = set_up_variable_cube(out_mask, "Land_Binary_Mask", "1") # modify cube coordinates to the designed value cube_in = modify_cube_coordinate_value(cube_in, in_lons, in_lats) cube_in_mask = modify_cube_coordinate_value(cube_in_mask, in_lons, in_lats) cube_out_mask = modify_cube_coordinate_value(cube_out_mask, out_lons, out_lats) return cube_in, cube_out_mask, cube_in_mask def define_source_target_grid_data_same_domain(): """ define cube_in, cube_in_mask,cube_out_mask, assume the same domain """ # source (input) grid in_lats = np.linspace(0, 15, 4) in_lons = np.linspace(0, 40, 5) # target (output) grid out_lats = np.linspace(0, 15, 7) out_lons = np.linspace(5, 40, 9) # assume a set of nwp data data = np.arange(20).reshape(4, 5).astype(np.float32) # input grid mask info in_mask = np.empty((4, 5), dtype=np.int) in_mask[:, :] = 1 in_mask[0, 2] = 0 in_mask[2, 2:4] = 0 in_mask[3, 2:4] = 0 # output grid mask info out_mask = np.empty((7, 9), dtype=np.int) out_mask[:, :] = 1 out_mask[0, 3:6] = 0 out_mask[1, 4] = 0 out_mask[4:9, 4:8] = 0 out_mask[6, 6] = 1 out_mask[1, 0] = 0 # create cube with default spacing cube_in = set_up_variable_cube(data, "air_temperature", "Celsius") cube_in_mask = set_up_variable_cube(in_mask, "Land_Binary_Mask", "1") cube_out_mask = set_up_variable_cube(out_mask, "Land_Binary_Mask", "1") # modify cube coordinates to the designed value cube_in = modify_cube_coordinate_value(cube_in, in_lons, in_lats) cube_in_mask = modify_cube_coordinate_value(cube_in_mask, in_lons, in_lats) cube_out_mask = modify_cube_coordinate_value(cube_out_mask, out_lons, out_lats) return cube_in, cube_out_mask, cube_in_mask def test_basic_indexes(): """Test basic_indexes for identical source and target domain case """ cube_in, cube_out_mask, _ = define_source_target_grid_data_same_domain() in_latlons = latlon_from_cube(cube_in) out_latlons = latlon_from_cube(cube_out_mask) in_lons_size = cube_in.coord(axis="x").shape[0] lat_spacing, lon_spacing = calculate_input_grid_spacing(cube_in) indexes = basic_indexes( out_latlons, in_latlons, in_lons_size, lat_spacing, lon_spacing ) test_results = indexes[58:63, :] expected_results = np.array( [ [12, 17, 18, 13], [12, 17, 18, 13], [13, 18, 19, 14], [13, 18, 19, 14], [13, 18, 19, 14], ] ) np.testing.assert_array_equal(test_results, expected_results) def test_regrid_nearest_2(): """Test nearest neighbour regridding option 'nearest-2'""" cube_in, cube_out_mask, _ = define_source_target_grid_data() regrid_nearest = RegridLandSea(regrid_mode="nearest-2",)(cube_in, cube_out_mask) expected_results = np.array( [ [0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3], [0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3], [5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8], [5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8], [10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13], [10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13], [10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13], [15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 18], ] ) np.testing.assert_allclose(regrid_nearest.data, expected_results, atol=1e-3) def test_regrid_bilinear_2(): """Test bilinear regridding option 'bilinear-2'""" cube_in, cube_out_mask, _ = define_source_target_grid_data() regrid_bilinear = RegridLandSea(regrid_mode="bilinear-2",)(cube_in, cube_out_mask) expected_results = np.array( [ [0.5, 0.8, 1.1, 1.4, 1.7, 2.0, 2.3, 2.6, 2.9, 3.2, 3.5], [2.5, 2.8, 3.1, 3.4, 3.7, 4.0, 4.3, 4.6, 4.9, 5.2, 5.5], [4.5, 4.8, 5.1, 5.4, 5.7, 6.0, 6.3, 6.6, 6.9, 7.2, 7.5], [6.5, 6.8, 7.1, 7.4, 7.7, 8.0, 8.3, 8.6, 8.9, 9.2, 9.5], [8.5, 8.8, 9.1, 9.4, 9.7, 10.0, 10.3, 10.6, 10.9, 11.2, 11.5], [10.5, 10.8, 11.1, 11.4, 11.7, 12.0, 12.3, 12.6, 12.9, 13.2, 13.5], [12.5, 12.8, 13.1, 13.4, 13.7, 14.0, 14.3, 14.6, 14.9, 15.2, 15.5], [14.5, 14.8, 15.1, 15.4, 15.7, 16.0, 16.3, 16.6, 16.9, 17.2, 17.5], ] ) np.testing.assert_allclose(regrid_bilinear.data, expected_results, atol=1e-3) def test_regrid_nearest_with_mask_2(): """Test nearest-with-mask-2 regridding""" cube_in, cube_out_mask, cube_in_mask = define_source_target_grid_data() regrid_nearest_with_mask = RegridLandSea( regrid_mode="nearest-with-mask-2", landmask=cube_in_mask, landmask_vicinity=250000000, )(cube_in, cube_out_mask) expected_results = np.array( [ [0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3], [0, 1, 1, 1, 7, 2, 7, 3, 3, 3, 3], [5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8], [5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9], [10, 11, 11, 11, 7, 7, 7, 8, 8, 8, 14], [10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 14], [10, 11, 11, 11, 12, 12, 7, 13, 13, 13, 14], [15, 16, 16, 16, 17, 17, 7, 18, 18, 18, 19], ] ) np.testing.assert_allclose( regrid_nearest_with_mask.data, expected_results, atol=1e-3 ) # consider constant field cube_in.data = np.repeat(1.0, 20).reshape(4, 5).astype(np.float32) regrid_nearest_with_mask = RegridLandSea( regrid_mode="nearest-with-mask-2", landmask=cube_in_mask, landmask_vicinity=250000000, )(cube_in, cube_out_mask) expected_results = np.repeat(1.0, 88).reshape(8, 11).astype(np.float32) np.testing.assert_allclose( regrid_nearest_with_mask.data, expected_results, atol=1e-3 ) def test_regrid_bilinear_with_mask_2(): """Test bilinear-with-mask-2 regridding """ cube_in, cube_out_mask, cube_in_mask = define_source_target_grid_data() regrid_bilinear_with_mask = RegridLandSea( regrid_mode="bilinear-with-mask-2", landmask=cube_in_mask, landmask_vicinity=250000000, )(cube_in, cube_out_mask) expected_results = np.array( [ [0.5, 0.8, 1.40096, 3.2916, 2.0, 2.0, 2.0, 4.94333, 3.25586, 3.2, 3.5], [2.5, 2.8, 3.1, 3.4, 5.48911, 2.76267, 6.32926, 4.6, 4.9, 5.2, 5.5], [4.5, 4.8, 5.1, 5.4, 5.7, 7.0154, 6.3, 6.6, 6.9, 7.2, 7.5], [6.5, 6.8, 7.1, 7.4, 7.7, 7.0, 7.19033, 7.6681, 7.6618, 9.2, 9.5], [ 8.5, 8.8, 9.1, 9.4, 8.10633, 7.0, 7.0, 7.62915, 7.21672, 9.11434, 10.52363, ], [ 10.5, 10.8, 11.00012, 11.01183, 13.15439, 12.0, 12.3, 12.6, 12.9, 13.71286, 15.74504, ], [ 12.5, 12.8, 12.23411, 13.25881, 14.14155, 14.0, 8.07328, 14.6, 14.9, 14.96332, 16.3334, ], [ 14.5, 14.8, 15.0997, 14.22659, 15.50905, 16.0, 9.8733, 16.6, 16.9, 16.91114, 17.03773, ], ] ) np.testing.assert_allclose( regrid_bilinear_with_mask.data, expected_results, atol=1e-3 ) # consider constant field cube_in.data = np.repeat(1.0, 20).reshape(4, 5).astype(np.float32) regrid_bilinear_with_mask = RegridLandSea( regrid_mode="bilinear-with-mask-2", landmask=cube_in_mask, landmask_vicinity=250000000, )(cube_in, cube_out_mask) expected_results = np.repeat(1.0, 88).reshape(8, 11).astype(np.float32) np.testing.assert_allclose( regrid_bilinear_with_mask.data, expected_results, atol=1e-3 )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 16529, 32501, 198, 2, 357, 34, 8, 3517, 12223, 15069, 2177, 12, 1238, 2481, 3395, 4452, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2297, 396, 3890, 290, ...
2.01275
5,961
#!/usr/bin/env python from setuptools import setup, find_packages import os requires = [ ] setup( name='details', version=open(os.path.join('details', '_version')).read(), description='Tools for processing AWS detailed billing reports', long_description=open('README.md').read(), author='Mitch Garnaat', author_email='mitch@scopely.com', url='https://github.com/scopely-devops/details', packages=find_packages(exclude=['tests*']), package_dir={'details': 'details'}, install_requires=requires, license=open("LICENSE").read(), classifiers=( 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ), )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 11748, 28686, 198, 198, 47911, 796, 685, 198, 60, 628, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 36604, ...
2.755501
409
''' Script to check the correctness of the analysis. The analysis is done on raw data and all results are compared to a recorded analysis. ''' import os import unittest import numpy as np from beam_telescope_analysis import track_analysis from beam_telescope_analysis.tools import test_tools if __name__ == '__main__': import logging logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - [%(levelname)-8s] (%(threadName)-10s) %(message)s") suite = unittest.TestLoader().loadTestsFromTestCase(TestTrackAnalysis) unittest.TextTestRunner(verbosity=2).run(suite)
[ 7061, 6, 12327, 284, 2198, 262, 29409, 286, 262, 3781, 13, 383, 3781, 318, 1760, 319, 8246, 1366, 290, 477, 2482, 389, 3688, 284, 257, 6264, 3781, 13, 198, 7061, 6, 198, 11748, 28686, 198, 198, 11748, 555, 715, 395, 198, 198, 11748,...
3.045685
197
# Licensed under a 3-clause BSD style license - see LICENSE.rst import glob import os import sys import json from os.path import join, isfile import pytest from asv import util from . import tools
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 81, 301, 198, 198, 11748, 15095, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 33918, 198, 6738, 28686, 13, 6978, 1330, 4654, 11, 318, 7753...
3.311475
61
# @author Metro # @time 2021/11/24 import os.path import gym from agents.pdqn import P_DQN from utilities.memory import ReplayBuffer from utilities.utilities import * from utilities.route_generator import generate_routefile
[ 2, 2488, 9800, 12477, 198, 2, 2488, 2435, 33448, 14, 1157, 14, 1731, 198, 11748, 28686, 13, 6978, 198, 198, 11748, 11550, 198, 6738, 6554, 13, 30094, 80, 77, 1330, 350, 62, 35, 48, 45, 198, 6738, 20081, 13, 31673, 1330, 23635, 28632...
3.373134
67
import sys import pprint import json import datetime import uuid import urllib import types import traceback from django.core.urlresolvers import reverse, resolve from django.http import HttpResponseRedirect, Http404, HttpResponseServerError, HttpResponseNotFound from django.conf import settings from django.contrib.auth.decorators import login_required from django.views.decorators.cache import never_cache from django.views.debug import ExceptionReporter, get_safe_settings from django.template import TemplateDoesNotExist, Context from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.shortcuts import render from splunkdj.decorators.render import render_to from splunkdj.utility import make_splunkweb_url from urlparse import urlparse import logging logger = logging.getLogger('spl.django.service') error_logger = logging.getLogger('spl.django.request_error') def format(value): """ Format values appropriately for json.dumps: - Basic types will remain the same - Unicode will be converted to str - Everything else will be formatted using pprint """ if value is None: return value if isinstance(value, (int, long, str, float, list, dict, tuple, bool, unicode)): return value return str(pprint.pformat(value))
[ 11748, 25064, 198, 11748, 279, 4798, 198, 11748, 33918, 198, 11748, 4818, 8079, 198, 11748, 334, 27112, 198, 11748, 2956, 297, 571, 198, 11748, 3858, 198, 11748, 12854, 1891, 198, 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, 690, 1...
3.221687
415
# -*- coding: utf-8 -*- import logging import utool as ut import six from . import draw_func2 as df2 from wbia.plottool import plot_helpers as ph from wbia.plottool import interact_helpers as ih from wbia.plottool.viz_featrow import draw_feat_row from wbia.plottool.viz_keypoints import show_keypoints from wbia.plottool import abstract_interaction (print, rrr, profile) = ut.inject2(__name__) logger = logging.getLogger('wbia') def ishow_keypoints(chip, kpts, desc, fnum=0, figtitle=None, nodraw=False, **kwargs): """ TODO: Depricate in favor of the class CommandLine: python -m wbia.plottool.interact_keypoints --test-ishow_keypoints --show python -m wbia.plottool.interact_keypoints --test-ishow_keypoints --show --fname zebra.png Example: >>> # DISABLE_DOCTEST >>> from wbia.plottool.interact_keypoints import * # NOQA >>> import numpy as np >>> import wbia.plottool as pt >>> import utool as ut >>> import pyhesaff >>> import vtool as vt >>> kpts, vecs, imgBGR = pt.viz_keypoints.testdata_kpts() >>> ut.quit_if_noshow() >>> #pt.interact_keypoints.ishow_keypoints(imgBGR, kpts, vecs, ori=True, ell_alpha=.4, color='distinct') >>> pt.interact_keypoints.ishow_keypoints(imgBGR, kpts, vecs, ori=True, ell_alpha=.4) >>> pt.show_if_requested() """ if isinstance(chip, six.string_types): import vtool as vt chip = vt.imread(chip) fig = ih.begin_interaction('keypoint', fnum) annote_ptr = [1] self = ut.DynStruct() # MOVE TO A CLASS INTERACTION self.kpts = kpts vecs = desc self.vecs = vecs # Draw without keypoints the first time _viz_keypoints(fnum, **kwargs) # MAYBE: remove kwargs ih.connect_callback(fig, 'button_press_event', _on_keypoints_click) if not nodraw: ph.draw()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 18931, 198, 11748, 3384, 970, 355, 3384, 198, 11748, 2237, 198, 6738, 764, 1330, 3197, 62, 20786, 17, 355, 47764, 17, 198, 6738, 266, 23339, 13, 489, 1252, 970, ...
2.32963
810
from .database import StDatabase from .telegram import StTelegram from .tinydb import TinyDataBase, TinySelect from .utility import StDispatch
[ 6738, 764, 48806, 1330, 520, 38105, 198, 6738, 764, 660, 30536, 1330, 520, 6767, 30536, 198, 6738, 764, 44152, 9945, 1330, 20443, 6601, 14881, 11, 20443, 17563, 198, 6738, 764, 315, 879, 1330, 520, 49354, 198 ]
3.972222
36
from algorithms.maths.gcd import gcd from typing import List def solve_chinese_remainder(num : List[int], rem : List[int]): """ Computes the smallest x that satisfies the chinese remainder theorem for a system of equations. The system of equations has the form: x % num[0] = rem[0] x % num[1] = rem[1] ... x % num[k - 1] = rem[k - 1] Where k is the number of elements in num and rem, k > 0. All numbers in num needs to be pariwise coprime otherwise an exception is raised returns x: the smallest value for x that satisfies the system of equations """ if not len(num) == len(rem): raise Exception("num and rem should have equal length") if not len(num) > 0: raise Exception("Lists num and rem need to contain at least one element") for n in num: if not n > 1: raise Exception("All numbers in num needs to be > 1") if not _check_coprime(num): raise Exception("All pairs of numbers in num are not coprime") k = len(num) x = 1 while True: i = 0 while i < k: if x % num[i] != rem[i]: break i += 1 if i == k: return x else: x += 1
[ 6738, 16113, 13, 11018, 82, 13, 70, 10210, 1330, 308, 10210, 198, 6738, 19720, 1330, 7343, 198, 198, 4299, 8494, 62, 354, 3762, 62, 2787, 391, 1082, 7, 22510, 1058, 7343, 58, 600, 4357, 816, 1058, 7343, 58, 600, 60, 2599, 198, 220, ...
2.402321
517
import spacy nlp = spacy.load("ja_core_news_sm") text = ( "" "" ) # doc = nlp(text) print([token.text for token in doc])
[ 11748, 599, 1590, 198, 198, 21283, 79, 796, 599, 1590, 13, 2220, 7203, 6592, 62, 7295, 62, 10827, 62, 5796, 4943, 198, 5239, 796, 357, 198, 220, 220, 220, 13538, 198, 220, 220, 220, 13538, 198, 8, 198, 198, 2, 220, 198, 15390, 796...
2.163934
61
# -*- coding: utf-8 -*- """ ## @author: lywen """ import sys import six import os import base64 import requests import numpy as np import cv2 from PIL import Image import traceback import uuid from glob import glob from bs4 import BeautifulSoup import numpy as np from scipy.spatial import distance as dist def _order_points(pts): # x """ --------------------- Tong_T CSDN https://blog.csdn.net/Tong_T/article/details/81907132 """ x_sorted = pts[np.argsort(pts[:, 0]), :] # # x left_most = x_sorted[:2, :] right_most = x_sorted[2:, :] # y left_most = left_most[np.argsort(left_most[:, 1]), :] (tl, bl) = left_most # ; # distance = dist.cdist(tl[np.newaxis], right_most, "euclidean")[0] (br, tr) = right_most[np.argsort(distance)[::-1], :] # return np.array([tl, tr, br, bl], dtype="float32") def solve(box): """ cx,cy w,h angle x = cx-w/2 y = cy-h/2 x1-cx = -w/2*cos(angle) +h/2*sin(angle) y1 -cy= -w/2*sin(angle) -h/2*cos(angle) h(x1-cx) = -wh/2*cos(angle) +hh/2*sin(angle) w(y1 -cy)= -ww/2*sin(angle) -hw/2*cos(angle) (hh+ww)/2sin(angle) = h(x1-cx)-w(y1 -cy) """ x1,y1,x2,y2,x3,y3,x4,y4= box[:8] cx = (x1+x3+x2+x4)/4.0 cy = (y1+y3+y4+y2)/4.0 w = (np.sqrt((x2-x1)**2+(y2-y1)**2)+np.sqrt((x3-x4)**2+(y3-y4)**2))/2 h = (np.sqrt((x2-x3)**2+(y2-y3)**2)+np.sqrt((x1-x4)**2+(y1-y4)**2))/2 #x = cx-w/2 #y = cy-h/2 sinA = (h*(x1-cx)-w*(y1 -cy))*1.0/(h*h+w*w)*2 if abs(sinA)>1: angle = None else: angle = np.arcsin(sinA) return angle,w,h,cx,cy def read_singLine_for_yolo(p): """ """ im = Image.open(p).convert('RGB') w,h = im.size boxes = [{'cx':w/2,'cy':h/2,'w':w,'h':h,'angle':0.0}] return im,boxes def xy_rotate_box(cx,cy,w,h,angle): """ cx,cy w,h angle x_new = (x-cx)*cos(angle) - (y-cy)*sin(angle)+cx y_new = (x-cx)*sin(angle) + (y-cy)*sin(angle)+cy """ cx = float(cx) cy = float(cy) w = float(w) h = float(h) angle = float(angle) x1,y1 = rotate(cx-w/2,cy-h/2,angle,cx,cy) x2,y2 = rotate(cx+w/2,cy-h/2,angle,cx,cy) x3,y3 = rotate(cx+w/2,cy+h/2,angle,cx,cy) x4,y4 = rotate(cx-w/2,cy+h/2,angle,cx,cy) return x1,y1,x2,y2,x3,y3,x4,y4 from numpy import cos,sin,pi,tan def rotate(x,y,angle,cx,cy): """ (x,y) (cx,cy) """ #angle = angle*pi/180 x_new = (x-cx)*cos(angle) - (y-cy)*sin(angle)+cx y_new = (x-cx)*sin(angle) + (y-cy)*cos(angle)+cy return x_new,y_new def get_rorate(boxes,im,degree=0): """ boxim """ imgW,imgH = im.size newBoxes = [] for line in boxes: cx0,cy0 = imgW/2.0,imgH/2.0 x1,y1,x2,y2,x3,y3,x4,y4 = xy_rotate_box(**line) x1,y1 = rotate(x1,y1,-degree/180*np.pi,cx0,cy0) x2,y2 = rotate(x2,y2,-degree/180*np.pi,cx0,cy0) x3,y3 = rotate(x3,y3,-degree/180*np.pi,cx0,cy0) x4,y4 = rotate(x4,y4,-degree/180*np.pi,cx0,cy0) box = (x1,y1,x2,y2,x3,y3,x4,y4) degree_,w_,h_,cx_,cy_ = solve(box) newLine = {'angle':degree_,'w':w_,'h':h_,'cx':cx_,'cy':cy_} newBoxes.append(newLine) return im.rotate(degree,center=(imgW/2.0,imgH/2.0 )),newBoxes def letterbox_image(image, size,fillValue=[128,128,128]): ''' resize image with unchanged aspect ratio using padding ''' image_w, image_h = image.size w, h = size new_w = int(image_w * min(w*1.0/image_w, h*1.0/image_h)) new_h = int(image_h * min(w*1.0/image_w, h*1.0/image_h)) resized_image = image.resize((new_w,new_h), Image.BICUBIC) if fillValue is None: fillValue = [int(x.mean()) for x in cv2.split(np.array(im))] boxed_image = Image.new('RGB', size, tuple(fillValue)) boxed_image.paste(resized_image,) return boxed_image,new_w/image_w def get_box_spilt(boxes,im,sizeW,SizeH,splitW=8,isRoate=False,rorateDegree=0): """ isRoate:box """ size = sizeW,SizeH if isRoate: ##box im,boxes = get_rorate(boxes,im,degree=rorateDegree) newIm,f = letterbox_image(im, size) newBoxes = resize_box(boxes,f) newBoxes = sum(box_split(newBoxes,splitW),[]) newBoxes = [box+[1] for box in newBoxes] return newBoxes,newIm def box_rotate(box,angle=0,imgH=0,imgW=0): """ 0\90\180\270, """ x1,y1,x2,y2,x3,y3,x4,y4 = box[:8] if angle==90: x1_,y1_ = y2,imgW-x2 x2_,y2_ = y3,imgW-x3 x3_,y3_ = y4,imgW-x4 x4_,y4_ = y1,imgW-x1 elif angle==180: x1_,y1_ = imgW-x3,imgH-y3 x2_,y2_ = imgW-x4,imgH-y4 x3_,y3_ = imgW-x1,imgH-y1 x4_,y4_ = imgW-x2,imgH-y2 elif angle==270: x1_,y1_ = imgH-y4,x4 x2_,y2_ = imgH-y1,x1 x3_,y3_ = imgH-y2,x2 x4_,y4_ = imgH-y3,x3 else: x1_,y1_,x2_,y2_,x3_,y3_,x4_,y4_ = x1,y1,x2,y2,x3,y3,x4,y4 return (x1_,y1_,x2_,y2_,x3_,y3_,x4_,y4_) def solve(box): """ cx,cy w,h angle x = cx-w/2 y = cy-h/2 x1-cx = -w/2*cos(angle) +h/2*sin(angle) y1 -cy= -w/2*sin(angle) -h/2*cos(angle) h(x1-cx) = -wh/2*cos(angle) +hh/2*sin(angle) w(y1 -cy)= -ww/2*sin(angle) -hw/2*cos(angle) (hh+ww)/2sin(angle) = h(x1-cx)-w(y1 -cy) """ x1,y1,x2,y2,x3,y3,x4,y4= box[:8] cx = (x1+x3+x2+x4)/4.0 cy = (y1+y3+y4+y2)/4.0 w = (np.sqrt((x2-x1)**2+(y2-y1)**2)+np.sqrt((x3-x4)**2+(y3-y4)**2))/2 h = (np.sqrt((x2-x3)**2+(y2-y3)**2)+np.sqrt((x1-x4)**2+(y1-y4)**2))/2 sinA = (h*(x1-cx)-w*(y1 -cy))*1.0/(h*h+w*w)*2 angle = np.arcsin(sinA) return angle,w,h,cx,cy from numpy import cos,sin,pi def xy_rotate_box(cx,cy,w,h,angle): """ cx,cy w,h angle x_new = (x-cx)*cos(angle) - (y-cy)*sin(angle)+cx y_new = (x-cx)*sin(angle) + (y-cy)*sin(angle)+cy """ cx = float(cx) cy = float(cy) w = float(w) h = float(h) angle = float(angle) x1,y1 = rotate(cx-w/2,cy-h/2,angle,cx,cy) x2,y2 = rotate(cx+w/2,cy-h/2,angle,cx,cy) x3,y3 = rotate(cx+w/2,cy+h/2,angle,cx,cy) x4,y4 = rotate(cx-w/2,cy+h/2,angle,cx,cy) return x1,y1,x2,y2,x3,y3,x4,y4 # def rotate_cut_img(im, degree, box, w, h, leftAdjust=False, rightAdjust=False, alph=0.2): # x1, y1, x2, y2, x3, y3, x4, y4 = box[:8] # # print('rotate_cut_img', x1, y1, x2, y2, x3, y3, x4, y4) # # x_center, y_center = np.mean([x1, x2, x3, x4]), np.mean([y1, y2, y3, y4]) # right = 0 # left = 0 # if rightAdjust: # right = 1 # if leftAdjust: # left = 1 # # # print(im.shape) # box = (max(1, x_center - w / 2 - left * alph * (w / 2)), # xmin # y_center - h / 2, # ymin # min(x_center + w / 2 + right * alph * (w / 2), im.shape[1] - 1), # xmax # y_center + h / 2) # ymax # # print('box', box) # # newW = int(box[2] - box[0]) # newH = int(box[3] - box[1]) # # # ===================================================== # # remap_points = np.array([[0, 0], [164, 0], [164, 48], [0, 48]], dtype=np.float32) # remap_points = np.array([[0, 0], [newW, 0], [newW, newH], [0, newH]], dtype=np.float32) # old_points = np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]], dtype=np.float32) # # opencv # M = cv2.getPerspectiveTransform(old_points, remap_points) # tmpImg = cv2.warpPerspective(im, M, (newW, newH)) # # cv2.imshow('rotate_cut_img', tmpImg) # # cv2.waitKey(0) # # return tmpImg, newW, newH def letterbox_image(image, size, fillValue=[128, 128, 128]): '''resize image with unchanged aspect ratio using padding''' image_w, image_h = image.size w, h = size new_w = int(image_w * min(w*1.0/image_w, h*1.0/image_h)) new_h = int(image_h * min(w*1.0/image_w, h*1.0/image_h)) resized_image = image.resize((new_w,new_h), Image.BICUBIC) if fillValue is None: fillValue = [int(x.mean()) for x in cv2.split(np.array(im))] boxed_image = Image.new('RGB', size, tuple(fillValue)) boxed_image.paste(resized_image, (0,0)) return boxed_image,new_w/image_w from scipy.ndimage import filters,interpolation,morphology,measurements,minimum #from pylab import amin, amax from numpy import amin, amax def estimate_skew_angle(raw): """ """ raw = resize_im(raw, scale=600, max_scale=900) image = raw-amin(raw) image = image/amax(image) m = interpolation.zoom(image,0.5) m = filters.percentile_filter(m,80,size=(20,2)) m = filters.percentile_filter(m,80,size=(2,20)) m = interpolation.zoom(m,1.0/0.5) w,h = min(image.shape[1],m.shape[1]),min(image.shape[0],m.shape[0]) flat = np.clip(image[:h,:w]-m[:h,:w]+1,0,1) d0,d1 = flat.shape o0,o1 = int(0.1*d0),int(0.1*d1) flat = amax(flat)-flat flat -= amin(flat) est = flat[o0:d0-o0,o1:d1-o1] angles = range(-15,15) estimates = [] for a in angles: roest =interpolation.rotate(est,a,order=0,mode='constant') v = np.mean(roest,axis=1) v = np.var(v) estimates.append((v,a)) _,a = max(estimates) return a def sort_box(box): """ box, box[index, 0] = x1 box[index, 1] = y1 box[index, 2] = x2 box[index, 3] = y2 box[index, 4] = x3 box[index, 5] = y3 box[index, 6] = x4 box[index, 7] = y4 """ box = sorted(box,key=lambda x:sum([x[1],x[3],x[5],x[7]])) return list(box) def get_boxes( bboxes): """ boxes: bounding boxes """ text_recs=np.zeros((len(bboxes), 8), np.int) index = 0 for box in bboxes: b1 = box[6] - box[7] / 2 b2 = box[6] + box[7] / 2 x1 = box[0] y1 = box[5] * box[0] + b1 x2 = box[2] y2 = box[5] * box[2] + b1 x3 = box[0] y3 = box[5] * box[0] + b2 x4 = box[2] y4 = box[5] * box[2] + b2 disX = x2 - x1 disY = y2 - y1 width = np.sqrt(disX*disX + disY*disY) fTmp0 = y3 - y1 fTmp1 = fTmp0 * disY / width x = np.fabs(fTmp1*disX / width) y = np.fabs(fTmp1*disY / width) if box[5] < 0: x1 -= x y1 += y x4 += x y4 -= y else: x2 += x y2 += y x3 -= x y3 -= y text_recs[index, 0] = x1 text_recs[index, 1] = y1 text_recs[index, 2] = x2 text_recs[index, 3] = y2 text_recs[index, 4] = x3 text_recs[index, 5] = y3 text_recs[index, 6] = x4 text_recs[index, 7] = y4 index = index + 1 return text_recs def union_rbox(result,alpha=0.1): """ box """ def diff(box1,box2): """ box1,box2 """ cy1 = box1['cy'] cy2 = box2['cy'] h1 = box1['h'] h2 = box2['h'] return abs(cy1-cy2)/max(0.01,min(h1/2,h2/2)) def sort_group_box(boxes): """ box, box """ N = len(boxes) boxes = sorted(boxes,key=lambda x:x['cx']) text = ' '.join([bx['text'] for bx in boxes]) box4 = np.zeros((N,8)) for i in range(N): cx =boxes[i]['cx'] cy = boxes[i]['cy'] degree =boxes[i]['degree'] w = boxes[i]['w'] h = boxes[i]['h'] x1,y1,x2,y2,x3,y3,x4,y4 = xy_rotate_box(cx, cy, w, h, degree/180*np.pi) box4[i] = [x1,y1,x2,y2,x3,y3,x4,y4] x1 = box4[:,0].min() y1 = box4[:,1].min() x2 = box4[:,2].max() y2 = box4[:,3].min() x3 = box4[:,4].max() y3 = box4[:,5].max() x4 = box4[:,6].min() y4 = box4[:,7].max() angle,w,h,cx,cy = solve([x1,y1,x2,y2,x3,y3,x4,y4]) return {'text':text,'cx':cx,'cy':cy,'w':w,'h':h,'degree':angle/np.pi*180} newBox = [] for line in result: if len(newBox)==0: newBox.append([line]) else: check=False for box in newBox[-1]: if diff(line,box)>alpha: check = True if not check: newBox[-1].append(line) else: newBox.append([line]) newBox = [sort_group_box(bx) for bx in newBox] return newBox def adjust_box_to_origin(img,angle, result): """ box """ h,w = img.shape[:2] if angle in [90,270]: imgW,imgH = img.shape[:2] else: imgH,imgW= img.shape[:2] newresult = [] for line in result: cx =line['box']['cx'] cy = line['box']['cy'] degree =line['box']['angle'] w = line['box']['w'] h = line['box']['h'] x1,y1,x2,y2,x3,y3,x4,y4 = xy_rotate_box(cx, cy, w, h, degree/180*np.pi) x1,y1,x2,y2,x3,y3,x4,y4 = box_rotate([x1,y1,x2,y2,x3,y3,x4,y4],angle=(360-angle)%360,imgH=imgH,imgW=imgW) box = x1,y1,x2,y2,x3,y3,x4,y4 newresult.append({'name':line['name'],'text':line['text'],'box':box}) return newresult
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 2235, 198, 31, 9800, 25, 22404, 21006, 198, 37811, 198, 11748, 25064, 198, 11748, 2237, 198, 11748, 28686, 198, 11748, 2779, 2414, 198, 11748, 7007, 198, 11748...
1.69454
7,857
# -*- coding: UTF-8 -*- import sys, time if __name__=='__main__': max_steps = 100 process_bar = ShowProcess(max_steps, 'OK') for i in range(max_steps): process_bar.show_process() time.sleep(0.1)
[ 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 198, 11748, 25064, 11, 640, 198, 198, 361, 11593, 3672, 834, 855, 6, 834, 12417, 834, 10354, 198, 220, 220, 220, 3509, 62, 20214, 796, 1802, 628, 220, 220, 220, 1429, 62,...
2.215686
102
''' You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers. For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1". Return the number of different expressions that you can build, which evaluates to target. ''' from collections import defaultdict input_val, target = [1,1,1,1,1], 3 res = Solution().findTargetSumWays(input_val, target)
[ 7061, 6, 198, 1639, 389, 1813, 281, 18253, 7177, 997, 82, 290, 281, 18253, 2496, 13, 198, 198, 1639, 765, 284, 1382, 281, 5408, 503, 286, 997, 82, 416, 4375, 530, 286, 262, 14354, 705, 10, 6, 290, 705, 19355, 878, 1123, 18253, 287...
3.490798
163
import numpy as np from fixtrack.frontend.pickable_base import PickableBase from vispy import scene
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 277, 6346, 39638, 13, 8534, 437, 13, 27729, 540, 62, 8692, 1330, 12346, 540, 14881, 198, 198, 6738, 1490, 9078, 1330, 3715, 628 ]
3.322581
31
""" Example of subscribing to a D-Bus signal using blocking I/O. This subscribes to the signal for a desktop notification being closed. To try it, start this script, then trigger a desktop notification, and close it somehow to trigger the signal. Use Ctrl-C to stop the script. This example relies on the ``org.freedesktop.Notifications.NotificationClosed`` signal; some desktops may not support it. See the notification spec for more details: https://people.gnome.org/~mccann/docs/notification-spec/notification-spec-latest.html Match rules are defined in the D-Bus specification: https://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-routing-match-rules """ from jeepney.bus_messages import MatchRule, message_bus from jeepney.integrate.blocking import connect_and_authenticate, Proxy from jeepney.wrappers import DBusAddress noti = DBusAddress('/org/freedesktop/Notifications', bus_name='org.freedesktop.Notifications', interface='org.freedesktop.Notifications') connection = connect_and_authenticate(bus="SESSION") match_rule = MatchRule( type="signal", sender=noti.bus_name, interface=noti.interface, member="NotificationClosed", path=noti.object_path, ) # This defines messages for talking to the D-Bus bus daemon itself: session_bus = Proxy(message_bus, connection) # Tell the session bus to pass us matching signal messages: print("Match added?", session_bus.AddMatch(match_rule) == ()) reasons = {1: 'expiry', 2: 'dismissal', 3: 'dbus', '4': 'undefined'} def notification_closed(data): """Callback for when we receive a notification closed signal""" nid, reason_no = data reason = reasons.get(reason_no, 'unknown') print('Notification {} closed by: {}'.format(nid, reason)) # Connect the callback to the relevant signal connection.router.subscribe_signal( callback=notification_closed, path=noti.object_path, interface=noti.interface, member="NotificationClosed" ) # Using dbus-send or d-feet or blocking_notify.py, send a notification and # manually close it or call ``.CloseNotification`` after a beat. try: while True: connection.recv_messages() except KeyboardInterrupt: pass connection.close()
[ 37811, 198, 16281, 286, 18412, 284, 257, 360, 12, 16286, 6737, 1262, 12013, 314, 14, 46, 13, 198, 1212, 11452, 274, 284, 262, 6737, 329, 257, 11364, 14483, 852, 4838, 13, 198, 198, 2514, 1949, 340, 11, 923, 428, 4226, 11, 788, 7616,...
3.062842
732
from shholiday import holiday2020 as hd daytuple = (1,1) nowholiday = hd.holiday2020() print(nowholiday.is_holiday(daytuple))
[ 6738, 427, 37689, 1330, 9912, 42334, 355, 289, 67, 198, 198, 820, 83, 29291, 796, 357, 16, 11, 16, 8, 198, 2197, 37689, 796, 289, 67, 13, 37689, 42334, 3419, 198, 4798, 7, 2197, 37689, 13, 271, 62, 37689, 7, 820, 83, 29291, 4008 ]
2.863636
44
from distutils.core import setup DISTNAME='pandas_composition' FULLVERSION='0.1' setup(name=DISTNAME, version=FULLVERSION, packages=['pandas_composition', ] )
[ 6738, 1233, 26791, 13, 7295, 1330, 9058, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 22...
1.161695
637
# Generated by Django 2.1.7 on 2019-02-27 14:23 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 22, 319, 13130, 12, 2999, 12, 1983, 1478, 25, 1954, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='xiandb', version='0.2.0', description='A database model for Xian', long_description=long_description, url='https://github.com/Kuba77/Xian-DB', author='Jakub Chronowski', author_email='jakub@chronow.ski', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: XIAN Collaborators', 'Topic :: Software Development :: Database', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7' ], keywords='xian database db', packages=['xiandb', 'xiandb.models'], install_requires=['mongokat', 'pyyaml', 'bcrypt'], extras_require={} )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 6738, 40481, 82, 1330, 1280, 198, 6738, 28686, 1330, 3108, 198, 198, 1456, 796, 3108, 13, 397, 2777, 776, 7, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 198, 198, 4480, 1280, 7, 6978, 13...
2.605114
352
from functools import partial import tensorflow as tf _EPSILON = tf.keras.backend.epsilon() # Helper functions below def _process_labels(labels, label_smoothing, dtype): labels = tf.dtypes.cast(labels, dtype=dtype) if label_smoothing is not None: labels = (1 - label_smoothing) * labels + label_smoothing * 0.5 return labels def _binary_focal_loss_from_logits(labels, logits, gamma, pos_weight, label_smoothing): labels = _process_labels(labels=labels, label_smoothing=label_smoothing, dtype=logits.dtype) # Compute probabilities for the positive class p = tf.math.sigmoid(logits) if label_smoothing is None: labels_shape = labels.shape logits_shape = logits.shape if not labels_shape.is_fully_defined() or labels_shape != logits_shape: labels_shape = tf.shape(labels) logits_shape = tf.shape(logits) shape = tf.broadcast_dynamic_shape(labels_shape, logits_shape) labels = tf.broadcast_to(labels, shape) logits = tf.broadcast_to(logits, shape) if pos_weight is None: loss_func = tf.nn.sigmoid_cross_entropy_with_logits else: loss_func = partial(tf.nn.weighted_cross_entropy_with_logits, pos_weight=pos_weight) loss = loss_func(labels=labels, logits=logits) modulation_pos = (1 - p)**gamma modulation_neg = p**gamma mask = tf.dtypes.cast(labels, dtype=tf.bool) modulation = tf.where(mask, modulation_pos, modulation_neg) return modulation * loss # Terms for the positive and negative class components of the loss pos_term = labels * ((1 - p)**gamma) neg_term = (1 - labels) * (p**gamma) # Term involving the log and ReLU log_weight = pos_term if pos_weight is not None: log_weight *= pos_weight log_weight += neg_term log_term = tf.math.log1p(tf.math.exp(-tf.math.abs(logits))) log_term += tf.nn.relu(-logits) log_term *= log_weight # Combine all the terms into the loss loss = neg_term * logits + log_term return loss def _binary_focal_loss_from_probs(labels, p, gamma, pos_weight, label_smoothing): q = 1 - p # For numerical stability (so we don't inadvertently take the log of 0) p = tf.math.maximum(p, _EPSILON) q = tf.math.maximum(q, _EPSILON) # Loss for the positive examples pos_loss = -(q**gamma) * tf.math.log(p) if pos_weight is not None: pos_loss *= pos_weight # Loss for the negative examples neg_loss = -(p**gamma) * tf.math.log(q) # Combine loss terms if label_smoothing is None: labels = tf.dtypes.cast(labels, dtype=tf.bool) loss = tf.where(labels, pos_loss, neg_loss) else: labels = _process_labels(labels=labels, label_smoothing=label_smoothing, dtype=p.dtype) loss = labels * pos_loss + (1 - labels) * neg_loss return loss
[ 6738, 1257, 310, 10141, 1330, 13027, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 62, 36, 3705, 4146, 1340, 796, 48700, 13, 6122, 292, 13, 1891, 437, 13, 538, 18217, 261, 3419, 628, 628, 198, 198, 2, 5053, 525, 5499, 2174, 6...
2.365992
1,235
import time from collections import OrderedDict from datetime import datetime, timedelta from django.db import models from django.conf import settings from django.utils.timezone import utc from .skills import Skill, SkillGroup from metrics.models import Corporation from tasks.models import EveApiCache, Task from evetool.storage import OverwriteStorage import utils #characters trained skills def trained_skills(self): cache_key = "trained_skills_%d" % self.pk result = utils.connection.get_cache(cache_key) if not result: cache_timer = 60 * 5 sheet = utils.connection.api_request("CharacterSheet", obj=self) groups = SkillGroup.objects.exclude( groupname="Fake Skills" ).order_by("groupname") skills = Skill.objects.order_by("typename") all_skills = OrderedDict() skillpoints = {} for group in groups: all_skills[group.groupname] = list() skillpoints[group.groupname] = 0 for skill in skills: trained = sheet.skills.Get(skill.typeid, False) if trained: all_skills[skill.skillgroup.groupname].append( { "skill": skill, "level": int(trained.level) } ) skillpoints[skill.skillgroup.groupname] += \ trained.skillpoints result = { "all_skills": all_skills, "skillpoints": skillpoints, } utils.connection.set_cache(cache_key, result, cache_timer) return result #get skillqueue #get total skillpoints for skills in queue #walletjournal def wallet_journal(self): cache_key = "walletjournal_character_%d" % self.pk result = utils.connection.get_cache(cache_key) if not result: self.update_journal() cache_timer = 60 * 10 utils.connection.set_cache(cache_key, True, cache_timer) return CharacterJournal.objects.filter(characterapi=self) #updates journal to current moment class CharacterApiIcon(models.Model): """ images related to characters """ relation = models.ForeignKey("characters.CharacterApi") size = models.IntegerField(choices=settings.IMAGE_SIZES) typeid = models.IntegerField() icon = models.ImageField( upload_to="images/characters/", storage=OverwriteStorage(), blank=True, null=True ) # def save(self, *args, **kwargs): # try: # temp = CharacterApiIcon.objects.get(pk=self.pk) # if temp.icon != self.icon: # temp.icon.delete() # except ObjectDoesNotExist: # pass # super(CharacterApiIcon, self).save(*args, **kwargs) #get list of wanted character icon sizes
[ 11748, 640, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 1...
2.18354
1,373
# -*- coding: utf-8 -*- from {{cookiecutter.skill_name}}.root import app __all__ = ['app']
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 22935, 44453, 8968, 353, 13, 42401, 62, 3672, 11709, 13, 15763, 1330, 598, 198, 198, 834, 439, 834, 796, 37250, 1324, 20520, 198 ]
2.421053
38
from django.urls import path from backend.api.v1.dialogs.views import ( DialogListCreateView, DialogRetrieveUpdateDestroyAPIView, DialogMembershipListCreateView, DialogMessageListCreateView, DialogMessageRetrieveUpdateDestroyAPIView, ) urlpatterns = [ path('', DialogListCreateView.as_view()), path('<int:pk>', DialogRetrieveUpdateDestroyAPIView.as_view()), path('membership/', DialogMembershipListCreateView.as_view()), path('messages/', DialogMessageListCreateView.as_view()), path('messages/<int:pk>', DialogMessageRetrieveUpdateDestroyAPIView.as_view()), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 30203, 13, 15042, 13, 85, 16, 13, 38969, 18463, 13, 33571, 1330, 357, 198, 220, 220, 220, 21269, 519, 8053, 16447, 7680, 11, 198, 220, 220, 220, 21269, 519, 9781, 30227, 10260, ...
2.736364
220
# coding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from bioblend import galaxy from biomaj2galaxy import config, pass_context from biomaj2galaxy.io import info, warn import click CONFIG_TEMPLATE = """## BioMAJ2Galaxy: Global Configuration File. # Each stanza should contain a single Galaxy server to interact with. # # You can set the key __default to the name of a default instance __default: local local: url: "%(url)s" apikey: "%(apikey)s" """ SUCCESS_MESSAGE = ( "Ready to go! Type `biomaj2galaxy` to get a list of commands you can execute." )
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 28686, 198, 198, 6738, 3182, 45292, 43...
3.065728
213
from ..datamart import * def test_create_dimension_insert_2_identical_lines(): ''' with 2 identical lines, only one gets stored ''' dimension = Dimension("test_dimension") dimension.addDimensionLine('test') dimension.addDimensionLine('test') assert dimension.id_value == 1 assert len(list(dimension.values)) == 1 def test_create_dimension_insert_2_identical_lines_and_1_different(): ''' with 2 identical lines and one different, only 2 get stored ''' dimension = Dimension("test_dimension") dimension.addDimensionLine('test') dimension.addDimensionLine('test2') dimension.addDimensionLine('test') assert dimension.id_value == 2 assert len(list(dimension.values)) == 2
[ 6738, 11485, 19608, 321, 433, 1330, 1635, 198, 198, 4299, 1332, 62, 17953, 62, 46156, 62, 28463, 62, 17, 62, 738, 605, 62, 6615, 33529, 198, 220, 220, 220, 705, 7061, 351, 362, 10411, 3951, 11, 691, 530, 3011, 8574, 198, 220, 220, ...
3.054393
239
# # msmarco doc: create the train.tsv triples # ------------------------------- import random random.seed(42) import argparse import os import sys from tqdm import tqdm sys.path.append(os.getcwd()) from matchmaker.evaluation.msmarco_eval import * from collections import defaultdict from matchmaker.dataloaders.bling_fire_tokenizer import BlingFireTokenizer # # config # parser = argparse.ArgumentParser() parser.add_argument('--out-file', action='store', dest='out_file', help='training output text file location', required=True) parser.add_argument('--out-file-ids', action='store', dest='out_file_ids', help='training output ids file location', required=True) parser.add_argument('--candidate-file', action='store', dest='candidate_file', help='trec ranking file location (lucene output)', required=True) parser.add_argument('--collection-file', action='store', dest='collection_file', help='collection.tsv location', required=True) parser.add_argument('--query-file', action='store', dest='query_file', help='query.tsv location', required=True) parser.add_argument('--qrel', action='store', dest='qrel_file', help='qrel location', required=True) args = parser.parse_args() max_triples = 10_000_000 max_doc_char_length = 150_000 max_doc_token_length = 10000 # # load data # ------------------------------- # collection = {} #collection_length = {} tokenizer = BlingFireTokenizer() with open(args.collection_file,"r",encoding="utf8") as collection_file: for line in tqdm(collection_file): ls = line.split("\t") # id<\t>text .... _id = ls[0] max_char_doc = ls[1].rstrip()[:max_doc_char_length] collection[_id] = max_char_doc #collection_length[_id] = len(tokenizer.tokenize(max_char_doc)) queries = {} with open(args.query_file,"r",encoding="utf8") as query_file: for line in tqdm(query_file): ls = line.split("\t") # id<\t>text .... _id = ls[0] queries[_id] = ls[1].rstrip() qrels = load_reference(args.qrel_file) # # produce output # ------------------------------- # triples = [] stats = defaultdict(int) with open(args.candidate_file,"r",encoding="utf8") as candidate_file: for line in tqdm(candidate_file): #if random.random() <= 0.5: continue #skip some entries for faster processing [topicid, _ , unjudged_docid, rank, _ , _ ] = line.split() #if int(rank) <= 100: # #if random.random() < 0.7: continue # skip 70% of candidates to speed up things... # #else: # stats['< 100 sampling count'] += 1 #else: # if random.random() <= 0.9: continue # skip 90% of candidates assumong top1k -> same number of samples from 0-100 as 101 - 1000 # else: # stats['> 100 sampling count'] += 1 if topicid not in queries or topicid not in qrels: # added: because we carved out the validation qrels from the train -> so there are some missing stats['skipped'] += 1 continue #assert topicid in qrels assert unjudged_docid in collection # Use topicid to get our positive_docid positive_docid = random.choice(qrels[topicid]) assert positive_docid in collection if unjudged_docid in qrels[topicid]: stats['docid_collision'] += 1 continue stats['kept'] += 1 #if collection_length[positive_docid] > max_doc_token_length and collection_length[unjudged_docid] > max_doc_token_length: # stats['both_to_long'] += 1 # continue #if collection_length[positive_docid] > max_doc_token_length: # stats['pos_to_long'] += 1 # continue #if collection_length[unjudged_docid] > max_doc_token_length: # stats['unjuged_to_long'] += 1 # continue triples.append((topicid,positive_docid,unjudged_docid)) # important: shuffle the train data random.shuffle(triples) with open(args.out_file,"w",encoding="utf8") as out_file_text ,\ open(args.out_file_ids,"w",encoding="utf8") as out_file_ids: for i,(topicid, positive_docid, unjudged_docid) in tqdm(enumerate(triples)): if i == max_triples: break if collection[positive_docid].strip() != "" and collection[unjudged_docid].strip() != "": out_file_ids.write(str(topicid)+"\t"+positive_docid+"\t"+unjudged_docid+"\n") out_file_text.write(queries[topicid]+"\t"+collection[positive_docid]+"\t"+collection[unjudged_docid]+"\n") for key, val in stats.items(): print(f"{key}\t{val}")
[ 2, 198, 2, 13845, 3876, 1073, 2205, 25, 2251, 262, 4512, 13, 912, 85, 1333, 2374, 220, 220, 198, 2, 34400, 24305, 198, 198, 11748, 4738, 198, 25120, 13, 28826, 7, 3682, 8, 198, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 11748,...
2.431454
1,933
from core.response import Response from communities.tests import TestCase
[ 6738, 4755, 13, 26209, 1330, 18261, 198, 6738, 5348, 13, 41989, 1330, 6208, 20448, 628, 628 ]
4.8125
16
# Author: Angela Chapman # Date: 8/6/2014 # # This file contains code to accompany the Kaggle tutorial # "Deep learning goes to the movies". The code in this file # is for Parts 2 and 3 of the tutorial, which cover how to # train a model using Word2Vec. # # *************************************** # # ****** Read the two training sets and the test set # import pandas as pd import os from nltk.corpus import stopwords import nltk.data import logging import numpy as np # Make sure that numpy is imported from gensim.models import Word2Vec from sklearn.ensemble import RandomForestClassifier from KaggleWord2VecUtility import KaggleWord2VecUtility # ****** Define functions to create average word vectors # if __name__ == '__main__': # Read data from files train = pd.read_csv(os.path.join(os.path.dirname(__file__), 'data', 'labeledTrainData.tsv'), header=0, delimiter="\t", quoting=3) test = pd.read_csv(os.path.join(os.path.dirname(__file__), 'data', 'testData.tsv'), header=0, delimiter="\t", quoting=3) unlabeled_train = pd.read_csv(os.path.join(os.path.dirname(__file__), 'data', "unlabeledTrainData.tsv"), header=0, delimiter="\t", quoting=3) # Verify the number of reviews that were read (100,000 in total) print "Read %d labeled train reviews, %d labeled test reviews, " \ "and %d unlabeled reviews\n" % (train["review"].size, test["review"].size, unlabeled_train["review"].size) # Load the punkt tokenizer tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') # ****** Split the labeled and unlabeled training sets into clean sentences # sentences = [] # Initialize an empty list of sentences print "Parsing sentences from training set" for review in train["review"]: sentences += KaggleWord2VecUtility.review_to_sentences(review, tokenizer) print "Parsing sentences from unlabeled set" for review in unlabeled_train["review"]: sentences += KaggleWord2VecUtility.review_to_sentences(review, tokenizer) # ****** Set parameters and train the word2vec model # # Import the built-in logging module and configure it so that Word2Vec # creates nice output messages logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', \ level=logging.INFO) # Set values for various parameters num_features = 300 # Word vector dimensionality min_word_count = 40 # Minimum word count num_workers = 4 # Number of threads to run in parallel context = 10 # Context window size downsampling = 1e-3 # Downsample setting for frequent words # Initialize and train the model (this will take some time) print "Training Word2Vec model..." model = Word2Vec(sentences, workers=num_workers, \ size=num_features, min_count=min_word_count, \ window=context, sample=downsampling, seed=1) # If you don't plan to train the model any further, calling # init_sims will make the model much more memory-efficient. model.init_sims(replace=True) # It can be helpful to create a meaningful model name and # save the model for later use. You can load it later using Word2Vec.load() model_name = "300features_40minwords_10context" model.save(model_name) model.doesnt_match("man woman child kitchen".split()) model.doesnt_match("france england germany berlin".split()) model.doesnt_match("paris berlin london austria".split()) model.most_similar("man") model.most_similar("queen") model.most_similar("awful") # ****** Create average vectors for the training and test sets # print "Creating average feature vecs for training reviews" trainDataVecs = getAvgFeatureVecs(getCleanReviews(train), model, num_features) print "Creating average feature vecs for test reviews" testDataVecs = getAvgFeatureVecs(getCleanReviews(test), model, num_features) # ****** Fit a random forest to the training set, then make predictions # # Fit a random forest to the training data, using 100 trees forest = RandomForestClassifier(n_estimators=100) print "Fitting a random forest to labeled training data..." forest = forest.fit(trainDataVecs, train["sentiment"]) # Test & extract results result = forest.predict(testDataVecs) # Write the test results output = pd.DataFrame(data={"id": test["id"], "sentiment": result}) output.to_csv("Word2Vec_AverageVectors.csv", index=False, quoting=3) print "Wrote Word2Vec_AverageVectors.csv"
[ 2, 220, 6434, 25, 17799, 29045, 198, 2, 220, 7536, 25, 807, 14, 21, 14, 4967, 198, 2, 198, 2, 220, 770, 2393, 4909, 2438, 284, 13873, 262, 509, 9460, 293, 11808, 198, 2, 220, 366, 29744, 4673, 2925, 284, 262, 6918, 1911, 220, 38...
2.774098
1,691
from .core import FullTimePositions
[ 6738, 764, 7295, 1330, 6462, 7575, 21604, 1756, 198 ]
4
9
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 16529, 35937, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 198, 2, 5964, 1321...
5.354167
96
# Python3 program to print # given matrix in spiral form # Driver Code a = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]] R = 3 C = 6 spiralPrint(R, C, a)
[ 2, 11361, 18, 1430, 284, 3601, 198, 2, 1813, 17593, 287, 23642, 1296, 628, 198, 198, 2, 12434, 6127, 198, 64, 796, 16410, 16, 11, 362, 11, 513, 11, 604, 11, 642, 11, 718, 4357, 198, 220, 220, 220, 220, 685, 22, 11, 807, 11, 86...
2.086957
92
""" Authorization Utilities """ from shared.models.user_entities import User from shared.service.jwt_auth_wrapper import JWTAuthManager manager = JWTAuthManager(oidc_vault_secret="oidc/rest", object_creator=lambda claims, assumed_role, user_roles: User( first_name=claims["given_name"], last_name=claims["family_name"], school=assumed_role, email=claims['email'] )) AUTH_USER = manager.auth_header()
[ 37811, 198, 13838, 1634, 41086, 198, 37811, 198, 6738, 4888, 13, 27530, 13, 7220, 62, 298, 871, 1330, 11787, 198, 6738, 4888, 13, 15271, 13, 73, 46569, 62, 18439, 62, 48553, 1330, 449, 54, 5603, 1071, 13511, 198, 198, 37153, 796, 449,...
1.925424
295
import matplotlib.pyplot as plt import numpy as np from photonpy.cpp.context import Context import photonpy.cpp.gaussian as gaussian from photonpy.smlm.util import imshow_hstack from photonpy.cpp.estimator import Estimator with Context() as ctx: g = gaussian.Gaussian(ctx) for cuda in [False]: print(f"CUDA = {cuda}") sigma=2 roisize=12 psf = g.CreatePSF_XYIBg(roisize, sigma, cuda) theta = [[4, 4, 1000, 3]] img = psf.ExpectedValue(theta) plt.figure() plt.set_cmap('inferno') smp = np.random.poisson(img) plt.imshow(smp[0]) psf_sigma = g.CreatePSF_XYIBgSigma(roisize, sigma, cuda) theta_s = [[4,4,1000,3,sigma]] img2 = psf_sigma.ExpectedValue(theta_s) CheckDeriv(psf, theta) # CheckDeriv(psf_sigma) print(f"PSF Sigma crlb: {psf_sigma.CRLB(theta_s)}") theta = psf_sigma.Estimate(smp)[0] print(theta)
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 48190, 9078, 13, 20322, 13, 22866, 1330, 30532, 198, 11748, 48190, 9078, 13, 20322, 13, 4908, 31562, 355, 31986, 31562, 198, 67...
1.845601
557
# -*- coding: utf-8 """Module for testing helper functions. 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 tests/tools_tests/helpers_tests.py SPDX-License-Identifier: MIT """ from nose.tools import eq_ from tespy.tools.helpers import newton def test_newton_bounds(): """ Test newton algorithm value limit handling. Try to calculate a zero crossing of a quadratic function in three tries. - zero crossing within limits, starting value near 4 - zero crossing within limits, starting value near -5 - zero crossing below minimum - zero crossing above maximum The function is x^2 + x - 20, there crossings are -5 and 4. """ result = newton(func, deriv, [], 0, valmin=-10, valmax=10, val0=0) msg = ('The newton algorithm should find the zero crossing at 4.0. ' + str(round(result, 1)) + ' was found instead.') eq_(4.0, result, msg) result = newton(func, deriv, [], 0, valmin=-10, valmax=10, val0=-10) msg = ('The newton algorithm should find the zero crossing at -5.0. ' + str(round(result, 1)) + ' was found instead.') eq_(-5.0, result, msg) result = newton(func, deriv, [], 0, valmin=-4, valmax=-2, val0=-3) msg = ('The newton algorithm should not be able to find a zero crossing. ' 'The value ' + str(round(result, 1)) + ' was found, but the ' 'algorithm should have found the lower boundary of -4.0.') eq_(-4.0, result, msg) result = newton(func, deriv, [], 0, valmin=-20, valmax=-10, val0=-10) msg = ('The newton algorithm should not be able to find a zero crossing. ' 'The value ' + str(round(result, 1)) + ' was found, but the ' 'algorithm should have found the upper boundary of -10.0.') eq_(-10.0, result, msg)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 26796, 329, 4856, 31904, 5499, 13, 198, 198, 1212, 2393, 318, 636, 286, 1628, 309, 1546, 20519, 357, 12567, 13, 785, 14, 78, 368, 1659, 14, 4879, 9078, 737, 632, 338, ...
2.785818
691
import formencode import pylons from pylons import app_globals as g def validate_custom(schema, **state_kwargs): """Validate a formencode schema. Works similar to the @validate decorator. On success return a dictionary of parameters from request.params. On failure throws a formencode.Invalid exception.""" # Create a state object if requested if state_kwargs: state = State(**state_kwargs) else: state = None # In case of validation errors an exception is thrown. This needs to # be caught elsewhere. if state_kwargs.get('variable_decode', False): params = formencode.variabledecode.variable_decode(pylons.request.params) print pylons.request.params print params else: params = pylons.request.params return schema.to_python(params, state) def htmlfill(html, exception_error=None): """Add formencode error messages to an HTML string. 'html' contains the HTML page with the form (e.g. created with render()). 'exception_error' is the formencode.Invalid-Exception from formencode.""" return formencode.htmlfill.render( form=html, defaults=pylons.request.params, errors=(exception_error and exception_error.unpack_errors()), encoding=pylons.response.determine_charset() )
[ 11748, 1296, 268, 8189, 220, 198, 11748, 279, 2645, 684, 198, 6738, 279, 2645, 684, 1330, 598, 62, 4743, 672, 874, 355, 308, 628, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.571429
539
""" Dynamo Utils ============ All utility functions for interactions with DynamoDB Functions - ensure_json - create_user_table - create_or_update_record - list_tables - list_records - get_record - delete_table - delete_record - check_active """ import boto3 from decimal import Decimal from constants import AWS_ACCESS_KEY, AWS_SECRET_KEY, AWS_REGION, DYNAMO_URL ddb = boto3.resource( 'dynamodb', aws_access_key_id = AWS_ACCESS_KEY, aws_secret_access_key = AWS_SECRET_KEY, endpoint_url = DYNAMO_URL, region_name = AWS_REGION ) client = boto3.client( 'dynamodb', aws_access_key_id = AWS_ACCESS_KEY, aws_secret_access_key = AWS_SECRET_KEY, endpoint_url = DYNAMO_URL, region_name = AWS_REGION ) def ensure_json(obj): """ Function to ensure that a python object is JSON serializable Params: obj::dict|[dict] Object to be JSON serializable Returns: obj::dict|[dict] Returns the JSON serializable object """ if isinstance(obj, list): for i in range(len(obj)): obj[i] = ensure_json(obj[i]) return obj elif isinstance(obj, dict): for k in obj.keys(): obj[k] = ensure_json(obj[k]) return obj elif isinstance(obj, Decimal): if obj % 1 == 0: return int(obj) else: return float(obj) else: return obj def create_user_table(): """ Function to create the "users" table in DynamoDB Returns: bool If the table was created or not """ try: table = ddb.create_table( TableName = "users", KeySchema = [ { "AttributeName": "username", "KeyType": "HASH" # Partition key }, { "AttributeName": "index", "KeyType": "RANGE" # Sort key } ], AttributeDefinitions = [ { "AttributeName": "username", "AttributeType": "S" }, { "AttributeName": "index", "AttributeType": "S" } ], ProvisionedThroughput = { "ReadCapacityUnits": 10, "WriteCapacityUnits": 10 } ) return True except client.exceptions.ResourceNotFoundException: print("Table does not exist") return False except Exception as e: print("Exception @ create_user_table\n{}".format(e)) return None def create_train_table(): """ Function to create the "trains" table in DynamoDB Returns: bool If the table was created or not """ try: table = ddb.create_table( TableName = "trains", KeySchema = [ { "AttributeName": "train_name", "KeyType": "HASH" # Partition key }, { "AttributeName": "train_type", "KeyType": "RANGE" # Sort key } ], AttributeDefinitions = [ { "AttributeName": "train_name", "AttributeType": "N" }, { "AttributeName": "train_type", "AttributeType": "S" } ], ProvisionedThroughput = { "ReadCapacityUnits": 10, "WriteCapacityUnits": 10 } ) return True except client.exceptions.ResourceNotFoundException: print("Table does not exist") return False except Exception as e: print("Exception @ create_user_table\n{}".format(e)) return None def create_or_update_record(tableName, record): """ Function to create or update a record in DynamoDB Params: tableName::str The table name to get the record record::dict The object to store Returns: bool If the record was inserted or not """ if not tableName or not record: return False if not {'username', 'index'}.issubset(record): return False try: res = ddb.Table(tableName).get_item( Key = { "username": record['username'], "index": record['index'] } ) record = { **res['Item'], **record } if 'Item' in res else record ddb.Table(tableName).put_item( Item = record ) return True except client.exceptions.ResourceNotFoundException: print("Table does not exist") return False except Exception as e: print("Exception @ create_or_update_record\n{}".format(e)) return None def list_tables(): """ Function to list all tables in DynamoDB Returns: tables::[str] The list of tables """ try: return client.list_tables()['TableNames'] except client.exceptions.ResourceNotFoundException: print("Tables do not exist") return False except Exception as e: print("Exception @ list_tables\n{}".format(e)) return None def list_records(tableName): """ Function to list all records from a DynamoDB table Params: tableName::str The table name to get the records Returns: records::[dict] The list of records stored in the table """ if not tableName: return False try: table = ddb.Table(tableName) res = table.scan() docs = ensure_json(res['Items']) while 'LastEvaluatedKey' in res: res = table.scan(ExclusiveStartKey = res['LastEvaluatedKey']) docs.extend(ensure_json(res['Items'])) return docs except client.exceptions.ResourceNotFoundException: print("Table does not exist") return False except Exception as e: print("Exception @ list_records\n{}".format(e)) return None def get_record(tableName, query): """ Function to retrieve one record from DynamoDB table Params: tableName::str The table name to get the record query::dict The query to fetch the record Returns: doc::dict The record retrieved from the table """ if not tableName or not query or not isinstance(query, dict): return False try: res = ddb.Table(tableName).get_item( Key = query ) doc = ensure_json(res['Item']) if 'Item' in res else None return doc except client.exceptions.ResourceNotFoundException: print("Table does not exist") return False except Exception as e: print("Exception @ get_record\n{}".format(e)) return None def delete_table(tableName): """ Function to delete a DynamoDB table Params: tableName::str The table name to delete Returns: bool If the table was deleted or not """ if not tableName: return False try: ddb.Table(tableName).delete() return True except client.exceptions.ResourceNotFoundException: print("Table does not exist") return False except Exception as e: print("Exception @ delete_table\n{}".format(e)) return None def delete_record(tableName, query): """ Function to delete a DynamoDB table Params: tableName::str The table name to get the record query::dict The query to fetch the record Returns: bool If the record was deleted or not """ if not tableName or not key or not val: return False try: res = ddb.Table(tableName).delete_item( Key = query ) print(res) return True except client.exceptions.ResourceNotFoundException: print("Table does not exist") return False except Exception as e: print("Exception @ delete_record\n{}".format(e)) return None def check_active(tableName): """ Function to check if a table is ACTIVE Params: tableName::str The table name to check Returns: bool If the table is active or not """ if not tableName: return False try: if ddb.Table(tableName).table_status == "ACTIVE": return True return False except client.exceptions.ResourceNotFoundException: print("Table does not exist") return False except Exception as e: print("Exception @ check_status\n{}".format(e)) return None
[ 37811, 198, 35, 4989, 78, 7273, 4487, 198, 25609, 198, 198, 3237, 10361, 5499, 329, 12213, 351, 41542, 11012, 198, 198, 24629, 2733, 198, 220, 220, 220, 532, 4155, 62, 17752, 198, 220, 220, 220, 532, 2251, 62, 7220, 62, 11487, 198, ...
2.105758
4,255
from .branch import Branch
[ 6738, 764, 1671, 3702, 1330, 20551 ]
4.333333
6
print('this is a test2 file')
[ 4798, 10786, 5661, 318, 257, 1332, 17, 2393, 11537, 198 ]
3
10
""" ******************************************************************************** compas_blender.forms ******************************************************************************** .. currentmodule:: compas_blender.forms """ __all__ = []
[ 37811, 198, 17174, 17174, 8412, 198, 5589, 292, 62, 2436, 2194, 13, 23914, 198, 17174, 17174, 8412, 198, 198, 492, 1459, 21412, 3712, 552, 292, 62, 2436, 2194, 13, 23914, 198, 198, 37811, 198, 198, 834, 439, 834, 796, 17635, 198 ]
6.02439
41
#!/usr/bin/python3 import sys import git r = git.Repo( sys.argv[1] ) num = 0 for info in r.blame( 'HEAD', sys.argv[2] ): num += 1 commit = info[0] all_lines = info[1] print( '%s %6d:%s' % (commit, num, all_lines[0]) ) for line in all_lines[1:]: num += 1 print( '%*s %6d:%s' % (40, '', num, line) )
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 11748, 25064, 198, 198, 11748, 17606, 198, 198, 81, 796, 17606, 13, 6207, 78, 7, 25064, 13, 853, 85, 58, 16, 60, 1267, 628, 198, 22510, 796, 657, 198, 198, 1640, 7508, 287, 374, 13, ...
1.954023
174
# configs for the model training # configs for the model testing # configs for hyperparameter tuning(SMAC3)
[ 2, 4566, 82, 329, 262, 2746, 3047, 198, 198, 2, 4566, 82, 329, 262, 2746, 4856, 198, 198, 2, 4566, 82, 329, 8718, 17143, 2357, 24549, 7, 12310, 2246, 18, 8, 198 ]
3.4375
32
# -*- coding: utf-8 -*- import unittest from uuid import uuid4 from copy import deepcopy from openprocurement.api.models import get_now from openprocurement.edge.tests.base import AuctionBaseWebTest, test_award, test_auction_data, test_document, ROUTE_PREFIX try: import openprocurement.auctions.core as auctions_core except ImportError: auctions_core = None def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(AuctionResourceTest)) suite.addTest(unittest.makeSuite(AuctionAwardResourceTest)) suite.addTest(unittest.makeSuite(AuctionAwardDocumentResourceTest)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 555, 715, 395, 198, 6738, 334, 27112, 1330, 334, 27112, 19, 198, 6738, 4866, 1330, 2769, 30073, 198, 198, 6738, 1280, 36942, 495, 434, 13, 15042, 13, 27530, 1330,...
2.796
250
from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.remote.webelement import WebElement
[ 6738, 384, 11925, 1505, 13, 11321, 13, 1069, 11755, 1330, 1400, 16678, 20180, 16922, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 47960, 13, 732, 1350, 1732, 1330, 5313, 20180, 628 ]
3.84375
32
from PyQt5.QtWidgets import QDialog from PyQt5 import uic from PyQt5.Qt import Qt from PyQt5.Qt import QShortcut from PyQt5.Qt import QKeySequence from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QInputDialog from PyQt5.Qt import QDateTime from PyQt5.Qt import QStyle from PyQt5.Qt import QNetworkCookie from PyQt5.QtWidgets import QTreeWidgetItem from mc.common.globalvars import gVar from mc.app.Settings import Settings from mc.common import const from mc.tools.TreeWidget import TreeWidget from mc.tools.IconProvider import IconProvider
[ 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1195, 44204, 198, 6738, 9485, 48, 83, 20, 1330, 334, 291, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 1330, 33734, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 1330, 1195, 164...
2.8
200
#!/usr/bin/env python3 import os import sys import logging import subprocess logging.basicConfig(level=logging.INFO) root_dir = 'submitted_data' submitted_file_split = set() for dir_, _, files in os.walk(root_dir): for file_name in files: rel_dir = os.path.relpath(dir_, root_dir) rel_file = os.path.join(root_dir, rel_dir, file_name) submitted_file_split.add(rel_file) for submitted_file in submitted_file_split: if submitted_file.startswith('submitted_data'): dir_name, data_type, file_name = submitted_file.split('/') out_dir_name = 'processed_data' if not os.path.isdir(out_dir_name): os.makedirs(out_dir_name, exist_ok=True) if not os.path.isdir(out_dir_name + '/' + data_type): os.makedirs(out_dir_name + '/' + data_type, exist_ok=True) outfile = submitted_file.replace(dir_name, out_dir_name) if not os.path.isfile(outfile): if not data_type == 'tad': from cimr.processor.utils import Infiler infile = Infiler( data_type, submitted_file, genome_build='b38', update_rsid=False, outfile=str(outfile), chunksize=700000 ) infile.read_file() if data_type == 'eqtl': from cimr.processor.query import Querier genes = list(infile.list_genes()) queried = Querier(genes) queried.form_query() else: logging.info(f' processed file already exists for {submitted_file}') logging.info(f' if reprocessing, delete {outfile} and file a new pull request')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 18931, 198, 11748, 850, 14681, 628, 198, 6404, 2667, 13, 35487, 16934, 7, 5715, 28, 6404, 2667, 13, 10778, 8, 628, 198, 15763, 62,...
1.968341
916
import enum
[ 11748, 33829, 201, 198, 201, 198, 201, 198 ]
2.125
8
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # MobileNet 224 (2017) # Paper: https://arxiv.org/pdf/1704.04861.pdf import os import tensorflow as tf from tensorflow.keras import layers, Input, Model def stem(inputs, alpha, n_filters, filter_size): """ Construct the stem group inputs : input tensor alpha : width multiplier """ # Convolutional block x = layers.ZeroPadding2D(padding=((0, 1), (0, 1)))(inputs) x = layers.Conv2D(n_filters, (filter_size, filter_size), strides=(2, 2), padding='valid')(x) x = layers.BatchNormalization()(x) x = layers.ReLU()(x) # Depthwise Separable Convolution Block x = depthwise_block(x, 64, alpha, (1, 1)) return x def classifier(x, alpha, dropout, n_classes): """ Construct the classifier group x : input to the classifier alpha : width multiplier dropout : dropout percentage n_classes : number of output classes """ # Flatten the feature maps into 1D feature maps (?, N) x = layers.GlobalAveragePooling2D()(x) # Reshape the feature maps to (?, 1, 1, 1024) shape = (1, 1, int(1024 * alpha)) x = layers.Reshape(shape)(x) # Perform dropout for preventing overfitting x = layers.Dropout(dropout)(x) # Use convolution for classifying (emulates a fully connected layer) x = layers.Conv2D(n_classes, (1, 1), padding='same')(x) x = layers.Activation('softmax')(x) # Reshape the resulting output to 1D vector of number of classes x = layers.Reshape((n_classes, ))(x) return x def depthwise_block(x, n_filters, alpha, strides): """ Construct a Depthwise Separable Convolution block x : input to the block n_filters : number of filters alpha : width multiplier strides : strides """ # Apply the width filter to the number of feature maps filters = int(n_filters * alpha) # Strided convolution to match number of filters if strides == (2, 2): x = layers.ZeroPadding2D(padding=((0, 1), (0, 1)))(x) padding = 'valid' else: padding = 'same' # Depthwise Convolution x = layers.DepthwiseConv2D((3, 3), strides, padding=padding)(x) x = layers.BatchNormalization()(x) x = layers.ReLU()(x) # Pointwise Convolution x = layers.Conv2D(filters, (1, 1), strides=(1, 1), padding='same')(x) x = layers.BatchNormalization()(x) x = layers.ReLU()(x) return x def get_configurable_hyperparams(): """This function is used to ge the configurable hyperparameters """ import yaml with open("cur_config.yaml") as fp: cur_cfg=yaml.load(fp) return (cur_cfg["cur_conf"][0], cur_cfg["cur_conf"][1], cur_cfg["cur_conf"][2], cur_cfg["cur_conf"][3], cur_cfg["cur_conf"][4]) def get_data(): """This function is used to get train and test data """ from tensorflow.keras.datasets import cifar10 import numpy as np (x_train, y_train), (x_test, y_test) = cifar10.load_data() x_train = (x_train / 255.0).astype(np.float32) x_test = (x_test / 255.0).astype(np.float32) return x_train, y_train, x_test, y_test if __name__=="__main__": # get configurable hyperparams (stem_n_filters, stem_filter_size depthwise_block1_n_filters, depthwise_block2_n_filters, depthwise_block3_n_filters, depthwise_block4_n_filters,)=get_configurable_hyperparams() alpha = 1 # width multiplier dropout = 0.5 # dropout percentage n_classes = 1000 # number of classes inputs = Input(shape=(224, 224, 3)) # Create the stem group x = stem(inputs, alpha, stem_n_filters, stem_filter_size) # First Depth wise Separable Convolution Group # Strided convolution - feature map size reduction x = depthwise_block(x, depthwise_block1_n_filters, alpha, strides=(2, 2)) x = depthwise_block(x, depthwise_block1_n_filters, alpha, strides=(1, 1)) # Second Depthwise Separable Convolution Group # Strided convolution - feature map size reduction x = depthwise_block(x, depthwise_block2_n_filters, alpha, strides=(2, 2)) x = depthwise_block(x, depthwise_block2_n_filters, alpha, strides=(1, 1)) # Third Depthwise Separable Convolution Group # Strided convolution - feature map size reduction x = depthwise_block(x, depthwise_block3_n_filters, alpha, strides=(2, 2)) for _ in range(5): x = depthwise_block(x, depthwise_block3_n_filters, alpha, strides=(1, 1)) # Fourth Depthwise Separable Convolution Group # Strided convolution - feature map size reduction x = depthwise_block(x, depthwise_block4_n_filters, alpha, strides=(2, 2)) x = depthwise_block(x, depthwise_block4_n_filters, alpha, strides=(1, 1)) # Create the classifier outputs = classifier(x, alpha, dropout, n_classes) # Instantiate the Model model = Model(inputs, outputs) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['acc']) model.summary() xtrain, ytrain, x_test, y_test=get_data() # train model model.fit(x_train, y_train, epochs=10, batch_size=32, validation_split=0.1, verbose=1) # save model fmodel=os.path.join(os.getcwd(),"model.h5") model.save(fmodel)
[ 2, 15069, 13130, 3012, 11419, 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, 743, 733...
2.56993
2,288
import numpy as np img_dtype = np.float32 imgX, imgY, imgZ = (256, 256, 150) imgs_path_withfaces = '../dataset/withfaces' imgs_path_nofaces = '../dataset/nofaces' imgX_dwt1, imgY_dwt1, imgZ_dwt1 = (128, 128, 75) imgs_path_withfaces_dwt = './dataset/withfaces' imgs_path_nofaces_dwt = './dataset/nofaces' dwt_flag = (True, False)[0] if dwt_flag: imgX, imgY, imgZ = imgX_dwt1, imgY_dwt1, imgZ_dwt1 imgs_path_withfaces = imgs_path_withfaces_dwt imgs_path_nofaces = imgs_path_nofaces_dwt
[ 11748, 299, 32152, 355, 45941, 198, 198, 9600, 62, 67, 4906, 796, 45941, 13, 22468, 2624, 198, 198, 9600, 55, 11, 33705, 56, 11, 33705, 57, 796, 357, 11645, 11, 17759, 11, 6640, 8, 198, 9600, 82, 62, 6978, 62, 4480, 32186, 796, 70...
2.024291
247
# Copyright (c) 2020 PaddlePaddle 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 sys import collections import random import math import cv2 import numbers import numpy as np if sys.version_info < (3, 3): Sequence = collections.Sequence Iterable = collections.Iterable else: Sequence = collections.abc.Sequence Iterable = collections.abc.Iterable __all__ = ['flip', 'resize', 'pad', 'rotate', 'to_grayscale'] def flip(image, code): """ Accordding to the code (the type of flip), flip the input image Args: image: Input image, with (H, W, C) shape code: Code that indicates the type of flip. -1 : Flip horizontally and vertically 0 : Flip vertically 1 : Flip horizontally Examples: .. code-block:: python import numpy as np from paddle.incubate.hapi.vision.transforms import functional as F fake_img = np.random.rand(224, 224, 3) # flip horizontally and vertically F.flip(fake_img, -1) # flip vertically F.flip(fake_img, 0) # flip horizontally F.flip(fake_img, 1) """ return cv2.flip(image, flipCode=code) def resize(img, size, interpolation=cv2.INTER_LINEAR): """ resize the input data to given size Args: input: Input data, could be image or masks, with (H, W, C) shape size: Target size of input data, with (height, width) shape. interpolation: Interpolation method. Examples: .. code-block:: python import numpy as np from paddle.incubate.hapi.vision.transforms import functional as F fake_img = np.random.rand(256, 256, 3) F.resize(fake_img, 224) F.resize(fake_img, (200, 150)) """ if isinstance(interpolation, Sequence): interpolation = random.choice(interpolation) if isinstance(size, int): h, w = img.shape[:2] if (w <= h and w == size) or (h <= w and h == size): return img if w < h: ow = size oh = int(size * h / w) return cv2.resize(img, (ow, oh), interpolation=interpolation) else: oh = size ow = int(size * w / h) return cv2.resize(img, (ow, oh), interpolation=interpolation) else: return cv2.resize(img, tuple(size[::-1]), interpolation=interpolation) def pad(img, padding, fill=(0, 0, 0), padding_mode='constant'): """Pads the given CV Image on all sides with speficified padding mode and fill value. Args: img (np.ndarray): Image to be padded. padding (int|tuple): Padding on each border. If a single int is provided this is used to pad all borders. If tuple of length 2 is provided this is the padding on left/right and top/bottom respectively. If a tuple of length 4 is provided this is the padding for the left, top, right and bottom borders respectively. fill (int|tuple): Pixel fill value for constant fill. Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. This value is only used when the padding_mode is constant padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant. ``constant`` means padding with a constant value, this value is specified with fill. ``edge`` means padding with the last value at the edge of the image. ``reflect`` means padding with reflection of image (without repeating the last value on the edge) padding ``[1, 2, 3, 4]`` with 2 elements on both sides in reflect mode will result in ``[3, 2, 1, 2, 3, 4, 3, 2]``. ``symmetric`` menas pads with reflection of image (repeating the last value on the edge) padding ``[1, 2, 3, 4]`` with 2 elements on both sides in symmetric mode will result in ``[2, 1, 1, 2, 3, 4, 4, 3]``. Returns: numpy ndarray: Padded image. Examples: .. code-block:: python import numpy as np from paddle.incubate.hapi.vision.transforms.functional import pad fake_img = np.random.rand(500, 500, 3).astype('float32') fake_img = pad(fake_img, 2) print(fake_img.shape) """ if not isinstance(padding, (numbers.Number, list, tuple)): raise TypeError('Got inappropriate padding arg') if not isinstance(fill, (numbers.Number, str, list, tuple)): raise TypeError('Got inappropriate fill arg') if not isinstance(padding_mode, str): raise TypeError('Got inappropriate padding_mode arg') if isinstance(padding, collections.Sequence) and len(padding) not in [2, 4]: raise ValueError( "Padding must be an int or a 2, or 4 element tuple, not a " + "{} element tuple".format(len(padding))) assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], \ 'Expected padding mode be either constant, edge, reflect or symmetric, but got {}'.format(padding_mode) PAD_MOD = { 'constant': cv2.BORDER_CONSTANT, 'edge': cv2.BORDER_REPLICATE, 'reflect': cv2.BORDER_DEFAULT, 'symmetric': cv2.BORDER_REFLECT } if isinstance(padding, int): pad_left = pad_right = pad_top = pad_bottom = padding if isinstance(padding, collections.Sequence) and len(padding) == 2: pad_left = pad_right = padding[0] pad_top = pad_bottom = padding[1] if isinstance(padding, collections.Sequence) and len(padding) == 4: pad_left, pad_top, pad_right, pad_bottom = padding if isinstance(fill, numbers.Number): fill = (fill,) * (2 * len(img.shape) - 3) if padding_mode == 'constant': assert (len(fill) == 3 and len(img.shape) == 3) or (len(fill) == 1 and len(img.shape) == 2), \ 'channel of image is {} but length of fill is {}'.format(img.shape[-1], len(fill)) img = cv2.copyMakeBorder( src=img, top=pad_top, bottom=pad_bottom, left=pad_left, right=pad_right, borderType=PAD_MOD[padding_mode], value=fill) return img def rotate(img, angle, interpolation=cv2.INTER_LINEAR, expand=False, center=None): """Rotates the image by angle. Args: img (numpy.ndarray): Image to be rotated. angle (float|int): In degrees clockwise order. interpolation (int, optional): interpolation: Interpolation method. expand (bool|optional): Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. center (2-tuple|optional): Optional center of rotation. Origin is the upper left corner. Default is the center of the image. Returns: numpy ndarray: Rotated image. Examples: .. code-block:: python import numpy as np from paddle.incubate.hapi.vision.transforms.functional import rotate fake_img = np.random.rand(500, 500, 3).astype('float32') fake_img = rotate(fake_img, 10) print(fake_img.shape) """ dtype = img.dtype h, w, _ = img.shape point = center or (w / 2, h / 2) M = cv2.getRotationMatrix2D(point, angle=-angle, scale=1) if expand: if center is None: cos = np.abs(M[0, 0]) sin = np.abs(M[0, 1]) nW = int((h * sin) + (w * cos)) nH = int((h * cos) + (w * sin)) M[0, 2] += (nW / 2) - point[0] M[1, 2] += (nH / 2) - point[1] dst = cv2.warpAffine(img, M, (nW, nH)) else: xx = [] yy = [] for point in (np.array([0, 0, 1]), np.array([w - 1, 0, 1]), np.array([w - 1, h - 1, 1]), np.array([0, h - 1, 1])): target = np.dot(M, point) xx.append(target[0]) yy.append(target[1]) nh = int(math.ceil(max(yy)) - math.floor(min(yy))) nw = int(math.ceil(max(xx)) - math.floor(min(xx))) M[0, 2] += (nw - w) / 2 M[1, 2] += (nh - h) / 2 dst = cv2.warpAffine(img, M, (nw, nh), flags=interpolation) else: dst = cv2.warpAffine(img, M, (w, h), flags=interpolation) return dst.astype(dtype) def to_grayscale(img, num_output_channels=1): """Converts image to grayscale version of image. Args: img (numpy.ndarray): Image to be converted to grayscale. Returns: numpy.ndarray: Grayscale version of the image. if num_output_channels == 1, returned image is single channel if num_output_channels == 3, returned image is 3 channel with r == g == b Examples: .. code-block:: python import numpy as np from paddle.incubate.hapi.vision.transforms.functional import to_grayscale fake_img = np.random.rand(500, 500, 3).astype('float32') fake_img = to_grayscale(fake_img) print(fake_img.shape) """ if num_output_channels == 1: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) elif num_output_channels == 3: img = cv2.cvtColor( cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB) else: raise ValueError('num_output_channels should be either 1 or 3') return img
[ 2, 15069, 357, 66, 8, 12131, 350, 37382, 47, 37382, 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...
2.309834
4,454
# -*- coding: utf-8 -*- """ Created on Fri Jan 29 13:38:35 2021 GROUND INVASION! The Game @author: Ashton Hansen (ashhansen6@outlook.com) """ # Packages used: import numpy as np import pandas as pd import random as rng from termcolor import colored # Defining starting forces ## Defenders: def_force = 1250 def_reserves = 400 defenders = def_force + def_reserves def_strength = def_force def_guard = def_force ## Attackers: att_force = 900 att_reserves = 1000 attackers = att_force + att_reserves att_strength = att_force att_guard = att_force # Defining strategies: ## Defenders: def_strat = ["draft", "turtle"] ### Draft ### Turtle ## Attackers: att_strat = ["blitz", "guerilla"] ### Blitz ### Guerilla # Ground Battle Event (Player == Attacker) wave = 0 player = input("Attacker or Defender? [A/D]:") while (attackers > 0) and (defenders > 0): # Wave Information wave = wave + 1 if wave == 1: print("############################################################") print("PREPARE FOR BATTLE! THE FIRST WAVE OF THE BATTLE BEGINS NOW.") print("############################################################") else: print("########## WAVE:", wave, "##########") print("#############################") print("Defending force strength:", def_force) print("Defending forces in reserve:", def_reserves) print("Attacking force strength:", att_force) print("Attacking forces in reserve:", att_reserves) if player =="A": # Active Player (Attacker) att_strat_chosen = input(colored("How should we proceed, commander? [blitz/guerilla]:", "yellow")) elif player == "D": # CPU Attacker att_strat_chosen = rng.choice(att_strat) # Defender Setup if player == "A": # CPU Defender if def_reserves > 0: def_strat = ["none", "draft", "draft", "draft", "draft", "draft", "draft", "turtle", "turtle", "turtle"] def_strat_chosen = rng.choice(def_strat) else: def_strat = ["none", "none", "turtle", "turtle", "turtle" ,"turtle", "turtle", "turtle", "turtle", "turtle"] def_strat_chosen = rng.choice(def_strat) elif player == "D": # Active Player (defender) def_strat_chosen = input(colored("How should we proceed, commander? [draft/turtle]:", "yellow")) if def_strat_chosen == "draft": draft_results = draft(def_force, def_reserves) def_force = draft_results[0] def_reserves = draft_results[1] def_strength = draft_results[2] def_guard = draft_results[3] elif def_strat_chosen == "turtle": turtle_results = turtle(def_force, def_reserves) def_force = turtle_results[0] def_reserves = turtle_results[1] def_strength = turtle_results[2] def_guard = turtle_results[3] elif def_strat_chosen == "none": print(colored("########## INTELLIGENCE REPORT ##########", on_color = "on_cyan")) print("It appears that the enemy will employ standard tactics...") def_force = def_force def_reserves = def_reserves def_strength = def_force def_guard = def_force print("Defending force strength:", def_force) print("Forces kept in reserve:", def_reserves) # Attacker Setup if att_strat_chosen == "blitz": blitz_results = blitz(att_force, att_reserves) att_force = blitz_results[0] att_reserves = blitz_results[1] att_strength = blitz_results[2] att_guard = blitz_results[3] elif att_strat_chosen == "guerilla": guerilla_results = guerilla(att_force, att_reserves) att_force = guerilla_results[0] att_reserves = guerilla_results[1] att_strength = guerilla_results[2] att_guard = guerilla_results[3] # Combat # Attacker damage def_guard = np.random.normal(def_guard, def_guard/10) * 0.50 att_strength = att_strength - def_guard if att_strength < 0: att_strength = 0 def_force = def_force - np.random.normal(att_strength, att_strength/10)//2 - (0.1*att_strength)//1 if def_force < 0: def_force = 0 # Defender damage att_guard = np.random.normal(att_guard, att_guard/10) * 0.50 - 0.1 def_strength = def_strength - att_guard if def_strength < 0: def_strength = 0 att_force = att_force - np.random.normal(def_strength, def_strength/10)//2 - (0.1*def_strength)//1 if att_force < 0: att_force = 0 # Post-wave results: print(colored("########## POST-WAVE RESULTS ##########", on_color = "on_cyan")) print(colored("Defenders:", on_color = "on_blue")) print("Surviving defensive forces:", def_force) print("Defenseive forces kept in reserve:", def_reserves) print("Defender strength estimate:", def_strength) print("Defender guard estimate:", def_guard) print(colored("Attackers:", on_color = "on_red")) print("Surviving attacker forces:", att_force) print("Attacker forces kept in reserve:", att_reserves) print("Attacker strength estimate:", att_strength) print("Attacker guard estimate:", att_guard) # Reset allocations # Defender reallocations: def_reserves = def_reserves + def_force def_force = 0 if def_reserves >= 1250: def_reserves = def_reserves - 1250 def_force = 1250 def_guard = def_force else: def_force = def_reserves def_reserves = 0 def_guard = def_force # Attacker reallocations: att_reserves = att_reserves + att_force att_force = 0 if att_reserves >= 900: att_reserves = att_reserves - 900 att_force = 900 att_guard = att_force else: att_force = att_reserves att_reserves = 0 att_guard = att_force defenders = def_force + def_reserves attackers = att_force + att_reserves # End of wave conditionals if (attackers > 0) and (defenders > 0) and (player == "A"): fightflight = input(colored("Continue or retreat?: [continue/retreat]:", "yellow")) if fightflight == "retreat": print(colored("########## WITHDRAWAL ##########", on_color = "on_blue")) print("You choose to withdraw your troops...") print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan")) print("Troops remaining:", attackers) print("Total losses:", (1900 - attackers)) print("Survival rate:", (attackers)/1900) print("Total assault waves:", wave) break else: print("The battle will continue next turn...") elif attackers <= 0 and player == "A": print(colored("########## FAILURE! ##########", on_color = "on_red")) print("Your assault has been repelled!") print("You return home, wondering what punishment for your failure awaits...") print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan")) print("Troops remaining:", attackers) print("Total losses:", (1900 - attackers)) print("Survival rate:", (attackers)/1900) print("Total assault waves:", wave) elif defenders <= 0 and player == "A": print(colored("########## SUCCESS! ##########", on_color = "on_green")) print("The defenders have been routed!") print("You may now decide the fate of the defending population...") print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan")) print("Troops remaining:", attackers) print("Total losses:", (1900 - attackers)) print("Survival rate:", (attackers)/1900) print("Total assault waves:", wave) elif (attackers > 0) and (defenders > 0) and (player == "D"): fightflight = input(colored("Defend or retreat?: [defend/retreat]:", "yellow")) if fightflight == "retreat": print(colored("########## WITHDRAWAL ##########", on_color = "on_blue")) print("You choose to withdraw your troops from the region...") print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan")) print("Troops remaining:", defenders) print("Total losses:", (1900 - defenders)) print("Survival rate:", (defenders)/1900) print("Total assault waves:", wave) break else: print("The battle will continue next turn...") elif defenders <= 0 and player == "D": print(colored("########## FAILURE! ##########", on_color = "on_red")) print("Your defense has been broken!") print("Enemy troops now occupy your lands and have claimed dominion...") print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan")) print("Troops remaining:", defenders) print("Total losses:", (1650 - defenders)) print("Survival rate:", (defenders)/1650) print("Total assault waves:", wave) elif attackers <= 0 and player == "D": print(colored("########## SUCCESS! ##########", on_color = "on_green")) print("The attackers have been repelled!") print("The storm has passed, and your people live another day...") print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan")) print("Troops remaining:", defenders) print("Total losses:", (1650 - defenders)) print("Survival rate:", (defenders)/1650) print("Total assault waves:", wave) print("#############################")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 19480, 2365, 2808, 1511, 25, 2548, 25, 2327, 33448, 201, 198, 201, 198, 46025, 34899, 1921, 2849, 0, 383, 3776, 201, 198, 31, 9800, 2...
2.389639
4,150
from django.conf.urls import include, url from django.views.generic.base import RedirectView from pretalx.event.models.event import SLUG_CHARS from pretalx.orga.views import cards from .views import ( admin, auth, cfp, dashboard, event, mails, organiser, person, plugins, review, schedule, speaker, submission, ) app_name = "orga" urlpatterns = [ url("^login/$", auth.LoginView.as_view(), name="login"), url("^logout/$", auth.logout_view, name="logout"), url("^reset/$", auth.ResetView.as_view(), name="auth.reset"), url(r"^reset/(?P<token>\w+)$", auth.RecoverView.as_view(), name="auth.recover"), url("^$", RedirectView.as_view(url="event", permanent=False)), url("^admin/$", admin.AdminDashboard.as_view(), name="admin.dashboard"), url("^admin/update/$", admin.UpdateCheckView.as_view(), name="admin.update"), url("^me$", event.UserSettings.as_view(), name="user.view"), url("^me/subuser$", person.SubuserView.as_view(), name="user.subuser"), url( r"^invitation/(?P<code>\w+)$", event.InvitationView.as_view(), name="invitation.view", ), url( "^organiser/$", dashboard.DashboardOrganiserListView.as_view(), name="organiser.list", ), url( "^organiser/new$", organiser.OrganiserDetail.as_view(), name="organiser.create" ), url( f"^organiser/(?P<organiser>[{SLUG_CHARS}]+)/", include( [ url("^$", organiser.OrganiserDetail.as_view(), name="organiser.view"), url( "^delete$", organiser.OrganiserDelete.as_view(), name="organiser.delete", ), url("^teams/$", organiser.TeamDetail.as_view(), name="organiser.teams"), url( "^teams/new$", organiser.TeamDetail.as_view(), name="organiser.teams.create", ), url( "^teams/(?P<pk>[0-9]+)/$", organiser.TeamDetail.as_view(), name="organiser.teams.view", ), url( "^teams/(?P<pk>[0-9]+)/delete$", organiser.TeamDelete.as_view(), name="organiser.teams.delete", ), url( "^teams/(?P<pk>[0-9]+)/tracks$", organiser.TeamTracks.as_view(), name="organiser.teams.tracks", ), url( "^teams/(?P<pk>[0-9]+)/delete/(?P<user_pk>[0-9]+)$", organiser.TeamDelete.as_view(), name="organiser.teams.delete_member", ), url( "^teams/(?P<pk>[0-9]+)/reset/(?P<user_pk>[0-9]+)$", organiser.TeamResetPassword.as_view(), name="organiser.team.password_reset", ), url( "^teams/(?P<pk>[0-9]+)/uninvite$", organiser.TeamUninvite.as_view(), name="organiser.teams.uninvite", ), url( "^teams/(?P<pk>[0-9]+)/resend$", organiser.TeamResend.as_view(), name="organiser.teams.resend", ), ] ), ), url("^event/new/$", event.EventWizard.as_view(), name="event.create"), url("^event/typeahead/$", event.event_list, name="event.typeahead"), url("^event/$", dashboard.DashboardEventListView.as_view(), name="event.list"), url( f"^event/(?P<event>[{SLUG_CHARS}]+)/", include( [ url( "^$", dashboard.EventDashboardView.as_view(), name="event.dashboard" ), url("^login/$", auth.LoginView.as_view(), name="event.login"), url("^reset/$", auth.ResetView.as_view(), name="event.auth.reset"), url( r"^reset/(?P<token>\w+)$", auth.RecoverView.as_view(), name="event.auth.recover", ), url("^delete$", event.EventDelete.as_view(), name="event.delete"), url("^live$", event.EventLive.as_view(), name="event.live"), url("^api/users$", person.UserList.as_view(), name="event.user_list"), url( "^cfp/$", RedirectView.as_view(pattern_name="orga:cfp.text.view"), name="cfp", ), url("^cfp/flow/$", cfp.CfPFlowEditor.as_view(), name="cfp.flow"), url( "^cfp/questions/$", cfp.CfPQuestionList.as_view(), name="cfp.questions.view", ), url( "^cfp/questions/new$", cfp.CfPQuestionDetail.as_view(), name="cfp.questions.create", ), url( "^cfp/questions/remind$", cfp.CfPQuestionRemind.as_view(), name="cfp.questions.remind", ), url( "^cfp/questions/(?P<pk>[0-9]+)/$", cfp.CfPQuestionDetail.as_view(), name="cfp.question.view", ), url( "^cfp/questions/(?P<pk>[0-9]+)/up$", cfp.question_move_up, name="cfp.questions.up", ), url( "^cfp/questions/(?P<pk>[0-9]+)/down$", cfp.question_move_down, name="cfp.questions.down", ), url( "^cfp/questions/(?P<pk>[0-9]+)/delete$", cfp.CfPQuestionDelete.as_view(), name="cfp.question.delete", ), url( "^cfp/questions/(?P<pk>[0-9]+)/edit$", cfp.CfPQuestionDetail.as_view(), name="cfp.question.edit", ), url( "^cfp/questions/(?P<pk>[0-9]+)/toggle$", cfp.CfPQuestionToggle.as_view(), name="cfp.question.toggle", ), url("^cfp/text$", cfp.CfPTextDetail.as_view(), name="cfp.text.view"), url( "^cfp/types/$", cfp.SubmissionTypeList.as_view(), name="cfp.types.view", ), url( "^cfp/types/new$", cfp.SubmissionTypeDetail.as_view(), name="cfp.types.create", ), url( "^cfp/types/(?P<pk>[0-9]+)/$", cfp.SubmissionTypeDetail.as_view(), name="cfp.type.view", ), url( "^cfp/types/(?P<pk>[0-9]+)/delete$", cfp.SubmissionTypeDelete.as_view(), name="cfp.type.delete", ), url( "^cfp/types/(?P<pk>[0-9]+)/default$", cfp.SubmissionTypeDefault.as_view(), name="cfp.type.default", ), url("^cfp/tracks/$", cfp.TrackList.as_view(), name="cfp.tracks.view"), url( "^cfp/tracks/new$", cfp.TrackDetail.as_view(), name="cfp.track.create", ), url( "^cfp/tracks/(?P<pk>[0-9]+)/$", cfp.TrackDetail.as_view(), name="cfp.track.view", ), url( "^cfp/tracks/(?P<pk>[0-9]+)/delete$", cfp.TrackDelete.as_view(), name="cfp.track.delete", ), url( "^cfp/access-codes/$", cfp.AccessCodeList.as_view(), name="cfp.access_code.view", ), url( "^cfp/access-codes/new$", cfp.AccessCodeDetail.as_view(), name="cfp.access_code.create", ), url( "^cfp/access-codes/(?P<code>[A-z0-9]+)/$", cfp.AccessCodeDetail.as_view(), name="cfp.access_code.view", ), url( "^cfp/access-codes/(?P<code>[A-z0-9]+)/send$", cfp.AccessCodeSend.as_view(), name="cfp.access_code.send", ), url( "^cfp/access-codes/(?P<code>[A-z0-9]+)/delete$", cfp.AccessCodeDelete.as_view(), name="cfp.access_code.delete", ), url( "^mails/", include( [ url( "^(?P<pk>[0-9]+)/$", mails.MailDetail.as_view(), name="mails.outbox.mail.view", ), url( "^(?P<pk>[0-9]+)/copy$", mails.MailCopy.as_view(), name="mails.outbox.mail.copy", ), url( "^(?P<pk>[0-9]+)/delete$", mails.OutboxPurge.as_view(), name="mails.outbox.mail.delete", ), url( "^(?P<pk>[0-9]+)/send$", mails.OutboxSend.as_view(), name="mails.outbox.mail.send", ), url( "^templates/$", mails.TemplateList.as_view(), name="mails.templates.list", ), url( "^templates/new$", mails.TemplateDetail.as_view(), name="mails.templates.create", ), url( "^templates/(?P<pk>[0-9]+)/$", mails.TemplateDetail.as_view(), name="mails.templates.view", ), url( "^templates/(?P<pk>[0-9]+)/delete$", mails.TemplateDelete.as_view(), name="mails.templates.delete", ), url( "^compose$", mails.ComposeMail.as_view(), name="mails.compose", ), url("^sent$", mails.SentMail.as_view(), name="mails.sent"), url( "^outbox/$", mails.OutboxList.as_view(), name="mails.outbox.list", ), url( "^outbox/send$", mails.OutboxSend.as_view(), name="mails.outbox.send", ), url( "^outbox/purge$", mails.OutboxPurge.as_view(), name="mails.outbox.purge", ), ] ), ), url( "^submissions/$", submission.SubmissionList.as_view(), name="submissions.list", ), url( "^submissions/new$", submission.SubmissionContent.as_view(), name="submissions.create", ), url( "^submissions/cards/$", cards.SubmissionCards.as_view(), name="submissions.cards", ), url( "^submissions/feed/$", submission.SubmissionFeed(), name="submissions.feed", ), url( "^submissions/statistics/$", submission.SubmissionStats.as_view(), name="submissions.statistics", ), url( "^submissions/feedback/$", submission.AllFeedbacksList.as_view(), name="submissions.feedback", ), url( r"^submissions/(?P<code>[\w-]+)/", include( [ url( "^$", submission.SubmissionContent.as_view(), name="submissions.content.view", ), url( "^submit$", submission.SubmissionStateChange.as_view(), name="submissions.submit", ), url( "^accept$", submission.SubmissionStateChange.as_view(), name="submissions.accept", ), url( "^reject$", submission.SubmissionStateChange.as_view(), name="submissions.reject", ), url( "^confirm", submission.SubmissionStateChange.as_view(), name="submissions.confirm", ), url( "^withdraw$", submission.SubmissionStateChange.as_view(), name="submissions.withdraw", ), url( "^delete", submission.SubmissionStateChange.as_view(), name="submissions.delete", ), url( "^cancel", submission.SubmissionStateChange.as_view(), name="submissions.cancel", ), url( "^speakers/$", submission.SubmissionSpeakers.as_view(), name="submissions.speakers.view", ), url( "^speakers/add$", submission.SubmissionSpeakersAdd.as_view(), name="submissions.speakers.add", ), url( "^speakers/delete$", submission.SubmissionSpeakersDelete.as_view(), name="submissions.speakers.delete", ), url( "^reviews/$", review.ReviewSubmission.as_view(), name="submissions.reviews", ), url( "^reviews/delete$", review.ReviewSubmissionDelete.as_view(), name="submissions.reviews.submission.delete", ), url( "^feedback/$", submission.FeedbackList.as_view(), name="submissions.feedback.list", ), url( "^toggle_featured$", submission.ToggleFeatured.as_view(), name="submissions.toggle_featured", ), url( "^anonymise/$", submission.Anonymise.as_view(), name="submissions.anonymise", ), ] ), ), url("^speakers/$", speaker.SpeakerList.as_view(), name="speakers.list"), url( "^speakers/(?P<pk>[0-9]+)/$", speaker.SpeakerDetail.as_view(), name="speakers.view", ), url( "^speakers/(?P<pk>[0-9]+)/reset$", speaker.SpeakerPasswordReset.as_view(), name="speakers.reset", ), url( "^speakers/(?P<pk>[0-9]+)/toggle-arrived$", speaker.SpeakerToggleArrived.as_view(), name="speakers.arrived", ), url( "^info/$", speaker.InformationList.as_view(), name="speakers.information.list", ), url( "^info/new$", speaker.InformationDetail.as_view(), name="speakers.information.create", ), url( "^info/(?P<pk>[0-9]+)/$", speaker.InformationDetail.as_view(), name="speakers.information.view", ), url( "^info/(?P<pk>[0-9]+)/delete$", speaker.InformationDelete.as_view(), name="speakers.information.delete", ), url( "^reviews/$", review.ReviewDashboard.as_view(), name="reviews.dashboard", ), url( "^reviews/regenerate/$", review.RegenerateDecisionMails.as_view(), name="reviews.regenerate", ), url( "^settings/$", event.EventDetail.as_view(), name="settings.event.view", ), url( "^settings/mail$", event.EventMailSettings.as_view(), name="settings.mail.view", ), url( "^settings/plugins$", plugins.EventPluginsView.as_view(), name="settings.plugins.select", ), url( "^settings/widget$", event.WidgetSettings.as_view(), name="settings.widget", ), url( "^settings/review/$", event.EventReviewSettings.as_view(), name="settings.review", ), url( "^settings/review/phase/(?P<pk>[0-9]+)/up$", event.phase_move_up, name="settings.review.phase.up", ), url( "^settings/review/phase/(?P<pk>[0-9]+)/down$", event.phase_move_down, name="settings.review.phase.down", ), url( "^settings/review/phase/(?P<pk>[0-9]+)/delete$", event.PhaseDelete.as_view(), name="settings.review.phasedelete", ), url( "^settings/review/phase/(?P<pk>[0-9]+)/activate$", event.PhaseActivate.as_view(), name="settings.review.phasedelete", ), url( "^schedule/$", schedule.ScheduleView.as_view(), name="schedule.main" ), url( "^schedule/export/$", schedule.ScheduleExportView.as_view(), name="schedule.export", ), url( "^schedule/export/trigger$", schedule.ScheduleExportTriggerView.as_view(), name="schedule.export.trigger", ), url( "^schedule/export/download$", schedule.ScheduleExportDownloadView.as_view(), name="schedule.export.download", ), url( "^schedule/release$", schedule.ScheduleReleaseView.as_view(), name="schedule.release", ), url( r"^schedule/quick/(?P<code>\w+)/$", schedule.QuickScheduleView.as_view(), name="schedule.quick", ), url( "^schedule/reset$", schedule.ScheduleResetView.as_view(), name="schedule.reset", ), url( "^schedule/toggle$", schedule.ScheduleToggleView.as_view(), name="schedule.toggle", ), url( "^schedule/resend_mails$", schedule.ScheduleResendMailsView.as_view(), name="schedule.resend_mails", ), url( "^schedule/rooms/$", schedule.RoomList.as_view(), name="schedule.rooms.list", ), url( "^schedule/rooms/new$", schedule.RoomDetail.as_view(), name="schedule.rooms.create", ), url( "^schedule/rooms/(?P<pk>[0-9]+)/$", schedule.RoomDetail.as_view(), name="schedule.rooms.view", ), url( "^schedule/rooms/(?P<pk>[0-9]+)/delete$", schedule.RoomDelete.as_view(), name="schedule.rooms.delete", ), url( "^schedule/rooms/(?P<pk>[0-9]+)/up$", schedule.room_move_up, name="schedule.rooms.up", ), url( "^schedule/rooms/(?P<pk>[0-9]+)/down$", schedule.room_move_down, name="schedule.rooms.down", ), url( "^schedule/api/talks/$", schedule.TalkList.as_view(), name="schedule.api.talks", ), url( "^schedule/api/talks/(?P<pk>[0-9]+)/$", schedule.TalkUpdate.as_view(), name="schedule.api.update", ), url( "^schedule/api/availabilities/(?P<talkid>[0-9]+)/(?P<roomid>[0-9]+)/$", schedule.RoomTalkAvailabilities.as_view(), name="schedule.api.availabilities", ), ] ), ), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 2291, 11, 19016, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 13, 8692, 1330, 2297, 1060, 7680, 198, 198, 6738, 2181, 282, 87, 13, 15596, 13, 27530, 13, 15596, 1330, 12419, 7340, 62...
1.482649
16,598
''' This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de). PM4Py is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PM4Py is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PM4Py. If not, see <https://www.gnu.org/licenses/>. ''' from enum import Enum from typing import Optional, Dict, Any, Tuple, List, Union from intervaltree import Interval, IntervalTree from pm4py.util import exec_utils def apply(points: List[Tuple[float, float]], parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> List[int]: """ Computes the overlap statistic given a list of points, expressed as (min_timestamp, max_timestamp) Parameters ----------------- points List of points with the aforementioned features parameters Parameters of the method, including: - Parameters.EPSILON Returns ----------------- overlap List associating to each point the number of intersecting points """ if parameters is None: parameters = {} epsilon = exec_utils.get_param_value(Parameters.EPSILON, parameters, 10 ** (-5)) points = [(x[0] - epsilon, x[1] + epsilon) for x in points] sorted_points = sorted(points) tree = IntervalTree() for p in sorted_points: tree.add(Interval(p[0], p[1])) overlap = [] for p in points: overlap.append(len(tree[p[0]:p[1]])) return overlap
[ 7061, 6, 198, 220, 220, 220, 770, 2393, 318, 636, 286, 3122, 19, 20519, 357, 5167, 14151, 25, 3740, 1378, 4426, 19, 9078, 13, 11147, 13, 69, 430, 403, 71, 30288, 13, 2934, 737, 628, 220, 220, 220, 3122, 19, 20519, 318, 1479, 3788,...
2.968354
632
from htmlman import HTMLMan from styleman import Template page=HTMLMan() page.make_responsive() page.add_title("Base Quiz") style=Template('antartica') page.add_body_class(style['page']) page.add_js("baseui.js") page.create_section('main',append=True) page['main'].add_style_class(style['main']) title=page.create_section('title') title.add_style_class(style['title']) title.add_content("Base Quiz") widget=page.create_section("widget") widget.add_style_class(style['widget']) label = page.create_section('label',ID='label') #label.add_style_class(style['center']) label.add_style(name='label',mode="class") label.style_to_cssman(style) label.style( "font-size","20pt", "font-family","monospace", "height","50px", "border-bottom","1px solid #ccd", ) label.add_content("0x0") answer_l=page.create_section("answer_l1",ID="label_t") answer_l.add_style_class(style["label"]) answer_l2=page.create_section("answer_l2",ID="label_b") answer_l2.add_style_class(style["label"]) controls = page.create_section("control") controls.add_style(name="control",mode="class",cssman_obj=style) controls.style( "display","grid", "grid-template-columns","1fr 1fr", "gap","10px", "padding","10px" ) rand_b=page.create_section('random',tag="button",inner_html="Random") rand_b.config_attr("type","button","onclick","randomize()") answer_b=page.create_section('answer_b',tag="button",inner_html="Answer") answer_b.config_attr("type","button","onclick","answer()") controls.add_content(rand_b) controls.add_content(answer_b) widget.add_content(label) widget.add_content(answer_l) widget.add_content(answer_l2) widget.add_content(controls) page['main'].add_content(title) page['main'].add_content(widget) page.render(style,html_path="baseui.html")
[ 6738, 27711, 805, 1330, 11532, 5124, 198, 6738, 3918, 805, 1330, 37350, 198, 198, 7700, 28, 28656, 5124, 3419, 198, 7700, 13, 15883, 62, 39772, 3419, 198, 7700, 13, 2860, 62, 7839, 7203, 14881, 2264, 528, 4943, 198, 7635, 28, 30800, 1...
2.669173
665
name = "cluster" num_cores = 1000 GENERAL_PARTITIONS = ["regular"] GPU_PARTITIONS = ["gpu"] PARTITIONS = GENERAL_PARTITIONS + GPU_PARTITIONS ACTIVE_JOB_STATES = ["RUNNING", "COMPLETING"] FINISHED_JOB_STATES = ["COMPLETED", "NODE_FAIL", "TIMEOUT", "FAILED", "CANCELLED"] JOB_STATES = ACTIVE_JOB_STATES + FINISHED_JOB_STATES def node2int(node): """custom function to convert nodename to int this one removes all chars from names like node1-001-01""" return int(''.join(filter(lambda x: x.isdigit(), node)))
[ 3672, 796, 366, 565, 5819, 1, 198, 22510, 62, 66, 2850, 796, 8576, 198, 198, 35353, 27130, 62, 30709, 2043, 11053, 796, 14631, 16338, 8973, 198, 33346, 62, 30709, 2043, 11053, 796, 14631, 46999, 8973, 198, 198, 30709, 2043, 11053, 796, ...
2.649485
194
# This file is part of the CERN Indico plugins. # Copyright (C) 2014 - 2021 CERN # # The CERN Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; see # the LICENSE file for more details. import dateutil.parser import pytz from flask import flash, request, session from flask_pluginengine import render_plugin_template, url_for_plugin from indico.core import signals from indico.core.config import config from indico.core.plugins import IndicoPlugin from indico.core.settings.converters import ModelListConverter from indico.modules.events.requests.models.requests import Request, RequestState from indico.modules.events.requests.views import WPRequestsEventManagement from indico.modules.rb.models.rooms import Room from indico.modules.users import User from indico.util.string import natural_sort_key from indico.web.forms.base import IndicoForm from indico.web.forms.fields import EmailListField, IndicoQuerySelectMultipleField, PrincipalListField from indico.web.menu import TopMenuItem from indico_room_assistance import _ from indico_room_assistance.blueprint import blueprint from indico_room_assistance.definition import RoomAssistanceRequest from indico_room_assistance.util import (can_request_assistance_for_event, event_has_room_with_support_attached, is_room_assistance_support)
[ 2, 770, 2393, 318, 636, 286, 262, 327, 28778, 1423, 3713, 20652, 13, 198, 2, 15069, 357, 34, 8, 1946, 532, 33448, 327, 28778, 198, 2, 198, 2, 383, 327, 28778, 1423, 3713, 20652, 389, 1479, 3788, 26, 345, 460, 17678, 4163, 198, 2, ...
3.372596
416
from datamart.materializers.materializer_base import MaterializerBase import os import urllib.request import sys import csv import copy import json from typing import List from pprint import pprint import re import typing from pandas import DataFrame import traceback
[ 6738, 4818, 321, 433, 13, 33665, 11341, 13, 33665, 7509, 62, 8692, 1330, 14633, 7509, 14881, 198, 198, 11748, 28686, 198, 11748, 2956, 297, 571, 13, 25927, 198, 11748, 25064, 198, 11748, 269, 21370, 198, 11748, 4866, 198, 11748, 33918, ...
3.857143
70
from typing import Dict, List, Tuple import pkg_resources def load_file(filename: str, directory: str) -> List[List[str]]: """Loads a data file stored in the Axelrod library's data subdirectory, likely for parameters for a strategy.""" path = "/".join((directory, filename)) data_bytes = pkg_resources.resource_string(__name__, path) data = data_bytes.decode("UTF-8", "replace") rows = [] for line in data.split("\n"): if line.startswith("#") or len(line) == 0: continue s = line.split(", ") rows.append(s) return rows def load_weights( filename: str = "ann_weights.csv", directory: str = "data" ) -> Dict[str, Tuple[int, int, List[float]]]: """Load Neural Network Weights.""" rows = load_file(filename, directory) d = dict() for row in rows: name = str(row[0]) num_features = int(row[1]) num_hidden = int(row[2]) weights = list(map(float, row[3:])) d[name] = (num_features, num_hidden, weights) return d def load_pso_tables(filename="pso_gambler.csv", directory="data"): """Load lookup tables.""" rows = load_file(filename, directory) d = dict() for row in rows: name, a, b, c, = str(row[0]), int(row[1]), int(row[2]), int(row[3]) values = list(map(float, row[4:])) d[(name, int(a), int(b), int(c))] = values return d
[ 6738, 19720, 1330, 360, 713, 11, 7343, 11, 309, 29291, 198, 198, 11748, 279, 10025, 62, 37540, 628, 198, 4299, 3440, 62, 7753, 7, 34345, 25, 965, 11, 8619, 25, 965, 8, 4613, 7343, 58, 8053, 58, 2536, 60, 5974, 198, 220, 220, 220, ...
2.388416
587
# -*- coding: utf-8 -*- from __future__ import unicode_literals # REST from rest_framework.viewsets import ViewSetMixin from rest_framework import routers, serializers, viewsets from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated, BasePermission from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.views import APIView from rest_framework import mixins, generics from rest_framework.response import Response from rest_framework.authtoken.models import Token # our models from blockchain.models import Block, Prescription, Transaction, Address from blockchain.utils import pubkey_string_to_rsa, savify_key, pubkey_base64_to_rsa, pubkey_base64_from_uri from .exceptions import NonValidPubKey # Define router router = routers.DefaultRouter() # add patient filter by email, after could modify with other router.register(r'rx-endpoint', PrescriptionViewSet, 'prescription-endpoint') # add patient filter by email, after could modify with other router.register(r'block', BlockViewSet, 'block-endpoint') # add patient filter by email, after could modify with other router.register(r'address', AddressViewSet, 'address_endpoint')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 2, 30617, 198, 6738, 1334, 62, 30604, 13, 1177, 28709, 1330, 3582, 7248, 35608, 259, 198, 6738, 133...
3.722857
350
# Copyright (c) 2016-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import atexit import logging import os import subprocess import sys from typing import List from .command import ClientException, ExitCode, State from .reporting import Reporting from .start import Start LOG = logging.getLogger(__name__)
[ 2, 15069, 357, 66, 8, 1584, 12, 25579, 11, 3203, 11, 3457, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, ...
3.90566
106
from collections import deque, defaultdict import os import sys import logging import time import json import gym import torch.nn as nn import torch import numpy as np import matplotlib.pyplot as plt from model import RL_Policy, Semantic_Mapping from utils.storage import GlobalRolloutStorage from envs import make_vec_envs from arguments import get_args import algo os.environ["OMP_NUM_THREADS"] = "1" if __name__ == "__main__": main()
[ 6738, 17268, 1330, 390, 4188, 11, 4277, 11600, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 18931, 198, 11748, 640, 198, 11748, 33918, 198, 11748, 11550, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 198, 11748, 299,...
3.163121
141
#!/usr/bin/env python # coding=utf-8 ''' Author: Shuangchi He / Yulv Email: yulvchi@qq.com Date: 2022-03-19 10:33:38 Motto: Entities should not be multiplied unnecessarily. LastEditors: Shuangchi He LastEditTime: 2022-03-23 00:52:55 FilePath: /Awesome-Ultrasound-Standard-Plane-Detection/src/ITN/srmg/core/RiemannianRight.py Description: Modify here please Init from https://github.com/yuanwei1989/plane-detection Author: Yuanwei Li (3 Oct 2018) # Copyright (c) 2006-2017, Nina Milone, Bishesh Kanal, Benjamin Hou # Copyright (c) 2006-2017, Imperial College of Science, Technology and Medicine # Produced at Biomedical Image Analysis Group # 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 holders nor the names of any # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. Statistics on Riemannian Manifolds and Groups --------------------------------------------- This is a set of codes to compare the computing of the different types of means on Lie groups. These codes can be used to reproduce the experiments illustrated in the video developed for the MICCAI Educational challenge 2014, available at: url of the video. :Authors: `Nina Miolane <website>` `Bishesh Khanal <website>` :Organization: Asclepios Team, INRIA Sophia Antipolis. :Version: 2017.07.05 Requirements ------------ * `Numpy 1.11 <http://www.numpy.org>`_ Notes ----- ---------- (1) Defining a mean on Lie group. Nina Miolane. Medical Imaging. 2013. <hal-00938320> ''' import numpy import math from srmg.common.group import * from srmg.common.util import * EPS = 1e-5 def riemExpR(a,f0,v): """ start: TODO What the function does clearer function name ? Inputs description: Outputs description: end: TODO Riemannian exponential and logarithm from any point f0 (for left- and right-invariant metric) """ f = grpCompose((riemExpIdR(a, numpy.linalg.lstsq(jR(f0),v)[0])), f0) return f def riemExpIdR(a,v): """ start: TODO What the function does clearer function name ? Inputs description: Outputs description: end: TODO Riemannian exponential and logarithm from Id (for left- and right-invariant metric) """ v=grpReg(-v); f = numpy.zeros(6) f[0:3] = v[0:3] f[3:6] = a * v[3:6] f = grpInv(f) return f def sigma2R(a,m,tabf,tabw): """ start: TODO What the function does clearer function name ? Inputs description: Outputs description: end: TODO """ siz = tabf.shape[0] if siz < 2: print('Error: Calculating variance requires at least 2 points') return 0 s = 0 for i in range(0,siz): s = s + tabw[i] * normA2R(a,m,riemLogR(a,m,tabf[i,:])); return s def riemLogR(a,f0,f): """ DESCRIPTION Attributes: a: ????? f0: ???? f: ???? Return: v: ????? """ v=numpy.dot(jR(f0),riemLogIdR(a,grpCompose(f,grpInv(f0)))) return v def riemLogIdR(a,f): """ DESCRIPTION Attributes: a: ????? f: ???? Return: v: ????? """ v = numpy.zeros(6) v[0:3] = f[0:3] v[3:6] = numpy.dot(rotMat(-f[0:3]),f[3:6]); return v def qR(a,f): """ Left- and right- invariant inner product in the principal chart (propagation of Frobenius inner product) Attributes: a: ????? f: ???? Return: g: ????? """ f = grpReg(f) g0 = numpy.zeros([6,6]) g0[0:3,0:3] = numpy.eye(3) g0[3:6,3:6] = a * numpy.eye(3) g = numpy.dot(numpy.dot(numpy.linalg.inv(jR(f).T) , g0) , numpy.linalg.inv(jR(f))) return g def jR(f): """ Differentials of the left and right translations for SO(3) in the principal chart Attributes: r: ????? Return: Jl: ????? """ #f = makeColVector(f,6); # unnecessary if 1D f = grpReg(f); Jr = numpy.zeros([6,6]) Jr[0:3,0:3] = jRotR(f[0:3]); Jr[3:6,0:3] = -skew(f[3:6]); Jr[3:6,3:6] = numpy.eye(3); return Jr def normA2R(a,f,v): """ This function calculates the normalised left Attributes: a: ????? f: ????? v: ????? Return: n: normalised vector """ v=grpReg(v); n=numpy.dot(numpy.dot(v.T,qR(a,f)),v); return n def frechetR(a,tabf,tabw): """ This function computes the frechet-L mean Attributes: img: The fixed image that will be transformed (simpleitk type) a: ????? tabf: SE3 data points (Nx6 vector) tabw: data point weights (Nx1 vector) Return: m: The mean """ siz = tabf.shape[0] if siz < 2: print('Error: Calculating mean requires at least 2 points') m = tabf[0,:] # Iteration 0 mbis=m; print('mbisR=' + str(mbis)) aux=numpy.zeros(6); for i in range (0,siz): aux=aux+tabw[i]*riemLogR(a,mbis,tabf[i,:]); m=riemExpR(a,mbis,aux); # Iteration 1 until converges while (normA2R(a,mbis,riemLogR(a,mbis,m))>EPS*sigma2R(a,mbis,tabf,tabw)): mbis=m; print('mbisR=' + str(mbis)) aux=numpy.zeros(6); for i in range (0,siz): aux=aux+tabw[i]*riemLogR(a,mbis,tabf[i,:]); m=riemExpR(a,mbis,aux); return m
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 28, 40477, 12, 23, 198, 7061, 6, 198, 13838, 25, 32344, 648, 11072, 679, 1220, 575, 377, 85, 198, 15333, 25, 331, 377, 85, 11072, 31, 38227, 13, 785, 198, 10430, 25, 3316...
2.262397
3,045
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: v0449gRpc.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0fv0449gRpc.proto\x12\tv0449gRpc\"\x1b\n\x0b\x64\x61taRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1a\n\x08\x64\x61ta2Plc\x12\x0e\n\x06xmlSer\x18\x01 \x01(\t\"\x1f\n\x0cslaveReq2Plc\x12\x0f\n\x07request\x18\x01 \x01(\x05\"\x1a\n\x08\x64\x61ta2Hmi\x12\x0e\n\x06xmlSer\x18\x01 \x01(\t\"\x1b\n\ndata2PlcJs\x12\r\n\x05jsSer\x18\x01 \x01(\t\"\x1b\n\ndata2HmiJs\x12\r\n\x05jsSer\x18\x01 \x01(\t\"\x1c\n\ndata2PlcPb\x12\x0e\n\x06xmlSer\x18\x01 \x01(\t\"\x1d\n\ndataAnswer\x12\x0f\n\x07message\x18\x01 \x01(\t2\x93\x01\n\x0cv0449gRpcSvc\x12=\n\x0bxchRtDataJs\x12\x15.v0449gRpc.data2PlcJs\x1a\x15.v0449gRpc.data2HmiJs\"\x00\x12\x44\n\x10xchRtDataJsSlave\x12\x17.v0449gRpc.slaveReq2Plc\x1a\x15.v0449gRpc.data2HmiJs\"\x00\x62\x06proto3') _DATAREQUEST = DESCRIPTOR.message_types_by_name['dataRequest'] _DATA2PLC = DESCRIPTOR.message_types_by_name['data2Plc'] _SLAVEREQ2PLC = DESCRIPTOR.message_types_by_name['slaveReq2Plc'] _DATA2HMI = DESCRIPTOR.message_types_by_name['data2Hmi'] _DATA2PLCJS = DESCRIPTOR.message_types_by_name['data2PlcJs'] _DATA2HMIJS = DESCRIPTOR.message_types_by_name['data2HmiJs'] _DATA2PLCPB = DESCRIPTOR.message_types_by_name['data2PlcPb'] _DATAANSWER = DESCRIPTOR.message_types_by_name['dataAnswer'] dataRequest = _reflection.GeneratedProtocolMessageType('dataRequest', (_message.Message,), { 'DESCRIPTOR' : _DATAREQUEST, '__module__' : 'v0449gRpc_pb2' # @@protoc_insertion_point(class_scope:v0449gRpc.dataRequest) }) _sym_db.RegisterMessage(dataRequest) data2Plc = _reflection.GeneratedProtocolMessageType('data2Plc', (_message.Message,), { 'DESCRIPTOR' : _DATA2PLC, '__module__' : 'v0449gRpc_pb2' # @@protoc_insertion_point(class_scope:v0449gRpc.data2Plc) }) _sym_db.RegisterMessage(data2Plc) slaveReq2Plc = _reflection.GeneratedProtocolMessageType('slaveReq2Plc', (_message.Message,), { 'DESCRIPTOR' : _SLAVEREQ2PLC, '__module__' : 'v0449gRpc_pb2' # @@protoc_insertion_point(class_scope:v0449gRpc.slaveReq2Plc) }) _sym_db.RegisterMessage(slaveReq2Plc) data2Hmi = _reflection.GeneratedProtocolMessageType('data2Hmi', (_message.Message,), { 'DESCRIPTOR' : _DATA2HMI, '__module__' : 'v0449gRpc_pb2' # @@protoc_insertion_point(class_scope:v0449gRpc.data2Hmi) }) _sym_db.RegisterMessage(data2Hmi) data2PlcJs = _reflection.GeneratedProtocolMessageType('data2PlcJs', (_message.Message,), { 'DESCRIPTOR' : _DATA2PLCJS, '__module__' : 'v0449gRpc_pb2' # @@protoc_insertion_point(class_scope:v0449gRpc.data2PlcJs) }) _sym_db.RegisterMessage(data2PlcJs) data2HmiJs = _reflection.GeneratedProtocolMessageType('data2HmiJs', (_message.Message,), { 'DESCRIPTOR' : _DATA2HMIJS, '__module__' : 'v0449gRpc_pb2' # @@protoc_insertion_point(class_scope:v0449gRpc.data2HmiJs) }) _sym_db.RegisterMessage(data2HmiJs) data2PlcPb = _reflection.GeneratedProtocolMessageType('data2PlcPb', (_message.Message,), { 'DESCRIPTOR' : _DATA2PLCPB, '__module__' : 'v0449gRpc_pb2' # @@protoc_insertion_point(class_scope:v0449gRpc.data2PlcPb) }) _sym_db.RegisterMessage(data2PlcPb) dataAnswer = _reflection.GeneratedProtocolMessageType('dataAnswer', (_message.Message,), { 'DESCRIPTOR' : _DATAANSWER, '__module__' : 'v0449gRpc_pb2' # @@protoc_insertion_point(class_scope:v0449gRpc.dataAnswer) }) _sym_db.RegisterMessage(dataAnswer) _V0449GRPCSVC = DESCRIPTOR.services_by_name['v0449gRpcSvc'] if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None _DATAREQUEST._serialized_start=30 _DATAREQUEST._serialized_end=57 _DATA2PLC._serialized_start=59 _DATA2PLC._serialized_end=85 _SLAVEREQ2PLC._serialized_start=87 _SLAVEREQ2PLC._serialized_end=118 _DATA2HMI._serialized_start=120 _DATA2HMI._serialized_end=146 _DATA2PLCJS._serialized_start=148 _DATA2PLCJS._serialized_end=175 _DATA2HMIJS._serialized_start=177 _DATA2HMIJS._serialized_end=204 _DATA2PLCPB._serialized_start=206 _DATA2PLCPB._serialized_end=234 _DATAANSWER._serialized_start=236 _DATAANSWER._serialized_end=265 _V0449GRPCSVC._serialized_start=268 _V0449GRPCSVC._serialized_end=415 # @@protoc_insertion_point(module_scope)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 410, 15, 31911, 70, 49, 14751, 13, 1676, 1462, 198, 37811, 8645, 515, 84...
2.218095
2,100
import datetime from django.core.management import call_command from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from resources_portal.management.commands.populate_dev_database import populate_dev_database from resources_portal.models import Material, Organization, User class SearchUsersEndpointTestCase(APITestCase): """ Tests /search/users operations. """ def test_search_for_name_returns_given_user(self): self.client.force_authenticate(user=self.primary_prof) search_url = ( reverse("search-users-list") + "?search=" + self.primary_prof.first_name + " " + self.primary_prof.last_name ) response = self.client.get(search_url) self.assertEqual(response.status_code, status.HTTP_200_OK) first_result_id = response.json()["results"][0]["id"] self.assertEqual(first_result_id, str(self.primary_prof.id)) def test_order_by_published_name_succeeds(self): self.client.force_authenticate(user=self.primary_prof) search_url = reverse("search-users-list") + "?ordering=published_name" response = self.client.get(search_url) self.assertEqual(response.status_code, status.HTTP_200_OK) user_published_names = [] for user in response.json()["results"]: if user["published_name"]: user_published_names.append(user["published_name"]) self.assertEqual(user_published_names, sorted(user_published_names)) def test_empty_search_returns_no_results(self): self.client.force_authenticate(user=self.primary_prof) search_url = reverse("search-users-list") + "?search=" response = self.client.get(search_url) self.assertEqual(response.status_code, status.HTTP_200_OK) user_count = int(response.json()["count"]) self.assertEqual(user_count, 0) class SearchOrganizationsEndpointTestCase(APITestCase): """ Tests /search/organizations operations. """ def test_search_for_organization_name_returns_given_organization(self): self.client.force_authenticate(user=self.primary_prof) search_url = reverse("search-organizations-list") + "?search=" + self.primary_lab.name response = self.client.get(search_url) self.assertEqual(response.status_code, status.HTTP_200_OK) first_result_id = int(response.json()["results"][0]["id"]) self.assertEqual(first_result_id, self.primary_lab.id) def test_search_for_owner_attribute_returns_related_organizations(self): self.client.force_authenticate(user=self.primary_prof) search_url = reverse("search-organizations-list") + "?search=" + self.primary_prof.email response = self.client.get(search_url) self.assertEqual(response.status_code, status.HTTP_200_OK) organization_count = int(response.json()["count"]) organization_names = [] for org in response.json()["results"]: organization_names.append(org["name"]) self.assertEqual( organization_count, len(Organization.objects.filter(owner=self.primary_prof)) ) for name in organization_names: self.assertTrue( Organization.objects.filter(name=name, owner=self.primary_prof).exists() )
[ 11748, 4818, 8079, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 1330, 869, 62, 21812, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 6738, 1334, 62, 30604, 1330, 3722, 198, 6738, 1334, 62, 30604, 13, 9288, 1330, 3486, 2...
2.508065
1,364
# Copyright 2019 Huawei Technologies Co., Ltd # # 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. """ Util for log module. """ import logging _LOGGER = logging.getLogger('MA') def _find_caller(): """ Bind findCaller() method, which is used to find the stack frame of the caller so that we can note the source file name, line number and function name. """ return _LOGGER.findCaller() def add_handler(self, handler): """ Add other handler supported by logging module. Args: handler (logging.Handler): Other handler supported by logging module. Raises: ValueError: If handler is not an instance of logging.Handler. """ if isinstance(handler, logging.Handler): self._logger.addHandler(handler) else: raise ValueError('handler must be an instance of logging.Handler,' ' but got {}'.format(type(handler))) def debug(self, tag, msg, *args): """ Log '[tag] msg % args' with severity 'DEBUG'. Args: tag (str): Logger tag. msg (str): Logger message. args (Any): Auxiliary value. """ caller_info = _find_caller() file_info = ':'.join([caller_info[0], str(caller_info[1])]) self._logger.debug(self._extra_fmt + msg, file_info, tag, *args) def info(self, tag, msg, *args): """ Log '[tag] msg % args' with severity 'INFO'. Args: tag (str): Logger tag. msg (str): Logger message. args (Any): Auxiliary value. """ caller_info = _find_caller() file_info = ':'.join([caller_info[0], str(caller_info[1])]) self._logger.info(self._extra_fmt + msg, file_info, tag, *args) def warn(self, tag, msg, *args): """ Log '[tag] msg % args' with severity 'WARNING'. Args: tag (str): Logger tag. msg (str): Logger message. args (Any): Auxiliary value. """ caller_info = _find_caller() file_info = ':'.join([caller_info[0], str(caller_info[1])]) self._logger.warning(self._extra_fmt + msg, file_info, tag, *args) def error(self, tag, msg, *args): """ Log '[tag] msg % args' with severity 'ERROR'. Args: tag (str): Logger tag. msg (str): Logger message. args (Any): Auxiliary value. """ caller_info = _find_caller() file_info = ':'.join([caller_info[0], str(caller_info[1])]) self._logger.error(self._extra_fmt + msg, file_info, tag, *args)
[ 2, 15069, 13130, 43208, 21852, 1766, 1539, 12052, 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.369092
1,333
workdays = float(input()) daily_tips = float(input()) exchange_rate = float(input()) salary = workdays * daily_tips annual_income = salary * 12 + salary * 2.5 net_income = annual_income - annual_income * 25 / 100 result = net_income / 365 * exchange_rate print('%.2f' % result)
[ 1818, 12545, 796, 12178, 7, 15414, 28955, 198, 29468, 62, 41315, 796, 12178, 7, 15414, 28955, 198, 1069, 3803, 62, 4873, 796, 12178, 7, 15414, 28955, 198, 198, 21680, 560, 796, 670, 12545, 1635, 4445, 62, 41315, 198, 198, 1236, 723, 6...
3.021505
93
from transformer_rankers.trainers import transformer_trainer from transformer_rankers.datasets import dataset, preprocess_scisumm_ranked from transformer_rankers.eval import results_analyses_tools from transformers import BertTokenizer, BertForSequenceClassification from sacred.observers import FileStorageObserver from sacred import Experiment import numpy as np import torch import pandas as pd import argparse import logging import sys ex = Experiment('BERT-ranker experiment') logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.StreamHandler(sys.stdout) ] ) if __name__ == "__main__": main()
[ 6738, 47385, 62, 43027, 364, 13, 27432, 364, 1330, 47385, 62, 2213, 10613, 198, 6738, 47385, 62, 43027, 364, 13, 19608, 292, 1039, 1330, 27039, 11, 662, 14681, 62, 1416, 271, 13929, 62, 28282, 198, 6738, 47385, 62, 43027, 364, 13, 182...
3.179724
217
#Q: Evaluate the sum of all the amicable numbers under 10000. #A: 31626 print sum_amicable(1,10000)
[ 2, 48, 25, 26439, 4985, 262, 2160, 286, 477, 262, 716, 18424, 3146, 739, 33028, 13, 198, 2, 32, 25, 34131, 2075, 198, 198, 4798, 2160, 62, 18127, 540, 7, 16, 11, 49388, 8, 198 ]
2.885714
35
import long_responses as long # Returns the probability of a message matching the responses that we have # Checks all the responses using the probability of the messages
[ 11748, 890, 62, 16733, 274, 355, 890, 198, 198, 2, 16409, 262, 12867, 286, 257, 3275, 12336, 262, 9109, 326, 356, 423, 628, 198, 2, 47719, 477, 262, 9109, 1262, 262, 12867, 286, 262, 6218, 628 ]
4.833333
36
from io import StringIO import numpy as np from h5py import File from keras.models import load_model as keras_load_model from PIL import Image, ImageOps
[ 6738, 33245, 1330, 10903, 9399, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 289, 20, 9078, 1330, 9220, 198, 6738, 41927, 292, 13, 27530, 1330, 3440, 62, 19849, 355, 41927, 292, 62, 2220, 62, 19849, 198, 6738, 350, 4146, 1330, ...
3.340426
47
from setuptools import setup setup( name="workshop-client", install_requires=["flask==1.1.1", "requests==2.22.0"], python_requires=">=3.7", classifiers=[ "Development Status :: 1 - Beta", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 38067, 12, 16366, 1600, 198, 220, 220, 220, 2721, 62, 47911, 28, 14692, 2704, 2093, 855, 16, 13, 16, 13, 16, 1600, 366, 8897, 3558, 855, 17, ...
2.497006
167
import json import unittest import pyfacebook.models as models
[ 11748, 33918, 198, 11748, 555, 715, 395, 198, 198, 11748, 12972, 19024, 13, 27530, 355, 4981, 628 ]
3.823529
17
# MIT License # # Copyright (c) 2020 Airbyte # # 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 json from datetime import datetime from typing import Dict, Generator from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteRecordMessage, AirbyteStream, ConfiguredAirbyteCatalog, Status, Type, ) from airbyte_cdk.sources import Source
[ 2, 17168, 13789, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 3701, 26327, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 10314, 3696, 357, ...
3.571776
411