content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/usr/bin/python3 import sys #import fileinput from operator import itemgetter myDictionary = {} myList=[] for line in sys.stdin: line = line.strip() line = line.split("\t") batsman, bowler, wickets = line[0], line[1], int(line[2]) if batsman not in myDictionary: myDictionary[batsman] = {} myDictionary[batsman][bowler] = [0,0] # [Wickets, Number of Balls Faced] elif batsman in myDictionary: if bowler not in myDictionary[batsman]: myDictionary[batsman][bowler] = [0,0] myDictionary[batsman][bowler][0] += wickets myDictionary[batsman][bowler][1] += 1 for batsman in list(myDictionary): # Remove batsman-bowler pair who has less than 5 deliveries in between. for bowler in list(myDictionary[batsman]): if myDictionary[batsman][bowler][1] <= 5: del myDictionary[batsman][bowler] for batsman in myDictionary: tempList = list(myDictionary[batsman].keys()) if len(tempList) > 0: for bowler in myDictionary[batsman]: myList.append((batsman, bowler, myDictionary[batsman][bowler][0], myDictionary[batsman][bowler][1])) #newList = sorted(myList, key=itemgetter(1)) newList = sorted(myList, key=itemgetter(0)) newList = sorted(newList, key=itemgetter(3)) newList = sorted(newList, key=itemgetter(2), reverse=True) for (batsman, bowler, wickets, deliveries) in newList: print(batsman + ',' + bowler + ',' + str(wickets) + ',' + str(deliveries))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 11748, 25064, 198, 198, 2, 11748, 2393, 15414, 198, 6738, 10088, 1330, 2378, 1136, 353, 198, 198, 1820, 35, 14188, 796, 23884, 198, 1820, 8053, 28, 21737, 198, 198, 1640, 1627, 287, 25064...
2.45799
607
from abstractions.datastore import Datastore from unittest.mock import Mock from google.cloud.datastore.entity import Entity from unittest.mock import patch import pytest """ #test_valid_information::ut #test_with_invalid_information::ut """
[ 6738, 12531, 507, 13, 19608, 459, 382, 1330, 16092, 459, 382, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 198, 6738, 23645, 13, 17721, 13, 19608, 459, 382, 13, 26858, 1330, 20885, 198, 6738, 555, 715, 395, 13, 76, 735, 1330,...
3.217949
78
import logging import logging.config import os from importlib.metadata import version from typing import Any, Union from .trace import ( make_request_logging_trace_config, make_sentry_trace_config, make_zipkin_trace_config, new_sampled_trace, new_trace, new_trace_cm, notrace, setup_sentry, setup_zipkin, setup_zipkin_tracer, trace, trace_cm, ) __version__ = version(__package__) __all__ = [ "init_logging", "HideLessThanFilter", "make_request_logging_trace_config", "make_sentry_trace_config", "make_zipkin_trace_config", "notrace", "setup_sentry", "setup_zipkin", "setup_zipkin_tracer", "trace", "trace_cm", "new_sampled_trace", "new_trace", "new_trace_cm", ] if "NP_LOG_LEVEL" in os.environ: _default_log_level = logging.getLevelName(os.environ["NP_LOG_LEVEL"]) else: _default_log_level = logging.WARNING DEFAULT_CONFIG = { "version": 1, "disable_existing_loggers": False, "formatters": { "standard": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"} }, "filters": { "hide_errors": {"()": f"{__name__}.HideLessThanFilter", "level": "ERROR"} }, "handlers": { "stdout": { "class": "logging.StreamHandler", "level": "DEBUG", "formatter": "standard", "stream": "ext://sys.stdout", "filters": ["hide_errors"], }, "stderr": { "class": "logging.StreamHandler", "level": "ERROR", "formatter": "standard", "stream": "ext://sys.stderr", }, }, "root": {"level": _default_log_level, "handlers": ["stderr", "stdout"]}, }
[ 11748, 18931, 198, 11748, 18931, 13, 11250, 198, 11748, 28686, 198, 6738, 1330, 8019, 13, 38993, 1330, 2196, 198, 6738, 19720, 1330, 4377, 11, 4479, 198, 198, 6738, 764, 40546, 1330, 357, 198, 220, 220, 220, 787, 62, 25927, 62, 6404, ...
2.149383
810
# Copyright 2017 QuantRocket - 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 os import requests from .exceptions import ImproperlyConfigured from quantrocket.cli.utils.output import json_to_cli # Instantiate houston so that all callers can share a TCP connection (for # performance's sake) houston = Houston() def ping(): """ Pings houston. Returns ------- json reply from houston """ response = houston.get("/ping") houston.raise_for_status_with_json(response) return response.json()
[ 2, 15069, 2177, 16972, 50218, 532, 1439, 6923, 33876, 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,...
3.427184
309
from random import shuffle from math import sqrt from enum import Enum from src.Sudoku.SudokuSolver import SudokuSolver from src.Sudoku.Sudoku import Sudoku """ **** SUDOKU GENERATOR **** Author: Andrea Pollastro Date: September 2018 """
[ 6738, 4738, 1330, 36273, 198, 6738, 10688, 1330, 19862, 17034, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 12351, 13, 50, 463, 11601, 13, 50, 463, 11601, 50, 14375, 1330, 14818, 11601, 50, 14375, 198, 6738, 12351, 13, 50, 463, 11601, ...
3
82
import argparse import random, os from os.path import join as j from collections import OrderedDict import conllu import torch import pathlib import tempfile import depedit import stanza.models.parser as parser from stanza.models.depparse.data import DataLoader from stanza.models.depparse.trainer import Trainer from stanza.models.common import utils from stanza.models.common.pretrain import Pretrain from stanza.models.common.doc import * from stanza.utils.conll import CoNLL PACKAGE_BASE_DIR = pathlib.Path(__file__).parent.absolute() # Parser arguments ----------------------------------------------------------------------------------------------------- # These args are used by stanza.models.parser. Keys should always exactly match those you'd get from the dictionary # obtained from running stanza.models.parser.parse_args(). The values below were selected through hyperoptimization. DEFAULT_PARSER_ARGS = { # general setup 'lang': 'cop', 'treebank': 'cop_scriptorium', 'shorthand': 'cop_scriptorium', 'data_dir': j(PACKAGE_BASE_DIR, 'data', 'depparse'), 'output_file': j(PACKAGE_BASE_DIR, 'coptic_data', 'scriptorium', 'pred.conllu'), 'seed': 1234, 'cuda': torch.cuda.is_available(), 'cpu': not torch.cuda.is_available(), 'save_dir': j(PACKAGE_BASE_DIR, "..", 'stanza_models'), 'save_name': None, # word embeddings 'pretrain': True, 'wordvec_dir': j(PACKAGE_BASE_DIR, 'coptic_data', 'wordvec'), 'wordvec_file': j(PACKAGE_BASE_DIR, 'coptic_data', 'wordvec', 'word2vec', 'Coptic', 'coptic_50d.vec.xz'), 'word_emb_dim': 50, 'word_dropout': 0.3, # char embeddings 'char': True, 'char_hidden_dim': 200, 'char_emb_dim': 50, 'char_num_layers': 1, 'char_rec_dropout': 0, # very slow! # pos tags 'tag_emb_dim': 5, 'tag_type': 'gold', # network params 'hidden_dim': 300, 'deep_biaff_hidden_dim': 200, 'composite_deep_biaff_hidden_dim': 100, 'transformed_dim': 75, 'num_layers': 3, 'pretrain_max_vocab': 250000, 'dropout': 0.5, 'rec_dropout': 0, # very slow! 'linearization': True, 'distance': True, # training 'sample_train': 1.0, 'optim': 'adam', 'lr': 0.002, 'beta2': 0.95, 'max_steps': 20000, 'eval_interval': 100, 'max_steps_before_stop': 2000, 'batch_size': 1500, 'max_grad_norm': 1.0, 'log_step': 20, # these need to be included or there will be an error when stanza tries to access them 'train_file': None, 'eval_file': None, 'gold_file': None, 'mode': None, } # Custom features ------------------------------------------------------------------------------------------------------ # Params for controlling the custom features we're feeding the network FEATURE_CONFIG = { # BIOLU or BIO 'features': [ 'foreign_word', 'morph_count', 'left_morph', 'entity', ], 'foreign_word_binary': True, 'morph_count_binary': False, 'entity_encoding_scheme': 'BIOLU', 'entity_dropout': 0.30, } # DepEdit preprocessor which removes gold morph data and makes a few other tweaks PREPROCESSOR = depedit.DepEdit(config_file=j(PACKAGE_BASE_DIR, "coptic_data", "depedit", "add_ud_and_flat_morph.ini"), options=type('', (), {"quiet": True, "kill": "both"})) # Load a lexicon of foreign words and initialize a lemma cache with open(j(PACKAGE_BASE_DIR, 'coptic_data', 'lang_lexicon.tab'), 'r', encoding="utf8") as f: FOREIGN_WORDS = {x.split('\t')[0]: x.split('\t')[1].rstrip() for x in f.readlines() if '\t' in x} FW_CACHE = {} # load known entities and sort in order of increasing token length with open(j(PACKAGE_BASE_DIR, 'coptic_data', 'entities.tab'), 'r', encoding="utf8") as f: KNOWN_ENTITIES = OrderedDict(sorted( ((x.split('\t')[0], x.split('\t')[1]) for x in f.readlines()), key=lambda x: len(x[0].split(" ")) )) FEATURE_FUNCTIONS = { 'foreign_word': _add_foreign_word_feature, 'left_morph': _add_left_morph_feature, 'morph_count': _add_morph_count_feature, 'entity': _add_entity_feature, } # public api ----------------------------------------------------------------------------------------------------------- def train(train, dev, save_name=None): """Train a new stanza model. :param train: either a conllu string or a path to a conllu file :param dev: either a conllu string or a path to a conllu file :param save_name: optional, a name for your model's save file, which will appear in 'stanza_models/' """ args = DEFAULT_PARSER_ARGS.copy() feature_config = FEATURE_CONFIG.copy() args['mode'] = 'train' args['train_file'] = _read_conllu_arg(train, feature_config) args['eval_file'] = _read_conllu_arg(dev, feature_config) args['gold_file'] = _read_conllu_arg(dev, feature_config, gold=True) if save_name: args['save_name'] = save_name parser.train(args) def test(test, save_name=None): """Evaluate using an existing stanza model. :param test: either a conllu string or a path to a conllu file :param save_name: optional, a name for your model's save file, which will appear in 'stanza_models/' """ args = DEFAULT_PARSER_ARGS.copy() feature_config = FEATURE_CONFIG.copy() args['mode'] = "predict" args['eval_file'] = _read_conllu_arg(test, feature_config) args['gold_file'] = _read_conllu_arg(test, feature_config, gold=True) if save_name: args['save_name'] = save_name return parser.evaluate(args)
[ 11748, 1822, 29572, 198, 11748, 4738, 11, 28686, 198, 6738, 28686, 13, 6978, 1330, 4654, 355, 474, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 11748, 369, 297, 84, 198, 11748, 28034, 198, 11748, 3108, 8019, 198, 11748, 20218, 775...
2.592507
2,162
if __name__ == '__main__': ans = makeSentence(12, '', 22.4) print(ans)
[ 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 9093, 796, 787, 31837, 594, 7, 1065, 11, 705, 3256, 2534, 13, 19, 8, 198, 220, 220, 220, 3601, 7, 504, 8, 198 ]
2.105263
38
__version__ = '0.1.0' from .parser import parse
[ 834, 9641, 834, 796, 705, 15, 13, 16, 13, 15, 6, 198, 198, 6738, 764, 48610, 1330, 21136, 198 ]
2.578947
19
from os.path import expanduser import sys import json ''' The configuration file will be stored as a json file @example { window: { w_dimension: 800 h_dimension: 600 resizeable: False } } '''
[ 6738, 28686, 13, 6978, 1330, 4292, 7220, 198, 11748, 25064, 198, 11748, 33918, 220, 198, 198, 7061, 6, 198, 197, 464, 8398, 2393, 481, 307, 8574, 355, 257, 33918, 2393, 628, 197, 31, 20688, 198, 197, 90, 198, 197, 197, 17497, 25, 13...
2.471264
87
#!/bin/python3 import sys import os import getopt import csv import json import itertools import zipfile import tarfile import binwalk import collections from heapq import nsmallest from collections import defaultdict import tlsh import numpy as np import matplotlib.pyplot as plt from multiprocessing.dummy import Pool from sklearn.cluster import * from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs from sklearn.preprocessing import StandardScaler from sklearn.externals import joblib pool = Pool() #Values are from the TLSH paper try: opts, args = getopt.getopt(sys.argv[1:], "hd:m:bn:t", ["help", "directory", "metadata", "binwalk", "number", "test"]) except getopt.GetoptError as err: print(err) # will print something like "option -a not recognized" usage() exit(2) directory = "" meta = "" use_binwalk = False n = 10 use_existing = False for o, a in opts: if o in ("-d", "--directory"): directory = a elif o in ("-h", "--help"): usage() exit() elif o in ("-m", "--metadata"): meta = a elif o in ("-b", "--binwalk"): use_binwalk = True elif o in ("-n", "--number"): n = int(a) elif o in ("-t", "--test"): use_existing = True if not directory: print("Program must be provided a file directory path") exit(1) file_list = list_files(directory) hash_list = [] if meta: meta_contents = parse_metadata_json(meta) else: meta_contents = None hash_list = [lsh_json(x) for x in zip(file_list, itertools.repeat(meta_contents))] if use_existing: file_data = np.load(".tmp.npz") #See https://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez for why this syntax is needed clustered_files = file_data['clusters'][()] cluster_hashes = file_data['hash_list'] ms = joblib.load('.tmp2.pkl') adj = np.zeros((len(hash_list), len(cluster_hashes)), int) #Compare new file hashes against saved data to get distances for i in range(len(hash_list)): for j in range(len(cluster_hashes)): adj[i][j] = diff_hash(hash_list[i], cluster_hashes[j]); cluster_labels = ms.predict(adj) for f in file_list: #Label of the prediucted file cluster lab = cluster_labels[file_list.index(f)] if lab not in clustered_files: print("{} does not belong to any existing cluster".format(f)) continue clus = clustered_files[lab] print("Target file {} is in cluster {}".format(f, lab)) for c in clus: print(c) #Empty line to separate cluster print outs print() exit() else: adj = np.zeros((len(hash_list), len(hash_list)), int) for i in range(len(hash_list)): for j in range(len(hash_list)): d = diff_hash(hash_list[i], hash_list[j]); adj[i][j] = d adj[j][i] = d best_cluster_count = 0 best_silhouette_score = -1.0 #Calculate the best cluster count in parallel silhouette_list = Pool().map(cl, zip(range(2, 16), itertools.repeat(adj))) best_cluster_count = silhouette_list.index(max(silhouette_list)) + 2 ms = MiniBatchKMeans(n_clusters=best_cluster_count) cluster_labels = ms.fit_predict(adj) clustered_files = {} for f in file_list: lab = cluster_labels[file_list.index(f)] if lab in clustered_files: clustered_files[lab].append(f) else: clustered_files[lab] = [f] print(clustered_files) np.savez(".tmp", clusters=clustered_files, hash_list=hash_list) joblib.dump(ms, '.tmp2.pkl') labels = ms.labels_ cluster_centers = ms.cluster_centers_ labels_unique = np.unique(labels) n_clusters_ = len(labels_unique) print("number of estimated clusters : %d" % n_clusters_) plt.figure(1) plt.clf() colors = itertools.cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') for k, col in zip(range(n_clusters_), colors): my_members = labels == k cluster_center = cluster_centers[k] plt.plot(adj[my_members, 0], adj[my_members, 1], col + '.') plt.plot(cluster_center[0], cluster_center[1], '+', markerfacecolor=col, markeredgecolor='k', markersize=5) plt.title('Estimated number of clusters: %d' % n_clusters_) plt.show()
[ 2, 48443, 8800, 14, 29412, 18, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 651, 8738, 198, 11748, 269, 21370, 198, 11748, 33918, 198, 11748, 340, 861, 10141, 198, 11748, 19974, 7753, 198, 11748, 13422, 7753, 198, 11748, 9874, 11152,...
2.385496
1,834
from pyomo.environ import * import numpy as np cijr = [] fjr = [] with open("./Test_Instances/RAND2000_120-80.txt") as instanceFile: n = int(instanceFile.readline()) clientsFacilitiesSizeStr = instanceFile.readline().strip().split(" ") instanceFile.readline() for phase in range(2): for i in range(1, len(clientsFacilitiesSizeStr)): if phase == 0: fjr.append([]) for j in range(int(clientsFacilitiesSizeStr[i])): fjr[i-1].append(float(instanceFile.readline().strip().split(" ")[0])) else: nextLine = instanceFile.readline().strip() cijr.append([]) j = 0 while(nextLine != ""): nextLineNumbers = nextLine.split(" ") cijr[i-1].append([]) for nextLinenumber in nextLineNumbers: cijr[i-1][j].append(float(nextLinenumber)) j+=1 nextLine = instanceFile.readline().strip() instanceFile.readline() instanceFile.close() #cijr = np.array( # [ # np.array([ # [1,1000,1000], # [15000,2,15000], # [20000,20000,3], # [1,40000,40000] # ]), # np.array([ # [10000,5,10000,10000,20000], # [30000,23000,3,24000,18000], # [28000,35000,21000,4,33000] # ]), # np.array([ # [16, 14], # [2, 18000], # [20000, 3], # [20000, 2], # [24, 25] # ]) # ] #) #fjr = np.array( # [ # [10,15,20], # [17,20,25,30,18], # [48,50] # ] #) I = range(len(cijr[0])) J = range(len(cijr[0][0])) R = range(1, len(fjr)+1) RM1 = range(1, len(fjr)) yjrIndexes = [] zirabIndexes = [] for r in R: for j in range(len(fjr[r-1])): yjrIndexes.append((r,j)) for i in I: for r in RM1: for a in range(len(cijr[r])): for b in range(len(cijr[r][0])): zirabIndexes.append((i,r,a,b)) model = ConcreteModel() model.vij1 = Var(I, J, domain=Binary) model.yjr = Var(yjrIndexes, domain=Binary) model.zirab = Var(zirabIndexes, domain=Binary) model.constraints = ConstraintList() for i in I: model.constraints.add(sum(model.vij1[i, j] for j in J) == 1) for j1 in J: model.constraints.add(sum(model.zirab[i,1,j1,b] for b in range(len(cijr[1][0]))) == model.vij1[i,j1]) model.constraints.add(model.vij1[i,j1] <= model.yjr[1,j1]) for r in range(2, len(fjr) + 1): if(r <= len(fjr) - 1): for a in range(len(cijr[r])): model.constraints.add(sum(model.zirab[i,r,a,b] for b in range(len(cijr[r][0]))) == sum(model.zirab[i,r-1,bp,a] for bp in range(len(cijr[r-1])))) for b in range(len(cijr[r-1][0])): model.constraints.add(sum(model.zirab[i,r-1,a,b,] for a in range(len(cijr[r-1]))) <= model.yjr[r, b]) model.objective = Objective( expr = sum(sum(cijr[0][i][j1]*model.vij1[i,j1] for j1 in J) for i in I) + sum(sum(sum(sum(cijr[r][a][b]*model.zirab[i,r,a,b] for b in range(len(cijr[r][0])))for a in range(len(cijr[r]))) for r in RM1) for i in I) + sum(sum(fjr[r-1][j]*model.yjr[r,j] for j in range(len(fjr[r-1]))) for r in R), sense=minimize ) results = SolverFactory('cplex').solve(model) results.write() #if results.solver.status: # model.pprint() #model.constraints.display()
[ 6738, 12972, 17902, 13, 268, 2268, 1330, 1635, 198, 11748, 299, 32152, 355, 45941, 198, 198, 979, 73, 81, 796, 17635, 198, 69, 73, 81, 796, 17635, 198, 4480, 1280, 7, 1911, 14, 14402, 62, 6310, 1817, 14, 49, 6981, 11024, 62, 10232, ...
1.945342
1,610
# # exports a specific folder in the import directory to the google cloud # # Syntax: # python3 import.py <GS URI> # # Example: # python3 import.py gs://bini-products-bucket/training-sets-2/intrusion/poc1_v1.2.0/frames # # import os import sys # uri cloud_uri = sys.argv[1] os.system('mkdir -p import') os.system('gsutil -m cp -c -r '+cloud_uri+' ./import/')
[ 2, 198, 2, 15319, 257, 2176, 9483, 287, 262, 1330, 8619, 284, 262, 23645, 6279, 198, 2, 198, 2, 26375, 897, 25, 198, 2, 21015, 18, 1330, 13, 9078, 1279, 14313, 43975, 29, 220, 198, 2, 220, 220, 198, 2, 17934, 25, 220, 198, 2, ...
2.446667
150
#!/usr/bin/env python import xml.etree.ElementTree as ET
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 628, 220, 220, 220, 220, 220, 220, 220, 220 ]
2.357143
28
import pytz from django.conf import settings
[ 11748, 12972, 22877, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 628 ]
3.833333
12
default_app_config = 'foundation.apps.FoundationConfig'
[ 12286, 62, 1324, 62, 11250, 796, 705, 42526, 13, 18211, 13, 21077, 341, 16934, 6, 198 ]
3.5
16
from flask import Flask from flask_migrate import Migrate from app.model import db from app.controller import api app = Flask(__name__) app.register_blueprint(api) app.config[ "SQLALCHEMY_DATABASE_URI" ] = "postgresql://newschatbotdevelopment:Wlk8skrHKvZEbM6Gw@database.internal.newschatbot.ceskodigital.net:5432/newschatbotdevelopment" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False migrate = Migrate(app, db) db.init_app(app) if __name__ == "__main__": app.run()
[ 6738, 42903, 1330, 46947, 198, 6738, 42903, 62, 76, 42175, 1330, 337, 42175, 198, 198, 6738, 598, 13, 19849, 1330, 20613, 198, 6738, 598, 13, 36500, 1330, 40391, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 1324, 13, 30238, ...
2.625
184
from .test_vehicles_crud import * from .test_soat_vehicles import *
[ 6738, 764, 9288, 62, 33892, 2983, 62, 6098, 463, 1330, 1635, 198, 6738, 764, 9288, 62, 568, 265, 62, 33892, 2983, 1330, 1635 ]
2.913043
23
"""Example on how to read sleep data from SIHA """ import os from tasrif.data_readers.siha_dataset import SihaDataset from tasrif.processing_pipeline import SequenceOperator from tasrif.processing_pipeline.custom import JqOperator from tasrif.processing_pipeline.pandas import ( ConvertToDatetimeOperator, JsonNormalizeOperator, SetIndexOperator, ) siha_folder_path = os.environ.get("SIHA_PATH") pipeline = SequenceOperator( [ SihaDataset(siha_folder_path, table_name="Data"), JqOperator( "map({patientID} + (.data.sleep[].data as $data | " + "($data.sleep | map(.) | .[]) | . * {levels: {overview : ($data.summary//{})}})) | " + "map (if .levels.data != null then . else .levels += {data: []} end) | " + "map(. + {type, dateOfSleep, minutesAsleep, logId, startTime, endTime, duration, isMainSleep," + " minutesToFallAsleep, minutesAwake, minutesAfterWakeup, timeInBed, efficiency, infoCode})" ), JsonNormalizeOperator( record_path=["levels", "data"], meta=[ "patientID", "logId", "dateOfSleep", "startTime", "endTime", "duration", "isMainSleep", "minutesToFallAsleep", "minutesAsleep", "minutesAwake", "minutesAfterWakeup", "timeInBed", "efficiency", "type", "infoCode", ["levels", "summary", "deep", "count"], ["levels", "summary", "deep", "minutes"], ["levels", "summary", "deep", "thirtyDayAvgMinutes"], ["levels", "summary", "wake", "count"], ["levels", "summary", "wake", "minutes"], ["levels", "summary", "wake", "thirtyDayAvgMinutes"], ["levels", "summary", "light", "count"], ["levels", "summary", "light", "minutes"], ["levels", "summary", "light", "thirtyDayAvgMinutes"], ["levels", "summary", "rem", "count"], ["levels", "summary", "rem", "minutes"], ["levels", "summary", "rem", "thirtyDayAvgMinutes"], ["levels", "overview", "totalTimeInBed"], ["levels", "overview", "totalMinutesAsleep"], ["levels", "overview", "stages", "rem"], ["levels", "overview", "stages", "deep"], ["levels", "overview", "stages", "light"], ["levels", "overview", "stages", "wake"], ], errors="ignore", ), ConvertToDatetimeOperator( feature_names=["dateTime"], infer_datetime_format=True ), SetIndexOperator("dateTime"), ] ) df = pipeline.process() print(df)
[ 37811, 16281, 319, 703, 284, 1100, 3993, 1366, 422, 25861, 7801, 198, 37811, 198, 11748, 28686, 198, 198, 6738, 256, 292, 81, 361, 13, 7890, 62, 961, 364, 13, 13396, 3099, 62, 19608, 292, 316, 1330, 15638, 3099, 27354, 292, 316, 198, ...
1.999307
1,444
import pytest from visionpy import Vision, Contract from visionpy import AsyncVision, AsyncContract from visionpy.keys import PrivateKey # vpioneer addr and key PRIVATE_KEY = PrivateKey(bytes.fromhex("a318cb4f1f3b87d604163e4a854312555d57158d78aef26797482d3038c4018b")) FROM_ADDR = 'VSfD1o6FPChqdqLgwJaztjckyyo2GSM1KP' TO_ADDR = 'VTCYvEK2ZuWvZ5LXqrLpU2GoRkFeJ1NrD2' # private_key: eed06aebdef88683ff5678b353d1281bb2b730113c9283f7ea96600a0d2c104f VRC20_CONTRACT_ADDR = 'VE2sE7iXbSyESQKMPLav5Q84EXEHZCnaRX'
[ 11748, 12972, 9288, 198, 198, 6738, 5761, 9078, 1330, 19009, 11, 17453, 198, 6738, 5761, 9078, 1330, 1081, 13361, 44206, 11, 1081, 13361, 45845, 198, 6738, 5761, 9078, 13, 13083, 1330, 15348, 9218, 198, 198, 2, 410, 79, 7935, 263, 37817...
1.980916
262
from django.db.models import Avg from store.models import Book, UserBookRelation
[ 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 33455, 198, 198, 6738, 3650, 13, 27530, 1330, 4897, 11, 11787, 10482, 6892, 341, 628 ]
3.608696
23
"""Default base class for PSP pages. This class is intended to be used in the future as the default base class for PSP pages in the event that some special processing is needed. Right now, no special processing is needed, so the default base class for PSP pages is the standard Webware Page. """ from Page import Page
[ 37811, 19463, 2779, 1398, 329, 48651, 5468, 13, 198, 198, 1212, 1398, 318, 5292, 284, 307, 973, 287, 262, 2003, 355, 262, 4277, 2779, 1398, 198, 1640, 48651, 5468, 287, 262, 1785, 326, 617, 2041, 7587, 318, 2622, 13, 198, 11028, 783, ...
4.337838
74
## # File: DictMethodEntityInstanceHelper.py # Author: J. Westbrook # Date: 16-Jul-2019 # Version: 0.001 Initial version # # # Updates: # 22-Nov-2021 dwp authSeqBeg and authSeqEnd are returned as integers but must be compared as strings in pAuthAsymD # ## """ This helper class implements methods supporting entity-instance-level functions in the RCSB dictionary extension. """ __docformat__ = "google en" __author__ = "John Westbrook" __email__ = "jwest@rcsb.rutgers.edu" __license__ = "Apache 2.0" # pylint: disable=too-many-lines import logging import re import time from collections import OrderedDict from mmcif.api.DataCategory import DataCategory from rcsb.utils.dictionary.DictMethodSecStructUtils import DictMethodSecStructUtils logger = logging.getLogger(__name__)
[ 2235, 198, 2, 9220, 25, 220, 220, 220, 360, 713, 17410, 32398, 33384, 47429, 13, 9078, 198, 2, 6434, 25, 220, 449, 13, 35345, 198, 2, 7536, 25, 220, 220, 220, 1467, 12, 16980, 12, 23344, 198, 2, 10628, 25, 657, 13, 8298, 20768, ...
3.082031
256
"""Long statement strings and other space consuming data definitions for testing are declared here. This is done to avoid clutter in main test files. """ from typing import Dict from typing import List from typing import Tuple import pytest from _pytest.fixtures import SubRequest from fi_parliament_tools.parsing.data_structures import MP chairman_texts = [ "Ilmoitetaan, ett valiokuntien ja kansliatoimikunnan vaalit toimitetaan ensi tiistaina 5. " "pivn toukokuuta kello 14 pidettvss tysistunnossa. Ehdokaslistat nit vaaleja varten " "on jtettv keskuskansliaan viimeistn ensi maanantaina 4. pivn toukokuuta kello 12.", "Toimi Kankaanniemen ehdotus 5 ja Krista Kiurun ehdotus 6 koskevat samaa asiaa, joten ensin " "nestetn Krista Kiurun ehdotuksesta 6 Toimi Kankaanniemen ehdotusta 5 vastaan ja sen " "jlkeen voittaneesta mietint vastaan.", "Kuhmosta oleva agrologi Tuomas Kettunen, joka varamiehen Oulun vaalipiirist on " "tullut Antti Rantakankaan sijaan, on tnn 28.11.2019 esittnyt puhemiehelle " "edustajavaltakirjansa ja ryhtynyt hoitamaan edustajantointaan.", ] speaker_texts = [ "Arvoisa puhemies! Hallituksen esityksen mukaisesti on varmasti hyv jatkaa mraikaisesti " "matkapuhelinliittymien telemarkkinointikieltoa. Kukaan kansalainen ei ole kyll ainakaan " "itselleni valittanut siit, ett en eivt puhelinkauppiaat soittele kotiliittymiin ja " "puhelimiin, ja mys operaattorit ovat olleet kohtuullisen tyytyvisi thn kieltoon. " "Ongelmia on kuitenkin muussa puhelinmyynniss ja telemarkkinoinnissa. Erityisesti " "nettiliittymien puhelinmyynniss on ongelmia. On aggressiivista myynti, ja ihmisill on " "eptietoisuutta siit, mit he ovat lopulta ostaneet. Lisksi mielestni on ongelmallista " "rajata vain puhelinliittymt telemarkkinointikiellon piiriin, kun viestint- ja " "mobiilipalveluiden puhelinkauppa on laajempi aihe ja se on laajempi ongelma ja ongelmia on " "tosiaan tss muidenkin tyyppisten sopimusten myynniss. Tm laki tmnsisltisen on " "varmasti ihan hyv, ja on hyv mraikaisesti jatkaa tt, mutta nkisin, ett sitten kun " "tm laki on kulumassa umpeen, meidn on palattava asiaan ja on tehtv joku lopullisempi " "ratkaisu tst telemarkkinoinnista. Ei voida menn tllaisen yhden sopimusalan " "mraikaisuudella eteenpin. Meidn tytyy tehd ratkaisut, jotka ovat laajempia ja jotka " "koskevat viestint-, tele- ja mobiilisopimusten puhelinmyynti laajemmin ja muutenkin " "puhelinmyynnin pelisntj laajemmin. Varmaankin paras ratkaisu olisi se, ett jatkossa " "puhelimessa tehty ostos pitisi varmentaa kirjallisesti esimerkiksi shkpostilla, " "tekstiviestill tai kirjeell. Meidn on ratkaistava jossain vaiheessa nm puhelinmyynniss " "olevat ongelmat ja ksiteltv asia kokonaisvaltaisesti. Kiitos. (Hlin)", "Arvoisa puhemies! Pienen, vastasyntyneen lapsen ensimminen ote on samaan aikaan luja ja " "hento. Siihen otteeseen kiteytyy paljon luottamusta ja vastuuta. Luottamusta siihen, ett " "molemmat vanhemmat ovat lsn lapsen elmss. Vastuuta siit, ett huominen on aina " "valoisampi. Luottamus ja vastuu velvoittavat mys meit pttji. Tmn hallituksen " "ptkset eivt perheiden kannalta ole olleet kovin hppisi. Paljon on leikattu perheiden " "arjesta, mutta toivon kipin hersi viime vuonna, kun hallitus ilmoitti, ett se toteuttaa " "perhevapaauudistuksen. Viime perjantaina hallituksen perheministeri kuitenkin ylltten " "ilmoitti, ett hn keskeytt tmn uudistuksen. Viel suurempi hmmstys oli se syy, jonka " "takia tm keskeytettiin. Ministeri ilmoitti, ett valmistellut mallit olisivat olleet " "huonoja suomalaisille perheille. Perheministeri Saarikko, kun te olette vastuussa tmn " "uudistuksen valmistelusta, niin varmasti suomalaisia perheit kiinnostaisi tiet, miksi te " "valmistelitte huonoja malleja.", "Arvoisa puhemies! Lmpimt osanotot omasta ja perussuomalaisten eduskuntaryhmn " "puolesta pitkaikaisen kansanedustajan Maarit Feldt-Rannan omaisille ja lheisille. " "Nuorten mielenterveysongelmat ovat vakava yhteiskunnallinen ongelma. " "Mielenterveysongelmat ovat kasvaneet viime vuosina rjhdysmisesti, mutta " "terveydenhuoltoon ei ole listty vastaavasti resursseja, vaan hoitoonpsy on " "ruuhkautunut. Masennuksesta krsii jopa 15 prosenttia nuorista, ahdistuneisuudesta 10 " "prosenttia, ja 1015 prosentilla on toistuvia itsetuhoisia ajatuksia. Monet nist " "ongelmista olisivat hoidettavissa, jos yhteiskunta ottaisi asian vakavasti. Turhan " "usein hoitoon ei kuitenkaan pse, vaan nuoret jtetn heitteille. Kysyn: mihin " "toimiin hallitus ryhtyy varmistaakseen, ett mielenterveysongelmista krsiville " "nuorille on tarjolla heidn tarvitsemansa hoito silloin kun he sit tarvitsevat?", ] speaker_lists = [ [ (1301, "Jani", "Mkel", "ps", ""), (1108, "Juha", "Sipil", "", "Pministeri"), (1301, "Jani", "Mkel", "ps", ""), (1108, "Juha", "Sipil", "", "Pministeri"), (1141, "Peter", "stman", "kd", ""), (947, "Petteri", "Orpo", "", "Valtiovarainministeri"), (1126, "Tytti", "Tuppurainen", "sd", ""), (1108, "Juha", "Sipil", "", "Pministeri"), (1317, "Simon", "Elo", "sin", ""), (1108, "Juha", "Sipil", "", "Pministeri"), ], [ (1093, "Juho", "Eerola", "ps", ""), (1339, "Kari", "Kulmala", "sin", ""), (887, "Sirpa", "Paatero", "sd", ""), (967, "Timo", "Heinonen", "kok", ""), ], [ (971, "Johanna", "Ojala-Niemel", "sd", ""), (1129, "Arja", "Juvonen", "ps", ""), (1388, "Mari", "Rantanen", "ps", ""), (1391, "Ari", "Koponen", "ps", ""), (1325, "Sari", "Tanus", "kd", ""), (971, "Johanna", "Ojala-Niemel", "sd", ""), ], ] chairman_statements = [ { "type": "C", "mp_id": 0, "firstname": "Mauri", "lastname": "Pekkarinen", "party": "", "title": "Ensimminen varapuhemies", "start_time": "", "end_time": "", "language": "", "text": "Ainoaan ksittelyyn esitelln pivjrjestyksen 4. asia. Ksittelyn pohjana on " "talousvaliokunnan mietint TaVM 18/2016 vp.", "offset": -1.0, "duration": -1.0, "embedded_statement": { "mp_id": 0, "title": "", "firstname": "", "lastname": "", "language": "", "text": "", "offset": -1.0, "duration": -1.0, }, }, { "type": "C", "mp_id": 0, "firstname": "Mauri", "lastname": "Pekkarinen", "party": "", "title": "Ensimminen varapuhemies", "start_time": "", "end_time": "", "language": "", "text": "Toiseen ksittelyyn esitelln pivjrjestyksen 3. asia. Keskustelu asiasta " "pttyi 6.6.2017 pidetyss tysistunnossa. Keskustelussa on Anna Kontula Matti Semin " "kannattamana tehnyt vastalauseen 2 mukaisen lausumaehdotuksen.", "offset": -1.0, "duration": -1.0, "embedded_statement": { "mp_id": 0, "title": "", "firstname": "", "lastname": "", "language": "", "text": "", "offset": -1.0, "duration": -1.0, }, }, { "type": "C", "mp_id": 0, "firstname": "Tuula", "lastname": "Haatainen", "party": "", "title": "Toinen varapuhemies", "start_time": "", "end_time": "", "language": "", "text": "Toiseen ksittelyyn esitelln pivjrjestyksen 6. asia. Nyt voidaan hyvksy " "tai hylt lakiehdotukset, joiden sisllst ptettiin ensimmisess ksittelyss.", "offset": -1.0, "duration": -1.0, "embedded_statement": { "mp_id": 0, "title": "", "firstname": "", "lastname": "", "language": "", "text": "", "offset": -1.0, "duration": -1.0, }, }, ] embedded_statements = [ { "mp_id": 0, "title": "Puhemies", "firstname": "Maria", "lastname": "Lohela", "language": "", "text": "Edustaja Laukkanen, ja sitten puhujalistaan.", "offset": -1.0, "duration": -1.0, }, { "mp_id": 0, "title": "", "firstname": "", "lastname": "", "language": "", "text": "", "offset": -1.0, "duration": -1.0, }, { "mp_id": 0, "title": "Ensimminen varapuhemies", "firstname": "Mauri", "lastname": "Pekkarinen", "language": "", "text": "Tm valtiovarainministerin puheenvuoro saattaa antaa aihetta muutamaan " "debattipuheenvuoroon. Pyydn niit edustajia, jotka haluavat kytt vastauspuheenvuoron, " "nousemaan yls ja painamaan V-painiketta.", "offset": -1.0, "duration": -1.0, }, { "mp_id": 0, "title": "Ensimminen varapuhemies", "firstname": "Antti", "lastname": "Rinne", "language": "", "text": "Meill on puoleenyhn vhn reilu kolme tuntia aikaa, ja valtioneuvoston pit " "sit ennen soveltamisasetus saattaa voimaan. Pyydn ottamaan tmn huomioon " "keskusteltaessa.", "offset": -1.0, "duration": -1.0, }, ] mps = [ MP( 103, "Matti", "Ahde", "o", "fi", 1945, "Sosialidemokraattinen eduskuntaryhm", "", "", "Oulu", "Oulun lnin vaalipiiri (03/1970-06/1990), Oulun vaalipiiri (03/2003-04/2011)", "kansakoulu, ammattikoulu, kansankorkeakoulu", ), MP( 1432, "Marko", "Kilpi", "m", "fi", 1969, "Parliamentary Group of the National Coalition Party", "police officer, writer", "Kuopio", "Rovaniemi", "Electoral District of Savo-Karelia (04/2019-)", "Degree in policing", ), MP( 1374, "Veronica", "Rehn-Kivi", "f", "sv", 1956, "Swedish Parliamentary Group", "architect, building supervision manager", "Kauniainen", "Helsinki", "Electoral District of Uusimaa (08/2016-)", "architect", ), MP( 1423, "Iiris", "Suomela", "f", "fi", 1994, "Green Parliamentary Group", "student of social sciences", "Tampere", "", "Electoral District of Pirkanmaa (04/2019-)", "", ), ]
[ 37811, 14617, 2643, 13042, 290, 584, 2272, 18587, 1366, 17336, 329, 4856, 389, 6875, 994, 13, 198, 198, 1212, 318, 1760, 284, 3368, 45343, 287, 1388, 1332, 3696, 13, 198, 37811, 198, 6738, 19720, 1330, 360, 713, 198, 6738, 19720, 1330, ...
1.957179
5,488
import sys import math import itertools from collections import deque sys.setrecursionlimit(10000000) input=lambda : sys.stdin.readline().rstrip() a,b,x=map(int,input().split()) if (a**2*b)-x<=(a**2*b)/2: c=2*((a**2*b)-x)/(a**2) print(math.degrees(math.atan2(c,a))) else: c=2*x/b/a print(math.degrees(math.atan2(b,c)))
[ 11748, 25064, 198, 11748, 10688, 198, 11748, 340, 861, 10141, 198, 6738, 17268, 1330, 390, 4188, 198, 17597, 13, 2617, 8344, 24197, 32374, 7, 16, 24598, 8, 198, 15414, 28, 50033, 1058, 25064, 13, 19282, 259, 13, 961, 1370, 22446, 81, ...
2.126582
158
import struct import itertools import freetype ENDIAN = '<' # always little endian # If you make a modified version, please change the URL in the string to # let people know what generated the file! # example: Bakefont 3.0.2 (compatible; Acme Inc version 1.3) ENCODER = "Bakefont 3.0.2 (https://github.com/golightlyb/bakefont3)" def fp26_6(native_num): """ Encode a number in 26.6 fixed point arithmatic with the lower 6 bytes used for the fractional component and the upper 26 bytes used for the integer component, returning a native int. Freetype uses this encoding to represent floats. """ if isinstance(native_num, int): result = native_num * 64 else: result = int(float(native_num) * 64.0) return int32(result) def cstring(nativeString, encoding="utf-8"): """null-terminated C-style string""" bytes = nativeString.encode(encoding); return bytes + b'\0'; def b8string(nativeString, encoding="utf-8"): """uint8 length-prefixed Pascal-style string plus a C-style null terminator aka a 'bastard string'.""" bytes = nativeString.encode(encoding); length = len(bytes) assert length < 256 return uint8(length) + bytes + b'\0';
[ 11748, 2878, 198, 11748, 340, 861, 10141, 198, 11748, 2030, 2963, 431, 198, 198, 10619, 16868, 796, 705, 27, 6, 1303, 1464, 1310, 886, 666, 198, 198, 2, 1002, 345, 787, 257, 9518, 2196, 11, 3387, 1487, 262, 10289, 287, 262, 4731, 28...
2.841379
435
"""Test health check"""
[ 37811, 14402, 1535, 2198, 37811, 628 ]
4.166667
6
""" This INTERNAL module is used to manage fbs's global state. Having it here, in one central place, allows fbs's test suite to manipulate the state to test various scenarios. """ from collections import OrderedDict SETTINGS = {} LOADED_PROFILES = [] COMMANDS = OrderedDict()
[ 37811, 198, 1212, 23255, 45, 1847, 8265, 318, 973, 284, 6687, 277, 1443, 338, 3298, 1181, 13, 11136, 340, 994, 11, 287, 198, 505, 4318, 1295, 11, 3578, 277, 1443, 338, 1332, 18389, 284, 18510, 262, 1181, 284, 1332, 198, 7785, 699, 1...
3.407407
81
# -*- coding: utf-8 -*- # # rtk.dao.RTKMatrix.py is part of The RTK Project # # All rights reserved. # Copyright 2007 - 2017 Andrew Rowland andrew.rowland <AT> reliaqual <DOT> com """ =============================================================================== The RTKMatrix Table =============================================================================== """ # pylint: disable=E0401 from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship # pylint: disable=E0401 # Import other RTK modules. from Utilities import none_to_default # pylint: disable=E0401 from dao.RTKCommonDB import RTK_BASE # pylint: disable=E0401
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 220, 220, 220, 220, 220, 220, 374, 30488, 13, 67, 5488, 13, 14181, 42, 46912, 13, 9078, 318, 636, 286, 383, 11923, 42, 4935, 198, 2, 198, 2, 1439, 2489,...
3.507772
193
import os import shutil pull_default() input('')
[ 11748, 28686, 198, 11748, 4423, 346, 198, 198, 31216, 62, 12286, 3419, 198, 15414, 7, 7061, 8, 198 ]
2.777778
18
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pyogp_webbot/', include('pyogp_webbot.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/', include(admin.site.urls)), (r'^$', 'pyogp_webbot.login.views.index'), (r'^pyogp_webbot/$', 'pyogp_webbot.login.views.index'), (r'^pyogp_webbot/login/$', 'pyogp_webbot.login.views.login'), (r'^pyogp_webbot/login/login_request/$', 'pyogp_webbot.login.views.login_request'), )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 13, 12286, 82, 1330, 1635, 198, 198, 2, 791, 23893, 262, 1306, 734, 3951, 284, 7139, 262, 13169, 25, 198, 2, 422, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 2, 13169, 13, 2306, 375, ...
2.390029
341
''' code emitters ''' import out, enums as e
[ 7061, 6, 2438, 27588, 1010, 705, 7061, 198, 11748, 503, 11, 551, 5700, 355, 304, 628 ]
2.875
16
""" GravMag: Classic 3D Euler deconvolution of magnetic data using an expanding window """ from fatiando import logger, mesher, gridder, utils, gravmag from fatiando.vis import mpl, myv log = logger.get() log.info(logger.header()) # Make a model bounds = [-5000, 5000, -5000, 5000, 0, 5000] model = [ mesher.Prism(-1500, -500, -1500, -500, 1000, 2000, {'magnetization':2}), mesher.Prism(500, 1500, 500, 2000, 1000, 2000, {'magnetization':2})] # Generate some data from the model shape = (100, 100) area = bounds[0:4] xp, yp, zp = gridder.regular(area, shape, z=-1) # Add a constant baselevel baselevel = 10 # Convert from nanoTesla to Tesla because euler and derivatives require things # in SI tf = (utils.nt2si(gravmag.prism.tf(xp, yp, zp, model, inc=-45, dec=0)) + baselevel) # Calculate the derivatives using FFT xderiv = gravmag.fourier.derivx(xp, yp, tf, shape) yderiv = gravmag.fourier.derivy(xp, yp, tf, shape) zderiv = gravmag.fourier.derivz(xp, yp, tf, shape) mpl.figure() titles = ['Total field', 'x derivative', 'y derivative', 'z derivative'] for i, f in enumerate([tf, xderiv, yderiv, zderiv]): mpl.subplot(2, 2, i + 1) mpl.title(titles[i]) mpl.axis('scaled') mpl.contourf(yp, xp, f, shape, 50) mpl.colorbar() mpl.m2km() mpl.show() # Pick the centers of the expanding windows # The number of final solutions will be the number of points picked mpl.figure() mpl.suptitle('Pick the centers of the expanding windows') mpl.axis('scaled') mpl.contourf(yp, xp, tf, shape, 50) mpl.colorbar() centers = mpl.pick_points(area, mpl.gca(), xy2ne=True) # Run the euler deconvolution on an expanding window # Structural index is 3 index = 3 results = [] for center in centers: results.append( gravmag.euler.expanding_window(xp, yp, zp, tf, xderiv, yderiv, zderiv, index, gravmag.euler.classic, center, 500, 5000)) print "Base level used: %g" % (baselevel) print "Estimated base level: %g" % (results[-1]['baselevel']) print "Estimated source location: %s" % (str(results[-1]['point'])) myv.figure() myv.points([r['point'] for r in results], size=300.) myv.prisms(model, opacity=0.5) axes = myv.axes(myv.outline(bounds), ranges=[b*0.001 for b in bounds]) myv.wall_bottom(bounds) myv.wall_north(bounds) myv.show()
[ 37811, 198, 38, 4108, 13436, 25, 13449, 513, 35, 412, 18173, 37431, 85, 2122, 286, 14091, 1366, 1262, 281, 198, 11201, 27225, 4324, 198, 37811, 198, 6738, 3735, 72, 25440, 1330, 49706, 11, 18842, 372, 11, 10706, 1082, 11, 3384, 4487, ...
2.514819
911
# Generated by Django 2.1.5 on 2019-01-22 09:39 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 20, 319, 13130, 12, 486, 12, 1828, 7769, 25, 2670, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
# Copyright 2019 The AmpliGraph Authors. All Rights Reserved. # # This file is Licensed under the Apache License, Version 2.0. # A copy of the Licence is available in LICENCE, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # from ampligraph.datasets import load_wn18, load_fb15k, load_fb15k_237, load_yago3_10, load_wn18rr, load_wn11, load_fb13 from ampligraph.datasets.datasets import _clean_data import numpy as np
[ 2, 15069, 13130, 383, 44074, 72, 37065, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 770, 2393, 318, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 13, 198, 2, 317, 4866, 286, 262, 10483, 594, 318, 1695, 287, 38559, 1...
2.812903
155
from io import StringIO from math import atan2, ceil from typing import Literal, Union, overload from common import PI, Real, TWOPI, deg, real, reduce_angle from functions import qbezeir_svg_given_middle from .circle import CircleBase, FixedCircle from .point import PointBase, Polar class FixedSector(SectorBase): __slots__ = '_hash', class MutableSector(SectorBase): __slots__ = () # TODO: add circle changing def fix(self, /): return FixedSector(self.circle, self.arc, self.start_arm) def unfix(self, /): return self def rotate(self, angle: Real, /): """ Rotates the sector by the given angle clockwise """ self.start_arm -= angle def Sector(circle: CircleBase, arc: Real, start_arm: Real = PI, /, *, fix: bool = True) -> SectorBase: check_arc(arc) arc = float(arc) start_arm = float(start_arm) if fix: return FixedSector(circle.fix(), arc, start_arm) return MutableSector(circle.fix(), arc, start_arm)
[ 6738, 33245, 1330, 10903, 9399, 198, 6738, 10688, 1330, 379, 272, 17, 11, 2906, 346, 198, 6738, 19720, 1330, 25659, 1691, 11, 4479, 11, 31754, 198, 198, 6738, 2219, 1330, 30434, 11, 6416, 11, 17306, 3185, 40, 11, 3396, 11, 1103, 11, ...
2.648579
387
import os COL_SEPARATOR = "\t" MULTI_SEPARATOR = "$" for neFile in os.listdir('data/'): neFile = 'data/' + neFile out_filename = neFile.replace('.tsv', "_mh.tsv") if os.path.isfile(out_filename) or '_mh' in neFile or os.path.isdir(neFile): continue out_f = open(out_filename, "w") with open(neFile, "r") as in_f: for line in in_f: if len(line) > 2: token_attrs = line.rstrip().split(COL_SEPARATOR) if (token_attrs[1] == "O") and (token_attrs[2] == "O"): new_label = "O" elif (token_attrs[1] != "O") and (token_attrs[2] == "O"): new_label = token_attrs[1] elif (token_attrs[1] == "O") and (token_attrs[2] != "O"): new_label = token_attrs[2] else: labels = [token_attrs[1], token_attrs[2]] labels.sort() new_label = labels[0] + MULTI_SEPARATOR + labels[1] out_f.write(token_attrs[0] + COL_SEPARATOR + new_label + "\n") else: out_f.write(line) out_f.close()
[ 11748, 28686, 198, 25154, 62, 5188, 27082, 25633, 796, 37082, 83, 1, 198, 44, 16724, 40, 62, 5188, 27082, 25633, 796, 17971, 1, 198, 1640, 497, 8979, 287, 28686, 13, 4868, 15908, 10786, 7890, 14, 6, 2599, 198, 220, 220, 220, 497, 89...
1.755319
658
import os import sys from pprint import pprint import click from pykechain.utils import temp_chdir from kecpkg.commands.utils import CONTEXT_SETTINGS from kecpkg.gpg import get_gpg, list_keys, hash_of_file from kecpkg.settings import SETTINGS_FILENAME, GNUPG_KECPKG_HOME, load_settings, DEFAULT_SETTINGS, ARTIFACTS_FILENAME, \ ARTIFACTS_SIG_FILENAME from kecpkg.utils import remove_path, echo_info, echo_success, echo_failure, get_package_dir, unzip_package def verify_signature(package_dir, artifacts_filename, artifacts_sig_filename): """ Check signature of the package. :param package_dir: directory fullpath of the package :param artifacts_filename: path of the artifacts file :param artifacts_sig_filename: path of the artifacts signature file :return: None """ gpg = get_gpg() artifacts_fp = os.path.join(package_dir, artifacts_filename) artifacts_sig_fp = os.path.join(package_dir, artifacts_sig_filename) if not os.path.exists(artifacts_fp): echo_failure("Artifacts file does not exist: '{}'".format(artifacts_filename)) sys.exit(1) if not os.path.exists(artifacts_sig_fp): echo_failure("Artifacts signature file does not exist: '{}'. Is the package signed?". format(artifacts_filename)) sys.exit(1) with open(artifacts_sig_fp, 'rb') as sig_fd: results = gpg.verify_file(sig_fd, data_filename=artifacts_fp) if results.valid: echo_info("Verified the signature and the signature is valid") echo_info("Signed with: '{}'".format(results.username)) elif not results.valid: echo_failure("Signature of the package is invalid") echo_failure(pprint(results.__dict__)) sys.exit(1) def verify_artifacts_hashes(package_dir, artifacts_filename): """ Check the hashes of the artifacts in the package. :param package_dir: directory fullpath of the package :param artifacts_filename: filename of the artifacts file :return: """ artifacts_fp = os.path.join(package_dir, artifacts_filename) if not os.path.exists(artifacts_fp): echo_failure("Artifacts file does not exist: '{}'".format(artifacts_filename)) sys.exit(1) with open(artifacts_fp, 'r') as fd: artifacts = fd.readlines() # process the file contents # A line is "README.md,sha256=d831....ccf79a,336" # ^filename ^algo ^hash ^size in bytes fails = [] for af in artifacts: # noinspection PyShadowingBuiltins,PyShadowingBuiltins filename, hash, orig_size = af.split(',') algorithm, orig_hash = hash.split('=') fp = os.path.join(package_dir, filename) if os.path.exists(fp): found_hash = hash_of_file(fp, algorithm) found_size = os.stat(fp).st_size if found_hash != orig_hash.strip() or found_size != int(orig_size.strip()): fails.append("File '{}' is changed in the package.".format(filename)) fails.append("File '{}' original checksum: '{}', found: '{}'".format(filename, orig_hash, found_hash)) fails.append("File '{}' original size: {}, found: {}".format(filename, orig_size, found_size)) else: fails.append("File '{}' does not exist".format(filename)) if fails: echo_failure('The package has been changed after building the package.') for fail in fails: print(fail) sys.exit(1) else: echo_info("Package contents succesfully verified.")
[ 11748, 28686, 198, 11748, 25064, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 198, 11748, 3904, 198, 6738, 12972, 365, 7983, 13, 26791, 1330, 20218, 62, 354, 15908, 198, 198, 6738, 885, 13155, 10025, 13, 9503, 1746, 13, 26791, 1330, 2290...
2.514467
1,417
import argparse import random SIGNATURE = b'\xDE\xAD\xBE\xEF\xC0\xFF\xEE\xAA\xBB\xCC\xDD\xEE\xFF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA' # Generate data in chunks of 1024 bytes. if __name__ == "__main__": main()
[ 11748, 1822, 29572, 198, 11748, 4738, 198, 198, 46224, 40086, 796, 275, 6, 59, 87, 7206, 59, 87, 2885, 59, 87, 12473, 59, 87, 25425, 59, 87, 34, 15, 59, 87, 5777, 59, 87, 6500, 59, 87, 3838, 59, 87, 15199, 59, 87, 4093, 59, 87...
1.908333
120
import datetime import io import os import re import subprocess import warnings from collections import namedtuple from decimal import Decimal from pathlib import Path import six from PyPDF2 import PdfFileMerger from reportlab.pdfgen import canvas def force_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if isinstance(s, bytes): if encoding == "utf-8": return s else: return s.decode("utf-8", errors).encode(encoding, errors) if strings_only and is_protected_type(s): return s if isinstance(s, six.memoryview): return bytes(s) if isinstance(s, Promise): return six.text_type(s).encode(encoding, errors) if not isinstance(s, six.string_types): try: if six.PY3: return six.text_type(s).encode(encoding) else: return bytes(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return b" ".join( force_bytes(arg, encoding, strings_only, errors) for arg in s ) return six.text_type(s).encode(encoding, errors) else: return s.encode(encoding, errors) def force_text(s, encoding="utf-8", strings_only=False, errors="strict"): """ Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if issubclass(type(s), six.text_type): return s if strings_only and is_protected_type(s): return s try: if not issubclass(type(s), six.string_types): if six.PY3: if isinstance(s, bytes): s = six.text_type(s, encoding, errors) else: s = six.text_type(s) elif hasattr(s, "__unicode__"): s = six.text_type(s) else: s = six.text_type(bytes(s), encoding, errors) else: # Note: We use .decode() here, instead of six.text_type(s, encoding, # errors), so that if s is a SafeBytes, it ends up being a # SafeText at the end. s = s.decode(encoding, errors) except UnicodeDecodeError as e: if not isinstance(s, Exception): raise DoctorUnicodeDecodeError(s, *e.args) else: # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII bytestring data without a # working unicode method. Try to handle this without raising a # further exception by individually forcing the exception args # to unicode. s = " ".join(force_text(arg, encoding, strings_only, errors) for arg in s) return s def smart_text(s, encoding="utf-8", strings_only=False, errors="strict"): """ Returns a text object representing 's' -- unicode on Python 2 and str on Python 3. Treats bytestrings using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_text(s, encoding, strings_only, errors) _PROTECTED_TYPES = six.integer_types + ( type(None), float, Decimal, datetime.datetime, datetime.date, datetime.time, ) def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_text(strings_only=True). """ return isinstance(obj, _PROTECTED_TYPES) def make_png_thumbnail_for_instance(filepath, max_dimension): """Abstract function for making a thumbnail for a PDF See helper functions below for how to use this in a simple way. :param filepath: The attr where the PDF is located on the item :param max_dimension: The longest you want any edge to be :param response: Flask response object """ command = [ "pdftoppm", "-singlefile", "-f", "1", "-scale-to", str(max_dimension), filepath, "-png", ] p = subprocess.Popen( command, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, stderr = p.communicate() return stdout, stderr.decode("utf-8"), str(p.returncode) def make_png_thumbnails(filepath, max_dimension, pages, directory): """Abstract function for making a thumbnail for a PDF See helper functions below for how to use this in a simple way. :param filepath: The attr where the PDF is located on the item :param max_dimension: The longest you want any edge to be :param response: Flask response object """ for page in pages: command = [ "pdftoppm", "-singlefile", "-f", str(page), "-scale-to", str(max_dimension), filepath, "-png", f"{directory.name}/thumb-{page}", ] p = subprocess.Popen( command, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) p.communicate() def pdf_bytes_from_image_array(image_list, output_path) -> None: """Make a pdf given an array of Image files :param image_list: List of images :type image_list: list :return: pdf_data :type pdf_data: PDF as bytes """ image_list[0].save( output_path, "PDF", resolution=100.0, save_all=True, append_images=image_list[1:], ) del image_list def strip_metadata_from_path(file_path): """Convert PDF file into PDF and remove metadata from it Stripping the metadata allows us to hash the PDFs :param pdf_bytes: PDF as binary content :return: PDF bytes with metadata removed. """ with open(file_path, "rb") as f: pdf_merger = PdfFileMerger() pdf_merger.append(io.BytesIO(f.read())) pdf_merger.addMetadata({"/CreationDate": "", "/ModDate": ""}) byte_writer = io.BytesIO() pdf_merger.write(byte_writer) return force_bytes(byte_writer.getvalue()) def strip_metadata_from_bytes(pdf_bytes): """Convert PDF bytes into PDF and remove metadata from it Stripping the metadata allows us to hash the PDFs :param pdf_bytes: PDF as binary content :return: PDF bytes with metadata removed. """ pdf_merger = PdfFileMerger() pdf_merger.append(io.BytesIO(pdf_bytes)) pdf_merger.addMetadata({"/CreationDate": "", "/ModDate": ""}) byte_writer = io.BytesIO() pdf_merger.write(byte_writer) return force_bytes(byte_writer.getvalue()) def cleanup_form(form): """Clean up a form object""" os.remove(form.cleaned_data["fp"]) def pdf_has_images(path: str) -> bool: """Check raw PDF for embedded images. We need to check if a PDF contains any images. If a PDF contains images it likely has content that needs to be scanned. :param path: Location of PDF to process. :return: Does the PDF contain images? :type: bool """ with open(path, "rb") as pdf_file: pdf_bytes = pdf_file.read() return True if re.search(rb"/Image ?/", pdf_bytes) else False def ocr_needed(path: str, content: str) -> bool: """Check if OCR is needed on a PDF Check if images are in PDF or content is empty. :param path: The path to the PDF :param content: The content extracted from the PDF. :return: Whether OCR should be run on the document. """ if content.strip() == "" or pdf_has_images(path): return True return False def make_page_with_text(page, data, h, w): """Make a page with text :param page: :param data: :param h: :param w: :return: """ packet = io.BytesIO() can = canvas.Canvas(packet, pagesize=(w, h)) # Set to a standard size and font for now. can.setFont("Helvetica", 9) # Make the text transparent can.setFillAlpha(0) for i in range(len(data["level"])): try: letter, (x, y, ww, hh), pg = ( data["text"][i], (data["left"][i], data["top"][i], data["width"][i], data["height"][i]), data["page_num"][i], ) except: continue # Adjust the text to an 8.5 by 11 inch page sub = ((11 * 72) / h) * int(hh) x = ((8.5 * 72) / w) * int(x) y = ((11 * 72) / h) * int(y) yy = (11 * 72) - y if int(page) == int(pg): can.drawString(x, yy - sub, letter) can.showPage() can.save() packet.seek(0) return packet
[ 11748, 4818, 8079, 198, 11748, 33245, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 850, 14681, 198, 11748, 14601, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 6738, 32465, 1330, 4280, 4402, 198, 6738, 3108, 8019, 1330, 10644, 198, 198...
2.369615
3,923
import gym import numpy as np import os import random import matplotlib.pyplot as plt from atariari.benchmark.wrapper import AtariARIWrapper # YarsRevenge # env_name = "DemonAttackDeterministic-v4" env = AtariARIWrapper(gym.make(env_name)) name = env.unwrapped.spec.id #ballgame = any(game in name for game in ["Pong", "Tennis"]) print(np.int16(3)) sad n_actions = env.action_space.n _ = env.reset() obs, _, done, info = env.step(0) r = 0 for t in range(50000): plt.imshow(env.render(mode='rgb_array'), interpolation='none') plt.plot() plt.pause(0.0001) # pause a bit so that plots are updated action = random.randint(0, n_actions - 1) obs, reward, done, info = env.step(action) r += reward print(reward) print_labels(info) if(done): break print(r)
[ 11748, 11550, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 4738, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 6738, 379, 2743, 2743, 13, 26968, 4102, 13, 48553, 1330, 35884, 33604, 3...
2.473684
323
# encoding: utf-8 from datetime import datetime
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 6738, 4818, 8079, 1330, 4818, 8079, 628, 198, 220, 220, 220, 220, 220, 220, 220, 220 ]
2.416667
24
import json import requests from os import path
[ 11748, 33918, 198, 11748, 7007, 198, 6738, 28686, 1330, 3108, 628, 628, 198 ]
4
13
if __name__ == '__main__': ll = LinkedList() ll.append(data="Fedor") ll.append(data="Julia") ll.append(data="Bentsi") ll.print() print("Length of the Linked list is: ", ll.length()) idx = 1 print(ll.get(index=idx)) print(f"Data at index {idx} is {ll[idx]}") print("Deleted: ", ll.erase(index=0)) ll.append(data="Fedor") ll.append(data="Bentsi") ll.set(index=3, new_data="Tim Peters") print(ll)
[ 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 32660, 796, 7502, 276, 8053, 3419, 198, 220, 220, 220, 32660, 13, 33295, 7, 7890, 2625, 42268, 273, 4943, 198, 220, 220, 220, 32660, 13, 33...
2.161905
210
# -*- coding: utf-8 -*- ''' Copyright (c) 2016, Virginia Tech All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. This material was prepared as an account of work sponsored by an agency of the United States Government. Neither the United States Government nor the United States Department of Energy, nor Virginia Tech, nor any of their employees, nor any jurisdiction or organization that has cooperated in the development of these materials, makes any warranty, express or implied, or assumes any legal liability or responsibility for the accuracy, completeness, or usefulness or any information, apparatus, product, software, or process disclosed, or represents that its use would not infringe privately owned rights. Reference herein to any specific commercial product, process, or service by trade name, trademark, manufacturer, or otherwise does not necessarily constitute or imply its endorsement, recommendation, favoring by the United States Government or any agency thereof, or Virginia Tech - Advanced Research Institute. The views and opinions of authors expressed herein do not necessarily state or reflect those of the United States Government or any agency thereof. VIRGINIA TECH ADVANCED RESEARCH INSTITUTE under Contract DE-EE0006352 #__author__ = "BEMOSS Team" #__credits__ = "" #__version__ = "2.0" #__maintainer__ = "BEMOSS Team" #__email__ = "aribemoss@gmail.com" #__website__ = "www.bemoss.org" #__created__ = "2014-09-12 12:04:50" #__lastUpdated__ = "2016-03-14 11:23:33" ''' from django.shortcuts import render_to_response from django.contrib.auth import authenticate, login from django.template import RequestContext from django.http import HttpResponseRedirect from django.contrib import messages import logging logger = logging.getLogger("views")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 7061, 6, 198, 15269, 357, 66, 8, 1584, 11, 6025, 9634, 198, 3237, 2489, 10395, 13, 198, 198, 7738, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 351, 393, 12...
3.857831
830
from html.parser import HTMLParser
[ 6738, 27711, 13, 48610, 1330, 11532, 46677, 198 ]
4.375
8
import logging import os.path import bolt import bolt.about PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) _src_dir = os.path.join(PROJECT_ROOT, 'bolt') _test_dir = os.path.join(PROJECT_ROOT, 'test') _output_dir = os.path.join(PROJECT_ROOT, 'output') _coverage_dir = os.path.join(_output_dir, 'coverage') config = { 'pip': { 'command': 'install', 'options': { 'r': './requirements.txt' } }, 'delete-pyc': { 'sourcedir': _src_dir, 'recursive': True, 'test-pyc': { 'sourcedir': _test_dir, } }, 'conttest' : { 'task': 'ut' }, 'mkdir': { 'directory': _output_dir, }, 'nose': { 'directory': _test_dir, 'ci': { 'options': { 'with-xunit': True, 'xunit-file': os.path.join(_output_dir, 'unit_tests_log.xml'), 'with-coverage': True, 'cover-erase': True, 'cover-package': 'bolt', 'cover-html': True, 'cover-html-dir': _coverage_dir, 'cover-branches': True, } } }, 'setup': { 'command': 'bdist_wheel', 'egg-info': { 'command': 'egg_info' } }, 'coverage': { 'task': 'nose', 'include': ['bolt'], 'output': os.path.join(_output_dir, 'ut_coverage') } } # Development tasks bolt.register_task('clear-pyc', ['delete-pyc', 'delete-pyc.test-pyc']) bolt.register_task('ut', ['clear-pyc', 'nose']) bolt.register_task('ct', ['conttest']) bolt.register_task('pack', ['setup', 'setup.egg-info']) # CI/CD tasks bolt.register_task('run-unit-tests', ['clear-pyc', 'mkdir', 'nose.ci']) # Default task (not final). bolt.register_task('default', ['pip', 'ut'])
[ 11748, 18931, 198, 11748, 28686, 13, 6978, 220, 198, 198, 11748, 18100, 198, 11748, 18100, 13, 10755, 198, 198, 31190, 23680, 62, 13252, 2394, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, ...
1.931794
953
from enum import Enum from pyxedit.xedit.attribute import XEditAttribute from pyxedit.xedit.generic import XEditGenericObject
[ 6738, 33829, 1330, 2039, 388, 198, 198, 6738, 12972, 87, 19312, 13, 87, 19312, 13, 42348, 1330, 1395, 18378, 33682, 198, 6738, 12972, 87, 19312, 13, 87, 19312, 13, 41357, 1330, 1395, 18378, 46189, 10267, 628, 198 ]
3.486486
37
#!/usr/bin/env python3 """ Author : Me <me@foo.com> Date : today Purpose: Rock the Casbah """ import argparse import io import os import sys # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-n', '--num', help='Number of lines', metavar='int', type=int, default=10) parser.add_argument('file', help='Input File', type=argparse.FileType('r')) args = parser.parse_args() if not args.num > 0: parser.error(f'--num "{args.num}" must be greater than 0') return args # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() for fh in args.file: print(fh.name) num_line = 0 for line in fh: num_line += 1 print(line, end='') if num_line == args.num: break # -------------------------------------------------- if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 13838, 1058, 2185, 1279, 1326, 31, 21943, 13, 785, 29, 198, 10430, 220, 220, 1058, 1909, 198, 30026, 3455, 25, 4631, 262, 11294, 47041, 198, 37811, 198, 198, 11748, 182...
2.178037
601
#!/usr/bin/env python import os import sys import unittest from collections import namedtuple sys.path = [ os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')) ] + sys.path from pluckit import pluck if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 555, 715, 395, 198, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 17597, 13, 6978, 796, 685, 28686, 13, 6978, 13, 397, 2777, 776,...
2.607843
102
from albumentations.core.transforms_interface import ImageOnlyTransform import albumentations.augmentations.functional as F import random
[ 6738, 435, 65, 1713, 602, 13, 7295, 13, 7645, 23914, 62, 39994, 1330, 7412, 10049, 41762, 198, 11748, 435, 65, 1713, 602, 13, 559, 5154, 602, 13, 45124, 355, 376, 198, 11748, 4738, 198 ]
4.058824
34
# -*- coding: utf-8 -*- from __future__ import unicode_literals import functools import six from django.utils.translation import ugettext_lazy as _ from django.template import TemplateDoesNotExist from django.template.loader import select_template from cms.plugin_base import CMSPluginBase, CMSPluginBaseMetaclass from cms.plugin_pool import plugin_pool from . import models, forms from .utils.urlmatch import urlmatch from .constants import ( HIDE_PROMO, HIDE_PROMO_ROLLOVER, HIDE_PROMO_VIDEO, HIDE_TWITTER, HIDE_COUNTERS, HIDE_RAWHTML, HIDE_GATED_CONTENT, HIDE_FLOAT, HIDE_LIGHTBOX, CUSTOM_PLUGINS, PROMO_CHILD_CLASSES, ) if not HIDE_PROMO: plugin_pool.register_plugin(PromoUnitPlugin) if not HIDE_TWITTER: plugin_pool.register_plugin(TwitterFeedPlugin) if not HIDE_COUNTERS: plugin_pool.register_plugin(CountersContainerPlugin) plugin_pool.register_plugin(CounterPlugin) #if 'Bootstrap4GridRowPlugin' in plugin_pool.plugins: #plugin_pool.plugins['Bootstrap4GridRowPlugin'].child_classes.append('CountersContainerPlugin') if not HIDE_RAWHTML: plugin_pool.register_plugin(RawHTMLPlugin) plugin_pool.register_plugin(RawHTMLWithIDPlugin) for name, parameters in CUSTOM_PLUGINS.items(): p = type( str(name.replace(' ', '') + 'Plugin'), (CustomPlugin,), {'name': name}, ) plugin_pool.register_plugin(p) if not HIDE_GATED_CONTENT: plugin_pool.register_plugin(GatedContentPlugin) class FloatPlugin(LayoutMixin, CMSPluginBase): module = 'JumpSuite Componens' name = _('Float Container') model = models.Float form = forms.FloatForm render_template = 'js_components/float.html' TEMPLATE_NAME = 'js_components/float_%s.html' #change_form_template = 'admin/js_components/float.html' allow_children = True if not HIDE_FLOAT: plugin_pool.register_plugin(FloatPlugin) class LightboxPlugin(LayoutMixin, CMSPluginBase): module = 'JumpSuite Componens' TEMPLATE_NAME = 'js_components/lightbox_%s.html' name = _('Lightbox') model = models.Lightbox form = forms.LightboxForm render_template = 'js_components/lightbox.html' allow_children = True child_classes = ['Bootstrap4PicturePlugin'] if not HIDE_LIGHTBOX: plugin_pool.register_plugin(LightboxPlugin)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 11748, 1257, 310, 10141, 198, 11748, 2237, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, ...
2.609081
903
import pytest from julia.core import JuliaOptions # fmt: off # fmt: off
[ 11748, 12972, 9288, 198, 198, 6738, 474, 43640, 13, 7295, 1330, 22300, 29046, 628, 198, 2, 46996, 25, 572, 628, 198, 198, 2, 46996, 25, 572, 198 ]
2.888889
27
import os import pathlib import typing import pytest from ext_argparse.parameter import Parameter from ext_argparse.param_enum import ParameterEnum from enum import Enum
[ 11748, 28686, 198, 11748, 3108, 8019, 198, 11748, 19720, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 1070, 62, 853, 29572, 13, 17143, 2357, 1330, 25139, 2357, 198, 6738, 1070, 62, 853, 29572, 13, 17143, 62, 44709, 1330, 25139, 2357, 4...
3.45098
51
#! /usr/local/bin/Python3.5 import urllib.request with open("images.csv", 'r') as csv: i = 0 for line in csv: line = line.split(',') if line[1] != '' and line[1] != "\n": urllib.request.urlretrieve(line[1].encode('utf-8'), ("img_" + str(i) + ".jpg").encode('utf-8')) print("Image saved".encode('utf-8')) i += 1 print("No result")
[ 2, 0, 1220, 14629, 14, 12001, 14, 8800, 14, 37906, 18, 13, 20, 198, 198, 11748, 2956, 297, 571, 13, 25927, 198, 198, 4480, 1280, 7203, 17566, 13, 40664, 1600, 705, 81, 11537, 355, 269, 21370, 25, 198, 220, 220, 220, 1312, 796, 657...
2.026042
192
''' API-related functions in one spot for convenience Created by NGnius 2019-06-15 ''' from flask import jsonify, request from threading import Semaphore, RLock single_semaphores = dict() resource_lock = RLock()
[ 7061, 6, 198, 17614, 12, 5363, 5499, 287, 530, 4136, 329, 15607, 198, 198, 41972, 416, 39058, 77, 3754, 13130, 12, 3312, 12, 1314, 198, 7061, 6, 198, 198, 6738, 42903, 1330, 33918, 1958, 11, 2581, 198, 6738, 4704, 278, 1330, 12449, ...
3.257576
66
""" productporter ~~~~~~~~~~~~~~~~~~~~ helper for uwsgi :copyright: (c) 2014 by the ProductPorter Team. :license: BSD, see LICENSE for more details. """ from productporter.app import create_app from productporter.configs.production import ProductionConfig app = create_app(config=ProductionConfig())
[ 37811, 198, 220, 220, 220, 1720, 26634, 198, 220, 220, 220, 220, 27156, 8728, 628, 220, 220, 220, 31904, 329, 334, 18504, 12397, 628, 220, 220, 220, 1058, 22163, 4766, 25, 357, 66, 8, 1946, 416, 262, 8721, 47, 4337, 4816, 13, 198, ...
3.329897
97
# BSD 3-Clause License # # Copyright (c) 2017 xxxx # All rights reserved. # Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ import time import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torchvision.models as models from torch.autograd import Variable if __name__ == '__main__': #cudnn.benchmark = True # This will make network slow ?? resnet18 = models.resnet18().npu() alexnet = models.alexnet().npu() vgg16 = models.vgg16().npu() squeezenet = models.squeezenet1_0().npu() mobilenet = MobileNet().npu() speed(resnet18, 'resnet18') speed(alexnet, 'alexnet') speed(vgg16, 'vgg16') speed(squeezenet, 'squeezenet') speed(mobilenet, 'mobilenet')
[ 2, 347, 10305, 513, 12, 2601, 682, 13789, 198, 2, 198, 2, 15069, 357, 66, 8, 2177, 2124, 31811, 198, 2, 1439, 2489, 10395, 13, 198, 2, 15069, 33448, 43208, 21852, 1766, 1539, 12052, 198, 2, 198, 2, 2297, 396, 3890, 290, 779, 287, ...
3.298984
689
from setuptools import setup, find_packages __version__ = '1.0.0' __author__ = 'Takumi Sueda' __author_email__ = 'puhitaku@gmail.com' __license__ = 'MIT License' __classifiers__ = ( 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ) with open('README.md', 'r') as f: readme = f.read() setup( name='tepracli', version=__version__, license=__license__, author=__author__, author_email=__author_email__, url='https://github.com/puhitaku/tepra-lite-esp32/tree/master/client', description='An example of tepra-lite-esp32 client / CLI', long_description=readme, long_description_content_type='text/markdown', classifiers=__classifiers__, packages=find_packages(), package_data={'': ['assets/ss3.ttf']}, include_package_data=True, install_requires=['click', 'pillow', 'qrcode[pil]', 'requests'], )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 834, 9641, 834, 796, 705, 16, 13, 15, 13, 15, 6, 198, 834, 9800, 834, 796, 705, 51, 461, 12994, 311, 1739, 64, 6, 198, 834, 9800, 62, 12888, 834, 796, 705, 79, ...
2.614987
387
# Como trabalhar com paths from os import path import time dadosArquivo()
[ 2, 955, 78, 491, 44349, 9869, 401, 13532, 198, 6738, 28686, 1330, 3108, 198, 11748, 640, 198, 198, 67, 22484, 3163, 421, 23593, 3419 ]
3.083333
24
#!/usr/bin/env python3 import os import colorsys import cv2 import numpy as np from scipy.stats import multivariate_normal from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 28686, 198, 11748, 7577, 893, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 34242, 1330, 1963, 42524, 62, 11265, 198, ...
2.859155
71
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-05-25 15:41 from __future__ import unicode_literals import app.utils from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 1485, 319, 2864, 12, 2713, 12, 1495, 1315, 25, 3901, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198,...
2.797297
74
""" module: basic_train.py - Model fitting methods docs : https://docs.fast.ai/train.html """ import pytest, fastai from fastai.vision import * from utils.fakes import * from utils.text import * from utils.mem import * from fastai.utils.mem import * from math import isclose torch_preload_mem() # this is not a fixture on purpose - the memory measurement tests are very sensitive, so # they need to be able to get a fresh learn object and not one modified by other tests. def learn_large_unfit(data): learn = create_cnn(data, models.resnet18, metrics=accuracy) return learn #check_mem_expected = report_mem_real #@pytest.mark.skip(reason="WIP")
[ 37811, 198, 21412, 25, 4096, 62, 27432, 13, 9078, 532, 9104, 15830, 5050, 198, 31628, 220, 1058, 3740, 1378, 31628, 13, 7217, 13, 1872, 14, 27432, 13, 6494, 198, 37811, 198, 198, 11748, 12972, 9288, 11, 3049, 1872, 198, 6738, 3049, 18...
3.148325
209
# return.none.py func() # the return of this call won't be collected. It's lost. a = func() # the return of this one instead is collected into `a` print(a) # prints: None
[ 2, 1441, 13, 23108, 13, 9078, 198, 198, 20786, 3419, 220, 1303, 262, 1441, 286, 428, 869, 1839, 470, 307, 7723, 13, 632, 338, 2626, 13, 198, 64, 796, 25439, 3419, 220, 1303, 262, 1441, 286, 428, 530, 2427, 318, 7723, 656, 4600, 64...
3.125
56
# -*- coding: utf-8 -*- __author__ = """Tom Smith""" __email__ = 'tom@takeontom.com' __version__ = '0.2.0' from pyperi.pyperi import Peri # noqa from pyperi.pyperi import PyPeriConnectionError # noqa
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 834, 9800, 834, 796, 37227, 13787, 4176, 37811, 198, 834, 12888, 834, 796, 705, 39532, 31, 20657, 756, 296, 13, 785, 6, 198, 834, 9641, 834, 796, 705, 15, 13, 1...
2.372093
86
import numpy as np import scipy.sparse as sparse from scipy.integrate import ode from scipy.interpolate import interp1d import time import control import control.matlab import numpy.random import pandas as pd from ltisim import LinearStateSpaceSystem from pendulum_model import * from pyMPC.mpc import MPCController # Reference model default parameters k_def = 5.0 tau_def = 120e-3 Acl_c_def = np.array([[0,1,0], [0, 0, k_def], [0, 0, -1/tau_def]]) Bcl_c_def = np.array([[0], [k_def], [1/tau_def] ]) # PID default parameters Ts_PID = 1e-3 # Reference trajectory t_ref_vec = np.array([0.0, 5.0, 10.0, 20.0, 25.0, 30.0, 40.0, 100.0]) p_ref_vec = np.array([0.0, 0.0, 0.8, 0.8, 0.0, 0.0, 0.8, 0.8]) rp_fun = interp1d(t_ref_vec, p_ref_vec, kind='linear') # MPC parameters Ts_MPC_def = 10e-3 Qx_def = 1.0 * sparse.diags([1.0, 0, 10.0]) # Quadratic cost for states x0, x1, ..., x_N-1 QxN_def = Qx_def Qr_def = 0.0 * sparse.eye(1) # Quadratic cost for u0, u1, ...., u_N-1 QDr_def = 1e-1 / (Ts_MPC_def ** 2) * sparse.eye(1) # Quadratic cost for Du0, Du1, ...., Du_N-1 # Defaults DEFAULTS_PENDULUM_MPC = { 'xref_cl_fun': xref_cl_fun_def, 'uref': np.array([0.0]), # N 'std_npos': 0*0.001, # m 'std_nphi': 0*0.00005, # rad 'std_dF': 0.05, # N 'w_F':20, # rad 'len_sim': 40, #s 'Acl_c': Acl_c_def, 'Bcl_c': Bcl_c_def, 'Ts_MPC': Ts_MPC_def, 'Np': 100, 'Nc': 50, 'Qx': Qx_def, 'QxN': QxN_def, 'Qr': Qr_def, 'QDr': QDr_def, 'Q_kal': np.diag([0.1, 10, 0.1, 10]), 'R_kal': 1*np.eye(2), 'QP_eps_abs': 1e-3, 'QP_eps_rel': 1e-3, 'seed_val': None } def get_default_parameters(sim_options): """ Which parameters are left to default ??""" default_keys = [key for key in DEFAULTS_PENDULUM_MPC if key not in sim_options] return default_keys if __name__ == '__main__': import matplotlib.pyplot as plt import matplotlib plt.close('all') simopt = DEFAULTS_PENDULUM_MPC time_sim_start = time.perf_counter() simout = simulate_pendulum_MPC(simopt) time_sim = time.perf_counter() - time_sim_start t = simout['t'] x = simout['x'] u = simout['u'] y = simout['y'] y_meas = simout['y_meas'] x_ref = simout['x_ref'] x_fast = simout['x_fast'] y_meas_fast = simout['y_meas_fast'] u_fast = simout['u_fast'] x_model = simout['x_model'] t_fast = simout['t_fast'] x_ref_fast = simout['x_ref_fast'] F_input = simout['Fd_fast'] status = simout['status'] ref_phi_fast = simout['ref_phi_fast'] uref = get_parameter(simopt, 'uref') nsim = len(t) nx = x.shape[1] ny = y.shape[1] y_ref = x_ref[:, [0, 2]] fig,axes = plt.subplots(4,1, figsize=(10,10), sharex=True) axes[0].plot(t, y_meas[:, 0], "b", label='p_meas') axes[0].plot(t_fast, x_fast[:, 0], "k", label='p') axes[0].plot(t, x_model[:, 0], "r", label='p model') axes[0].plot(t, x_ref[:, 0], "k--", label='p reference') axes[0].set_ylim(-2.0,2.0) axes[0].set_title("Position (m)") axes[1].plot(t_fast, x_fast[:, 1], "k", label='v') axes[1].plot(t, x_model[:, 1], "r", label='v model') axes[1].set_ylim(-3,3.0) axes[1].set_title("Speed (m/s)") axes[2].plot(t, y_meas[:, 1]*RAD_TO_DEG, "b", label='phi_meas') axes[2].plot(t_fast, x_fast[:, 2]*RAD_TO_DEG, 'k', label="phi") axes[2].plot(t, x_model[:, 2]*RAD_TO_DEG, "r", label='phi model') axes[2].plot(t_fast, ref_phi_fast[:,0]*RAD_TO_DEG, "k--", label="phi_ref") axes[2].set_ylim(-20,20) axes[2].set_title("Angle (deg)") axes[3].plot(t, u[:,0], label="F") axes[3].plot(t_fast, F_input, "k", label="Fd") axes[3].plot(t, uref*np.ones(np.shape(t)), "r--", label="F_ref") axes[3].set_ylim(-20,20) axes[3].set_title("Force (N)") for ax in axes: ax.grid(True) ax.legend() X = np.hstack((t_fast, x_fast, u_fast, y_meas_fast, F_input)) COL_T = ['time'] COL_X = ['p', 'v', 'theta', 'omega'] COL_U = ['u'] COL_D = ['d'] COL_Y = ['p_meas', 'theta_meas'] COL = COL_T + COL_X + COL_U + COL_Y + COL_D df_X = pd.DataFrame(X, columns=COL) df_X.to_csv("pendulum_data_PID.csv", index=False)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 13, 82, 29572, 355, 29877, 198, 6738, 629, 541, 88, 13, 18908, 4873, 1330, 267, 2934, 198, 6738, 629, 541, 88, 13, 3849, 16104, 378, 1330, 987, 79, 16, 67, 198, 11748, 640, ...
1.939982
2,216
from flask import Blueprint, current_app main = Blueprint('main', __name__)
[ 6738, 42903, 1330, 39932, 11, 1459, 62, 1324, 198, 198, 12417, 796, 39932, 10786, 12417, 3256, 11593, 3672, 834, 8, 628, 198 ]
3.590909
22
from enum import Enum from .dev import Dev
[ 6738, 33829, 1330, 2039, 388, 198, 6738, 764, 7959, 1330, 6245 ]
3.818182
11
import pandas as pd from matplotlib.colors import LinearSegmentedColormap # Dataset data = pd.read_csv("./hr.csv") entries = len(data) bins = 10 # Data analysis analysis = { "bins": 10, "balance_threshold": 0.1 } # Plot labels labels = ["satisfaction_level", "average_montly_hours", "last_evaluation", "time_spend_company", "number_project", "Work_accident", "left", "promotion_last_5years", "sales", "salary"] pretty_prints = ["Self-reported satisfaction", "AVG Monthly hours", "Time since last valuation, in years", "Time in company, in years", "Projects", "Accidents", "Left", "Promoted (last 5 years)", "Department", "Salary"] short_pretty_prints = ["Injuries", "Work hours", "Last evaluation", "Left", "Projects", "Promotion", "Wage", "Satisfaction", "Years in company", "Dpt."] departments_pretty_prints = ["Information Technology", "R&D", "Accounting", "Human Resources", "Management", "Marketing", "Product Management", "Sales", "Support", "Technical"] labels_pretty_print = {k: v for k, v in zip(labels, pretty_prints)} short_labels_pretty_print = {k: v for k, v in zip(labels, short_pretty_prints)} labels_pretty_print["salary_int"] = "Salary" continuous_labels = labels[0:2] discrete_labels = labels[2:5] categorical_labels = labels[5:-1] ordinal_labels = labels[-1:] correlated_labels = continuous_labels + discrete_labels + ["salary_int"] categorical_labels_pretty_prints = { "Work_accident": ("Not Injured", "Injured"), "left": ("Stayed", "Left"), "promotion_last_5years": ("Not promoted", "Promoted"), "sales": tuple(departments_pretty_prints) } ordinal_labels_pretty_prints = { "salary": ("Low", "Medium", "High"), } ordered_ordinal_vars = { "salary": ["low", "medium", "high"] } departments = set(data["sales"]) # Scatter plot scatter = { "sampling_size": 100, # size of each sample "samples": 5, # number of samples to extract "edge_bins": 1, # edge bins possibly containing outliers "bins": 10, "replace": True } clusetering_types = ["normal", "discrete", "raw"] # Graphs palette = { "main": "#FE4365", "complementary": "#FC9D9A", "pr_complementary": "#F9CDAD", "sc_complementary": "#C8C8A9", "secondary": "#83AF9B" } round_palette = { "main": palette["secondary"], "secondary": palette["complementary"], "pr_complementary": palette["sc_complementary"], "sc_complementary": palette["secondary"] } large_palette = { "navy": "#001f3f", "blue": "#0074D9", "green": "#2ECC40", "olive": "#3D9970", "orange": "#FF851B", "yellow": "#FFDC00", "red": "#FF4136", "maroon": "#85144b", "black": "#111111", "grey": "#AAAAAA" } large_palette_full = { "navy": "#001f3f", "blue": "#0074D9", "aqua": "#7FDBFF", "teal": "#39CCCC", "olive": "#3D9970", "green": "#2ECC40", "lime": "#01FF70", "yellow": "#FFDC00", "orange": "#FF851B", "red": "#FF4136", "maroon": "#85144b", "fuchsia": "#F012BE", "purple": "#B10DC9", "black": "#111111", "grey": "#AAAAAA", "silver": "#DDDDDD" } large_palette_stacked = { "navy": "#001f3f", "blue": "#0074D9", "olive": "#3D9970", "orange": "#FF851B", "green": "#2ECC40", "yellow": "#FFDC00", "red": "#FF4136", "maroon": "#85144b", "black": "#111111", "grey": "#AAAAAA", "stack": large_palette["orange"] } cmap_pale_pink = LinearSegmentedColormap.from_list("Pale pink", [palette["pr_complementary"], palette["main"]], N=1000000) cmap_pale_pink_and_green = LinearSegmentedColormap.from_list("Pale pink&green", [palette["main"], palette["complementary"], palette["pr_complementary"], palette["sc_complementary"], palette["secondary"]], N=1000000)
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 2603, 29487, 8019, 13, 4033, 669, 1330, 44800, 41030, 12061, 5216, 579, 499, 198, 198, 2, 16092, 292, 316, 198, 7890, 796, 279, 67, 13, 961, 62, 40664, 7, 1911, 14, 11840, 13, 40664, 4943,...
1.823333
2,700
# Author: Vishal Gaur # Created: 17-01-2021 20:31:34 # function to find GCD using Basic Euclidean Algorithm # Driver Code to test above function a = 14 b = 35 g = gcdEuclid(a, b) print("GCD of", a, "&", b, "is: ", g) a = 56 b = 125 g = gcdEuclid(a, b) print("GCD of", a, "&", b, "is: ", g)
[ 2, 6434, 25, 220, 220, 36900, 282, 402, 2899, 198, 2, 15622, 25, 220, 1596, 12, 486, 12, 1238, 2481, 220, 1160, 25, 3132, 25, 2682, 198, 198, 2, 2163, 284, 1064, 402, 8610, 1262, 14392, 48862, 485, 272, 978, 42289, 628, 198, 2, ...
2.214815
135
# modules/InterpolationLayer.py from torch.nn import Module from functions.MotionSymmetryLayer import MotionSymmetryLayer
[ 2, 13103, 14, 9492, 16104, 341, 49925, 13, 9078, 198, 6738, 28034, 13, 20471, 1330, 19937, 198, 6738, 5499, 13, 45740, 13940, 3020, 11973, 49925, 1330, 20843, 13940, 3020, 11973, 49925, 628 ]
3.84375
32
import numpy from steer2HarmMtx import steer2HarmMtx def steer(*args): ''' Steer BASIS to the specfied ANGLE. function res = steer(basis,angle,harmonics,steermtx) BASIS should be a matrix whose columns are vectorized rotated copies of a steerable function, or the responses of a set of steerable filters. ANGLE can be a scalar, or a column vector the size of the basis. HARMONICS (optional, default is N even or odd low frequencies, as for derivative filters) should be a list of harmonic numbers indicating the angular harmonic content of the basis. STEERMTX (optional, default assumes cosine phase harmonic components, and filter positions at 2pi*n/N) should be a matrix which maps the filters onto Fourier series components (ordered [cos0 cos1 sin1 cos2 sin2 ... sinN]). See steer2HarmMtx.m Eero Simoncelli, 7/96. Ported to Python by Rob Young, 5/14. ''' if len(args) < 2: print 'Error: input parameters basis and angle are required!' return basis = args[0] num = basis.shape[1] angle = args[1] if isinstance(angle, (int, long, float)): angle = numpy.array([angle]) else: if angle.shape[0] != basis.shape[0] or angle.shape[1] != 1: print 'ANGLE must be a scalar, or a column vector the size of the basis elements' return # If HARMONICS are not passed, assume derivatives. if len(args) < 3: if num%2 == 0: harmonics = numpy.array(range(num/2))*2+1 else: harmonics = numpy.array(range((15+1)/2))*2 else: harmonics = args[2] if len(harmonics.shape) == 1 or harmonics.shape[0] == 1: # reshape to column matrix harmonics = harmonics.reshape(harmonics.shape[0], 1) elif harmonics.shape[0] != 1 and harmonics.shape[1] != 1: print 'Error: input parameter HARMONICS must be 1D!' return if 2*harmonics.shape[0] - (harmonics == 0).sum() != num: print 'harmonics list is incompatible with basis size!' return # If STEERMTX not passed, assume evenly distributed cosine-phase filters: if len(args) < 4: steermtx = steer2HarmMtx(harmonics, numpy.pi*numpy.array(range(num))/num, 'even') else: steermtx = args[3] steervect = numpy.zeros((angle.shape[0], num)) arg = angle * harmonics[numpy.nonzero(harmonics)[0]].T if all(harmonics): steervect[:, range(0,num,2)] = numpy.cos(arg) steervect[:, range(1,num,2)] = numpy.sin(arg) else: steervect[:, 1] = numpy.ones((arg.shape[0],1)) steervect[:, range(0,num,2)] = numpy.cos(arg) steervect[:, range(1,num,2)] = numpy.sin(arg) steervect = numpy.dot(steervect,steermtx) if steervect.shape[0] > 1: tmp = numpy.dot(basis, steervect) res = sum(tmp).T else: res = numpy.dot(basis, steervect.T) return res
[ 11748, 299, 32152, 198, 6738, 27401, 17, 39, 1670, 44, 17602, 1330, 27401, 17, 39, 1670, 44, 17602, 198, 198, 4299, 27401, 46491, 22046, 2599, 198, 220, 220, 220, 705, 7061, 2441, 263, 29809, 1797, 284, 262, 1020, 69, 798, 33278, 2538...
2.334112
1,284
import aiohttp import asyncio import os import zipfile from pydest.api import API from pydest.manifest import Manifest
[ 11748, 257, 952, 4023, 198, 11748, 30351, 952, 198, 11748, 28686, 198, 11748, 19974, 7753, 198, 198, 6738, 279, 5173, 395, 13, 15042, 1330, 7824, 198, 6738, 279, 5173, 395, 13, 805, 8409, 1330, 36757, 628, 628 ]
3.324324
37
# Generated by Django 3.2.1 on 2021-05-06 22:30 import django.contrib.gis.db.models.fields from django.db import migrations
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 16, 319, 33448, 12, 2713, 12, 3312, 2534, 25, 1270, 198, 198, 11748, 42625, 14208, 13, 3642, 822, 13, 70, 271, 13, 9945, 13, 27530, 13, 25747, 198, 6738, 42625, 14208, 13, 9945, 1330, 157...
2.73913
46
#!/usr/bin/python # -*- coding: utf8 -*- import os import re import textwrap import requests import unicodedata from datetime import datetime, timedelta from flask import Flask, g, request, render_template, abort, make_response from flask_babel import Babel, gettext from jinja2 import evalcontextfilter, Markup app = Flask(__name__, static_url_path='/static') app.config['BABEL_DEFAULT_LOCALE'] = 'sk' app.jinja_options = {'extensions': ['jinja2.ext.with_', 'jinja2.ext.i18n']} babel = Babel(app) EVENT = gettext('PyCon SK 2018') DOMAIN = 'https://2018.pycon.sk' API_DOMAIN = 'https://api.pycon.sk' LANGS = ('en', 'sk') TIME_FORMAT = '%Y-%m-%dT%H:%M:%S+00:00' NOW = datetime.utcnow().strftime(TIME_FORMAT) SRC_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__))) LOGO_PYCON = 'logo/pycon_logo_square.svg' LDJSON_SPY = { "@type": "Organization", "name": "SPy o. z.", "url": "https://spy.pycon.sk", "logo": "https://spy.pycon.sk/img/logo/spy-logo.png", "sameAs": [ "https://facebook.com/pyconsk", "https://twitter.com/pyconsk", "https://www.linkedin.com/company/spy-o--z-", "https://github.com/pyconsk", ] } LDJSON_PYCON = { "@context": "http://schema.org", "@type": "Event", "name": EVENT, "description": gettext("PyCon will be back at Slovakia in 2018 again. PyCon SK is a community-organized conference " "for the Python programming language."), "startDate": "2018-03-09T9:00:00+01:00", "endDate": "2018-03-11T18:00:00+01:00", "image": DOMAIN + "/static/img/logo/pycon_long_2018.png", "location": { "@type": "Place", "name": "FIIT STU", "address": { "@type": "PostalAddress", "streetAddress": "Ilkoviova 2", "addressLocality": "Bratislava 4", "postalCode": "842 16", "addressCountry": gettext("Slovak Republic") }, }, "url": DOMAIN, "workPerformed": { "@type": "CreativeWork", "name": EVENT, "creator": LDJSON_SPY } } # calendar settings ICAL_LEN = 70 # length of a calendar (ical) line ICAL_NL = '\\n\n' # calendar newline IGNORE_TALKS = ['Break', 'Coffee Break'] TYPE = { 'talk': gettext('Talk'), 'workshop': gettext('Workshop'), } TAGS = { 'ai': gettext('Machine Learning / AI'), 'community': gettext('Community / Diversity / Social'), 'data': gettext('Data Science'), 'devops': 'DevOps', 'docs': gettext('Documentation'), 'edu': gettext('Education'), 'generic': gettext('Python General'), 'security': gettext('Security'), 'softskills': gettext('Soft Skills'), 'hardware': gettext('Hardware'), 'web': gettext('Web Development'), 'other': gettext('Other'), } FRIDAY_START = datetime(2018, 3, 9, hour=9) SATURDAY_START = datetime(2018, 3, 10, hour=9) SUNDAY_START = datetime(2018, 3, 11, hour=10, minute=15) FRIDAY_TRACK1 = ( {"pause": 5, 'title': gettext("Conference Opening"), 'duration': 25, 'flag': 'other', 'type': 'talk'}, {"pause": 15, 'title': gettext("FaaS and Furious - Zero to Serverless in 60 seconds - Anywhere")}, {"pause": 15, 'title': gettext("Docs or it didn't happen")}, {"pause": 5, 'title': gettext("GraphQL is the new black")}, {"pause": 60, 'title': gettext("To the Google in 80 Days")}, {"pause": 5, 'title': gettext("Unsafe at Any Speed")}, {"pause": 15, 'title': gettext("Protecting Privacy and Security For Yourself and Your Community")}, {"pause": 5, 'title': gettext("ZODB: The Graph database for Python Developers.")}, {"pause": 15, 'title': gettext("Differentiable programming in Python and Gluon for (not only medical) image analysis")}, {"pause": 5, 'title': gettext("Vim your Python, Python your Vim")}, ) FRIDAY_TRACK2 = ( {"pause": 5, 'title': gettext("Conference Opening in Kiwi.com Hall"), 'duration': 25}, {"pause": 5, 'title': gettext("Python Days in Martin and follow-up activities")}, {"pause": 15, 'title': gettext("Python programming till graduation")}, {"pause": 5, 'title': gettext("Open educational resources for learning Python")}, {"pause": 60, 'title': gettext("About Ninjas and Mentors: CoderDojo in Slovakia")}, {"pause": 5, 'title': gettext("Community based courses")}, {"pause": 15, 'title': gettext("How do we struggle with Python in Martin?")}, {"pause": 5, 'title': gettext("Why hardware attracts kids and adults to IT")}, {"pause": 5, 'title': gettext("Panel discussion: Teaching IT in Slovakia - where is it heading?")}, {"pause": 5, 'title': gettext("EDU Talks"), 'duration': 30, 'language': 'SK', 'flag': 'edu', 'type': 'talk'}, ) FRIDAY_WORKSHOPS1 = ( {"pause": 10, 'title': gettext("How to create interactive maps in Python / R")}, {"pause": 60, 'title': gettext("Working with XML")}, {"pause": 5, 'title': gettext("Managing high-available applications in production")}, ) FRIDAY_WORKSHOPS2 = ( {"pause": 40, 'title': gettext("Workshop: An Introduction to Ansible")}, {"pause": 5, 'title': gettext("Introduction to Machine Learning with Python")}, ) FRIDAY_HALLWAY = ( {"pause": 0, 'title': gettext("OpenPGP key-signing party"), 'duration': 30, 'link': 'https://github.com/pyconsk/2018.pycon.sk/tree/master/openpgp-key-signing-party', 'flag': 'security'}, ) SATURDAY_TRACK1 = ( {"pause": 5, 'title': gettext("Conference Opening"), 'duration': 25, 'flag': 'other', 'type': 'talk'}, {"pause": 5, 'title': gettext("Solutions Reviews")}, {"pause": 15, 'title': gettext("Campaign Automation & Abusing Celery Properly")}, {"pause": 5, 'title': gettext("The Truth about Mastering Big Data")}, {"pause": 5, 'title': gettext("Industrial Machine Learning: Building scalable distributed machine learning pipelines with Python")}, {"pause": 25, 'title': gettext("Programming contest Semi finale"), 'duration': 30, 'flag': 'other', 'link': 'https://app.pycon.sk'}, {"pause": 5, 'title': gettext("Pythonic code, by example")}, {"pause": 15, 'title': gettext("Our DevOps journey, is SRE the next stop?")}, {"pause": 5, 'title': gettext("Implementing distributed systems with Consul")}, {"pause": 15, 'title': gettext("Designing fast and scalable Python MicroServices with django")}, {"pause": 5, 'title': gettext("When your wetware has too many threads - Tips from an ADHDer on how to improve your focus")}, {"pause": 5, 'title': gettext("Programming Python as performance: live coding with FoxDot")}, {"pause": 5, 'title': gettext("Programming Contest Grand Finale"), 'duration': 30, 'flag': 'other', 'type': 'talk', 'language': 'EN'}, {"pause": 5, 'title': gettext("Lightning Talks"), 'duration': 45, 'flag': 'other', 'type': 'talk'}, ) SATURDAY_TRACK2 = ( {"pause": 5, 'title': gettext("Conference Opening in Kiwi.com Hall"), 'duration': 25}, {"pause": 5, 'title': gettext("Meteo data in Python. Effectively.")}, {"pause": 15, 'title': gettext("Around the World in 30 minutes")}, {"pause": 5, 'title': gettext("LOCKED SHIELDS: What a good cyber testing looks like")}, {"pause": 60, 'title': gettext("Kiwi.com in ZOO")}, {"pause": 5, 'title': gettext("Keynote in Kiwi.com Hall"), 'duration': 30, 'flag': 'generic', 'type': 'talk'}, {"pause": 15, 'title': gettext("Skynet your Infrastructure with QUADS")}, {"pause": 5, 'title': gettext("Automated network OS testing")}, {"pause": 15, 'title': gettext("Tools to interact with Bitcoin and Ethereum")}, {"pause": 5, 'title': gettext("7 Steps to a Clean Issue Tracker")}, {"pause": 5, 'title': gettext("The Concierge Paradigm")}, ) SATURDAY_WORKSHOPS1 = ( {"pause": 55, 'title': gettext("Effectively running python applications in Kubernetes/OpenShift")}, {"pause": 5, 'title': gettext("Roboworkshop")}, ) SATURDAY_WORKSHOPS2 = ( {"pause": 55, 'title': gettext("Microbit:Slovakia")}, {"pause": 5, 'title': gettext("Coding in Python: A high-school programming lesson")}, ) SATURDAY_HALLWAY1 = ( {"pause": 0, 'title': gettext("Pandas documentation sprint"), 'duration': 360, 'link': 'https://python-sprints.github.io/pandas/', 'flag': 'docs'}, ) SATURDAY_HALLWAY2 = ( {"pause": 145, 'title': gettext("Programming contest"), 'duration': 95, 'flag': 'other', 'link': 'https://app.pycon.sk'}, {"pause": 5, 'title': gettext("Conference organizers meetup"), 'duration': 30, 'flag': 'community'}, ) SUNDAY_TRACK1 = ( {"pause": 5, 'title': gettext("Charon and the way out from a pickle hell")}, {"pause": 15, 'title': gettext("Making Python Behave")}, {"pause": 5, 'title': gettext("Secret information about the code we write")}, {"pause": 60, 'title': gettext("How to connect objects with each other in different situations with Pythonic ways - association, aggregation, composition and etc.")}, {"pause": 5, 'title': gettext("APIs: Gateway to world's data")}, {"pause": 15, 'title': gettext("Getting started with HDF5 and PyTables")}, {"pause": 5, 'title': gettext("Real-time personalized recommendations using embeddings")}, {"pause": 5, 'title': gettext("Quiz"), 'duration': 30, 'flag': 'other', 'type': 'talk'}, ) SUNDAY_WORKSHOPS1 = ( {"pause": 40, 'title': gettext("Real-time transcription and sentiment analysis of audio streams; on the phone and in the browser")}, {"pause": 5, 'title': gettext("Learn MongoDB by modeling PyPI in a document database")}, ) SUNDAY_WORKSHOPS2 = ( {"pause": 15, 'title': gettext("Testing Essentials for Scientists and Engineers")}, {"pause": 5, 'title': gettext("Cython: Speed up your code without going insane")}, ) SUNDAY_WORKSHOPS3 = ( {"pause": 15, 'title': gettext("Meet the pandas")}, {"pause": 5, 'title': gettext("Serverless with OpenFaaS and Python")}, ) SUNDAY_WORKSHOPS4 = ( {"pause": 5, 'title': gettext("Django Girls"), 'duration': 540, 'flag': 'web', 'type': 'workshop'}, ) SUNDAY_HALLWAY = ( {"pause": 5, 'title': gettext("Documentation clinic/helpdesk")}, ) AULA1 = { 'name': gettext('Kiwi.com Hall'), 'number': '-1.61', } AULA2 = { 'name': gettext('Python Software Foundation Hall'), 'number': '-1.65', } AULA3 = { 'name': gettext('SPy - Hall A'), 'number': '-1.57', } AULA4 = { 'name': gettext('SPy - Hall B'), 'number': '-1.57', } AULA5 = { 'name': gettext('Django Girls Auditorium'), 'number': '+1.31', } HALLWAY = { 'name': gettext('Hallway'), 'number': '', } def get_conference_data(url='', filters=''): """Connect to API and get public talks and speakers data.""" url = API_DOMAIN + url if filters: url = url + '&' + filters r = requests.get(url) return r.json() API_DATA_SPEAKERS = get_conference_data(url='/event/2018/speakers/') API_DATA_TALKS = get_conference_data(url='/event/2018/talks/') def _get_template_variables(**kwargs): """Collect variables for template that repeats, e.g. are in body.html template""" lang = get_locale() variables = { 'title': EVENT, 'logo': LOGO_PYCON, # TODO: Do we need this? 'ld_json': LDJSON_PYCON } variables['ld_json']['url'] = DOMAIN + '/' + lang + '/' variables.update(kwargs) if 'current_lang' in g: variables['lang_code'] = g.current_lang else: variables['lang_code'] = app.config['BABEL_DEFAULT_LOCALE'] return variables def generate_track(api_data, track_data, start, flag=None): """Helper function to mix'n'match API data, with schedule order defined here, to generate schedule dict""" template_track_data = [] for talk in track_data: # Check if talk is in API talk_api_data = next((item for item in api_data if item['title'] == talk['title']), None) # If talk is not in API data we'll use text from track_data dict == same structure for template generation if not talk_api_data: talk_api_data = talk if not flag or ('flag' in talk_api_data and flag == talk_api_data['flag']): # Store data to be displayed in template template_track_data.append({ "start": start, "talk": talk_api_data }) start = start + timedelta(minutes=talk_api_data.get('duration', 0)) # start = start + timedelta(minutes=talk_api_data['duration']) if not flag: # Generate break break_name = gettext('Break') if talk['pause'] in (40, 60): break_name = gettext('Lunch ') if talk['pause'] in (15, 20): break_name = gettext('Coffee Break ') template_track_data.append({ 'start': start, 'talk': {'title': break_name}, 'css': 'break' }) start = start + timedelta(minutes=talk['pause']) # break time does not comes from API always defined in track return template_track_data def generate_schedule(api_data, flag=None): return [ { 'room': AULA1, 'start': FRIDAY_START, 'schedule': generate_track(api_data, FRIDAY_TRACK1, FRIDAY_START, flag=flag), 'day': 'friday', 'block_start': True, }, { 'room': AULA2, 'start': FRIDAY_START, 'schedule': generate_track(api_data, FRIDAY_TRACK2, FRIDAY_START, flag=flag), 'day': 'friday' }, { 'room': AULA3, 'start': FRIDAY_START, 'schedule': generate_track(api_data, FRIDAY_WORKSHOPS1, FRIDAY_START+timedelta(minutes=30), flag=flag), 'day': 'friday' }, { 'room': AULA4, 'start': FRIDAY_START, 'schedule': generate_track(api_data, FRIDAY_WORKSHOPS2, FRIDAY_START+timedelta(minutes=30), flag=flag), 'day': 'friday', }, { 'room': HALLWAY, 'start': FRIDAY_START+timedelta(minutes=395), 'schedule': generate_track(api_data, FRIDAY_HALLWAY, FRIDAY_START+timedelta(minutes=395), flag=flag), 'day': 'saturday', 'block_end': True, }, { 'room': AULA1, 'start': SATURDAY_START, 'schedule': generate_track(api_data, SATURDAY_TRACK1, SATURDAY_START, flag=flag), 'day': 'saturday', 'block_start': True, }, { 'room': AULA2, 'start': SATURDAY_START, 'schedule': generate_track(api_data, SATURDAY_TRACK2, SATURDAY_START, flag=flag), 'day': 'saturday' }, { 'room': AULA3, 'start': SATURDAY_START, 'schedule': generate_track(api_data, SATURDAY_WORKSHOPS1, SATURDAY_START+timedelta(minutes=30), flag=flag), 'day': 'saturday' }, { 'room': AULA4, 'start': SATURDAY_START, 'schedule': generate_track(api_data, SATURDAY_WORKSHOPS2, SATURDAY_START+timedelta(minutes=30), flag=flag), 'day': 'saturday' }, { 'room': HALLWAY, 'start': SATURDAY_START+timedelta(minutes=60), 'schedule': generate_track(api_data, SATURDAY_HALLWAY1, SATURDAY_START+timedelta(minutes=60), flag=flag), 'day': 'saturday', }, { 'room': HALLWAY, 'start': SATURDAY_START+timedelta(minutes=30), 'schedule': generate_track(api_data, SATURDAY_HALLWAY2, SATURDAY_START+timedelta(minutes=30), flag=flag), 'day': 'saturday', 'block_end': True, }, { 'room': AULA1, 'start': SUNDAY_START, 'schedule': generate_track(api_data, SUNDAY_TRACK1, SUNDAY_START, flag=flag), 'day': 'sunday', 'block_start': True, }, { 'room': AULA2, 'start': SUNDAY_START, 'schedule': generate_track(api_data, SUNDAY_WORKSHOPS1, SUNDAY_START, flag=flag), 'day': 'sunday' }, { 'room': AULA3, 'start': SUNDAY_START, 'schedule': generate_track(api_data, SUNDAY_WORKSHOPS2, SUNDAY_START, flag=flag), 'day': 'sunday' }, { 'room': AULA4, 'start': SUNDAY_START, 'schedule': generate_track(api_data, SUNDAY_WORKSHOPS3, SUNDAY_START, flag=flag), 'day': 'sunday' }, { 'room': AULA5, 'start': SUNDAY_START, 'schedule': generate_track(api_data, SUNDAY_WORKSHOPS4, SUNDAY_START-timedelta(minutes=135), flag=flag), 'day': 'sunday', }, { 'room': HALLWAY, 'start': SUNDAY_START, 'schedule': generate_track(api_data, SUNDAY_HALLWAY, SUNDAY_START+timedelta(minutes=45), flag=flag), 'day': 'sunday', 'block_end': True, }, ] def _timestamp(dt=None): if dt is None: dt = datetime.now() fmt = '%Y%m%dT%H%M%S' return dt.strftime(fmt) def _ignore_talk(title, names=IGNORE_TALKS): # yes, we can paste unicode symbols, but if we change the symbol this test will still work max_appended_symbols = 2 return any((title == name or title[:-(_len+1)] == name) for _len in range(max_appended_symbols) for name in names) def _hash_event(track, slot): room = track.get('room') name = room.get('name') ts = _timestamp(slot.get('start')) _hash = str(hash('{name}:{ts}'.format(name=name, ts=ts))) _hash = _hash.replace('-', '*') return '-'.join(_hash[i*5:(i+1)*5] for i in range(4)) def _normalize(text, tag=None, subsequent_indent=' ', **kwargs): # tag must be always included to determine amount of space left in the first line if tag: max_width = ICAL_LEN - len(tag) - 1 else: max_width = ICAL_LEN text = text.strip().replace('\n', ICAL_NL) return '\n'.join(textwrap.wrap(text, width=max_width, subsequent_indent=subsequent_indent, **kwargs)) # CALENDAR FUNCTIONS def get_mtime(filename): """Get last modification time from file""" mtime = datetime.fromtimestamp(os.path.getmtime(filename)) return mtime.strftime(TIME_FORMAT) SITEMAP_DEFAULT = {'prio': '0.1', 'freq': 'weekly'} SITEMAP = { 'sitemap.xml': {'prio': '0.9', 'freq': 'daily', 'lastmod': get_mtime(__file__)}, 'index.html': {'prio': '1', 'freq': 'daily'}, 'schedule.html': {'prio': '0.9', 'freq': 'daily'}, 'speakers.html': {'prio': '0.9', 'freq': 'daily'}, 'hall_of_fame.html': {'prio': '0.5', 'freq': 'weekly'}, 'tickets.html': {'prio': '0.5', 'freq': 'weekly'}, } def get_lastmod(route, sitemap_entry): """Used by sitemap() below""" if 'lastmod' in sitemap_entry: return sitemap_entry['lastmod'] template = route.rule.split('/')[-1] template_file = os.path.join(SRC_DIR, 'templates', template) if os.path.exists(template_file): return get_mtime(template_file) return NOW if __name__ == "__main__": app.run(debug=True, host=os.environ.get('FLASK_HOST', '127.0.0.1'), port=int(os.environ.get('FLASK_PORT', 5000)), use_reloader=True)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 23, 532, 9, 12, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 2420, 37150, 198, 11748, 7007, 198, 11748, 28000, 9043, 1045, 198, 6738, 4818, 8079, 1330...
2.337083
8,268
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, 15720, 602, 198, 6738, 42625, 14208, 13, 10414, 1330, ...
3.111111
45
#!/usr/bin/env python import argparse import fishact if __name__ == '__main__': parser = argparse.ArgumentParser( description='Validate data files.') parser.add_argument('activity_fname', metavar='activity_file', type=str, help='Name of activity file.') parser.add_argument('gtype_fname', metavar='genotype_file', type=str, help='Name of genotype file.') args = parser.parse_args() print('------------------------------------------------') print('Checking genotype file...') fishact.validate.test_genotype_file(args.gtype_fname) print('------------------------------------------------\n\n\n') print('------------------------------------------------') print('Checking activity file...') fishact.validate.test_activity_file(args.activity_fname, args.gtype_fname) print('------------------------------------------------')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 1822, 29572, 198, 198, 11748, 5916, 529, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 30751, 796, 1822, 29572, 13, 28100, 1713, 4...
2.974359
312
#!/usr/bin/env python3 from sys import stdout,stderr,exit from optparse import OptionParser from newick_parser import parse_tree_iterator, Branch from tree_span import calculateSpan from copy import deepcopy if __name__ == '__main__': usage = 'usage: %prog [options] <NEWICK FILE>' parser = OptionParser(usage=usage) parser.add_option('-s', '--scale_factor', dest='scale_factor', help='Scale factor of distances in tree', type=float, default=0, metavar='FLOAT') parser.add_option('-a', '--absolute_length', dest='absolute', help='Absolute length of maximal distance in tree', type=float, default=0, metavar='FLOAT') (options, args) = parser.parse_args() if len(args) != 1: parser.print_help() exit(1) if not ((options.absolute > 0) ^ (options.scale_factor > 0)): print('!! Specify either scale factor or absolute length with ' + \ 'strictly positive number', file = stderr) exit(1) for tree in parse_tree_iterator(open(args[0])): if options.absolute > 0: print(rescale_absolute(tree, options.absolute), file = stdout) else: print(rescale(tree, options.scale_factor), file = stdout)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 25064, 1330, 14367, 448, 11, 301, 1082, 81, 11, 37023, 198, 6738, 2172, 29572, 1330, 16018, 46677, 198, 6738, 649, 624, 62, 48610, 1330, 21136, 62, 21048, 62, 48727, 11,...
2.510978
501
from stable_baselines3 import PPO import os from setup_gym_env import SnakeEnv import time #models_dir = "./models/1644408901/" + "40000" #models_dir = "./models/1644462865/" + "120000" #models_dir = "./models/1644466638/" + "100000" models_dir = "./models/1644485414/" + "100000" env = SnakeEnv() env.reset() model = PPO.load(models_dir) episodes = 10 # snake doesn't known where itself for episode in range(episodes): done = False obs = env.reset() #while True:#not done: while not done: action, _states = model.predict(obs) #print("action",action) obs, reward, done, info = env.step(action) #print('reward',reward) if done == True: print(done) env.render()
[ 6738, 8245, 62, 12093, 20655, 18, 1330, 350, 16402, 198, 11748, 28686, 198, 6738, 9058, 62, 1360, 76, 62, 24330, 1330, 16705, 4834, 85, 198, 11748, 640, 628, 198, 198, 2, 27530, 62, 15908, 796, 366, 19571, 27530, 14, 1433, 2598, 1821,...
2.38141
312
#!/usr/bin/env python3 import yoda, sys import h5py import numpy as np def createDatasets(f, binids, variations, depth=1, compression=4): """ Create data sets in the HDF5 file. """ nbins=len(binids) nvars=len(variations) # The fundamental moments/elements of yoda objecs floats = [ "sumw", "sumw2", "sumwx", "sumwx2", "sumwy", "sumwy2", "sumwxy", "numEntries", "xval", "xerr-", "xerr+", "yval", "yerr-", "yerr+", "xmin", "xmax", "ymin", "ymax" ] # The datasets have 3 axes: binid, weight variation, point in parameter space for df in floats: f.create_dataset(df, (nbins,nvars,depth), maxshape=(None,None,None), dtype='f' , chunks=True, compression=compression) # Lookups --- helps when reading data and reconstucting YODA objects f.create_group("Histo1D") f.create_group("Histo2D") f.create_group("Profile1D") f.create_group("Counter") f.create_group("Scatter1D") f.create_group("Scatter2D") # This is the one that works well with hdf5 when reading std::string in C++ dt = h5py.special_dtype(vlen=str) # We use these simple lists as lookup tables to associate the elements of the datasets ^^^ with # the actual YODA Analysis objects import numpy as np f.create_dataset("binids", data=np.array(binids, dtype=dt)) f.create_dataset("variations", data=np.array(variations, dtype=dt)) def dbn1ToArray(dbn): """ The try except block deals with the underflow things not having xmin, xmax """ try: return np.array([dbn.sumW(), dbn.sumW2(), dbn.sumWX(), dbn.sumWX2(), dbn.numEntries(), dbn.xMin(), dbn.xMax()]) except: return np.array([dbn.sumW(), dbn.sumW2(), dbn.sumWX(), dbn.sumWX2(), dbn.numEntries(), 0, 0]) def H2dbn2ToArray(dbn): """ The try except block deals with the underflow things not having xmin, xmax """ try: return np.array([dbn.sumW(), dbn.sumW2(), dbn.sumWX(), dbn.sumWX2(), dbn.sumWY(), dbn.sumWY2(), dbn.sumWXY(), dbn.numEntries(), dbn.xMin(), dbn.xMax(), dbn.yMin(), dbn.yMax()]) except: return np.array([dbn.sumW(), dbn.sumW2(), dbn.sumWX(), dbn.sumWX2(), dbn.sumWY(), dbn.sumWY2(), dbn.sumWXY(), dbn.numEntries(), 0, 0, 0, 0]) if __name__=="__main__": import sys import optparse, os, sys op = optparse.OptionParser(usage=__doc__) op.add_option("-v", "--debug", dest="DEBUG", action="store_true", default=False, help="Turn on some debug messages") op.add_option("-o", dest="OUTPUT", default="analysisobjects.h5", help="Output HDF5 file (default: %default)") opts, args = op.parse_args() YODAFILES = args from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() binids, VVV, aix, aix_flat, central = None, None, None, None, None if rank==0: # TODO if len(args)==1 and os.path.isdir(args[0]) --- hierarchical reading with pnames finding etc # Let's assume they are all consistent TODO add robustness DATA0 = yoda.readYODA(args[0]) L = sorted(list(DATA0.keys())) names = [x for x in L ]# if not "/RAW" in x] central = [x for x in names if not x.endswith("]")] variations = [x for x in names if x.endswith("]")] # TODO In principle one probably should check that all variations are always the # same, we assume this is the case here var = [] for c in central: var.append([x for x in variations if x.startswith(c+"[")]) ## Thats the weight and weight variation order we store the data in VVV = ["CentralWeight"] import re p=re.compile("\[(.*?)\]") for x in var[0]: try: VVV.append(p.findall(x)[0]) except Exception as e: print(x, e) binids = mkBinids(DATA0) # Hierarchical, i.e. top layer is the AnalysisObject type aix = mkIndexDict(DATA0, binids) # Object name as keys and lists of indices as values aix_flat = {} for k, v in aix.items(): aix_flat.update(v) binids = comm.bcast(binids, root=0) VVV = comm.bcast(VVV, root=0) aix = comm.bcast(aix, root=0) aix_flat = comm.bcast(aix_flat, root=0) central = comm.bcast(central, root=0) # NOTE dataset operations are collective # This require h5py to use and H5 that is build with MPI try: f = h5py.File(opts.OUTPUT, "w", driver='mpio', comm=MPI.COMM_WORLD) except: f = h5py.File(opts.OUTPUT, "w") createDatasets(f, binids, VVV, depth=len(YODAFILES)) createIndexDS(f, aix) rankwork = chunkIt([i for i in range(len(YODAFILES))], size) if rank==0 else None rankwork = comm.scatter(rankwork, root=0) # This part is MPI trivial for num, findex in enumerate(rankwork): DATA = yoda.readYODA(YODAFILES[findex]) for hname in central: _hname=mkSafeHname(hname) fillDatasets(f, aix_flat[_hname], VVV, DATA, hname, depth=findex) if rank==0: print("[{}] --- {}/{} complete".format(rank, num, len(rankwork))) sys.stdout.flush() f.close()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 628, 198, 11748, 331, 11329, 11, 25064, 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 198, 4299, 2251, 27354, 292, 1039, 7, 69, 11, 9874, 2340, 11, 13991, 11, 67...
2.142012
2,535
import zipfile import os import glob import sys # Actual directory that we could find somewhere # Reading the first arg written in the console (program name not included) fileTest = Folder(sys.argv[1])
[ 11748, 19974, 7753, 198, 11748, 28686, 198, 11748, 15095, 198, 11748, 25064, 198, 198, 2, 33520, 8619, 326, 356, 714, 1064, 7382, 198, 198, 2, 11725, 262, 717, 1822, 3194, 287, 262, 8624, 357, 23065, 1438, 407, 3017, 8, 198, 7753, 144...
3.903846
52
from functools import partial from airflow.operators.python_operator import ShortCircuitOperator
[ 6738, 1257, 310, 10141, 1330, 13027, 198, 198, 6738, 45771, 13, 3575, 2024, 13, 29412, 62, 46616, 1330, 10073, 31560, 5013, 18843, 1352, 628, 198 ]
4
25
# Imports import pandas as pd import pickle from keras.models import load_model from preprocess import preprocess from preprocess import prep_text #Logging import logging logging.getLogger().setLevel(logging.INFO) logging.info('Loading comments to classify...') # Enter comment to be classified below comment_to_classify = '' def return_label(predicted_probs): """ Function that takes in a list of 7 class probabilities and returns the labels with probabilities over a certain threshold. """ threshold = 0.4 labels = [] classes = ['clean', 'toxic', 'severe toxic', 'obscene', 'threat', 'insult', 'identity hate'] i = 0 while i < len(classes): if predicted_probs[i] > threshold: labels.append(classes[i]) i += 1 return (labels) def predict_label(comment_str): """ Function that takes in a comment in string form and returns the predicted class labels: not toxic, toxic, severe toxic, obscene, threat, insults, identity hate. May output multiple labels. """ data = pd.DataFrame(data=[comment_str], columns=['comment_text']) logging.info('Comments loaded.') # Preprocess text X_to_predict = preprocess(data) # Identify data to make predictions from X_to_predict = X_to_predict['model_text'] # Format data properly X_to_predict = prep_text(X_to_predict) logging.info('Loading model...') # Load CNN from disk cnn = load_model('model/CNN/binarycrossentropy_adam/model-04-0.9781.hdf5') logging.info('Model loaded.') logging.info('Making prediction(s)...') # Make predictions preds = cnn.predict(X_to_predict) for each_comment, prob in zip(data['comment_text'], preds): print('COMMENT:') print(each_comment) print() print('PREDICTION:') print(return_label(prob)) print() logging.info('Finished.') predict_label(comment_to_classify)
[ 2, 1846, 3742, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2298, 293, 198, 6738, 41927, 292, 13, 27530, 1330, 3440, 62, 19849, 198, 6738, 662, 14681, 1330, 662, 14681, 198, 6738, 662, 14681, 1330, 3143, 62, 5239, 198, 198, 2, ...
2.678426
737
from .efficientdet import EfficientDet
[ 6738, 764, 16814, 15255, 1330, 412, 5632, 11242, 628 ]
4.444444
9
import json import logging import boto3 from box import Box from crhelper import CfnResource from schema import Optional import codesmith.common.naming as naming from codesmith.common.cfn import resource_properties from codesmith.common.schema import encoded_bool, non_empty_string, tolerant_schema from codesmith.common.ssm import put_string_parameter, silent_delete_parameter_from_event helper = CfnResource() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) properties_schema = tolerant_schema({ 'UserPoolId': non_empty_string, 'UserPoolClientId': non_empty_string, Optional('All', default=False): encoded_bool, Optional('Domains', default=[]): [str], Optional('Emails', default=[]): [str] }) ssm = boto3.client('ssm') def handler(event, context): logger.info('event: %s', event) helper(event, context)
[ 11748, 33918, 198, 11748, 18931, 198, 198, 11748, 275, 2069, 18, 198, 6738, 3091, 1330, 8315, 198, 6738, 1067, 2978, 525, 1330, 327, 22184, 26198, 198, 6738, 32815, 1330, 32233, 198, 198, 11748, 12416, 22947, 13, 11321, 13, 77, 3723, 35...
3.024561
285
n = int(input('Digite um nmero: ')) print('Seu nmero {}. O antecessor {} e seu sucessor {}'.format(n, n - 1, n + 1))
[ 77, 796, 493, 7, 15414, 10786, 19511, 578, 23781, 299, 647, 78, 25, 705, 4008, 198, 4798, 10786, 4653, 84, 299, 647, 78, 220, 23884, 13, 440, 29692, 919, 273, 220, 23884, 304, 384, 84, 424, 919, 273, 220, 23884, 4458, 18982, 7, 77...
2.222222
54
# Given two binary trees, check if the first tree is subtree of the second one. # A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. # The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. # Driver program to test above function """ TREE 1 Construct the following tree 26 / \ 10 3 / \ \ 4 6 3 \ 30 """ T = Node(26) T.right = Node(3) T.right.right = Node(3) T.left = Node(10) T.left.left = Node(4) T.left.left.right = Node(30) T.left.right = Node(6) """ TREE 2 Construct the following tree 10 / \ 4 6 \ 30 """ S = Node(10) S.right = Node(6) S.left = Node(4) S.left.right = Node(30) if is_subtree(T, S): print "Tree 2 is subtree of Tree 1" else : print "Tree 2 is not a subtree of Tree 1"
[ 2, 11259, 734, 13934, 7150, 11, 2198, 611, 262, 717, 5509, 318, 13284, 631, 286, 262, 1218, 530, 13, 198, 198, 2, 317, 13284, 631, 286, 257, 5509, 309, 318, 257, 5509, 311, 17747, 286, 257, 10139, 287, 309, 290, 477, 286, 663, 253...
2.3
410
from typing import List, Optional from papi_sdk.models.search.base_affiliate_response import ( BaseAffiliateSearchData, BaseAffiliateSearchResponse, BaseHotel, BaseRate, ) from papi_sdk.models.search.base_request import BaseAffiliateRequest
[ 6738, 19720, 1330, 7343, 11, 32233, 198, 198, 6738, 279, 15042, 62, 21282, 74, 13, 27530, 13, 12947, 13, 8692, 62, 2001, 49826, 62, 26209, 1330, 357, 198, 220, 220, 220, 7308, 35191, 49826, 18243, 6601, 11, 198, 220, 220, 220, 7308, ...
3.022989
87
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019-01-02 16:44 # @Author : zhangzhen # @Site : # @File : torch_neural_networks.py # @Software: PyCharm import torch import torch.nn as nn import torch.nn.functional as F if __name__ == '__main__': net = Net() criterion = nn.MSELoss() print(net) params = list(net.parameters()) print(":", len(params)) for param in params: print(param.size()) input = torch.randn(1, 1, 32, 32) target = torch.randn(10) out = net(input) loss = criterion(out, target) print(100 * "=") print(out, target) print("Loss:", loss) print(loss.grad_fn) # MSELoss print(loss.grad_fn.next_functions[0][0]) # Linear print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLU net.zero_grad() print('conv1.bias.grad before backward') print(net.conv1.bias.grad) loss.backward() print('conv1.bias.grad after backward') print(net.conv1.bias.grad)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 220, 220, 220, 1058, 13130, 12, 486, 12, 2999, 1467, 25, 2598, 198, 2, 2488, 13838, 220, 1058, 1976, ...
2.283105
438
from bottle import route, run, template gitdict = {'po2go':{'https://github.com/cadamswaite/po2go.git:master':'https://github.com/cadamswaite/po2go.git:gh-pages'}} # Handle http requests to the root address run(host='0.0.0.0', port=80)
[ 6738, 9294, 1330, 6339, 11, 1057, 11, 11055, 198, 198, 18300, 11600, 796, 1391, 6, 7501, 17, 2188, 10354, 90, 6, 5450, 1378, 12567, 13, 785, 14, 66, 324, 321, 2032, 64, 578, 14, 7501, 17, 2188, 13, 18300, 25, 9866, 10354, 6, 5450,...
2.474227
97
""" Leonard always DRIVES Sheldon (this module is the __main__ driver for Sheldon) """ import argparse import sys import os try: from cooper import Sheldon except: from .cooper import Sheldon # Extensions for python source files EXTENSIONS = [".py", ".mpy"] if __name__ == "__main__": main()
[ 37811, 198, 36185, 446, 1464, 10560, 42472, 34536, 357, 5661, 8265, 318, 262, 11593, 12417, 834, 4639, 329, 34536, 8, 198, 37811, 198, 11748, 1822, 29572, 198, 11748, 25064, 198, 11748, 28686, 198, 198, 28311, 25, 198, 220, 220, 220, 42...
3.164948
97
# -*- coding: utf-8 -*-
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628, 628, 628 ]
1.8125
16
"""Basic tests for the CherryPy core: request handling.""" from cherrypy.test import test test.prefer_parent_path() import cherrypy from cherrypy import _cptools, tools from cherrypy.lib import http, static import types import os localDir = os.path.dirname(__file__) log_file = os.path.join(localDir, "test.log") log_access_file = os.path.join(localDir, "access.log") favicon_path = os.path.join(os.getcwd(), localDir, "../favicon.ico") defined_http_methods = ("OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", "PROPFIND") tools.login_redir = _cptools.Tool('before_handler', login_redir) root.divorce = Divorce() cherrypy.config.update({ 'log.error_file': log_file, 'environment': 'test_suite', 'server.max_request_body_size': 200, 'server.max_request_header_size': 500, }) appconf = { '/': {'log.access_file': log_access_file}, '/method': {'request.methods_with_bodies': ("POST", "PUT", "PROPFIND")}, } cherrypy.tree.mount(root, config=appconf) # Client-side code # from cherrypy.test import helper if __name__ == '__main__': setup_server() helper.testmain()
[ 37811, 26416, 5254, 329, 262, 23165, 20519, 4755, 25, 2581, 9041, 526, 15931, 198, 198, 6738, 23612, 9078, 13, 9288, 1330, 1332, 198, 9288, 13, 3866, 2232, 62, 8000, 62, 6978, 3419, 198, 198, 11748, 23612, 9078, 198, 6738, 23612, 9078, ...
2.237847
576
# Solution 1 input = readInputFile("input.txt").strip() print(input) lowest = input.split("-")[0] highest = input.split("-")[1] current = int(input.split("-")[0]) print(lowest) print(highest) resultArr = [] while current <= int(highest): if checkNeverDecreaseRule(current) and checkHasAdjacentSame(current): resultArr.append(current) #print(checkNeverDecreaseRule(lowest)) #print(checkHasAdjacentSame(lowest)) current += 1 print(len(resultArr))
[ 2, 28186, 352, 198, 198, 15414, 796, 1100, 20560, 8979, 7203, 15414, 13, 14116, 11074, 36311, 3419, 198, 198, 4798, 7, 15414, 8, 198, 198, 9319, 395, 796, 5128, 13, 35312, 7203, 12, 4943, 58, 15, 60, 198, 35323, 796, 5128, 13, 35312...
2.715976
169
#Transactions classes. from e2e.Classes.Transactions.Transaction import Transaction from e2e.Classes.Transactions.Transactions import Transactions #TestError Exception. from e2e.Tests.Errors import TestError #RPC class. from e2e.Meros.RPC import RPC #Sleep standard function. from time import sleep #Verify a Transaction. #Verify the Transactions.
[ 2, 8291, 4658, 6097, 13, 198, 6738, 304, 17, 68, 13, 9487, 274, 13, 8291, 4658, 13, 48720, 1330, 45389, 198, 6738, 304, 17, 68, 13, 9487, 274, 13, 8291, 4658, 13, 8291, 4658, 1330, 46192, 198, 198, 2, 14402, 12331, 35528, 13, 198,...
3.330189
106
import pygame from graphics.component import Component
[ 11748, 12972, 6057, 198, 6738, 9382, 13, 42895, 1330, 35100, 628 ]
5.090909
11
import json import os.path import logging import csv from random import randint logger = logging.getLogger() logger.setLevel(logging.INFO)
[ 11748, 33918, 198, 11748, 28686, 13, 6978, 198, 11748, 18931, 198, 11748, 269, 21370, 198, 6738, 4738, 1330, 43720, 600, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 3419, 198, 6404, 1362, 13, 2617, 4971, 7, 6404, 2667, 13, ...
3.204545
44
from pathlib import Path import cv2 import json import math import numpy as np from argparse import ArgumentParser if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('input_dir', type=str, help='Directory where the frame image and the json label be') parser.add_argument('output_dir', type=str, help='Directory where the textline would be extracted to') parser.add_argument('--ext', type=str, default='png') args = parser.parse_args() input_dir = Path(args.input_dir) output_dir = Path(args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) jsons = list(input_dir.glob('*.json')) json_path: Path for json_path in jsons: label_dict = json.load(open(json_path, 'rt')) if len(label_dict['shapes']) == 0: continue frame = cv2.imread(str(json_path.with_suffix(f'.{args.ext}'))) for i, shape in enumerate(label_dict['shapes']): points = order_points(shape['points']) tl, tr, br, bl = points width = int(np.round(max([distance(tl, tr), distance(bl, br)]))) height = int(np.round(max([distance(tl, bl), distance(tr, br)]))) dst = np.array([[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]], dtype=np.float32) M = cv2.getPerspectiveTransform(np.array(points, dtype=np.float32), dst) warp = cv2.warpPerspective(frame, M, (width, height)) output_path = output_dir.joinpath(json_path.stem + f'.{args.ext}') cv2.imwrite(str(output_path), warp)
[ 6738, 3108, 8019, 1330, 10644, 198, 11748, 269, 85, 17, 198, 11748, 33918, 198, 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1822, 29572, 1330, 45751, 46677, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 124...
2.140898
802
# ***** BEGIN GPL LICENSE BLOCK ***** # # # This program 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 2 # of the License, or (at your option) any later version. # # This program 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 this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ***** END GPL LICENCE BLOCK ***** import bpy import os
[ 2, 25998, 9, 347, 43312, 38644, 38559, 24290, 9878, 11290, 25998, 9, 198, 2, 198, 2, 198, 2, 770, 1430, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 198, 2, 13096, 340, 739, 262, 2846, 286, 262, 22961, 3611, 5094...
3.728111
217
#!/usr/bin/env python3 # # Proxy alerts generated by Prometheus Alertmanager turning them into # nagios passive alert information. # # Copyright 2019-2020, PostgreSQL Infrastructure Team # Author: Magnus Hagander # import argparse import http.server import json import time import sys missed_alerts = 0 if __name__ == "__main__": global args parser = argparse.ArgumentParser( description="Create nagios alerts from prometheus monitors" ) parser.add_argument('--hostsuffix', help='Suffix to add to hostnamees') parser.add_argument('--port', help='TCP port to bind to') parser.add_argument('--nagioscmd', help='Path to nagios command file') args = parser.parse_args() if not args.port: print("Port must be specified") sys.exit(1) if not args.nagioscmd: print("Nagios command path must be specified") sys.exit(1) server_address = ('localhost', int(args.port)) httpd = http.server.HTTPServer(server_address, NotificationHandler) httpd.serve_forever()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 198, 2, 38027, 21675, 7560, 416, 42696, 23276, 37153, 6225, 606, 656, 198, 2, 299, 363, 4267, 14513, 7995, 1321, 13, 198, 2, 198, 2, 15069, 13130, 12, 42334, 11, 2947, 47701, ...
2.870879
364
#!/usr/bin/env python # -*- coding: utf-8 -*- # # __init__.py # @Author : wanhanwan (wanshuai_shufe@163.com) # @Date : 2019/11/25 1:20:12 from .filter import llt_filter
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 11593, 15003, 834, 13, 9078, 198, 2, 2488, 13838, 1058, 266, 272, 7637, 8149, 357, 86, 504, 13415, 1872, ...
2.125
80