content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# -*- coding: utf-8 -*- import os import urllib.parse from datetime import date, datetime from functools import partial from urllib.parse import quote_plus import pandas as pd import plotly.express as px import pytz from csci_utils.luigi.requires import Requirement, Requires from csci_utils.luigi.target import TargetOutput from django.template.loader import render_to_string from luigi import ( DateParameter, ExternalTask, ListParameter, LocalTarget, Parameter, Target, Task, ) from plotly.io import to_image from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail from .models import Subscription from .tasks_fetch import ConvertAQIFileToParquet
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 2956, 297, 571, 13, 29572, 198, 6738, 4818, 8079, 1330, 3128, 11, 4818, 8079, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 2956, 2...
3.051724
232
#!/usr/bin/env python3 # Converts MCO annotation into pseudo English phonetics for use by the aeneas alignment package # lines prefixed with '#' are returned with the '#' removed, but otherwise unchanged. if __name__ == "__main__": test()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 628, 198, 2, 1482, 24040, 337, 8220, 23025, 656, 24543, 3594, 32896, 14596, 329, 779, 416, 262, 257, 1734, 292, 19114, 5301, 198, 2, 3951, 7694, 2966, 351, 705, 2, 6, 389, 4504, 351, ...
3.378378
74
import pytest from django.test import TestCase, Client from django.core.urlresolvers import reverse from molo.core.tests.base import MoloTestCaseMixin from molo.core.models import Main, SiteLanguageRelation, Languages from molo.usermetadata.models import PersonaIndexPage, PersonaPage from wagtail.wagtailcore.models import Site from wagtail.contrib.settings.context_processors import SettingsProxy
[ 11748, 12972, 9288, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 11, 20985, 198, 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, 690, 1330, 9575, 198, 198, 6738, 285, 14057, 13, 7295, 13, 41989, 13, 8692, 1330, 337, 14057, ...
3.589286
112
import psycopg2 url = "dbname='da43n1slakcjkc' user='msqgxzgmcskvst' host='ec2-54-80-184-43.compute-1.amazonaws.com' port=5432 password='9281f925b1e2298e8d62812d9d4e430c1054db62e918c282d7039fa85b1759fa'"
[ 11748, 17331, 22163, 70, 17, 198, 198, 6371, 796, 366, 9945, 3672, 11639, 6814, 3559, 77, 16, 6649, 461, 66, 73, 74, 66, 6, 2836, 11639, 907, 80, 70, 87, 89, 39870, 6359, 74, 85, 301, 6, 2583, 11639, 721, 17, 12, 4051, 12, 1795,...
1.915888
107
from constants import cursor
[ 6738, 38491, 1330, 23493, 628, 628, 198 ]
4.714286
7
import numpy as np import shapely.geometry as geom
[ 11748, 299, 32152, 355, 45941, 198, 11748, 5485, 306, 13, 469, 15748, 355, 4903, 296, 198 ]
3.1875
16
from django.contrib import admin from .models import Tag, Article
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 764, 27530, 1330, 17467, 11, 10172, 628, 628, 198 ]
3.55
20
#!/usr/bin/env python3 # Copyright (c) 2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Useful Script constants and utils.""" from test_framework.script import CScript # To prevent a "tx-size-small" policy rule error, a transaction has to have a # non-witness size of at least 82 bytes (MIN_STANDARD_TX_NONWITNESS_SIZE in # src/policy/policy.h). Considering a Tx with the smallest possible single # input (blank, empty scriptSig), and with an output omitting the scriptPubKey, # we get to a minimum size of 60 bytes: # # Tx Skeleton: 4 [Version] + 1 [InCount] + 1 [OutCount] + 4 [LockTime] = 10 bytes # Blank Input: 32 [PrevTxHash] + 4 [Index] + 1 [scriptSigLen] + 4 [SeqNo] = 41 bytes # Output: 8 [Amount] + 1 [scriptPubKeyLen] = 9 bytes # # Hence, the scriptPubKey of the single output has to have a size of at # least 22 bytes, which corresponds to the size of a P2WPKH scriptPubKey. # The following script constant consists of a single push of 21 bytes of 'a': # <PUSH_21> <21-bytes of 'a'> # resulting in a 22-byte size. It should be used whenever (small) fake # scriptPubKeys are needed, to guarantee that the minimum transaction size is # met. DUMMY_P2WPKH_SCRIPT = CScript([b'a' * 21])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 357, 66, 8, 13130, 383, 6185, 7231, 6505, 198, 2, 4307, 6169, 739, 262, 17168, 3788, 5964, 11, 766, 262, 19249, 198, 2, 2393, 27975, 45761, 393, 2638, 1378, 2503, 13, ...
3.179856
417
#!/usr/bin/env python # # Copyright (C) 2006 British Broadcasting Corporation and Kamaelia Contributors(1) # All Rights Reserved. # # You may only modify and redistribute this under the terms of any of the # following licenses(2): Mozilla Public License, V1.1, GNU General # Public License, V2.0, GNU Lesser General Public License, V2.1 # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://kamaelia.sourceforge.net/AUTHORS - please extend this file, # not this notice. # (2) Reproduced in the COPYING file, and at: # http://kamaelia.sourceforge.net/COPYING # Under section 3.5 of the MPL, we are using this text since we deem the MPL # notice inappropriate for this file. As per MPL/GPL/LGPL removal of this # notice is prohibited. # # Please contact us via: kamaelia-list-owner@lists.sourceforge.net # to discuss alternative licensing. # ------------------------------------------------------------------------- # Licensed to the BBC under a Contributor Agreement: RJL """(Bit)Torrent IPC messages""" from Kamaelia.BaseIPC import IPC # ====================== Messages to send to TorrentMaker ======================= # ========= Messages for TorrentPatron to send to TorrentService ================ # a message for TorrentClient (i.e. to be passed on by TorrentService) # request to add a TorrentPatron to a TorrentService's list of clients # request to remove a TorrentPatron from a TorrentService's list of clients # ==================== Messages for TorrentClient to produce ==================== # a new torrent has been added with id torrentid # the torrent you requested me to download is already being downloaded as torrentid # for some reason the torrent could not be started # message containing the current status of a particular torrent # ====================== Messages to send to TorrentClient ====================== # create a new torrent (a new download session) from a .torrent file's binary contents # close a running torrent
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 357, 34, 8, 4793, 3517, 32250, 10501, 290, 509, 1689, 25418, 25767, 669, 7, 16, 8, 198, 2, 220, 220, 220, 220, 1439, 6923, 33876, 13, 198, 2, 198, 2, 921, 743, ...
3.815939
527
from __future__ import print_function, unicode_literals from binascii import unhexlify from enum import Enum import os import pwd import six from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, Enum as SQLAEnum, Numeric from sqlalchemy import event from sqlalchemy.dialects.postgresql import HSTORE from sqlalchemy.schema import Table, FetchedValue, CheckConstraint, ForeignKey, DDL from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.ext.mutable import MutableDict from .compat import MemberCompat, SocietyCompat, AdminsSetCompat __all__ = ["Member", "Society", "PendingAdmin", "POSTGRES_USER", "RESTRICTED"] # Should we make the notes & danger flags, and pending-admins # tables available? # These postgres roles have special permissions / are mentioned # in the schema. Everyone else should connect as 'nobody' schema_users = ("root", "srcf-admin", "hades") # When connecting over a unix socket, postgres uses `getpeereid` # for authentication; this is the number that matters: euid_name = pwd.getpwuid(os.geteuid()).pw_name if euid_name in schema_users or euid_name.endswith("-adm"): POSTGRES_USER = euid_name else: POSTGRES_USER = "nobody" is_root = POSTGRES_USER == "root" or POSTGRES_USER.endswith("-adm") is_webapp = POSTGRES_USER == "srcf-admin" is_hades = POSTGRES_USER == "hades" RESTRICTED = not is_root CRSID_TYPE = String(7) SOCIETY_TYPE = String(16) Base = declarative_base() society_admins = Table( 'society_admins', Base.metadata, Column('crsid', CRSID_TYPE, ForeignKey('members.crsid'), primary_key=True), Column('society', SOCIETY_TYPE, ForeignKey('societies.society'), primary_key=True), ) if is_root or is_webapp: JobState = SQLAEnum('unapproved', 'queued', 'running', 'done', 'failed', 'withdrawn', name='job_state') LogType = SQLAEnum('created', 'started', 'progress', 'output', 'done', 'failed', 'note', name='log_type') LogLevel = SQLAEnum('debug', 'info', 'warning', 'error', 'critical', name='log_level') event.listen( Base.metadata, "before_create", DDL("CREATE EXTENSION hstore") ) else: PendingAdmin = None LogLevel = None Domain = None HTTPSCert = None JobState = None Job = None JobLog = None if __name__ == "__main__": dump_schema()
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 9874, 292, 979, 72, 1330, 555, 33095, 75, 1958, 198, 6738, 33829, 1330, 2039, 388, 198, 11748, 28686, 198, 11748, 279, 16993, 198, 198, 11...
2.602051
975
import os import numpy as np import pytest import vtk import pyvista from pyvista import examples from pyvista.plotting import system_supports_plotting beam = pyvista.UnstructuredGrid(examples.hexbeamfile) # create structured grid x = np.arange(-10, 10, 2) y = np.arange(-10, 10, 2) z = np.arange(-10, 10, 2) x, y, z = np.meshgrid(x, y, z) sgrid = pyvista.StructuredGrid(x, y, z) try: test_path = os.path.dirname(os.path.abspath(__file__)) test_data_path = os.path.join(test_path, 'test_data') except: test_path = '/home/alex/afrl/python/source/pyvista/tests' def test_grid_points(): """Test the points methods on UniformGrid and RectilinearGrid""" points = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]]) grid = pyvista.UniformGrid() grid.points = points assert grid.dimensions == [2, 2, 2] assert grid.spacing == [1, 1, 1] assert grid.origin == [0., 0., 0.] assert np.allclose(np.unique(grid.points, axis=0), np.unique(points, axis=0)) opts = np.c_[grid.x, grid.y, grid.z] assert np.allclose(np.unique(opts, axis=0), np.unique(points, axis=0)) # Now test rectilinear grid del grid grid = pyvista.RectilinearGrid() grid.points = points assert grid.dimensions == [2, 2, 2] assert np.allclose(np.unique(grid.points, axis=0), np.unique(points, axis=0)) def test_grid_extract_selection_points(): grid = pyvista.UnstructuredGrid(sgrid) sub_grid = grid.extract_selection_points([0]) assert sub_grid.n_cells == 1 sub_grid = grid.extract_selection_points(range(100)) assert sub_grid.n_cells > 1 def test_gaussian_smooth(): uniform = examples.load_uniform() active = uniform.active_scalars_name values = uniform.active_scalars uniform = uniform.gaussian_smooth(scalars=active) assert uniform.active_scalars_name == active assert uniform.active_scalars.shape == values.shape assert not np.all(uniform.active_scalars == values) values = uniform.active_scalars uniform = uniform.gaussian_smooth(radius_factor=5, std_dev=1.3) assert uniform.active_scalars_name == active assert uniform.active_scalars.shape == values.shape assert not np.all(uniform.active_scalars == values)
[ 11748, 28686, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 11748, 410, 30488, 198, 198, 11748, 12972, 85, 12523, 198, 6738, 12972, 85, 12523, 1330, 6096, 198, 6738, 12972, 85, 12523, 13, 29487, 889, 1330, 1080, ...
2.271218
1,084
import asyncio import logging from collections import defaultdict from typing import Optional, List, Dict from aiohttp import web from aiohttp.web_runner import AppRunner, TCPSite from quadradiusr_server.auth import Auth from quadradiusr_server.config import ServerConfig from quadradiusr_server.cron import Cron, SetupService from quadradiusr_server.db.base import Game, Lobby from quadradiusr_server.db.database_engine import DatabaseEngine from quadradiusr_server.db.repository import Repository from quadradiusr_server.game import GameInProgress from quadradiusr_server.lobby import LiveLobby from quadradiusr_server.notification import NotificationService from quadradiusr_server.utils import import_submodules routes = web.RouteTableDef() def get_url(self, protocol: str = 'http') -> str: # TCPSite.name is not implemented properly self._ensure_started() addr = self.address scheme = self._get_scheme(protocol) return f'{scheme}://{addr[0]}:{addr[1]}' def get_href(self, protocol: str = 'http') -> str: if self.config.href: return f'{self._get_scheme(protocol)}://{self.config.href}' else: return self.get_url(protocol) def run(self) -> int: loop = asyncio.new_event_loop() try: loop.run_until_complete(self._run_async()) return 0 except KeyboardInterrupt: logging.info('Interrupted') loop.run_until_complete(self.shutdown()) return -1 finally: loop.close() def register_gateway(self, gateway): user_id = gateway.user_id self.gateway_connections[user_id].append(gateway) def unregister_gateway(self, gateway): user_id = gateway.user_id self.gateway_connections[user_id].remove(gateway) def start_lobby(self, lobby: Lobby) -> LiveLobby: if lobby.id_ not in self.lobbies.keys(): self.lobbies[lobby.id_] = LiveLobby( lobby.id_, self.repository, self.notification_service) return self.lobbies[lobby.id_] def start_game(self, game: Game) -> GameInProgress: if game.id_ not in self.games.keys(): self.games[game.id_] = GameInProgress( game, self.repository, self.config.game) return self.games[game.id_] # importing submodules automatically registers endpoints import quadradiusr_server.rest import_submodules(quadradiusr_server.rest)
[ 11748, 30351, 952, 198, 11748, 18931, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 19720, 1330, 32233, 11, 7343, 11, 360, 713, 198, 198, 6738, 257, 952, 4023, 1330, 3992, 198, 6738, 257, 952, 4023, 13, 12384, 62, 16737, 1330, 2034, ...
2.5
1,000
gfg(2) gfg(3,[3,2,1]) gfg(3)
[ 198, 70, 40616, 7, 17, 8, 198, 70, 40616, 7, 18, 17414, 18, 11, 17, 11, 16, 12962, 198, 70, 40616, 7, 18, 8, 198 ]
1.2
25
import json, pickle, sys, os from parmed.geometry import distance2 from parmed.topologyobjects import Atom import operator import parmed import math if __name__ == "__main__": # Define the input res_atom = sys.argv[1] prot_file = sys.argv[2] find_interaction(res_atom, prot_file)
[ 11748, 33918, 11, 2298, 293, 11, 25064, 11, 28686, 198, 6738, 1582, 1150, 13, 469, 15748, 1330, 5253, 17, 198, 6738, 1582, 1150, 13, 4852, 1435, 48205, 1330, 33102, 198, 11748, 10088, 198, 11748, 1582, 1150, 198, 11748, 10688, 628, 628,...
2.72973
111
"""Module help_info.""" __author__ = 'Joan A. Pinol (japinol)'
[ 37811, 26796, 1037, 62, 10951, 526, 15931, 201, 198, 834, 9800, 834, 796, 705, 9908, 272, 317, 13, 13727, 349, 220, 357, 73, 499, 259, 349, 33047, 201, 198, 201, 198 ]
2.193548
31
import warnings warnings.simplefilter('ignore') import argparse import pickle import numpy as np import pandas as pd import networkx as nx import scipy.sparse as sp from network_propagation_methods import minprop_2 from sklearn.metrics import roc_auc_score, auc import matplotlib.pyplot as plt #### Parameters ############# parser = argparse.ArgumentParser(description='Runs MINProp') parser.add_argument('--alphaP', type=float, default=0.25, help='diffusion parameter for the protein-protein interaction network') parser.add_argument('--alphaD', type=float, default=0.25, help='diffusion parameter for the disease similarity network') parser.add_argument('--max_iter', type=int, default=1000, help='maximum number of iterations') parser.add_argument('--eps', type=float, default=1.0e-6, help='convergence threshold') parser.add_argument('--dir_data', type=str, default='./data/', help='directory of pickled network data') args = parser.parse_args() #### load data ############ ### protein-protein interaction network with open(args.dir_data + 'norm_adj_networkP.pickle', mode='rb') as f: norm_adj_networkP = pickle.load(f) nb_proteins = norm_adj_networkP.shape[0] ### disease similarity network with open(args.dir_data + 'adj_networkD.pickle', mode='rb') as f: adj_networkD = pickle.load(f) nb_diseases = adj_networkD.shape[0] # normalized adjacency matrix deg_networkD = np.sum(adj_networkD, axis=0) norm_adj_networkD = sp.csr_matrix(adj_networkD / np.sqrt(np.dot(deg_networkD.T, deg_networkD)), dtype=np.float64) del(adj_networkD) del(deg_networkD) ### protein-disease network (data used in PRINCE study) with open(args.dir_data + 'biadj_networkPD.pickle', mode='rb') as f: biadj_networkPD = pickle.load(f) # get the list of protein-disease pairs PD_pairs = biadj_networkPD.nonzero() # number of protein-disease pairs nb_PD_pairs = len(PD_pairs[0]) #### Network propagation MINProp ########################### roc_value_set = np.array([], dtype=np.float64) rankings = np.array([], dtype=np.int64) for i in range(nb_PD_pairs): # leave-one-out validation # remove a protein-disease association idx_P = PD_pairs[0][i] idx_D = PD_pairs[1][i] biadj_networkPD[idx_P, idx_D] = 0.0 biadj_networkPD.eliminate_zeros() # normalized biadjacency matrix (ToDo: faster implementation) degP = np.sum(biadj_networkPD, axis=1) degD = np.sum(biadj_networkPD, axis=0) norm_biadj_networkPD = sp.csr_matrix(biadj_networkPD / np.sqrt(np.dot(degP, degD)), dtype=np.float64) norm_biadj_networkPD.data[np.isnan(norm_biadj_networkPD.data)] = 0.0 norm_biadj_networkPD.eliminate_zeros() # set initial label yP = np.zeros(nb_proteins, dtype=np.float64) yD = np.zeros(nb_diseases, dtype=np.float64) yD[idx_D] = 1.0 # propagation fP, fD, convergent = minprop_2(norm_adj_networkP, norm_adj_networkD, norm_biadj_networkPD, yP, yD, args.alphaP, args.alphaD, args.eps, args.max_iter) # ranking labels_real = np.zeros(nb_proteins) labels_real[idx_P] = 1 rank = int(np.where(labels_real[np.argsort(-fP)]==1)[0]) + 1 rankings = np.append(rankings, rank) # get AUC value roc_value = roc_auc_score(labels_real, fP) print(i, "AUC:", roc_value, convergent) roc_value_set = np.append(roc_value_set, roc_value) # reassign the protein-disease association biadj_networkPD[idx_P, idx_D] = 1.0 print("Average AUC", np.mean(roc_value_set)) # compute sensitivity and top rate (ROC-like curve) # ToDo: faster implementation sen_set = np.array([], dtype=np.float64) top_rate_set = np.array([], dtype=np.float64) for k in range(nb_proteins): # sensitibity sen = (rankings <= (k+1)).sum() / nb_PD_pairs # top rate top_rate = (k + 1) / nb_proteins sen_set = np.append(sen_set, sen) top_rate_set = np.append(top_rate_set, top_rate) # get AUC value print("Summarized AUC", auc(top_rate_set, sen_set)) # plot ROC-like curve plt.scatter(top_rate_set, sen_set) plt.show()
[ 11748, 14601, 198, 40539, 654, 13, 36439, 24455, 10786, 46430, 11537, 198, 198, 11748, 1822, 29572, 198, 11748, 2298, 293, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 3127, 87, 355, 299, 87, 198...
2.53856
1,569
n = [] i = 0 for c in range(0, 5): n1 = int(input('Digite um valor: ')) if c == 0 or n1 > n[-1]: n.append(n1) print(f'Adicionado na posio {c} da lista...') else: pos = 0 while pos < len(n): if n1 <= n[pos]: n.insert(pos, n1) print(f'Adicionado na posio {pos} da lista...') break pos += 1 print(f'Os valores digitados em ordem foram {n}')
[ 77, 796, 17635, 198, 72, 796, 657, 198, 1640, 269, 287, 2837, 7, 15, 11, 642, 2599, 198, 220, 220, 220, 299, 16, 796, 493, 7, 15414, 10786, 19511, 578, 23781, 1188, 273, 25, 705, 4008, 198, 220, 220, 220, 611, 269, 6624, 657, 39...
1.763566
258
import cv2 import numpy as np import random import copy import dlib from keras.models import Sequential from keras.optimizers import SGD from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras.models import load_model from convnetskeras.convnets import preprocess_image_batch, convnet from convnetskeras.imagenet_tool import synset_to_dfs_ids np.set_printoptions(threshold=np.inf) #----------------------------Globals------------------------------------------------------------ MIN_AREA = 20 MAX_AREA = 500 MIN_RED_DENSITY = 0.4 MIN_BLACk_DENSITY_BELOW = 0 MIN_POLYAPPROX = 3 WIDTH_HEIGHT_RATIO = [0.333, 1.5] #range #------------------------------------------------------------------------------------------------ tracker_list = [] TRACK_FRAME = 10 VOTE_FRAME = 3 frame0_detections = [] frame1_detections = [] frame2_detections = [] frame_detections = [] RADIAL_DIST = 10 #------------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------------------------ BOUNDING_BOX = [0,0,0,0] #x1, y1, x2, y2 #------------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------------------------ print "Loading model" model = create_model() model.load_weights("../model/traffic_light_weights.h5") #------------------------------------------------------------------------------------------------ sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True) model_heatmap = convnet('vgg_19',weights_path="../model/weights/vgg19_weights.h5", heatmap=True) model_heatmap.compile(optimizer=sgd, loss='mse') traffic_light_synset = "n06874185" ids = synset_to_dfs_ids(traffic_light_synset) #------------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------------------------ clipnum = raw_input("Enter Clip number:\n") f=open('../../dayTrain/dayClip'+str(clipnum)+'/frameAnnotationsBULB.csv','r') inputs=f.read() f.close(); inputs=inputs.split() inputs=[i.split(";") for i in inputs] for i in range(21): inputs.pop(0) # fourcc = cv2.VideoWriter_fourcc(*'XVID') fourcc = cv2.cv.CV_FOURCC(*'XVID') out = cv2.VideoWriter('output'+str(clipnum)+'.avi',fourcc, 20.0, (1280,960)) #------------------------------------------------------------------------------------------------ frame_num = -1 VIOLATION = -1 for i in inputs: if i[1]=="stop": filename="../../dayTrain/dayClip"+str(clipnum)+"/frames/"+i[0][12:len(i[0])] original_img=cv2.imread(filename) img=copy.copy(original_img) height, width, channels = img.shape if(frame_num == -1): center_x = width/2 center_y = height/2 BB_width = width/4 BB_height = height/4 BOUNDING_BOX = [center_x-BB_width,center_y-BB_height,center_x + BB_width, center_y + BB_height ] frame_num += 1 #------------------detection begins-------------------------------------------------------- if(frame_num % TRACK_FRAME < VOTE_FRAME): #VOTE_FRAME = 3, then 0,1,2 allowed #------------------reset------------------------ if(frame_num % TRACK_FRAME == 0): tracker_list = [] frame0_detections = [] frame1_detections = [] frame2_detections = [] #------------------reset------------------------ #-----------preprocess------------------------------------ img = cv2.medianBlur(img,3) # Median Blur to Remove Noise img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) b,g,r = cv2.split(img) clahe = cv2.createCLAHE(clipLimit=7.0, tileGridSize=(8,8)) # Adaptive histogram equilization clahe = clahe.apply(r) img = cv2.merge((b,g,clahe)) #---------------------------------------------------------- #----------red threshold the HSV image-------------------- img1 = cv2.inRange(img, np.array([0, 100, 100]), np.array([10,255,255])) #lower red hue img2 = cv2.inRange(img, np.array([160, 100, 100]), np.array([179,255,255])) #upper red hue img3 = cv2.inRange(img, np.array([160, 40, 60]), np.array([180,70,80])) img4 = cv2.inRange(img, np.array([0, 150, 40]), np.array([20,190,75])) img5 = cv2.inRange(img, np.array([145, 35, 65]), np.array([170,65,90])) img = cv2.bitwise_or(img1,img3) img = cv2.bitwise_or(img,img2) img = cv2.bitwise_or(img,img4) img = cv2.bitwise_or(img,img5) cv2.medianBlur(img,7) ret,thresh = cv2.threshold(img,127,255,0) #---------------------------------------------------------- #--------------------Heatmap------------------------------------ im_heatmap = preprocess_image_batch([filename], color_mode="bgr") out_heatmap = model_heatmap.predict(im_heatmap) heatmap = out_heatmap[0,ids].sum(axis=0) my_range = np.max(heatmap) - np.min(heatmap) heatmap = heatmap / my_range heatmap = heatmap * 255 heatmap = cv2.resize(heatmap,(width,height)) cv2.imwrite("heatmap.png",heatmap) cv2.imwrite("image.png",original_img) heatmap[heatmap < 128] = 0 # Black heatmap[heatmap >= 128] = 255 # White heatmap = np.asarray(heatmap,dtype=np.uint8) #---------------------------------------------------------- thresh = cv2.bitwise_and(thresh,heatmap) #---------------------------------------------------------- contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) for cnt in contours: area = cv2.contourArea(cnt) x,y,w,h = cv2.boundingRect(cnt) red_density = (area*1.0)/(w*h) width_height_ratio = (w*1.0)/h perimeter = cv2.arcLength(cnt, True) approx = cv2.approxPolyDP(cnt, 0.04 * perimeter, True) temp=cv2.cvtColor(original_img[y+h:y+2*h,x:x+w], cv2.COLOR_RGB2GRAY) (thresh, temp) = cv2.threshold(temp, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) black_density_below = ((w*h - cv2.countNonZero(temp))*1.0)/(w*h) if area>MIN_AREA and area<MAX_AREA and len(approx) > MIN_POLYAPPROX and red_density > MIN_RED_DENSITY and width_height_ratio < WIDTH_HEIGHT_RATIO[1] and width_height_ratio > WIDTH_HEIGHT_RATIO[0] and black_density_below > MIN_BLACk_DENSITY_BELOW: try: r_x1=x-50 r_y1=y-50 r_x2=x+w+50 r_y2=y+h+50 temp=original_img[r_y1:r_y2,r_x1:r_x2] xx=cv2.resize(temp,(128,128)) xx=np.asarray(xx) xx=np.transpose(xx,(2,0,1)) xx=np.reshape(xx,(1,3,128,128)) if model.predict_classes(xx,verbose=0)==[1]: cv2.rectangle(original_img, (x,y), (x+w,y+h),(0,255,0), 2) #append detections if frame_num % TRACK_FRAME == 0: frame0_detections.append((x,y,w,h)) elif frame_num%TRACK_FRAME == 1: frame1_detections.append((x,y,w,h)) elif frame_num%TRACK_FRAME == 2: frame2_detections.append((x,y,w,h)) else: cv2.rectangle(original_img, (x,y), (x+w,y+h),(255,0,0), 1) except Exception as e: cv2.rectangle(original_img, (x,y), (x+w,y+h),(0,255,0), 2) #edges are allowed print e pass #--------------------Violation in Detect Phase------------------------------ frame_detections = [] if(frame_num % TRACK_FRAME == 0): frame_detections = frame0_detections if(frame_num % TRACK_FRAME == 1): frame_detections = frame1_detections if(frame_num % TRACK_FRAME == 2): frame_detections = frame2_detections #--------------------Violation in Detect Phase------------------------------ #compute and start tracking if frame_num % TRACK_FRAME == 2: all_detections = frame0_detections + frame1_detections + frame2_detections final_detections = prune_detection(all_detections) for (x,y,w,h) in final_detections: tracker = dlib.correlation_tracker() tracker.start_track(original_img, dlib.rectangle(x,y,(x+w),(y+h))) tracker_list.append(tracker) #------------------detection end---------------------------------------------------- #------------------tracking begins---------------------------------------------------- else: frame_detections = [] for tracker in tracker_list: tracker.update(original_img) rect = tracker.get_position() pt1 = (int(rect.left()), int(rect.top())) pt2 = (int(rect.right()), int(rect.bottom())) cv2.rectangle(original_img, pt1, pt2, (255, 255, 255), 2) frame_detections.append((pt1[0], pt1[1], pt2[0]-pt1[0], pt2[1]-pt1[1])) #------------------ tracking end---------------------------------------------------- if(is_violation(frame_detections) == True): cv2.rectangle(original_img, (BOUNDING_BOX[0],BOUNDING_BOX[1]), (BOUNDING_BOX[2],BOUNDING_BOX[3]),(0, 0, 255), 2) else: cv2.rectangle(original_img, (BOUNDING_BOX[0],BOUNDING_BOX[1]), (BOUNDING_BOX[2],BOUNDING_BOX[3]),(60, 255, 255), 2) cv2.imshow("Annotated",original_img) out.write(original_img) ch = 0xFF & cv2.waitKey(1) if ch == 27: break cv2.destroyAllWindows() #------------------------------------------------------------------------------------------------
[ 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 198, 11748, 4866, 198, 11748, 288, 8019, 198, 198, 6738, 41927, 292, 13, 27530, 1330, 24604, 1843, 198, 6738, 41927, 292, 13, 40085, 11341, 1330, 26147, 35, 198, ...
2.239275
5,128
######################################################################################################################## # # # This file is part of kAIvy # # # # Copyright (c) 2019-2021 by the kAIvy team and contributors # # # ######################################################################################################################## import numpy as np from kaivy.geometry.geometry2d import Geometry2D from kaivy.geometry.transformation2d import Transformation2D from kivy.graphics import Line, SmoothLine, Color
[ 29113, 29113, 29113, 14468, 7804, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 2...
1.675762
623
import copy from pathlib import Path from typing import Dict, Union, List from collections import defaultdict import numpy as np from typeguard import typechecked from zsvision.zs_utils import memcache, concat_features from utils.util import memory_summary from base.base_dataset import BaseDataset
[ 11748, 4866, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 360, 713, 11, 4479, 11, 7343, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2099, 14864, 1330, 2099, 26752, 198, 6738, 1...
3.682927
82
from django import forms from django.forms.models import inlineformset_factory from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailadmin.widgets import AdminPageChooser from wagtail.wagtailsearch import models EditorsPickFormSetBase = inlineformset_factory(models.Query, models.EditorsPick, form=EditorsPickForm, can_order=True, can_delete=True, extra=0)
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 42625, 14208, 13, 23914, 13, 27530, 1330, 26098, 687, 2617, 62, 69, 9548, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, 4808, 198, 198, 6738, 266, ...
3.235294
119
""" Copyright BOOSTRY Co., Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 """ from typing import ( List, Dict, Any ) from pydantic import BaseModel from fastapi.openapi.utils import get_openapi from fastapi.exceptions import RequestValidationError from app.exceptions import ( InvalidParameterError, SendTransactionError, AuthorizationError, ServiceUnavailableError ) DEFAULT_RESPONSE = { 400: { "description": "Invalid Parameter Error / Send Transaction Error", "model": Error400Model }, 401: { "description": "Authorization Error", "model": Error401Model }, 404: { "description": "Not Found Error", "model": Error404Model }, 405: { "description": "Method Not Allowed", "model": Error405Model }, 422: { "description": "Validation Error", "model": Error422Model }, 503: { "description": "Service Unavailable Error", "model": Error503Model } }
[ 37811, 198, 15269, 347, 6684, 2257, 18276, 1766, 1539, 12052, 13, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 1...
2.863469
542
import os import sys sys.path.insert(0, "../../") import matchzoo as mz import typing import pandas as pd import matchzoo from matchzoo.preprocessors.units.tokenize import Tokenize, WordPieceTokenize from matchzoo.engine.base_preprocessor import load_preprocessor import pickle import utils os.environ["CUDA_VISIBLE_DEVICES"] = "6" input_dir = "../../data/" model_dir = "../../models/arcii" num_epochs = 10 utils.ensure_dir(model_dir) with open(os.path.join(input_dir, "train.pkl"), 'rb') as f: train_pack_processed = pickle.load(f) print(train_pack_processed.frame().head()) with open(os.path.join(input_dir, "test.pkl"), 'rb') as f: test_pack_processed = pickle.load(f) print(test_pack_processed.frame().head()) preprocessor = load_preprocessor(dirpath=os.path.join(input_dir)) print(preprocessor._context) glove_embedding = mz.datasets.embeddings.load_glove_embedding(dimension=100) ranking_task = mz.tasks.Classification() ranking_task.metrics = ['accuracy'] print("`ranking_task` initialized with metrics", ranking_task.metrics) model = mz.models.ArcII() model.params.update(preprocessor.context) model.params['task'] = ranking_task model.params['embedding_output_dim'] = 100 model.params['embedding_trainable'] = True model.params['num_blocks'] = 2 model.params['kernel_1d_count'] = 32 model.params['kernel_1d_size'] = 3 model.params['kernel_2d_count'] = [64, 64] model.params['kernel_2d_size'] = [3, 3] model.params['pool_2d_size'] = [[3, 3], [3, 3]] model.params['optimizer'] = 'adam' model.build() model.compile() model.backend.summary() embedding_matrix = glove_embedding.build_matrix(preprocessor.context['vocab_unit'].state['term_index']) model.load_embedding_matrix(embedding_matrix) test_x, test_y = test_pack_processed.unpack() evaluate = mz.callbacks.EvaluateAllMetrics(model, x=test_x, y=test_y, batch_size=128) dump_prediction = mz.callbacks.DumpPrediction(model, x=test_x, y=test_y, batch_size=128, model_save_path=model_dir) train_generator = mz.DataGenerator( train_pack_processed, num_dup=2, num_neg=1, batch_size=128, ) print('num batches:', len(train_generator)) history = model.fit_generator(train_generator, epochs=num_epochs, callbacks=[evaluate, dump_prediction], workers=4, use_multiprocessing=True)
[ 11748, 28686, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 366, 40720, 40720, 4943, 198, 198, 11748, 2872, 89, 2238, 355, 285, 89, 198, 11748, 19720, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2872, 89, ...
2.635104
866
# -*- coding: utf-8; -*- """AST markers for internal communication. *Internal* here means they are to be never passed to Python's `compile`; macros may use them to work together. """ __all__ = ["ASTMarker", "get_markers", "delete_markers", "check_no_markers_remaining"] import ast from . import core, utils, walkers def get_markers(tree, cls=ASTMarker): """Return a `list` of any `cls` instances found in `tree`. For output validation.""" w = ASTMarkerCollector() w.visit(tree) return w.collected def delete_markers(tree, cls=ASTMarker): """Delete any `cls` ASTMarker instances found in `tree`. The deletion takes place by replacing each marker node with the actual AST node stored in its `body` attribute. """ return ASTMarkerDeleter().visit(tree) def check_no_markers_remaining(tree, *, filename, cls=None): """Check that `tree` has no AST markers remaining. If a class `cls` is provided, only check for markers that `isinstance(cls)`. If there are any, raise `MacroExpansionError`. No return value. `filename` is the full path to the `.py` file, for error reporting. Convenience function. """ cls = cls or ASTMarker remaining_markers = get_markers(tree, cls) if remaining_markers: codes = [utils.format_context(node, n=5) for node in remaining_markers] locations = [utils.format_location(filename, node, code) for node, code in zip(remaining_markers, codes)] report = "\n\n".join(locations) raise core.MacroExpansionError(f"{filename}: AST markers remaining after expansion:\n{report}")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 26, 532, 9, 12, 198, 37811, 11262, 19736, 329, 5387, 6946, 13, 198, 198, 9, 37693, 9, 994, 1724, 484, 389, 284, 307, 1239, 3804, 284, 11361, 338, 4600, 5589, 576, 63, 26, 198, 20285, ...
2.856637
565
import boto3 import json import numpy as np import base64, os, boto3, ast, json endpoint = 'myprojectcapstone'
[ 11748, 275, 2069, 18, 198, 11748, 33918, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2779, 2414, 11, 28686, 11, 275, 2069, 18, 11, 6468, 11, 33918, 220, 628, 628, 198, 437, 4122, 796, 705, 1820, 16302, 11128, 6440, 6, 198, 220, ...
2.1
70
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import openvino.runtime.opset9 as ov import numpy as np import pytest from tests.runtime import get_runtime from openvino.runtime.utils.types import get_element_type_str from openvino.runtime.utils.types import get_element_type
[ 2, 15069, 357, 34, 8, 2864, 12, 1238, 1828, 8180, 10501, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 11748, 1280, 85, 2879, 13, 43282, 13, 404, 2617, 24, 355, 19643, 198, 11748, 299, 32152, ...
3.204082
98
from typing import List, Union from pytest import raises from graphql.error import GraphQLError, format_error from graphql.language import Node, Source from graphql.pyutils import Undefined
[ 6738, 19720, 1330, 7343, 11, 4479, 198, 198, 6738, 12972, 9288, 1330, 12073, 198, 198, 6738, 4823, 13976, 13, 18224, 1330, 29681, 48, 2538, 81, 1472, 11, 5794, 62, 18224, 198, 6738, 4823, 13976, 13, 16129, 1330, 19081, 11, 8090, 198, ...
3.784314
51
# -------------------------------------------------------- # (c) Copyright 2014 by Jason DeLaat. # Licensed under BSD 3-clause licence. # -------------------------------------------------------- import unittest from pymonad.Maybe import Maybe, Just, First, Last, _Nothing, Nothing from pymonad.Reader import curry from pymonad.test.MonadTester import * from pymonad.test.MonoidTester import * if __name__ == "__main__": unittest.main()
[ 2, 20368, 22369, 198, 2, 357, 66, 8, 15069, 1946, 416, 8982, 1024, 14772, 265, 13, 198, 2, 49962, 739, 347, 10305, 513, 12, 565, 682, 17098, 13, 198, 2, 20368, 22369, 198, 198, 11748, 555, 715, 395, 198, 6738, 12972, 2144, 324, 13...
3.745763
118
# Copyright 2022 Canonical Ltd. # See LICENSE file for licensing details. __version__ = "0.0.8" # flake8: noqa: F401,F402 from . import errors, events, relation, testing from .relation import EndpointWrapper
[ 2, 15069, 33160, 19507, 605, 12052, 13, 198, 2, 4091, 38559, 24290, 2393, 329, 15665, 3307, 13, 198, 834, 9641, 834, 796, 366, 15, 13, 15, 13, 23, 1, 198, 198, 2, 781, 539, 23, 25, 645, 20402, 25, 376, 21844, 11, 37, 32531, 198,...
3.181818
66
#!/usr/bin/python3 # Fetch torrent sizes # TODO: Report number of files before we go etc import os from torrentool.api import Torrent from fnmatch import fnmatch root = '/opt/radio/collections' pattern = "*.torrent" alltorrentsize = 0 print("Thanks for using The Librarian.") for path, subdirs, files in os.walk(root): for name in files: if fnmatch(name, pattern): torrentstats = Torrent.from_file(os.path.join(path, name)) alltorrentsize += torrentstats.total_size print('Torrent size ' + str(torrentstats.total_size) + ' for a total so far of ' + str(alltorrentsize)) print('DEBUG' + os.path.join(path, name)) # Reading filesize my_torrent = Torrent.from_file('/opt/radio/collections/arienscompanymanuals/archive.org/download/collection_01_ariens_manuals/collection_01_ariens_manuals_archive.torrent') size = my_torrent.total_size # Total files size in bytes. print(size)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 376, 7569, 24458, 10620, 198, 2, 16926, 46, 25, 6358, 1271, 286, 3696, 878, 356, 467, 3503, 198, 11748, 28686, 198, 6738, 24458, 970, 13, 15042, 1330, 43399, 198, 6738, 24714, 15699, ...
2.740525
343
""" Flask LoginManager plugin. Import and execute ``login.init_app(app)`` in a factory function to use. """ from typing import Any, Callable, TYPE_CHECKING from functools import wraps from flask import redirect, request, url_for, current_app from flask_login import current_user from flask_login.login_manager import LoginManager from .errors import IllegalAccessError if TYPE_CHECKING: from werkzeug.wrappers import Response login = LoginManager() def admin_required(func: Callable) -> Callable: """Make view only accessible to admins. Args: func: Callabe to wrap. Returns: Wrapped callable - only callable when user is an admin. """ return decorated_view
[ 37811, 46947, 23093, 13511, 13877, 13, 198, 198, 20939, 290, 12260, 7559, 38235, 13, 15003, 62, 1324, 7, 1324, 8, 15506, 287, 257, 8860, 2163, 284, 779, 13, 198, 198, 37811, 198, 198, 6738, 19720, 1330, 4377, 11, 4889, 540, 11, 41876,...
3.242009
219
from tkinter import * from ModeEnum import Mode import SerialHelper import Views.StaticView import Views.CustomWidgets.Silder from ColorEnum import Color from functools import partial from Views.CommandPanel import CommandPanel from Views.ListItem import ListItem from ProcessControl import ProcessManager, ProcessCommandEnum import os, signal menuBackgroundColor = "#262e30" menuForegroundColor = "#e5e4c5" menuActiveForegroundColor = menuForegroundColor menuActiveBackgroundColor = "#464743" mainBackgroundColor = "#1b2122" #from SerialHelper import getSerialPorts #for sp in getSerialPorts(): # print(sp) # Start the app up! app = App() app.master.title("RGB Lights 3000") app.master.config(menu=app.my_menu, background=mainBackgroundColor) #subprocess.call(["./controller.py", "/dev/ttyUSB0"]) # Start up the app and the process manager pid = os.fork() if pid: # parent app.mainloop() os.kill(pid, signal.SIGTERM) else: # child exec(open("./code/ProcessControl/ProcessManager.py").read()) #os.execlp("python3", "python3", "./ProcessControl/ProcessManager.py") #os.system("controller.py") #app.mainloop() #print("here")
[ 6738, 256, 74, 3849, 1330, 1635, 198, 6738, 10363, 4834, 388, 1330, 10363, 198, 11748, 23283, 47429, 198, 11748, 29978, 13, 45442, 7680, 198, 198, 11748, 29978, 13, 15022, 54, 312, 11407, 13, 50, 688, 263, 198, 6738, 5315, 4834, 388, ...
2.972222
396
import os import json import tempfile import shutil import unittest from sarpy.io.complex.sicd import SICDReader from sarpy.io.product.sidd import SIDDReader from sarpy.io.product.sidd_schema import get_schema_path from sarpy.processing.sidd.sidd_product_creation import create_detected_image_sidd, create_dynamic_image_sidd, create_csi_sidd from sarpy.processing.ortho_rectify import NearestNeighborMethod from tests import parse_file_entry try: from lxml import etree except ImportError: etree = None product_file_types = {} this_loc = os.path.abspath(__file__) file_reference = os.path.join(os.path.split(this_loc)[0], 'product_file_types.json') # specifies file locations if os.path.isfile(file_reference): with open(file_reference, 'r') as fi: the_files = json.load(fi) for the_type in the_files: valid_entries = [] for entry in the_files[the_type]: the_file = parse_file_entry(entry) if the_file is not None: valid_entries.append(the_file) product_file_types[the_type] = valid_entries sicd_files = product_file_types.get('SICD', [])
[ 11748, 28686, 198, 11748, 33918, 198, 11748, 20218, 7753, 198, 11748, 4423, 346, 198, 11748, 555, 715, 395, 198, 198, 6738, 264, 5117, 88, 13, 952, 13, 41887, 13, 21383, 67, 1330, 311, 2149, 35, 33634, 198, 6738, 264, 5117, 88, 13, ...
2.435146
478
import numpy as np import scipy.sparse as sp from westpa.tools import Plotter # A useful dataclass used as a wrapper for w_ipa to facilitate # ease-of-use in ipython/jupyter notebooks/sessions. # It basically just wraps up numpy arrays and dicts. # Similar to the above, but slightly expanded to contain information from analysis files. # This handles the 'schemes', and all assorted data.
[ 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 13, 82, 29572, 355, 599, 198, 198, 6738, 7421, 8957, 13, 31391, 1330, 28114, 353, 198, 198, 2, 317, 4465, 4818, 330, 31172, 973, 355, 257, 29908, 329, 266, 62, 541, 64, 284, ...
3.504425
113
import random # use of the random module print(random.random()) # a float value >= 0.0 and < 1.0 print(random.random()*100) # a float value >= 0.0 and < 100.0 # use of the randint method print(random.randint(1, 100)) # an int from 1 to 100 print(random.randint(101, 200)) # an int from 101 to 200 print(random.randint(0, 7)) # an int from 0 7 die1 = random.randint(1, 6) die2 = random.randint(1, 6) print("Your roll: ", die1, die2) print(random.randrange(1, 100)) # an int from 1 to 99 print(random.randrange(100, 200, 2)) # an even int from 100 to 198 print(random.randrange(11, 250, 2)) # an odd int from 11 to 249
[ 11748, 4738, 198, 198, 2, 779, 286, 262, 4738, 8265, 198, 4798, 7, 25120, 13, 25120, 28955, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1303, 257, 12178, 1988, 18189, 657, 13, 15, 290, 1279, 352, 13, 15, 198, 4798, 7, 25120, 13, ...
2.411348
282
from PyInquirer import style_from_dict, Token, prompt, Separator from lnt.graphics.utils import vars_to_string # Mark styles prompt_style = style_from_dict({ Token.Separator: '#6C6C6C', Token.QuestionMark: '#FF9D00 bold', #Token.Selected: '', # default Token.Selected: '#5F819D', Token.Pointer: '#FF9D00 bold', Token.Instruction: '', # default Token.Answer: '#5F819D bold', Token.Question: '', }) # Mark prompt configurations
[ 6738, 9485, 818, 29782, 81, 1330, 3918, 62, 6738, 62, 11600, 11, 29130, 11, 6152, 11, 8621, 283, 1352, 198, 6738, 300, 429, 13, 70, 11549, 13, 26791, 1330, 410, 945, 62, 1462, 62, 8841, 198, 198, 2, 2940, 12186, 198, 16963, 457, 6...
2.481283
187
import os import struct import json from time import sleep import hashlib import threading from socket import socket, AF_INET, SOCK_STREAM, SOCK_DGRAM from datetime import * from re import compile import time import logging
[ 11748, 28686, 198, 11748, 2878, 198, 11748, 33918, 198, 6738, 640, 1330, 3993, 198, 11748, 12234, 8019, 198, 11748, 4704, 278, 198, 6738, 17802, 1330, 17802, 11, 12341, 62, 1268, 2767, 11, 311, 11290, 62, 2257, 32235, 11, 311, 11290, 62...
3.612903
62
import mock from maildown import renderer import mistune import pygments from pygments import lexers from pygments.formatters import html import premailer import jinja2
[ 11748, 15290, 198, 6738, 17266, 688, 593, 1330, 9851, 11882, 198, 11748, 4020, 1726, 198, 11748, 12972, 11726, 198, 6738, 12972, 11726, 1330, 31191, 364, 198, 6738, 12972, 11726, 13, 18982, 1010, 1330, 27711, 198, 11748, 4199, 603, 263, 1...
3.638298
47
from generator import * from iterator import * if __name__ == "__main__": while True: print("Enter 1, if you want to generate prime Lucas Number.") print("Enter 2, if you want to iterate prime Lucas Number.") print("Or 0, if you want to get out: ") count = intInput("") if count == 1: n = nInput() print("First " + str(n) + " prime Lucas Number:") gen = generator(n) printGenerator(gen) elif count == 2: n = nInput() print("First " + str(n) + " prime Lucas Number:") iter = IteratorLucasNumbers() printIterator(iter) elif count == 0: break else: print("Enter 1, or 2, or 0!")
[ 6738, 17301, 1330, 1635, 198, 6738, 41313, 1330, 1635, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 981, 6407, 25, 198, 220, 220, 220, 220, 220, 220, 220, 3601, 7203, 17469, 352, 11, 611, 34...
2.163793
348
from setuptools import setup version = '1.0.10' setup( name='grail', version=version, classifiers=[ 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', ], packages=[ 'grail', ], description='Grail is a library which allows test script creation based on steps. ' 'It helps to structure your tests and get rid of additional test documentation for your code.', include_package_data=True, author='Wargaming.NET', author_email='web_qa_auto@wargaming.net', url='https://github.com/wgnet/grail' )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 9641, 796, 705, 16, 13, 15, 13, 940, 6, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 70, 30224, 3256, 198, 220, 220, 220, 2196, 28, 9641, 11, 198, 220, 220, 220, 1398, 13350, ...
2.636015
261
import os import unittest import tempfile from boltdb import BoltDB
[ 11748, 28686, 198, 11748, 555, 715, 395, 198, 11748, 20218, 7753, 198, 198, 6738, 18100, 9945, 1330, 21764, 11012, 628 ]
3.5
20
#!/usr/bin/python # Copyright (C) International Business Machines Corp., 2006 # Author: Stefan Berger <stefanb@us.ibm.com> # Basic VM creation test from XmTestLib import xapi from XmTestLib.XenAPIDomain import XmTestAPIDomain from XmTestLib import * from xen.xend import XendAPIConstants import commands import os try: # XmTestAPIDomain tries to establish a connection to XenD domain = XmTestAPIDomain() except Exception, e: SKIP("Skipping test. Error: %s" % str(e)) vm_uuid = domain.get_uuid() session = xapi.connect() domain.start(startpaused=True) res = session.xenapi.VM.get_power_state(vm_uuid) if res != XendAPIConstants.XEN_API_VM_POWER_STATE[XendAPIConstants.XEN_API_VM_POWER_STATE_PAUSED]: FAIL("VM was not started in 'paused' state") res = session.xenapi.VM.unpause(vm_uuid) res = session.xenapi.VM.get_power_state(vm_uuid) if res != XendAPIConstants.XEN_API_VM_POWER_STATE[XendAPIConstants.XEN_API_VM_POWER_STATE_RUNNING]: FAIL("VM could not be put into 'running' state") console = domain.getConsole() try: run = console.runCmd("cat /proc/interrupts") except ConsoleError, e: saveLog(console.getHistory()) FAIL("Could not access proc-filesystem") res = session.xenapi.VM.pause(vm_uuid) res = session.xenapi.VM.get_power_state(vm_uuid) if res != XendAPIConstants.XEN_API_VM_POWER_STATE[XendAPIConstants.XEN_API_VM_POWER_STATE_PAUSED]: FAIL("VM could not be put into 'paused' state") res = session.xenapi.VM.unpause(vm_uuid) res = session.xenapi.VM.get_power_state(vm_uuid) if res != XendAPIConstants.XEN_API_VM_POWER_STATE[XendAPIConstants.XEN_API_VM_POWER_STATE_RUNNING]: FAIL("VM could not be 'unpaused'") domain.stop() domain.destroy()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 2, 15069, 357, 34, 8, 4037, 7320, 31182, 11421, 1539, 4793, 198, 2, 6434, 25, 28842, 33337, 1279, 301, 891, 272, 65, 31, 385, 13, 571, 76, 13, 785, 29, 198, 198, 2, 14392, 16990, 6...
2.434473
702
"""Fourier transform non-linear Poisson solver""" # This module is concerned with solving the "non-linear Poisson" # equation # Delta(u) = f(u,z) # on a uniform rectangular mesh, with u = u0 on the boundary. # # We solve the equation by an iterative method, solving an # approximation to the linearized equation at u_i to get u_{i+1} and # terminating when u_{i+1} - u_i is small enough. # # The key feature of this solve is that we use a very coarse # approximation of the linearization---chosen specifically so that it # can be solved by Fourier transform methods. The coarse # approxmination means that each iteration makes little progress # toward the final solution, and many iterations are necessary. # However, the availability of efficient FFT routines means that each # iteration is very fast, and so in many cases there is a net gain # compared to a direct method. # # The exact linearized equation for v = u-u0 is # Delta(vdot) - d1F(v,z) vdot = F(v,z) - Delta(vdot) (*) # where # F(v,z) = f(u0+v,z) - Delta(u0) # We rewrite (*) as # (Delta - A)vdot = RHS # This is exactly solvable by Fourier methods if A is a constant # function. # # To approximate a solution, we replace A = d1F(v,z) by a constant # that is in some way representative of its values on he grid points. # We follow the suggestion of [1] to use the "minimax" value # # A = (max(d1F) + min(d1F)) / 2 # # where max and min are taken over the grid. # # References # # [1] Concus, P. and Golub, G. H. 1973. Use of fast direct methods for # the efficient numerical solution of nonseparable elliptic # equations. SIAM J. Numer. Anal., 10: 1103-1103. # # KNOWN ISSUES: # # * The initialization code assumes that u_0 is harmonic in a # neighborhood of the boundary of the mesh. This is not a # fundamental requirement of the method, but because u_0 cannot be # easily extended to a doubly-periodic function its Laplacian is # computed by a finite difference scheme rather than by FFT methods. # Being harmonic at the boundary allows us to simply zero out the # Laplacian at the edges and ignore this issue. # # (Note that this assumption is satisfied for the applications to # the self-duality equations for which this solver was developed0). from __future__ import absolute_import import numpy as np import scipy.signal from dst2 import dst2, idst2, dst2freq from solverexception import SolverException import time import logging logger = logging.getLogger(__name__)
[ 37811, 37, 280, 5277, 6121, 1729, 12, 29127, 7695, 30927, 1540, 332, 37811, 198, 198, 2, 770, 8265, 318, 5213, 351, 18120, 262, 366, 13159, 12, 29127, 7695, 30927, 1, 198, 2, 16022, 198, 2, 220, 220, 220, 220, 16978, 7, 84, 8, 796...
3.251638
763
# -*- coding: utf-8 -*- from datetime import datetime from sqlalchemy.dialects.mysql import LONGTEXT from sqlalchemy.orm import load_only from sqlalchemy import func from flask import abort from markdown import Markdown,markdown from app.models import db,fragment_tags_table from app.models.tag import Tag from app.whoosh import search_helper
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 44161, 282, 26599, 13, 38969, 478, 82, 13, 28744, 13976, 1330, 44533, 32541, 198, 6738, 44161, 282, 26599, 13, 579, 1330, ...
3.252336
107
# -*- coding: utf-8 -*- from django.db import migrations, models import django.utils.timezone import django.db.models.deletion from django.conf import settings
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 26791, 13, 2435, 11340, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2...
2.963636
55
from .constants import SUCCESS_KEY, MESSAGE_KEY, DATA_KEY from cloudygram_api_server.scripts import CGMessage from typing import List
[ 6738, 764, 9979, 1187, 1330, 13558, 4093, 7597, 62, 20373, 11, 337, 1546, 4090, 8264, 62, 20373, 11, 42865, 62, 20373, 198, 6738, 40026, 4546, 62, 15042, 62, 15388, 13, 46521, 220, 1330, 29925, 12837, 198, 6738, 19720, 1330, 7343, 198 ]
3.292683
41
import math from mathutils import Euler import bpy from .portal2_entity_classes import * from .portal_entity_handlers import PortalEntityHandler local_entity_lookup_table = PortalEntityHandler.entity_lookup_table.copy() local_entity_lookup_table.update(entity_class_handle)
[ 11748, 10688, 198, 198, 6738, 10688, 26791, 1330, 412, 18173, 198, 11748, 275, 9078, 198, 6738, 764, 634, 282, 17, 62, 26858, 62, 37724, 1330, 1635, 198, 6738, 764, 634, 282, 62, 26858, 62, 4993, 8116, 1330, 25663, 32398, 25060, 198, ...
3.337349
83
from collections import namedtuple
[ 6738, 17268, 1330, 3706, 83, 29291, 628 ]
5.142857
7
from django.urls import reverse from Net640.settings import FRONTEND_DATE_FORMAT
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 6738, 3433, 31102, 13, 33692, 1330, 8782, 35830, 10619, 62, 35, 6158, 62, 21389, 1404, 628 ]
3.28
25
"""A module for converting a data source to TFRecords.""" import os import json import copy import csv from pathlib import Path from shutil import rmtree import PIL.Image as Image import tensorflow as tf from tqdm import tqdm from .feature import items_to_features from .errors import DirNotFoundError, InvalidDatasetFormat from ..config import IMAGE_WIDTH, IMAGE_HEIGHT, DATASET_DIR, TFRECORDS_SIZE # ------------------------------------------------------------------------------ # CSV/COCO Dataset Detectors # ------------------------------------------------------------------------------ def is_csv_input(input_dir: Path) -> bool: """ Tests if the input directory represents CSV dataset format. Args: input_dir (Path): The input directory to test. Returns: status (bool): Returns `True` if the input directory represents CSV dataset format and `False` otherwise. """ return set(os.listdir(input_dir)) == set( [ "images", "instances_train.csv", "instances_test.csv", "instances_val.csv", "categories.json", ] ) def is_coco_input(input_dir: Path) -> bool: """ Tests if the input directory represents COCO dataset format. Args: input_dir (Path): The input directory to test. Returns: status (bool): Returns `True` if the input directory represents COCO dataset format and `False` otherwise. """ root_artifacts = os.listdir(input_dir) if "annotations" in root_artifacts: annotations_artifacts = os.listdir(input_dir / "annotations") stems_artifacts = [ Path(artifact).stem for artifact in annotations_artifacts ] return set(stems_artifacts).issubset(set(root_artifacts)) return False # ------------------------------------------------------------------------------ # CSV/COCO Dataset Iterators # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # Dataset to TFRecords Transformer # ------------------------------------------------------------------------------ def instances_to_tfrecords( instance_file: Path, output_dir: Path, items: DatasetIterator, size: int, image_width: int, image_height: int, verbose: bool, ): """ Converse instances to tfrecords. Args: instance_file (Path): The path to the instance file to read data from. output_dir (Path): The path to the output directory to save generated TFRecords. items (DatasetIterator): The CSV or COCO dataset iterator. size (int): The number of images per partion. image_width (int): The TFRecords image width resize to. image_height (int): The TFRecords image height resize to. verbose (bool): The flag to set verbose mode. """ tfrecords_dir = output_dir / instance_file.stem tfrecords_dir.mkdir(exist_ok=True) # The TFRecords writer. writer = None # The index for the next TFRecords partition. part_index = -1 # The count of how many records stored in the TFRecords files. It # is set here to maximum capacity (as a trick) to make the "if" # condition in the loop equals to True and start 0 - partition. part_count = size # Initializes the progress bar of verbose mode is on. if verbose: pbar = tqdm(total=len(items)) for item in items: if item: if part_count >= size: # The current partition has been reached the maximum capacity, # so we need to start a new one. if writer is not None: # Closes the existing TFRecords writer. writer.close() part_index += 1 writer = tf.io.TFRecordWriter( str(tfrecords_dir / f"part-{part_index}.tfrecord") ) part_count = 0 example = get_example(item) if example: writer.write(example.SerializeToString()) part_count += 1 # Updates the progress bar of verbose mode is on. if verbose: pbar.update(1) # Closes the existing TFRecords writer after the last row. writer.close() def create_tfrecords( dataset_dir: str = DATASET_DIR, tfrecords_dir: str = None, size: int = TFRECORDS_SIZE, image_width: int = IMAGE_WIDTH, image_height: int = IMAGE_HEIGHT, selected_categories: list = [], verbose: bool = False, ): """ This function transforms CSV or COCO dataset to TFRecords. Args: dataset_dir (str): The path to the data set directory to transform. tfrecords_dir (str): The path to the output directory to save generated TFRecords. size (int): The number of images per partion. image_width (int): The TFRecords image width resize to. image_height (int): The TFRecords image height resize to. selected_categories (list): The list of selected category IDs. verbose (bool): The flag to set verbose mode. Raises: DirNotFoundError: If input or output directories do not exist. InvalidDatasetFormat: If the input dataset has invalid CSV or COCO format. """ input_dir = Path(dataset_dir) if not input_dir.exists(): raise DirNotFoundError("input dataset", input_dir) if tfrecords_dir is None: output_dir = input_dir.parent / (input_dir.name + "-tfrecords") else: output_dir = Path(tfrecords_dir) if not output_dir.parent.exists(): raise DirNotFoundError("parent (to output)", output_dir.parent) if output_dir.exists(): rmtree(output_dir) output_dir.mkdir(exist_ok=True) if is_csv_input(input_dir): for instance_file in input_dir.rglob("*.csv"): instances_to_tfrecords( instance_file, output_dir, CsvIterator(instance_file, selected_categories), size, image_width, image_height, verbose, ) elif is_coco_input(input_dir): for instance_file in (input_dir / "annotations").rglob("*.json"): instances_to_tfrecords( instance_file, output_dir, CocoIterator(instance_file, selected_categories), size, image_width, image_height, verbose, ) else: raise InvalidDatasetFormat()
[ 37811, 32, 8265, 329, 23202, 257, 1366, 2723, 284, 24958, 6690, 3669, 526, 15931, 198, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 4866, 198, 11748, 269, 21370, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 4423, 346, 1330, 374, ...
2.384323
2,896
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to non-U.S. persons whether in the United States or abroad requires # an export license or other authorization. # # Contractor Name: Raytheon Company # Contractor Address: 6825 Pine Street, Suite 340 # Mail Stop B8 # Omaha, NE 68106 # 402.291.0100 # # See the AWIPS II Master Rights File ("Master Rights File.pdf") for # further licensing information. ## # ---------------------------------------------------------------------------- # This software is in the public domain, furnished "as is", without technical # support, and with no warranty, express or implied, as to its usefulness for # any purpose. # # ExUtil1 # # Author: # ---------------------------------------------------------------------------- ToolType = "numeric" WeatherElementEdited = "T" from numpy import * import SmartScript import Common VariableList = [("Model:" , "", "D2D_model")]
[ 2235, 198, 2, 770, 3788, 373, 4166, 290, 1220, 393, 9518, 416, 7760, 1169, 261, 5834, 11, 198, 2, 12997, 284, 17453, 46133, 16945, 54, 12, 2713, 12, 34, 48, 12, 940, 3134, 351, 262, 1294, 5070, 13, 198, 2, 220, 198, 2, 471, 13, ...
3.248062
387
import pathlib import datetime path = 'c:/Users/Jacob/PycharmProjects/KryptoSkatt/Data/' trans_in = list() trans_out = list() bitcoin_dict = dict() ethereum_dict = dict() USD_NOK_dict = dict() main()
[ 11748, 3108, 8019, 198, 11748, 4818, 8079, 198, 198, 6978, 796, 705, 66, 14079, 14490, 14, 46751, 14, 20519, 354, 1670, 16775, 82, 14, 42, 6012, 78, 15739, 1078, 14, 6601, 14, 6, 198, 7645, 62, 259, 796, 1351, 3419, 198, 7645, 62, ...
2.589744
78
import numpy as np import scipy.special as ss import pathlib from Particle import Particle
[ 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 13, 20887, 355, 37786, 198, 11748, 3108, 8019, 198, 6738, 2142, 1548, 1330, 2142, 1548, 628, 628, 628, 628, 628, 628, 628, 628, 198 ]
3.147059
34
from .switch import EKFSwitch, RelaySwitch, InitialModeSwitch from .camera_t265 import CameraT265 from .camera_d435 import CameraD435
[ 6738, 764, 31943, 1330, 412, 42, 37, 38978, 11, 4718, 323, 38978, 11, 20768, 19076, 38978, 198, 6738, 764, 25695, 62, 83, 22980, 1330, 20432, 51, 22980, 198, 6738, 764, 25695, 62, 67, 40064, 1330, 20432, 35, 40064 ]
3.5
38
import os import time import datetime
[ 11748, 28686, 198, 11748, 640, 198, 11748, 4818, 8079, 198 ]
3.8
10
#!/usr/bin/env python3 # IBM_PROLOG_BEGIN_TAG # # Copyright 2019,2020 IBM International Business Machines Corp. # # 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. # # IBM_PROLOG_END_TAG import logging as logger import sys import vapi import vapi_cli.cli_utils as cli_utils from vapi_cli.cli_utils import reportSuccess, reportApiError, translate_flags # All of Vision Tools requires python 3.6 due to format string # Make the check in a common location if sys.hexversion < 0x03060000: sys.exit("Python 3.6 or newer is required to run this program.") token_usage = """ Usage: users token --user=<user-name> --password=<password> Where: --user Required parameter containing the user login name --password Required parameter containing the user's password Gets an authentication token for the given user""" server = None # --- Token Operation ---------------------------------------------- def token(params): """ Handles getting an authentication token for a specific user""" user = params.get("--user", None) pw = params.get("--password", None) rsp = server.users.get_token(user, pw) if rsp is None or rsp.get("result", "fail") == "fail": reportApiError(server, f"Failed to get token for user '{user}'") else: reportSuccess(server, rsp["token"]) cmd_usage = f""" Usage: users {cli_utils.common_cmd_flags} <operation> [<args>...] Where: {cli_utils.common_cmd_flag_descriptions} <operation> is required and must be one of: token -- gets an authentication token for the given user Use 'users <operation> --help' for more information on a specific command.""" usage_stmt = { "usage": cmd_usage, "token": token_usage } operation_map = { "token": token } if __name__ == "__main__": main(None)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 19764, 62, 4805, 33462, 62, 33, 43312, 62, 42197, 198, 2, 198, 2, 15069, 13130, 11, 42334, 19764, 4037, 7320, 31182, 11421, 13, 198, 2, 198, 2, 220, 49962, 739, 262, 24843, ...
3.172652
724
# This script loads the pre-trained scaler and models and contains the # predict_smile() function to take in an image and return smile predictions import joblib from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing.image import img_to_array, array_to_img from PIL import Image import numpy as np # Set new frame size dimensions img_width, img_height = (100, 100) # Scaler and model imports scaler = joblib.load('./models/scaler.save') model = load_model('./models/my_model.h5') model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) def predict_smile(gray_img, box, count): """Make prediction on a new image whether a person is smiling or not. Parameters ---------- gray_img : numpy.ndarray of dtype int Grayscale image in numpy.ndarray of current frame. box : tuple (left, top, right, bottom) locating face bounding box in pixel locations. count : int Number of faces detected in current frame. Returns ------- numpy.ndarray of dtype float Probabilities of no smile (second number) and smile (first number). i.e. array([[0.972528 , 0.02747207]], dtype=float32) """ # Save a copy of current frame gray_img = gray_img.reshape(gray_img.shape+(1,)) # (height, width, 1) array_to_img(gray_img).save(f'./images/temp/current_frame_{count}.jpg') # Load image gray_img = Image.open(f'./images/temp/current_frame_{count}.jpg') # Crop face, resize to 100x100 pixels, and save a copy face_crop = gray_img.resize((img_width, img_height), box=box) face_crop.save(f'./images/temp/face_crop_current_frame_{count}.jpg') # Load image and convert to np.array face_crop = Image.open(f'./images/temp/face_crop_current_frame_{count}.jpg') new_face_array = np.array(img_to_array(face_crop)) # (100, 100, 1) # Reshape new_face_array = new_face_array.reshape(1, img_width*img_height) # (1, 10_000) # Transform with pre-trained scaler new_face_array = scaler.transform(new_face_array) new_face_array = new_face_array.reshape(1, img_width, img_height, 1) # (1, 100, 100, 1) return model.predict(new_face_array)
[ 2, 770, 4226, 15989, 262, 662, 12, 35311, 16578, 263, 290, 4981, 290, 4909, 262, 198, 2, 4331, 62, 5796, 576, 3419, 2163, 284, 1011, 287, 281, 2939, 290, 1441, 8212, 16277, 198, 198, 11748, 1693, 8019, 198, 6738, 11192, 273, 11125, ...
2.70438
822
import sys import webbrowser import os from comicstreamerlib.folders import AppFolders from PyQt4 import QtGui,QtCore if __name__ == '__main__': QtGui().run()
[ 11748, 25064, 198, 11748, 3992, 40259, 198, 11748, 28686, 198, 6738, 9048, 5532, 263, 8019, 13, 11379, 364, 1330, 2034, 37, 727, 364, 198, 198, 6738, 9485, 48, 83, 19, 1330, 33734, 8205, 72, 11, 48, 83, 14055, 198, 220, 220, 220, 22...
2.478873
71
""" IO Handler for LAS (and compressed LAZ) file format """ import laspy import numpy as np from laserchicken import keys from laserchicken.io.base_io_handler import IOHandler from laserchicken.io.utils import convert_to_short_type, select_valid_attributes DEFAULT_LAS_ATTRIBUTES = { 'x', 'y', 'z', 'intensity', 'gps_time', 'raw_classification', }
[ 37811, 24418, 32412, 329, 406, 1921, 357, 392, 25388, 9131, 57, 8, 2393, 5794, 37227, 198, 11748, 300, 5126, 88, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 12855, 354, 5973, 1330, 8251, 198, 6738, 12855, 354, 5973, 13, 952, 1...
2.643357
143
import numpy as np import pandas as pd
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 628, 628, 198 ]
2.866667
15
from pybmrb import Spectra, Histogram import plotly.io as pio pio.renderers.default = "browser" peak_list=Spectra.n15hsqc(bmrb_ids=15060, legend='residue') peak_list=Spectra.c13hsqc(bmrb_ids=15060, legend='residue') peak_list=Spectra.tocsy(bmrb_ids=15060, legend='residue')
[ 6738, 12972, 20475, 26145, 1330, 13058, 430, 11, 5590, 21857, 198, 198, 11748, 7110, 306, 13, 952, 355, 279, 952, 198, 79, 952, 13, 10920, 19288, 13, 12286, 796, 366, 40259, 1, 198, 198, 36729, 62, 4868, 28, 49738, 430, 13, 77, 1314...
2.387931
116
#!/usr/bin/env python3 import io import xml.etree.ElementTree as ET import argparse ns = {'ns1': 'http://www.sifinfo.org/infrastructure/2.x', 'ns2': 'http://stumo.transcriptcenter.com'} def process_course(course, year): title = course.find(".//ns1:CourseTitle", ns).text course_code = course.find(".//ns1:CourseCode", ns).text mark_data = course.find(".//ns1:MarkData", ns) grade_level = course.find(".//ns1:GradeLevelWhenTaken/ns1:Code", ns).text letter_grade = mark_data.find("ns1:Letter", ns).text number_grade = mark_data.find("ns1:Percentage", ns).text comments = mark_data.find("ns1:Narrative", ns).text # get extended info extended_info = course.find("ns1:SIF_ExtendedElements", ns) term = extended_info.find("ns1:SIF_ExtendedElement[@Name='StoreCode']", ns).text teacher_fn = extended_info.find("ns1:SIF_ExtendedElement[@Name='InstructorFirstName']", ns).text teacher_ln = extended_info.find("ns1:SIF_ExtendedElement[@Name='InstructorLastName']", ns).text school_name = extended_info.find("ns1:SIF_ExtendedElement[@Name='SchoolName']", ns).text return Grade(year, grade_level, term, course_code, title, letter_grade, number_grade, comments, teacher_fn, teacher_ln, school_name) # Placeholder for markdown format for a list of grades # Take the list and sort it with appropriate headers. # TBD if we need to figure pass in meta data, whether we figure it out, or if we make assumptions. # concat all of the XML lines in the file, then return it # Skip all up to the start of the XML if __name__ == "__main__": import sys parser = argparse.ArgumentParser(description='Report Card Generator.') parser.add_argument('--output_basename', action='store', default='report_card', help='Output file to report results to (default: standard out)') # First arg is the data file parser.add_argument('data_file') args = parser.parse_args() basename = args.output_basename print("output = ", basename) print("parsing ", args.data_file) valid_xml = extractValidXML(args.data_file) (student_info, grades, years) = process_data(args.data_file) years.sort() for year in years: (grades_by_course, grades_by_period, headers_by_course) = organize_grades( [a for a in grades if (a.year == year)]) print("*******************", year, "***************") schools = [g.school for g in grades if (g.year == year)] terms = [g.term for g in grades if (g.year == year)] report_text = generate_year_report(student_info, year, grades_by_course, set(schools), set(terms)) file_name = f"{basename}-{year}.html" generate_html_file(file_name, report_text)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 33245, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 198, 11748, 1822, 29572, 198, 198, 5907, 796, 1391, 6, 5907, 16, 10354, 705, 4023, 1378, 2503, 13,...
2.666349
1,049
# -*- coding: utf-8 -*- # @Time : 2020-04-11 12:34 # @Author : speeding_moto import numpy as np import pandas as pd from matplotlib import pyplot as plt EUNITE_PATH = "dataset/eunite.xlsx" PARSE_TABLE_NAME = "mainData" def load_eunite_data(): """ return the generated load data, include all the features wo handle """ data = open_file() X, Y = generate_features(data) return X.values, Y.values def generate_features(df): """ parse the data, wo need to transfer the class number to ont_hot for our calculate later """ months = df["Month"] days = df["Day"] one_hot_months = cast_to_one_hot(months, n_classes=12) days = cast_to_one_hot(days, n_classes=31) one_hot_months = pd.DataFrame(one_hot_months) days = pd.DataFrame(days) df = pd.merge(left=df, right=one_hot_months, left_index=True, right_index=True) df = pd.merge(left=df, right=days, left_index=True, right_index=True) y = df['Max Load'] # think, maybe wo need to normalization the temperature data, temperature = normalization(df['Temp'].values) temperature = pd.DataFrame(temperature) df = pd.merge(left=df, right=temperature, left_index=True, right_index=True) drop_columns = ["ID", "Month", "Day", "Year", "Max Load", "Temp"] df.drop(drop_columns, axis=1, inplace=True) print(df[0:10], "\n", y[0]) return df, y def cast_to_one_hot(data, n_classes): """ cast the classifier data to one hot """ one_hot_months = np.eye(N=n_classes)[[data - 1]] return one_hot_months def open_file(): """ open the eunite load excel file to return """ xlsx_file = pd.ExcelFile(EUNITE_PATH) return xlsx_file.parse(PARSE_TABLE_NAME) if __name__ == '__main__': df = open_file() show_month_temperature_load_image(df) x, y = load_eunite_data() print(x.shape)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 220, 220, 220, 1058, 12131, 12, 3023, 12, 1157, 1105, 25, 2682, 198, 2, 2488, 13838, 220, 1058, 26347, 62, 76, 2069, 198, 198, 11748, 299, 32152, 355, ...
2.450065
771
import numpy as np import pytest from piescope.data.mocktypes import MockAdornedImage import piescope.fibsem autoscript = pytest.importorskip( "autoscript_sdb_microscope_client", reason="Autoscript is not available." ) try: from autoscript_sdb_microscope_client import SdbMicroscopeClient microscope = SdbMicroscopeClient() microscope.connect("localhost") except Exception as e: pytest.skip("AutoScript cannot connect to localhost, skipping all AutoScript tests.", allow_module_level=True) def test_initialize(): """Test connecting to the microscope offline with localhost.""" microscope = piescope.fibsem.initialize("localhost") def test_move_to_light_microscope(microscope): original_position = microscope.specimen.stage.current_position final_position = piescope.fibsem.move_to_light_microscope(microscope) assert np.isclose(final_position.x, original_position.x + 50e-3, atol=1e-7) assert np.isclose(final_position.y, original_position.y + 0.) assert np.isclose(final_position.z, original_position.z) assert np.isclose(final_position.r, original_position.r) assert np.isclose(final_position.t, original_position.t) def test_move_to_electron_microscope(microscope): original_position = microscope.specimen.stage.current_position final_position = piescope.fibsem.move_to_electron_microscope(microscope) assert np.isclose(final_position.x, original_position.x - 50e-3, atol=1e-7) assert np.isclose(final_position.y, original_position.y - 0.) assert np.isclose(final_position.z, original_position.z) assert np.isclose(final_position.r, original_position.r) assert np.isclose(final_position.t, original_position.t) def test_new_ion_image(microscope): result = piescope.fibsem.new_ion_image(microscope) assert microscope.imaging.get_active_view() == 2 assert result.data.shape == (884, 1024) def test_new_electron_image(microscope): result = piescope.fibsem.new_electron_image(microscope) assert microscope.imaging.get_active_view() == 1 assert result.data.shape == (884, 1024) def test_last_ion_image(microscope): result = piescope.fibsem.last_ion_image(microscope) assert microscope.imaging.get_active_view() == 2 assert result.data.shape == (884, 1024) def test_last_electron_image(microscope): result = piescope.fibsem.last_electron_image(microscope) assert microscope.imaging.get_active_view() == 1 assert result.data.shape == (884, 1024) def test_create_rectangular_pattern(microscope, image): x0 = 2 x1 = 8 y0 = 3 y1 = 7 depth = 1e-6 output = piescope.fibsem.create_rectangular_pattern( microscope, image, x0, x1, y0, y1, depth) expected_center_x = 0 expected_center_y = 0 expected_width = 6e-6 expected_height = 4e-6 assert np.isclose(output.center_x, expected_center_x) assert np.isclose(output.center_y, expected_center_y) assert np.isclose(output.width, expected_width) assert np.isclose(output.height, expected_height) assert np.isclose(output.depth, depth) # depth is unchanged assert np.isclose(output.rotation, 0) # no rotation by befault def test_empty_rectangular_pattern(microscope, image): x0 = None x1 = None y0 = 3 y1 = 7 depth = 1e-6 output = piescope.fibsem.create_rectangular_pattern( microscope, image, x0, x1, y0, y1, depth) assert output is None
[ 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 198, 6738, 47199, 66, 3008, 13, 7890, 13, 76, 735, 19199, 1330, 44123, 2782, 26994, 5159, 198, 11748, 47199, 66, 3008, 13, 69, 571, 43616, 198, 198, 2306, 418, 6519, 796, 12...
2.695788
1,282
import streamlit as st import pandas as pd import matplotlib.pyplot as plt import csv import numpy as np import pydeck as pdk from PIL import Image #rank_map whole_mao(),rank_map() #rank_map(),rank # main()
[ 11748, 4269, 18250, 355, 336, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 11748, 269, 21370, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 12972, ...
2.34
100
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.keras.models import Sequential from tensorflow.keras.models import load_model from tensorflow.keras import utils import tensorflow as tf import numpy as np import argparse import logging import os # Set Log Level os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Seed for Reproducability SEED = 123 np.random.seed(SEED) tf.random.set_seed(SEED) # Setup Logger logger = logging.getLogger('sagemaker') logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) if __name__ == '__main__': logger.info(f'[Using TensorFlow version: {tf.__version__}]') DEVICE = '/cpu:0' args, _ = parse_args() epochs = args.epochs # Load train, validation and test sets from S3 X_train, y_train = get_train_data(args.train) X_validation, y_validation = get_validation_data(args.val) X_test, y_test = get_test_data(args.test) with tf.device(DEVICE): # Data Augmentation TRAIN_BATCH_SIZE = 32 data_generator = ImageDataGenerator(width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True) train_iterator = data_generator.flow(X_train, y_train, batch_size=TRAIN_BATCH_SIZE) # Define Model Architecture model = Sequential() # CONVOLUTIONAL LAYER 1 model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu', input_shape=(32, 32, 3))) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2)) # CONVOLUTIONAL LAYER 1 model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2)) # CONVOLUTIONAL LAYER 3 model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.3)) # FULLY CONNECTED LAYER model.add(Flatten()) model.add(Dense(500, activation='relu')) model.add(Dropout(0.4)) model.add(Dense(10, activation='softmax')) model.summary() # Compile Model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # Train Model BATCH_SIZE = 32 STEPS_PER_EPOCH = int(X_train.shape[0]/TRAIN_BATCH_SIZE) model.fit(train_iterator, steps_per_epoch=STEPS_PER_EPOCH, batch_size=BATCH_SIZE, epochs=epochs, validation_data=(X_validation, y_validation), callbacks=[], verbose=2, shuffle=True) # Evaluate on Test Set result = model.evaluate(X_test, y_test, verbose=1) print(f'Test Accuracy: {result[1]}') # Save Model model.save(f'{args.model_dir}/1')
[ 6738, 11192, 273, 11125, 13, 6122, 292, 13, 75, 6962, 1330, 34872, 17, 35, 11, 5436, 27201, 278, 17, 35, 11, 1610, 41769, 11, 360, 1072, 11, 14258, 448, 11, 347, 963, 26447, 1634, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 3...
2.162457
1,465
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import from django.db import models, migrations import jsonfield.fields
[ 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, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, ...
3.269231
52
import re import json import tornado.web import tornado.httpclient tornado.httpclient.AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient") import tornadoes from utils.es import (ESQuery, ESQueryBuilder, MGQueryError, ElasticSearchException, ES_INDEX_NAME_ALL) from utils.dotfield import parse_dot_fields from config import ES_HOST
[ 11748, 302, 198, 11748, 33918, 198, 198, 11748, 33718, 13, 12384, 198, 11748, 33718, 13, 4023, 16366, 198, 45910, 4533, 13, 4023, 16366, 13, 42367, 40717, 11792, 13, 11250, 495, 7203, 45910, 4533, 13, 66, 6371, 62, 4023, 16366, 13, 34, ...
2.671141
149
""" Th vin ny vit ra phc v cho mn hc `Cc m hnh ngu nhin v ng dng` S dng cc th vin `networkx, pandas, numpy, matplotlib` """ import networkx as nx import numpy as np import matplotlib.pyplot as plt from matplotlib.image import imread import pandas as pd
[ 37811, 198, 817, 410, 259, 299, 88, 9090, 2179, 872, 66, 410, 1727, 285, 77, 289, 66, 4600, 34, 66, 285, 289, 77, 71, 299, 5162, 299, 20079, 410, 23370, 288, 782, 63, 198, 50, 288, 782, 36624, 294, 410, 259, 4600, 27349, 87, 11,...
2.544554
101
import os import json import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, TensorDataset, SequentialSampler from transformers import CamembertTokenizer, CamembertForSequenceClassification import pandas as pd from tqdm import tqdm, trange # tokenizer = CamembertTokenizer.from_pretrained('/home/crannou/workspace/sentiment-eai/data/36e8f471-821d-4270-be56-febb1be36c26') # model = CamembertForSequenceClassification.from_pretrained('/home/crannou/workspace/sentiment-eai/data/36e8f471-821d-4270-be56-febb1be36c26') # tokenizer = CamembertTokenizer.from_pretrained('/home/crannou/workspace/sentiment-eai/7a37b1e5-8e7b-45d1-9e87-7314e8e66c0c/') # model = CamembertForSequenceClassification.from_pretrained('/home/crannou/workspace/sentiment-eai/7a37b1e5-8e7b-45d1-9e87-7314e8e66c0c/') tokenizer = CamembertTokenizer.from_pretrained('/home/crannou/workspace/serving-preset-images/sentiment-analysis-fr/app/model_sources') model = CamembertForSequenceClassification.from_pretrained('/home/crannou/workspace/serving-preset-images/sentiment-analysis-fr/app/model_sources') if __name__ == '__main__': eval_model()
[ 11748, 28686, 198, 11748, 33918, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 28034, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 11, 14534, 16305, 20053, 11, 309, 22854, 27354, 292, 316, 11, 24604, 1843, 16305, 20053...
2.58296
446
print (19 // 2 ) print( 19%2)
[ 4798, 357, 1129, 3373, 362, 1267, 198, 4798, 7, 678, 4, 17, 8 ]
2.230769
13
from django.conf import settings from django.contrib.gis.db import models # integrate with the django-locator app for easy geo lookups if it's installed if 'locator.objects' in settings.INSTALLED_APPS: from locator.objects.models import create_locator_object models.signals.post_save.connect(create_locator_object, sender=Campground)
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 70, 271, 13, 9945, 1330, 4981, 198, 198, 2, 19386, 351, 262, 42625, 14208, 12, 17946, 1352, 598, 329, 2562, 40087, 804, 4739, 611, 340, 338, 6589, ...
3.235849
106
#users from django.urls import path from users.views import RegisterView, ImageCodeView,SmsCodeView urlpatterns = [ #path #path path('register/', RegisterView.as_view(),name='register'), # path('imagecode/',ImageCodeView.as_view(),name='imagecode'), # path('smscode/',SmsCodeView.as_view(),name='smscode'), ]
[ 2, 18417, 220, 198, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 2985, 13, 33571, 1330, 17296, 7680, 11, 7412, 10669, 7680, 11, 50, 907, 10669, 7680, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 1303, 69...
2.615385
130
#!/usr/bin/python from builtins import object from builtins import str import sys import traceback sys.path.append("/opt/contrail/fabric_ansible_playbooks/module_utils") # noqa from filter_utils import _task_done, _task_error_log, _task_log, FilterLog from job_manager.job_utils import JobVncApi
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 6738, 3170, 1040, 1330, 2134, 198, 6738, 3170, 1040, 1330, 965, 198, 11748, 25064, 198, 11748, 12854, 1891, 198, 198, 17597, 13, 6978, 13, 33295, 7203, 14, 8738, 14, 3642, 30224, 14, 364...
3.01
100
"""Provides the MENU html string which is appended to all templates Please note that the MENU only works in [Fast](https://www.fast.design/) based templates. If you need some sort of custom MENU html string feel free to customize this code. """ from awesome_panel_extensions.frameworks.fast.fast_menu import to_menu from src.shared import config if config.applications: MENU = to_menu( config.applications.values(), accent_color=config.color_primary, expand=["Main"] ).replace("\n", "") else: MENU = ""
[ 37811, 15946, 1460, 262, 41597, 52, 27711, 4731, 543, 318, 598, 1631, 284, 477, 24019, 198, 198, 5492, 3465, 326, 262, 41597, 52, 691, 2499, 287, 685, 22968, 16151, 5450, 1378, 2503, 13, 7217, 13, 26124, 34729, 1912, 24019, 13, 198, 1...
3.174699
166
import os import boto3 import numpy as np import tensorflow as tf from flask import Flask from dotenv import load_dotenv from pymongo import MongoClient from keras.models import load_model from sklearn.preprocessing import LabelEncoder from werkzeug.datastructures import FileStorage from werkzeug.middleware.proxy_fix import ProxyFix from flask_restplus import Api, Resource from utils.Model import ModelManager load_dotenv() # Mongodb connection client = MongoClient(os.environ['MONGO_CLIENT_URL']) db = client.registry # AWS S3 connection session = boto3.Session( aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'], aws_secret_access_key=os.environ['AWS_SECRET_KEY'] ) s3 = session.resource('s3') # App and API setup app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) api = Api(app, version="1.0", title="Anomaly Detection", description="") ns = api.namespace('api') single_parser = api.parser() single_parser.add_argument("files", location="files", type=FileStorage, action='append', required=True) graph = tf.get_default_graph() backup_model = load_model("./models/backup/model.h5") backup_label_encoder = LabelEncoder() backup_label_encoder.classes_ = np.load("./models/backup/classes.npy") if __name__ == "__main__": app.run(debug=True, host="0.0.0.0")
[ 11748, 28686, 198, 11748, 275, 2069, 18, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 42903, 1330, 46947, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 6738, 279, 4948, 25162, 133...
2.839207
454
# Given an array containing None values fill in the None values with most recent # non None value in the array from random import random test = list(map(int, input().split())) print(fill1(test)) print(fill2(test))
[ 2, 11259, 281, 7177, 7268, 6045, 3815, 6070, 287, 262, 6045, 3815, 351, 749, 2274, 220, 198, 2, 1729, 6045, 1988, 287, 262, 7177, 198, 198, 6738, 4738, 1330, 4738, 198, 198, 9288, 796, 1351, 7, 8899, 7, 600, 11, 5128, 22446, 35312, ...
3.5
62
# useful functions for BEAST tests # put here instead of having in every tests import os.path import numpy as np import h5py from astropy.io import fits from astropy.utils.data import download_file __all__ = ['download_rename', 'compare_tables', 'compare_fits', 'compare_hdf5'] def download_rename(filename): """Download a file and rename it to have the right extension. Otherwise, downloaded file will not have an extension at all and an extension is needed for the BEAST. Parameters ---------- filename : str name of file to download """ url_loc = 'http://www.stsci.edu/~kgordon/beast/' fname_dld = download_file('%s%s' % (url_loc, filename)) extension = filename.split('.')[-1] fname = '%s.%s' % (fname_dld, extension) os.rename(fname_dld, fname) return fname def compare_tables(table_cache, table_new): """ Compare two tables using astropy tables routines. Parameters ---------- table_cache : astropy table table_new : astropy table data for comparision. """ assert len(table_new) == len(table_cache) for tcolname in table_new.colnames: # test numerical types for closeness # and other types for equality if table_new[tcolname].data.dtype.kind in ['f', 'i']: np.testing.assert_allclose(table_new[tcolname], table_cache[tcolname], err_msg=('%s columns not equal' % tcolname)) else: np.testing.assert_equal(table_new[tcolname], table_cache[tcolname], err_msg=('%s columns not equal' % tcolname)) def compare_fits(fname_cache, fname_new): """ Compare two FITS files. Parameters ---------- fname_cache : str fname_new : type names to FITS files """ fits_cache = fits.open(fname_cache) fits_new = fits.open(fname_new) assert len(fits_new) == len(fits_cache) for k in range(1, len(fits_new)): qname = fits_new[k].header['EXTNAME'] np.testing.assert_allclose(fits_new[k].data, fits_cache[qname].data, err_msg=('%s FITS extension not equal' % qname)) def compare_hdf5(fname_cache, fname_new, ctype=None): """ Compare two hdf files. Parameters ---------- fname_cache : str fname_new : type names to hdf5 files ctype : str if set, string to identify the type of data being tested """ hdf_cache = h5py.File(fname_cache, 'r') hdf_new = h5py.File(fname_new, 'r') # go through the file and check if it is exactly the same for sname in hdf_cache.keys(): if isinstance(hdf_cache[sname], h5py.Dataset): cvalue = hdf_cache[sname] cvalue_new = hdf_new[sname] if ctype is not None: osname = '%s/%s' % (ctype, sname) else: osname = sname if cvalue.dtype.fields is None: np.testing.assert_allclose(cvalue.value, cvalue_new.value, err_msg='testing %s' % (osname), rtol=1e-6) else: for ckey in cvalue.dtype.fields.keys(): err_msg = 'testing %s/%s' % (osname, ckey) np.testing.assert_allclose(cvalue.value[ckey], cvalue_new.value[ckey], err_msg=err_msg, rtol=1e-5)
[ 2, 4465, 5499, 329, 9348, 11262, 5254, 198, 2, 1234, 994, 2427, 286, 1719, 287, 790, 5254, 198, 11748, 28686, 13, 6978, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 289, 20, 9078, 198, 198, 6738, 6468, 28338, 13, 952, 1330, ...
1.918
2,000
# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from ... import models as _models from ..._vendor import _convert_request from ...operations._page_blob_operations import build_clear_pages_request, build_copy_incremental_request, build_create_request, build_get_page_ranges_diff_request, build_get_page_ranges_request, build_resize_request, build_update_sequence_number_request, build_upload_pages_from_url_request, build_upload_pages_request T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
[ 2, 279, 2645, 600, 25, 15560, 28, 18820, 12, 21834, 12, 6615, 198, 2, 19617, 28, 40477, 12, 23, 198, 2, 16529, 35937, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, ...
3.839695
393
# Detlev Aschhoff info@vmais.de # The MIT License (MIT) # # Copyright (c) 2020 # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import time from tkinter import * from tkinter import ttk from tkinter.messagebox import * import serial root=Tk() root.title("ESP Autostart Changer") err="" #---------------------------------------------------------------------------------- #---------- Witgets laden frameButton = Frame(root) frameButton.pack(fill='both') button2=Button(frameButton, text="Autostart ON ", command=autoon) button2.pack(side="right",padx="5",pady="2") button1=Button(frameButton, text="Autostart OFF ", command=autooff) button1.pack(side="right",padx="5") hinweis = Label(root, fg = "lightgreen",bg = "gray", font = "Verdana 10 bold" ) hinweis.pack(fill='both',padx="5",pady="2") hinweistxt="Change Autostart " hinweis.config(text=hinweistxt) status = Label(root) status.pack(fill='both',padx="5",pady="2") statustxt=" " status.config(text=statustxt) #------------------------------------------------------------------------------------ start() root.mainloop()
[ 2, 4614, 2768, 1081, 354, 36092, 7508, 31, 85, 2611, 271, 13, 2934, 198, 2, 383, 17168, 13789, 357, 36393, 8, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 198, 2, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, ...
3.21131
672
from django.apps import AppConfig from django.contrib.admin.apps import AdminConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 28482, 13, 18211, 1330, 32053, 16934, 628, 628 ]
3.625
24
import os import urllib.request os.makedirs('saved_models', exist_ok=True) model_path = 'http://shape2prog.csail.mit.edu/repo/wrn_40_2_vanilla/ckpt_epoch_240.pth' model_dir = 'saved_models/wrn_40_2_vanilla' os.makedirs(model_dir, exist_ok=True) urllib.request.urlretrieve(model_path, os.path.join(model_dir, model_path.split('/')[-1])) print(f"Downloaded {model_path.split('repo/')[-1]} to saved_models/") model_path = 'http://shape2prog.csail.mit.edu/repo/resnet56_vanilla/ckpt_epoch_240.pth' model_dir = 'saved_models/resnet56_vanilla' os.makedirs(model_dir, exist_ok=True) urllib.request.urlretrieve(model_path, os.path.join(model_dir, model_path.split('/')[-1])) print(f"Downloaded {model_path.split('repo/')[-1]} to saved_models/") model_path = 'http://shape2prog.csail.mit.edu/repo/resnet110_vanilla/ckpt_epoch_240.pth' model_dir = 'saved_models/resnet110_vanilla' os.makedirs(model_dir, exist_ok=True) urllib.request.urlretrieve(model_path, os.path.join(model_dir, model_path.split('/')[-1])) print(f"Downloaded {model_path.split('repo/')[-1]} to saved_models/") model_path = 'http://shape2prog.csail.mit.edu/repo/resnet32x4_vanilla/ckpt_epoch_240.pth' model_dir = 'saved_models/resnet32x4_vanilla' os.makedirs(model_dir, exist_ok=True) urllib.request.urlretrieve(model_path, os.path.join(model_dir, model_path.split('/')[-1])) print(f"Downloaded {model_path.split('repo/')[-1]} to saved_models/") model_path = 'http://shape2prog.csail.mit.edu/repo/vgg13_vanilla/ckpt_epoch_240.pth' model_dir = 'saved_models/vgg13_vanilla' os.makedirs(model_dir, exist_ok=True) urllib.request.urlretrieve(model_path, os.path.join(model_dir, model_path.split('/')[-1])) print(f"Downloaded {model_path.split('repo/')[-1]} to saved_models/") model_path = 'http://shape2prog.csail.mit.edu/repo/ResNet50_vanilla/ckpt_epoch_240.pth' model_dir = 'saved_models/ResNet50_vanilla' os.makedirs(model_dir, exist_ok=True) urllib.request.urlretrieve(model_path, os.path.join(model_dir, model_path.split('/')[-1])) print(f"Downloaded {model_path.split('repo/')[-1]} to saved_models/")
[ 11748, 28686, 201, 198, 11748, 2956, 297, 571, 13, 25927, 201, 198, 201, 198, 418, 13, 76, 4335, 17062, 10786, 82, 9586, 62, 27530, 3256, 2152, 62, 482, 28, 17821, 8, 201, 198, 201, 198, 19849, 62, 6978, 796, 705, 4023, 1378, 43358,...
2.249733
937
__author__ = 'alex jiang' __version__ = '2.3.3'
[ 834, 9800, 834, 796, 705, 1000, 87, 474, 15483, 6, 198, 834, 9641, 834, 796, 705, 17, 13, 18, 13, 18, 6, 198 ]
2.086957
23
#!/usr/bin/env python # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """ Scenario spawning elements to make the town dynamic and interesting """ import math from collections import OrderedDict import py_trees import numpy as np import carla from srunner.scenariomanager.carla_data_provider import CarlaDataProvider from srunner.scenariomanager.scenarioatomics.atomic_behaviors import AtomicBehavior from srunner.scenarios.basic_scenario import BasicScenario DEBUG_COLORS = { 'road': carla.Color(0, 0, 255), # Blue 'opposite': carla.Color(255, 0, 0), # Red 'junction': carla.Color(0, 0, 0), # Black 'entry': carla.Color(255, 255, 0), # Yellow 'exit': carla.Color(0, 255, 255), # Teal 'connect': carla.Color(0, 255, 0), # Green } DEBUG_TYPE = { 'small': [0.8, 0.1], 'medium': [0.5, 0.15], 'large': [0.2, 0.2], } def draw_string(world, location, string='', debug_type='road', persistent=False): """Utility function to draw debugging strings""" v_shift, _ = DEBUG_TYPE.get('small') l_shift = carla.Location(z=v_shift) color = DEBUG_COLORS.get(debug_type, 'road') life_time = 0.07 if not persistent else 100000 world.debug.draw_string(location + l_shift, string, False, color, life_time) def draw_point(world, location, point_type='small', debug_type='road', persistent=False): """Utility function to draw debugging points""" v_shift, size = DEBUG_TYPE.get(point_type, 'small') l_shift = carla.Location(z=v_shift) color = DEBUG_COLORS.get(debug_type, 'road') life_time = 0.07 if not persistent else 100000 world.debug.draw_point(location + l_shift, size, color, life_time) def get_same_dir_lanes(waypoint): """Gets all the lanes with the same direction of the road of a wp""" same_dir_wps = [waypoint] # Check roads on the right right_wp = waypoint while True: possible_right_wp = right_wp.get_right_lane() if possible_right_wp is None or possible_right_wp.lane_type != carla.LaneType.Driving: break right_wp = possible_right_wp same_dir_wps.append(right_wp) # Check roads on the left left_wp = waypoint while True: possible_left_wp = left_wp.get_left_lane() if possible_left_wp is None or possible_left_wp.lane_type != carla.LaneType.Driving: break if possible_left_wp.lane_id * left_wp.lane_id < 0: break left_wp = possible_left_wp same_dir_wps.append(left_wp) return same_dir_wps def get_opposite_dir_lanes(waypoint): """Gets all the lanes with opposite direction of the road of a wp""" other_dir_wps = [] other_dir_wp = None # Get the first lane of the opposite direction left_wp = waypoint while True: possible_left_wp = left_wp.get_left_lane() if possible_left_wp is None: break if possible_left_wp.lane_id * left_wp.lane_id < 0: other_dir_wp = possible_left_wp break left_wp = possible_left_wp if not other_dir_wp: return other_dir_wps # Check roads on the right right_wp = other_dir_wp while True: if right_wp.lane_type == carla.LaneType.Driving: other_dir_wps.append(right_wp) possible_right_wp = right_wp.get_right_lane() if possible_right_wp is None: break right_wp = possible_right_wp return other_dir_wps def get_lane_key(waypoint): """Returns a key corresponding to the waypoint lane. Equivalent to a 'Lane' object and used to compare waypoint lanes""" return '' if waypoint is None else get_road_key(waypoint) + '*' + str(waypoint.lane_id) def get_road_key(waypoint): """Returns a key corresponding to the waypoint road. Equivalent to a 'Road' object and used to compare waypoint roads""" return '' if waypoint is None else str(waypoint.road_id)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 198, 2, 770, 670, 318, 11971, 739, 262, 2846, 286, 262, 17168, 5964, 13, 198, 2, 1114, 257, 4866, 11, 766, 1279, 5450, 1378, 44813, 1668, 13, 2398, 14, 677, 4541, 14, 36393...
2.500625
1,600
#!/usr/bin/env python from argparse import ArgumentParser import sys from comp_pi import compute_pi if __name__ == '__main__': status = main() sys.exit(status)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 1822, 29572, 1330, 45751, 46677, 198, 11748, 25064, 198, 6738, 552, 62, 14415, 1330, 24061, 62, 14415, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198,...
2.898305
59
#!/usr/bin/env python3 import unittest import torch from Lgpytorch.lazy import CatLazyTensor, NonLazyTensor from Lgpytorch.test.lazy_tensor_test_case import LazyTensorTestCase if __name__ == "__main__": unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 555, 715, 395, 198, 198, 11748, 28034, 198, 198, 6738, 406, 70, 9078, 13165, 354, 13, 75, 12582, 1330, 5181, 43, 12582, 51, 22854, 11, 8504, 43, 12582, 51, 22854, 198...
2.478723
94
import datetime from sqlalchemy import Column, Integer, Boolean, ForeignKey, String, DateTime, UniqueConstraint, ForeignKeyConstraint from sqlalchemy.orm import relationship from dbConfig import Base, engine Base.metadata.create_all(engine)
[ 11748, 4818, 8079, 198, 6738, 44161, 282, 26599, 1330, 29201, 11, 34142, 11, 41146, 11, 8708, 9218, 11, 10903, 11, 7536, 7575, 11, 30015, 3103, 2536, 2913, 11, 8708, 9218, 3103, 2536, 2913, 198, 6738, 44161, 282, 26599, 13, 579, 1330, ...
3.716418
67
import paddle import paddle.nn as nn import paddle.nn.functional as F from paddle.nn.initializer import Assign import math
[ 11748, 39517, 198, 11748, 39517, 13, 20471, 355, 299, 77, 198, 11748, 39517, 13, 20471, 13, 45124, 355, 376, 198, 6738, 39517, 13, 20471, 13, 36733, 7509, 1330, 2195, 570, 198, 11748, 10688, 628 ]
3.647059
34
default_app_config = 'players.apps.PlayersConfig'
[ 12286, 62, 1324, 62, 11250, 796, 705, 32399, 13, 18211, 13, 24860, 16934, 6, 198 ]
3.333333
15
# Copyright 2019 The Forte Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Utility functions related to input/output. """ import os __all__ = [ "maybe_create_dir", "ensure_dir", "get_resource" ] import sys def maybe_create_dir(dirname: str) -> bool: r"""Creates directory if it does not exist. Args: dirname (str): Path to the directory. Returns: bool: Whether a new directory is created. """ if not os.path.isdir(dirname): os.makedirs(dirname) return True return False def ensure_dir(filename: str): """ Args: filename: Returns: """ d = os.path.dirname(filename) if d: maybe_create_dir(d)
[ 2, 15069, 13130, 383, 6401, 68, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 2...
2.877315
432
import re from AFD import AFD
[ 198, 11748, 302, 198, 6738, 12341, 35, 1330, 12341, 35, 628 ]
2.909091
11
from typing import List, Dict import pathlib import shutil import enum from typer import Option as O_ import typer from cs_tools.helpers.cli_ux import console, frontend, CSToolsGroup, CSToolsCommand from cs_tools.util.datetime import to_datetime from cs_tools.tools.common import run_tql_command, run_tql_script, tsload from cs_tools.util.algo import chunks from cs_tools.settings import TSConfig from cs_tools.const import FMT_TSLOAD_DATETIME from cs_tools.thoughtspot import ThoughtSpot from cs_tools.tools import common from .util import FileQueue HERE = pathlib.Path(__file__).parent def _format_metadata_objects(queue, metadata: List[Dict]): """ Standardize data in an expected format. This is a simple transformation layer, we are fitting our data to be record-based and in the format that's expected for an eventual tsload command. """ for parent in metadata: queue.put({ 'guid_': parent['id'], 'name': parent['name'], 'description': parent.get('description'), 'author_guid': parent['author'], 'author_name': parent['authorName'], 'author_display_name': parent['authorDisplayName'], 'created': to_datetime(parent['created'], unit='ms').strftime(FMT_TSLOAD_DATETIME), 'modified': to_datetime(parent['modified'], unit='ms').strftime(FMT_TSLOAD_DATETIME), # 'modified_by': parent['modifiedBy'] # user.guid 'type': SystemType.to_friendly(parent['type']) if parent.get('type') else 'column', 'context': parent.get('owner') }) def _format_dependency(queue, parent_guid, dependencies: Dict[str, Dict]): """ Standardize data in an expected format. This is a simple transformation layer, we are fitting our data to be record-based and in the format that's expected for an eventual tsload command. """ for dependency in dependencies: queue.put({ 'guid_': dependency['id'], 'parent_guid': parent_guid, 'name': dependency['name'], 'description': dependency.get('description'), 'author_guid': dependency['author'], 'author_name': dependency['authorName'], 'author_display_name': dependency['authorDisplayName'], 'created': to_datetime(dependency['created'], unit='ms').strftime(FMT_TSLOAD_DATETIME), 'modified': to_datetime(dependency['modified'], unit='ms').strftime(FMT_TSLOAD_DATETIME), # 'modified_by': dependency['modifiedBy'] # user.guid 'type': SystemType.to_friendly(dependency['type']) }) app = typer.Typer( help=""" Make Dependencies searchable in your platform. [b][yellow]USE AT YOUR OWN RISK![/b] This tool uses private API calls which could change on any version update and break the tool.[/] Dependencies can be collected for various types of metadata. For example, many tables are used within a worksheet, while many worksheets will have answers and pinboards built on top of them. \b Metadata Object Metadata Dependent - guid - guid - name - parent guid - description - name - author guid - description - author name - author guid - author display name - author name - created - author display name - modified - created - object type - modified - context - object type \f Also available, but not developed for.. Tag / Stickers -> TAG Embrace Connections -> DATA_SOURCE """, cls=CSToolsGroup, options_metavar='[--version, --help]' )
[ 6738, 19720, 1330, 7343, 11, 360, 713, 198, 11748, 3108, 8019, 198, 11748, 4423, 346, 198, 11748, 33829, 198, 198, 6738, 1259, 525, 1330, 16018, 355, 440, 62, 198, 11748, 1259, 525, 198, 198, 6738, 50115, 62, 31391, 13, 16794, 364, 13...
2.499342
1,520
#!/usr/bin/python import math import random from utils.log import log from bots.simpleBots import BasicBot
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 10688, 198, 11748, 4738, 198, 198, 6738, 3384, 4487, 13, 6404, 1330, 2604, 198, 6738, 29641, 13, 36439, 33, 1747, 1330, 14392, 20630, 198 ]
3.205882
34
import uuid from typing import Dict, List from nehushtan.ws.NehushtanWebsocketConnectionEntity import NehushtanWebsocketConnectionEntity
[ 11748, 334, 27112, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 198, 198, 6738, 497, 71, 1530, 38006, 13, 18504, 13, 8199, 71, 1530, 38006, 1135, 1443, 5459, 32048, 32398, 1330, 44470, 1530, 38006, 1135, 1443, 5459, 32048, 32398, 628 ]
3.475
40
from .interface import Beverage, CondimentDecorator
[ 6738, 764, 39994, 1330, 22185, 496, 11, 9724, 3681, 10707, 273, 1352, 628, 628 ]
3.928571
14
# # # Copyright 2009 HPGL Team # # This file is part of HPGL (High Perfomance Geostatistics Library). # # HPGL 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, version 2 of the License. # # HPGL 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 HPGL. If not, see http://www.gnu.org/licenses/. # from geo import * from sys import * import os import time if not os.path.exists("results/"): os.mkdir("results/") if not os.path.exists("results/medium/"): os.mkdir("results/medium/") #grid = SugarboxGrid(166, 141, 225) #prop = load_cont_property("test_data/BIG_HARD_DATA.INC", -99) grid = SugarboxGrid(166, 141, 20) prop = load_cont_property("test_data/BIG_SOFT_DATA_CON_160_141_20.INC",-99) sgs_params = { "prop": prop, "grid": grid, "seed": 3439275, "kriging_type": "sk", "radiuses": (20, 20, 20), "max_neighbours": 12, "covariance_type": covariance.exponential, "ranges": (10, 10, 10), "sill": 0.4 } for x in xrange(1): time1 = time.time() psgs_result = sgs_simulation(workers_count = x+2, use_new_psgs = True, **sgs_params) time2 = time.time() print "Workers: %s" % (x+2) print "Time: %s" % (time2 - time1) write_property(psgs_result, "results/medium/PSGS_workers_1.inc", "PSIS_MEDIUM_workers_1", -99)
[ 2, 201, 198, 2, 201, 198, 2, 220, 220, 15069, 3717, 6574, 8763, 4816, 201, 198, 2, 201, 198, 2, 220, 220, 770, 2393, 318, 636, 286, 6574, 8763, 357, 11922, 2448, 69, 296, 590, 2269, 455, 265, 3969, 10074, 737, 201, 198, 2, 201, ...
2.600634
631
friendly_camera_mapping = { "GM1913": "Oneplus 7 Pro", "FC3170": "Mavic Air 2", # An analogue scanner in FilmNeverDie "SP500": "Canon AE-1 Program" }
[ 13120, 62, 25695, 62, 76, 5912, 796, 1391, 198, 220, 220, 220, 366, 15548, 1129, 1485, 1298, 366, 3198, 9541, 767, 1041, 1600, 198, 220, 220, 220, 366, 4851, 18, 17279, 1298, 366, 44, 615, 291, 3701, 362, 1600, 198, 220, 220, 220, ...
2.371429
70
from typing_extensions import Annotated, TypeGuard from typing import TypeVar, List, Set, Dict from refined.predicates import ( PositivePredicate, NegativePredicate, ValidIntPredicate, ValidFloatPredicate, EmptyPredicate, NonEmptyPredicate, TrimmedPredicate, IPv4Predicate, IPv6Predicate, XmlPredicate, CsvPredicate ) __all__ = [ # numeric types 'Positive', 'Negative', # string types 'TrimmedString', 'ValidIntString', 'ValidFloatString', 'XmlString', 'CsvString', 'IPv4String', 'IPv6String', # generic collection types 'Empty', 'NonEmpty', # concrete collection types 'NonEmptyString', 'NonEmptyList', 'NonEmptySet', 'NonEmptyDict', ] _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") Positive = Annotated[_T1, PositivePredicate[_T1]] Negative = Annotated[_T1, NegativePredicate[_T1]] TrimmedString = Annotated[str, TrimmedPredicate[str]] ValidIntString = Annotated[str, ValidIntPredicate[str]] ValidFloatString = Annotated[str, ValidFloatPredicate[str]] XmlString = Annotated[str, XmlPredicate[str]] CsvString = Annotated[str, CsvPredicate[str]] IPv4String = Annotated[str, IPv4Predicate[str]] IPv6String = Annotated[str, IPv6Predicate[str]] Empty = Annotated[_T1, EmptyPredicate[_T1]] NonEmpty = Annotated[_T1, NonEmptyPredicate[_T1]] NonEmptyString = Annotated[str, NonEmptyPredicate[str]] NonEmptyList = Annotated[List[_T1], NonEmptyPredicate[List[_T1]]] NonEmptySet = Annotated[Set[_T1], NonEmptyPredicate[Set[_T1]]] NonEmptyDict = Annotated[Dict[_T1, _T2], NonEmptyPredicate[Dict[_T1, _T2]]]
[ 6738, 19720, 62, 2302, 5736, 1330, 1052, 1662, 515, 11, 5994, 24502, 198, 6738, 19720, 1330, 5994, 19852, 11, 7343, 11, 5345, 11, 360, 713, 198, 198, 6738, 20449, 13, 28764, 16856, 1330, 357, 198, 220, 220, 220, 33733, 39156, 5344, 11...
2.530421
641
from setuptools import setup with open("README.md", "r") as f: long_description = f.read() setup(name="SpotPRIS2", version='0.3.1', author="Adrian Freund", author_email="adrian@freund.io", url="https://github.com/freundTech/SpotPRIS2", description="MPRIS2 interface for Spotify Connect", long_description=long_description, packages=['spotpris2'], package_dir={'spotpris2': "spotpris2"}, package_data={'spotpris2': ['mpris/*.xml', 'html/*.html']}, install_requires=[ "PyGObject", "pydbus", "spotipy>=2.8", "appdirs", ], entry_points={ 'console_scripts': ["spotpris2=spotpris2.__main__:main"] }, classifiers=[ "Development Status :: 3 - Alpha", "Environment :: No Input/Output (Daemon)", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3 :: Only", "Topic :: Multimedia :: Sound/Audio", ], python_requires='>=3.6', )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 277, 13, 961, 3419, 198, 198, 40406, 7, 3672, 2625, 32565, 4805, 17...
2.192381
525
# Generated by Django 4.0.3 on 2022-04-02 17:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 604, 13, 15, 13, 18, 319, 33160, 12, 3023, 12, 2999, 1596, 25, 2624, 201, 198, 201, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 201, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 201, ...
2.762712
59