content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
import os from datetime import timedelta # ~~~~~ PATH ~~~~~ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ~~~~~ TEST ~~~~~ TEST_RUN = getenv_boolean('TEST_RUN', False) # ~~~~~ API ~~~~~ # ~~~~~ SECRET ~~~~~ SECRET_KEY = os.getenv('SECRET_KEY', 'cuerno de unicornio :D') if not SECRET_KEY: SECRET_KEY = os.urandom(32) # ~~~~~ APPS ~~~~~ APPS = [ 'health_check', 'token', 'hello_world' ] # ~~~~~ JWT ~~~~~ JWT_EXPIRATION_DELTA = timedelta(hours=int(os.getenv('ACCESS_TOKEN_EXPIRE_MINUTES', 10))) # in hours JWT_REFRESH_EXPIRATION_DELTA = timedelta(hours=int(os.getenv('JWT_REFRESH_EXPIRATION_DELTA', 10))) # in hours JWT_AUTH_HEADER_PREFIX = os.getenv('JWT_AUTH_HEADER_PREFIX', 'JWT') JWT_SECRET_KEY = SECRET_KEY # ~~~~~ CORS ~~~~~ BACKEND_CORS_ORIGINS = os.getenv( 'BACKEND_CORS_ORIGINS' ) # a string of origins separated by commas, e.g: 'http://localhost, http://localhost:4200, http://localhost:3000 # ~~~~~ APP ~~~~~ PROJECT_NAME = os.getenv('PROJECT_NAME', 'Fastapi') # ~~~~~ EMAIL ~~~~~ SENTRY_DSN = os.getenv('SENTRY_DSN') SMTP_TLS = getenv_boolean('SMTP_TLS', True) SMTP_PORT = None _SMTP_PORT = os.getenv('SMTP_PORT') if _SMTP_PORT is not None: SMTP_PORT = int(_SMTP_PORT) SMTP_HOST = os.getenv('SMTP_HOST') SMTP_USER = os.getenv('SMTP_USER') SMTP_PASSWORD = os.getenv('SMTP_PASSWORD') EMAILS_FROM_EMAIL = os.getenv('EMAILS_FROM_EMAIL') EMAILS_FROM_NAME = PROJECT_NAME EMAIL_RESET_TOKEN_EXPIRE_HOURS = 48 EMAIL_TEMPLATES_DIR = '/app/app/email-templates/build' EMAILS_ENABLED = SMTP_HOST and SMTP_PORT and EMAILS_FROM_EMAIL # ~~~~~ DATA_BASE ~~~~~ DATABASES = { 'type': os.environ.get('type', 'postgresql'), 'database': os.environ.get('database', 'fastapi'), 'username': os.environ.get('username', 'myproject'), 'password': os.environ.get('password', 'myproject'), 'host': os.environ.get('host', 'localhost'), 'port': os.environ.get('port', 5432) } # ~~~~~ OAUTH 2 ~~~~~ SCOPES = { 'read': 'Read', 'write': 'Write' }
[ 11748, 28686, 198, 6738, 4818, 8079, 1330, 28805, 12514, 628, 628, 198, 2, 220, 8728, 93, 46490, 220, 8728, 93, 198, 198, 33, 11159, 62, 34720, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, ...
2.228916
913
import skvideo.io import skvideo.utils import numpy as np import os import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest @unittest.skipIf(not skvideo._HAS_FFMPEG, "FFmpeg required for this test.") @unittest.skipIf(not skvideo._HAS_AVCONV, "LibAV required for this test.") @unittest.skipIf(not skvideo._HAS_FFMPEG, "FFmpeg required for this test.") @unittest.skipIf(not skvideo._HAS_AVCONV, "LibAV required for this test.")
[ 11748, 1341, 15588, 13, 952, 198, 11748, 1341, 15588, 13, 26791, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 361, 25064, 13, 9641, 62, 10951, 1279, 357, 17, 11, 767, 2599, 198, 220, 220, 220, 13...
2.681564
179
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... setup( name = "snotebook", version = "0.2.2", author = "Nicole A Montano", author_email = "n@nicolemon.com", description = ("A rudimentary CLI to write and organize text"), license = "MIT", keywords = "cli commandline terminal notes python", url = "https://github.com/nicolemon/snote", packages=['snote'], long_description=read('README.md'), classifiers=[ "Development Status :: 3 - Alpha", 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', ], extras_require={ 'test': ['pytest'], }, entry_points={ 'console_scripts': [ 'snote=snote:main', ], }, )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 2, 34030, 2163, 284, 1100, 262, 20832, 11682, 23...
2.574684
395
from .gan_attack import GAN_Attack # noqa: F401 from .generator_attack import Generator_Attack # noqa: F401 from .mi_face import MI_FACE # noqa: F401
[ 6738, 764, 1030, 62, 20358, 1330, 402, 1565, 62, 27732, 220, 1303, 645, 20402, 25, 376, 21844, 198, 6738, 764, 8612, 1352, 62, 20358, 1330, 35986, 62, 27732, 220, 1303, 645, 20402, 25, 376, 21844, 198, 6738, 764, 11632, 62, 2550, 1330...
2.886792
53
import functools import io import builtin_dataset_mocks import pytest from torchdata.datapipes.iter import IterDataPipe from torchvision.prototype import datasets from torchvision.prototype.utils._internal import sequence_to_str _loaders = [] _datasets = [] # TODO: this can be replaced by torchvision.prototype.datasets.list() as soon as all builtin datasets are supported TMP = [ "mnist", "fashionmnist", "kmnist", "emnist", "qmnist", "cifar10", "cifar100", "caltech256", "caltech101", "imagenet", ] for name in TMP: loader = functools.partial(builtin_dataset_mocks.load, name) _loaders.append(pytest.param(loader, id=name)) info = datasets.info(name) _datasets.extend( [ pytest.param(*loader(**config), id=f"{name}-{'-'.join([str(value) for value in config.values()])}") for config in info._configs ] ) loaders = pytest.mark.parametrize("loader", _loaders) builtin_datasets = pytest.mark.parametrize(("dataset", "mock_info"), _datasets)
[ 11748, 1257, 310, 10141, 198, 11748, 33245, 198, 198, 11748, 3170, 259, 62, 19608, 292, 316, 62, 76, 3320, 198, 11748, 12972, 9288, 198, 6738, 28034, 7890, 13, 19608, 499, 18636, 13, 2676, 1330, 40806, 6601, 47, 3757, 198, 6738, 28034, ...
2.437209
430
from django.urls import path from . import views urlpatterns = [ path("signup/", views.SignUp.as_view(), name="signup"), path("manageuserprofile/", views.manage_user_profile, name="manageuserprofile"), path("followingprocessor/", views.follow, name="followuser"), path("unfollowingprocessor/", views.unfollow, name='unfollowuser'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 7203, 12683, 929, 14, 1600, 5009, 13, 11712, 4933, 13, 292, 62, 1177, 22784, 1438, 2625, 12683, ...
2.991453
117
def format_client_list_result(result, exclude_attributes=None): """ Format an API client list return which contains a list of objects. :param exclude_attributes: Optional list of attributes to exclude from the item. :type exclude_attributes: ``list`` :rtype: ``list`` of ``dict`` """ formatted = [] for item in result: value = item.to_dict(exclude_attributes=exclude_attributes) formatted.append(value) return formatted
[ 4299, 5794, 62, 16366, 62, 4868, 62, 20274, 7, 20274, 11, 19607, 62, 1078, 7657, 28, 14202, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 18980, 281, 7824, 5456, 1351, 1441, 543, 4909, 257, 1351, 286, 5563, 13, 628, 220, 220,...
2.975155
161
__all__ = [ 'raytheon', 'vividsolutions' ]
[ 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 705, 2433, 1169, 261, 3256, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 705, 85, 1699, 82, 14191, 6, 198, 220, 220, 220, ...
1.471698
53
import os from unittest import TestCase from gene_loci_comparison import Locus import matplotlib import matplotlib.pyplot as plt from bokeh.plotting import output_file, show, save matplotlib.rcParams['font.family'] = "PT Sans Narrow" save_plots = False assert os.path.isfile('tests/test_loci.py'), f'Please set working directory to git root!' pgap_file = 'tests/data/PGAP/FAM3257.gbk' prokka_file = 'tests/data/Prokka/FAM3257.gbk' new_prokka_file = 'tests/data/Prokka/Lbombicola_ESL0228.gbk' bad_first_gene_file = 'tests/data/FirstGene/REFERENCE.gbk' yeast_file = 'tests/data/yeast/R64-3-1.gbk'
[ 11748, 28686, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 9779, 62, 75, 1733, 62, 785, 1845, 1653, 1330, 406, 10901, 198, 11748, 2603, 29487, 8019, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 1...
2.489627
241
import threading import unittest import mock from sia_load_tester import jobs from sia_load_tester import dataset_uploader from sia_load_tester import sia_client as sc from sia_load_tester import upload_queue
[ 11748, 4704, 278, 198, 11748, 555, 715, 395, 198, 198, 11748, 15290, 198, 198, 6738, 264, 544, 62, 2220, 62, 4879, 353, 1330, 3946, 198, 6738, 264, 544, 62, 2220, 62, 4879, 353, 1330, 27039, 62, 25850, 263, 198, 6738, 264, 544, 62, ...
3.117647
68
import torch from torch.autograd import grad from torch.functional import unique from deepmechanics import utilities import unittest
[ 11748, 28034, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 3915, 198, 6738, 28034, 13, 45124, 1330, 3748, 198, 6738, 2769, 1326, 3147, 873, 1330, 20081, 198, 11748, 555, 715, 395, 628 ]
4.1875
32
""" Classes used to identify and build Construction objects """ import collections import copy import networkx as nx from positions import Dummy, Positions, PositionsTF, Walker from debugging import Debugger from .cx import Construction class CXbuilder(object): """Identifies and builds constructions using Text-Fabric nodes.""" def __init__(self): """Initialize CXbuilder, giving methods for CX detection.""" # cache matched constructions for backreferences self.cache = collections.defaultdict( lambda: collections.defaultdict() ) # NB: objects below should be overwritten # and configured for the particular cxs needed self.cxs = tuple() self.yieldsto = {} # for drip-bucket categories self.dripbucket = tuple() def cxcache(self, element, name, method): """Get cx from cache or run.""" try: return self.cache[element][name] except KeyError: return method(element) def test_result(self, test, *cases): """Return the result of a test as a new Construction object""" # return last test if test: cx = Construction( match=test[-1], cases=cases, **test[-1] ) self.cache[cx.element][cx.name] = cx return cx else: return Construction(cases=cases, **cases[0]) def test(self, *cases): """Populate Construction obj based on a cases's all Truth value. The last-matching case will be used to populate a Construction object. This allows more complex cases to take precedence over simpler ones. Args: cases: an arbitrary number of dictionaries, each of which contains a string key that describes the test and a test that evals to a Boolean. Returns: a populated or blank Construction object """ # find cases where all cnds == True test = [ case for case in cases if all(case['conds'].values()) and all(get_roles(case).values()) ] return self.test_result(test, *cases) def findall(self, element): """Runs analysis for all constructions with an element. Returns as dict with test:result as key:value. """ results = [] # add cxs from this builder for funct in self.cxs: cx = funct(element) if cx: results.append(cx) return results def sortbyslot(self, cxlist): """Sort constructions by order of contained slots.""" sort = sorted( ((sorted(cx.slots), cx) for cx in cxlist), key=lambda k: k[0] ) return [cx[-1] for cx in sort] def clusterCXs(self, cxlist): """Cluster constructions which overlap in their slots/roles. Overlapping constructions form a graph wherein the constructions are nodes and the overlaps are edges. This algorithm retrieves all interconnected constructions. It does so with a recursive check for overlapping slot sets. Merging the slot sets produces new overlaps. The algorithm passes over all constructions until no further overlaps are detected. Args: cxlist: list of Construction objects Returns: list of lists, where each embedded list is a cluster of overlapping constructions. """ clusters = [] cxlist = [i for i in cxlist] # operate on copy # iterate until no more intersections found thiscluster = [cxlist.pop(0)] theseslots = set(s for s in thiscluster[0].slots) # loop continues as it snowballs and picks up slots # loop stops when a complete loop produces no other matches while cxlist: matched = False # whether loop was successful for cx in cxlist: if theseslots & set(cx.slots): thiscluster.append(cx) theseslots |= set(cx.slots) matched = True # cxlist shrinks; when empty, it stops loop cxlist = [ cx for cx in cxlist if cx not in thiscluster ] # assemble loop if not matched: clusters.append(thiscluster) thiscluster = [cxlist.pop(0)] theseslots = set(s for s in thiscluster[0].slots) # add last cluster clusters.append(thiscluster) return clusters def yields(self, cx1, cx2): """Determine whether to submit cx1 to cx2.""" # determine which yields dict to use # yielding can be configured generally # or specific to a pattern and its rules yieldsto = cx1.__dict__.get('yieldsto', self.yieldsto) # get name or class yields cx1yields = yieldsto.get( cx1.name, yieldsto.get(cx1.kind, set()) ) # test yields if type(cx1yields) == set: return bool({cx2.name, cx2.kind} & cx1yields) elif type(cx1yields) == bool: return cx1yields def interslots(self, cx1, cx2): """Get the intersecting slots of two CXs Return as sorted tuple. """ return tuple(sorted( set(cx1.slots) & set(cx2.slots) )) def slots2node(self, cx, slots): """Get a CX node from a tuple of slots.""" return_node = None # return last matching node for node in nx.bfs_tree(cx.graph, cx): if cx.getslots(node) == slots and type(node) != int: return_node = node return return_node def intersect_node(self, cx1, cx2): """Get node from cx1 with slots common with cx2.""" intersect = self.interslots(cx1, cx2) return self.slots2node(cx1, intersect) def weaveCX(self, cxlist, debug=False): """Weave together constructions on their intersections. Overlapping constructions form a graph wherein constructions are nodes and the overlaps are edges. The graph indicates that the constructions function together as one single unit. weaveCX combines all constructions into a single one. Moving from right-to-left (Hebrew), the function consumes and subsumes subsequent constructions to previous ones. The result is a single unit with embedding based on the order of consumption. Roles in previous constructions are thus expanded into the constructions of their subsequent constituents. For instance, take the following phrase in English: > "to the dog" Say a CXbuilder object contains basic noun patterns and can recognize the following contained constructions: > cx Preposition: ('prep', to), ('obj', the), > cx Definite: ('art', the), ('noun', dog) When the words of the constructions are compared, an overlap can be seen: > cx Preposition: to the > cx Definite: the dog The overlap in this case is "the". The overlap suggests that the slot filled by "the" in the Preposition construction should be expanded. This can be done by remapping the role filled by "the" alone to the subsequent Definite construction. This results in embedding: > cx Preposition: ('prep', to), ('obj', cx Definite: ('art', the), ('noun', dog)) weaveCX accomplishes this by calling the updaterole method native to Construction objects. The end result is a list of merged constructions that contain embedding. Args: cxlist: a list of constructions pre-sorted for word order; the list shrinks throughout recursive iteration until the job is finished cx: a construction object to begin/continue analysis on debug: an option to display debugging messages for when things go wrong 🤪 Prerequisites: self.yieldsto: A dictionary in CXbuilder that tells weaveCX to subsume one construction into another regardless of word order. Key is name of submissive construction, value is a set of dominating constructions. Important for, e.g., cases of quantification where a head-noun might be preceded by a chain of quantifiers but should still be at the top of the structure since it is more semantically prominent. Returns: a list of composed constructions """ db = Debugger(debug) db.say(f'\nReceived cxlist {cxlist}', 0) # compile all cxs to here root = copy.deepcopy(cxlist.pop(0)) db.say(f'Beginning analysis with {root}') # begin matching and remapping while cxlist: # get next cx ncx = copy.deepcopy(cxlist.pop(0)) # find root node with slots intersecting next cx db.say(f'comparing {root} with {ncx}', 1) node = self.intersect_node(root, ncx) db.say(f'intersect is at {node}') # remove cxs covered by larger version if root in ncx: db.say(f'root {root} in ncx {ncx}...replacing root with ncx') root = ncx # update yielded nodes elif self.yields(node, ncx): db.say(f'{node} being yielded to {ncx}') # get top-most yielding node path = nx.shortest_path(root.graph, root, node) while path and self.yields(path[-1], ncx): node = path.pop(-1) db.say(f'top-yielding node is {node}', 2) # update ncx graph db.say(f'comparing {ncx} with {node}') ncxnode = self.intersect_node(ncx, node) db.say(f'intersect is at {ncxnode}') ncx.updategraph(ncxnode, node) db.say(f'ncx updated to {ncx}') # update root graph or remap root to ncx if root != node: rnode = self.intersect_node(root, ncx) db.say(f'replacing node {rnode} in root {root} with {ncx}') root.updategraph(rnode, ncx) else: # switch root and ncx db.say(f'switching {root} with {ncx}') root = ncx # update all non-yielding nodes else: db.say(f'\tupdating {node} in root with {ncx}') root.updategraph(node, ncx) return root def analyzestretch(self, stretch, duplicate=False, debug=False): """Analyze an entire stretch of a linguistic unit. Applies construction tests for every constituent and merges all overlapping constructions into a single construction. Args: stretch: an iterable containing elements that are tested by construction tests to build Construction objects. e.g. stretch might be a list of TF word nodes. duplicate: whether to keep a copy of an analyzed cx debug: option to display debuggin messages Returns: list of merged constructions """ db = Debugger(debug) # match elements to constructions based on tests rawcxs = [] covered = set() for element in stretch: matches = self.findall(element) if matches: rawcxs.extend(matches) covered |= set( el for cx in matches for el in cx.graph ) # keep copy of the cx if duplicate: rawcxs.append(element) covered.add(element) # apply drip-bucket categories for element in set(stretch) - covered: for funct in self.dripbucket: dripcx = funct(element) if dripcx: rawcxs.append(dripcx) db.say(f'rawcxs found: {rawcxs}...') # return empty results if not rawcxs: db.say(f'!no cx pattern matches! returning []') return [] # cluster and sort matched constructions clsort = [ self.sortbyslot(cxlist) for cxlist in self.clusterCXs(rawcxs) ] db.say(f'cxs clustered into: {clsort}...') db.say(f'Beginning weaveCX method...') # merge overlapping constructions cxs = [ self.weaveCX(cluster, debug=debug) for cluster in clsort ] return self.sortbyslot(cxs) class CXbuilderTF(CXbuilder): """Build Constructions with TF integration.""" def getP(self, node, context=None): """Get Positions object for a TF node. Return Dummy object if not node. """ context = context or self.context if not node: return Dummy return PositionsTF(node, context, self.tf.api).get def getWk(self, node, context=None): """Get Walker object for a TF word node. Return Dummy object if not node. """ if not node: return Dummy() # format tf things to send thisotype = self.F.otype.v(node) get_context = context or self.context context = self.L.u(node, get_context)[0] positions = self.L.d(context, thisotype) return Walker(node, positions)
[ 37811, 198, 9487, 274, 973, 284, 5911, 290, 1382, 20395, 5563, 198, 37811, 198, 198, 11748, 17268, 198, 11748, 4866, 198, 11748, 3127, 87, 355, 299, 87, 198, 6738, 6116, 1330, 360, 13513, 11, 18574, 1756, 11, 18574, 1756, 10234, 11, 1...
2.04805
7,180
import os import re import argparse import datetime import pandas as pd from sklearn.model_selection import StratifiedKFold from classifier import MultiClassifierModel from classifier import BinaryClassifierModel from factory import get_dataset, get_model from util.seed import set_seed from util.yml import get_config from logging import getLogger, DEBUG, INFO, StreamHandler, FileHandler, Formatter logger = getLogger(__name__) # いずれはvalidation dataなしで学習させるよー # fold0フォルダ邪魔 if __name__ == '__main__': args = parse_args() main(args)
[ 11748, 28686, 198, 11748, 302, 198, 11748, 1822, 29572, 198, 11748, 4818, 8079, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 29186, 1431, 42, 37, 727, 198, 198, 6738, 1398, 7483, 1330, ...
2.901042
192
''' tuple: is immutable once created (cannot append) ''' #my_tuple = 'a','b','c','d','e' #print(my_tuple) #my_second_tuple = ('a','b','c','d','e') #print(my_second_tuple) #not_a_tuple = ('a') #print( type(not_a_tuple) ) #a_tuple = ('a',) #print( type( a_tuple) ) #print(my_tuple[1]) #print(my_second_tuple[1:3]) ''' Dictionary is a collection of key value pairs with JSON files, treat as dictionary ''' my_car = { 'color':'red', 'maker': 'toyota', 'year':2015 } print(my_car.get('color')) #or print(my_car['maker']) print(my_car.items()) print(my_car.values()) print(my_car.keys()) #adding new entry in dictionary my_car['model']='corola' print(my_car['model']) print('year' in my_car)
[ 7061, 6, 198, 83, 29291, 25, 318, 40139, 1752, 2727, 357, 66, 34574, 24443, 8, 198, 7061, 6, 198, 198, 2, 1820, 62, 83, 29291, 796, 705, 64, 41707, 65, 41707, 66, 41707, 67, 41707, 68, 6, 198, 2, 4798, 7, 1820, 62, 83, 29291, ...
2.22291
323
#!/usr/bin/python # fruits.py basket = ('oranges', 'pears', 'apples', 'bananas') fruits = {}.fromkeys(basket, 0) print(fruits) fruits['oranges'] = 12 fruits['pears'] = 8 fruits['apples'] = 4 print(fruits.setdefault('oranges', 11)) print(fruits.setdefault('kiwis', 11)) print(fruits)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 2, 15921, 13, 9078, 198, 198, 65, 11715, 796, 19203, 273, 6231, 3256, 705, 431, 945, 3256, 705, 1324, 829, 3256, 705, 3820, 15991, 11537, 198, 198, 69, 50187, 796, 23884, 13, 6738, 130...
2.38843
121
import math from mcts.node import Node
[ 11748, 10688, 198, 198, 6738, 285, 310, 82, 13, 17440, 1330, 19081, 628, 198 ]
3
14
# -*- coding: utf-8 -*- if __name__ == '__main__': main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 220, 220, 220, 1388, 3419, 201, 198 ]
1.775
40
/anaconda3/lib/python3.7/hmac.py
[ 14, 272, 330, 13533, 18, 14, 8019, 14, 29412, 18, 13, 22, 14, 71, 20285, 13, 9078 ]
1.882353
17
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from space_api.proto import server_pb2 as server__pb2
[ 2, 2980, 515, 416, 262, 308, 49, 5662, 11361, 8435, 17050, 13877, 13, 8410, 5626, 48483, 0, 198, 11748, 1036, 14751, 198, 198, 6738, 2272, 62, 15042, 13, 1676, 1462, 1330, 4382, 62, 40842, 17, 355, 4382, 834, 40842, 17, 628, 628 ]
3.333333
42
# pylint: disable=line-too-long,too-many-lines,missing-docstring,arguments-differ,unused-argument __all__ = ['I3D_InceptionV1', 'i3d_inceptionv1_kinetics400'] from mxnet import nd from mxnet import init from mxnet.context import cpu from mxnet.gluon.block import HybridBlock from mxnet.gluon import nn from mxnet.gluon.nn import BatchNorm from mxnet.gluon.contrib.nn import HybridConcurrent from gluoncv.model_zoo.googlenet import googlenet class I3D_InceptionV1(HybridBlock): r"""Inception v1 model from `"Going Deeper with Convolutions" <https://arxiv.org/abs/1409.4842>`_ paper. Inflated 3D model (I3D) from `"Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset" <https://arxiv.org/abs/1705.07750>`_ paper. Slight differences between this implementation and the original implementation due to padding. Parameters ---------- nclass : int Number of classes in the training dataset. pretrained : bool or str. Boolean value controls whether to load the default pretrained weights for model. String value represents the hashtag for a certain version of pretrained weights. pretrained_base : bool or str, optional, default is True. Load pretrained base network, the extra layers are randomized. Note that if pretrained is `True`, this has no effect. dropout_ratio : float, default is 0.5. The dropout rate of a dropout layer. The larger the value, the more strength to prevent overfitting. num_segments : int, default is 1. Number of segments used to evenly divide a video. num_crop : int, default is 1. Number of crops used during evaluation, choices are 1, 3 or 10. feat_ext : bool. Whether to extract features before dense classification layer or do a complete forward pass. init_std : float, default is 0.001. Standard deviation value when initialize the dense layers. ctx : Context, default CPU. The context in which to load the pretrained weights. partial_bn : bool, default False. Freeze all batch normalization layers during training except the first layer. norm_layer : object Normalization layer used (default: :class:`mxnet.gluon.nn.BatchNorm`) Can be :class:`mxnet.gluon.nn.BatchNorm` or :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`. norm_kwargs : dict Additional `norm_layer` arguments, for example `num_devices=4` for :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`. """ def i3d_inceptionv1_kinetics400(nclass=400, pretrained=False, pretrained_base=True, ctx=cpu(), root='~/.mxnet/models', use_tsn=False, num_segments=1, num_crop=1, partial_bn=False, feat_ext=False, **kwargs): r"""Inception v1 model trained on Kinetics400 dataset from `"Going Deeper with Convolutions" <https://arxiv.org/abs/1409.4842>`_ paper. Inflated 3D model (I3D) from `"Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset" <https://arxiv.org/abs/1705.07750>`_ paper. Parameters ---------- nclass : int. Number of categories in the dataset. pretrained : bool or str. Boolean value controls whether to load the default pretrained weights for model. String value represents the hashtag for a certain version of pretrained weights. pretrained_base : bool or str, optional, default is True. Load pretrained base network, the extra layers are randomized. Note that if pretrained is `True`, this has no effect. ctx : Context, default CPU. The context in which to load the pretrained weights. root : str, default $MXNET_HOME/models Location for keeping the model parameters. num_segments : int, default is 1. Number of segments used to evenly divide a video. num_crop : int, default is 1. Number of crops used during evaluation, choices are 1, 3 or 10. partial_bn : bool, default False. Freeze all batch normalization layers during training except the first layer. feat_ext : bool. Whether to extract features before dense classification layer or do a complete forward pass. """ model = I3D_InceptionV1(nclass=nclass, partial_bn=partial_bn, pretrained=pretrained, pretrained_base=pretrained_base, feat_ext=feat_ext, num_segments=num_segments, num_crop=num_crop, dropout_ratio=0.5, init_std=0.01, ctx=ctx, **kwargs) if pretrained: from ..model_store import get_model_file model.load_parameters(get_model_file('i3d_inceptionv1_kinetics400', tag=pretrained, root=root), ctx=ctx) from ...data import Kinetics400Attr attrib = Kinetics400Attr() model.classes = attrib.classes model.collect_params().reset_ctx(ctx) return model
[ 2, 279, 2645, 600, 25, 15560, 28, 1370, 12, 18820, 12, 6511, 11, 18820, 12, 21834, 12, 6615, 11, 45688, 12, 15390, 8841, 11, 853, 2886, 12, 26069, 263, 11, 403, 1484, 12, 49140, 198, 198, 834, 439, 834, 796, 37250, 40, 18, 35, 6...
2.440599
2,138
from twitter.twitter_api import TwitterAPI import logging import requests from dotenv import load_dotenv from os import getenv load_dotenv('/opt/airflow/aws_twi_env/.env') # Creating a specific class to interact with get_users_id endpoint. logger = logging.getLogger(__name__) logging.basicConfig(level = logging.INFO) # Specify the usernames that you want to lookup below # You can enter up to 100 comma-separated values. # User fields are adjustable, options include: # created_at, description, entities, id, location, name, # pinned_tweet_id, profile_image_url, protected, # public_metrics, url, username, verified, and withheld
[ 6738, 17044, 13, 6956, 62, 15042, 1330, 3009, 17614, 198, 11748, 18931, 198, 11748, 7007, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 6738, 28686, 1330, 651, 24330, 198, 198, 2220, 62, 26518, 24330, 10786, 14, 8738, 14, ...
3.295
200
import weakref from .entity import Entity
[ 11748, 4939, 5420, 198, 198, 6738, 764, 26858, 1330, 20885, 198 ]
3.909091
11
import keras from keras.models import Sequential from keras.layers import Dense
[ 11748, 41927, 292, 201, 198, 6738, 41927, 292, 13, 27530, 1330, 24604, 1843, 201, 198, 6738, 41927, 292, 13, 75, 6962, 1330, 360, 1072, 201, 198, 201, 198 ]
3.035714
28
""" Unit tests for the Friedman module """ import math import numpy as np import vtk import glenoidplanefitting.algorithms.models as mdl def test_make_plane_model(): """ Tests that make_plane_model returns a plane centred on the plane centre with the correct normal vector """ plane_centre = [1.0, 3.0, 5.0] plane_normal = [7.0, 11.0, 13.0] plane_size = 200.0 plane_resolution = 20 plane = mdl.make_plane_model(plane_centre, plane_normal, plane_resolution, plane_size) assert isinstance (plane, vtk.vtkPlaneSource)#pylint:disable=no-member assert np.array_equal(np.array(plane.GetCenter()), np.array(plane_centre)) denormalised_normal = np.linalg.norm(np.array(plane_normal)) \ * np.array(plane.GetNormal()) assert np.allclose(denormalised_normal, np.array(plane_normal)) assert plane.GetXResolution() == plane_resolution assert plane.GetYResolution() == plane_resolution actual_plane_size = np.linalg.norm(np.array(plane.GetPoint1()) - np.array(plane.GetPoint2())) expected_plane_size = math.sqrt(2 * (plane_size * plane_size)) assert math.isclose(actual_plane_size, expected_plane_size) def test_friedman_model(): """ Tests that make Friedman model returns the appropriate line """ point1 = (2.0, 3.0, 5.0) point2 = (7.0, 11.0, 13.0) line = mdl.make_friedman_model(point1, point2) assert isinstance(line, vtk.vtkLineSource)#pylint:disable=no-member assert line.GetPoint1() == point1 assert line.GetPoint2() == point2 def test_vault_model(): """ Tests that make vault model returns the appropriate line """ point1 = (1.0, 1.0, 2.0) point2 = (3.0, 5.0, 8.0) line = mdl.make_vault_model(point1, point2) assert isinstance(line, vtk.vtkLineSource)#pylint:disable=no-member assert line.GetPoint1() == point1 assert line.GetPoint2() == point2
[ 37811, 198, 26453, 5254, 329, 262, 25865, 8265, 198, 37811, 198, 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 410, 30488, 198, 11748, 1278, 268, 1868, 11578, 891, 2535, 13, 282, 7727, 907, 13, 27530, 355, 285, 25404, 19...
2.382979
846
# pylint: disable=redefined-outer-name, no-member from copy import deepcopy import numpy as np import pytest from numpy.testing import assert_allclose, assert_array_almost_equal, assert_array_equal from scipy.stats import linregress from xarray import DataArray, Dataset from ...data import concat, convert_to_inference_data, from_dict, load_arviz_data from ...rcparams import rcParams from ...stats import ( apply_test_function, compare, ess, hdi, loo, loo_pit, psislw, r2_score, summary, waic, ) from ...stats.stats import _gpinv from ...stats.stats_utils import get_log_likelihood from ..helpers import check_multiple_attrs, multidim_models # pylint: disable=unused-import rcParams["data.load"] = "eager" @pytest.fixture(scope="session") @pytest.fixture(scope="session") @pytest.mark.parametrize("method", ["stacking", "BB-pseudo-BMA", "pseudo-BMA"]) @pytest.mark.parametrize("multidim", [True, False]) @pytest.mark.parametrize("ic", ["loo", "waic"]) @pytest.mark.parametrize("method", ["stacking", "BB-pseudo-BMA", "pseudo-BMA"]) @pytest.mark.parametrize("scale", ["log", "negative_log", "deviance"]) @pytest.mark.parametrize("ic", ["loo", "waic"]) @pytest.mark.parametrize("method", ["stacking", "BB-pseudo-BMA", "pseudo-BMA"]) @pytest.mark.parametrize("var_names_expected", ((None, 10), ("mu", 1), (["mu", "tau"], 2))) METRICS_NAMES = [ "mean", "sd", "hdi_3%", "hdi_97%", "mcse_mean", "mcse_sd", "ess_mean", "ess_sd", "ess_bulk", "ess_tail", "r_hat", ] @pytest.mark.parametrize( "params", (("all", METRICS_NAMES), ("stats", METRICS_NAMES[:4]), ("diagnostics", METRICS_NAMES[4:])), ) @pytest.mark.parametrize("fmt", ["wide", "long", "xarray"]) @pytest.mark.parametrize("order", ["C", "F"]) @pytest.mark.parametrize("origin", [0, 1, 2, 3]) @pytest.mark.parametrize( "stat_funcs", [[np.var], {"var": np.var, "var2": lambda x: np.var(x) ** 2}] ) @pytest.mark.parametrize("fmt", [1, "bad_fmt"]) @pytest.mark.parametrize("order", [1, "bad_order"]) @pytest.mark.parametrize("scale", ["log", "negative_log", "deviance"]) @pytest.mark.parametrize("multidim", (True, False)) def test_waic(centered_eight, multidim_models, scale, multidim): """Test widely available information criterion calculation""" if multidim: assert waic(multidim_models.model_1, scale=scale) is not None waic_pointwise = waic(multidim_models.model_1, pointwise=True, scale=scale) else: assert waic(centered_eight, scale=scale) is not None waic_pointwise = waic(centered_eight, pointwise=True, scale=scale) assert waic_pointwise is not None assert "waic_i" in waic_pointwise def test_waic_bad(centered_eight): """Test widely available information criterion calculation""" centered_eight = deepcopy(centered_eight) del centered_eight.sample_stats["log_likelihood"] with pytest.raises(TypeError): waic(centered_eight) del centered_eight.sample_stats with pytest.raises(TypeError): waic(centered_eight) def test_waic_bad_scale(centered_eight): """Test widely available information criterion calculation with bad scale.""" with pytest.raises(TypeError): waic(centered_eight, scale="bad_value") @pytest.mark.parametrize("scale", ["log", "negative_log", "deviance"]) @pytest.mark.parametrize("scale", ["log", "negative_log", "deviance"]) @pytest.mark.parametrize("multidim", (True, False)) def test_loo(centered_eight, multidim_models, scale, multidim): """Test approximate leave one out criterion calculation""" if multidim: assert loo(multidim_models.model_1, scale=scale) is not None loo_pointwise = loo(multidim_models.model_1, pointwise=True, scale=scale) else: assert loo(centered_eight, scale=scale) is not None loo_pointwise = loo(centered_eight, pointwise=True, scale=scale) assert loo_pointwise is not None assert "loo_i" in loo_pointwise assert "pareto_k" in loo_pointwise assert "loo_scale" in loo_pointwise def test_loo_bad_scale(centered_eight): """Test loo with bad scale value.""" with pytest.raises(TypeError): loo(centered_eight, scale="bad_scale") @pytest.mark.parametrize("scale", ["log", "negative_log", "deviance"]) @pytest.mark.parametrize("probs", [True, False]) @pytest.mark.parametrize("kappa", [-1, -0.5, 1e-30, 0.5, 1]) @pytest.mark.parametrize("sigma", [0, 2]) @pytest.mark.parametrize("func", [loo, waic]) @pytest.mark.parametrize( "args", [ {"y": "obs"}, {"y": "obs", "y_hat": "obs"}, {"y": "arr", "y_hat": "obs"}, {"y": "obs", "y_hat": "arr"}, {"y": "arr", "y_hat": "arr"}, {"y": "obs", "y_hat": "obs", "log_weights": "arr"}, {"y": "arr", "y_hat": "obs", "log_weights": "arr"}, {"y": "obs", "y_hat": "arr", "log_weights": "arr"}, {"idata": False}, ], ) @pytest.mark.parametrize( "args", [ {"y": "y"}, {"y": "y", "y_hat": "y"}, {"y": "arr", "y_hat": "y"}, {"y": "y", "y_hat": "arr"}, {"y": "arr", "y_hat": "arr"}, {"y": "y", "y_hat": "y", "log_weights": "arr"}, {"y": "arr", "y_hat": "y", "log_weights": "arr"}, {"y": "y", "y_hat": "arr", "log_weights": "arr"}, {"idata": False}, ], ) @pytest.mark.parametrize("input_type", ["idataarray", "idatanone_ystr", "yarr_yhatnone"]) def test_loo_pit_bad_input(centered_eight, input_type): """Test incompatible input combinations.""" arr = np.random.random((8, 200)) if input_type == "idataarray": with pytest.raises(ValueError, match=r"type InferenceData or None"): loo_pit(idata=arr, y="obs") elif input_type == "idatanone_ystr": with pytest.raises(ValueError, match=r"all 3.+must be array or DataArray"): loo_pit(idata=None, y="obs") elif input_type == "yarr_yhatnone": with pytest.raises(ValueError, match=r"y_hat.+None.+y.+str"): loo_pit(idata=centered_eight, y=arr, y_hat=None) @pytest.mark.parametrize("arg", ["y", "y_hat", "log_weights"]) def test_loo_pit_bad_input_type(centered_eight, arg): """Test wrong input type (not None, str not DataArray.""" kwargs = {"y": "obs", "y_hat": "obs", "log_weights": None} kwargs[arg] = 2 # use int instead of array-like with pytest.raises(ValueError, match="not {}".format(type(2))): loo_pit(idata=centered_eight, **kwargs) @pytest.mark.parametrize("incompatibility", ["y-y_hat1", "y-y_hat2", "y_hat-log_weights"]) def test_loo_pit_bad_input_shape(incompatibility): """Test shape incompatiblities.""" y = np.random.random(8) y_hat = np.random.random((8, 200)) log_weights = np.random.random((8, 200)) if incompatibility == "y-y_hat1": with pytest.raises(ValueError, match="1 more dimension"): loo_pit(y=y, y_hat=y_hat[None, :], log_weights=log_weights) elif incompatibility == "y-y_hat2": with pytest.raises(ValueError, match="y has shape"): loo_pit(y=y, y_hat=y_hat[1:3, :], log_weights=log_weights) elif incompatibility == "y_hat-log_weights": with pytest.raises(ValueError, match="must have the same shape"): loo_pit(y=y, y_hat=y_hat[:, :100], log_weights=log_weights) @pytest.mark.parametrize("pointwise", [True, False]) @pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize( "kwargs", [ {}, {"group": "posterior_predictive", "var_names": {"posterior_predictive": "obs"}}, {"group": "observed_data", "var_names": {"both": "obs"}, "out_data_shape": "shape"}, {"var_names": {"both": "obs", "posterior": ["theta", "mu"]}}, {"group": "observed_data", "out_name_data": "T_name"}, ], ) def test_apply_test_function(centered_eight, pointwise, inplace, kwargs): """Test some usual call cases of apply_test_function""" centered_eight = deepcopy(centered_eight) group = kwargs.get("group", "both") var_names = kwargs.get("var_names", None) out_data_shape = kwargs.get("out_data_shape", None) out_pp_shape = kwargs.get("out_pp_shape", None) out_name_data = kwargs.get("out_name_data", "T") if out_data_shape == "shape": out_data_shape = (8,) if pointwise else () if out_pp_shape == "shape": out_pp_shape = (4, 500, 8) if pointwise else (4, 500) idata = deepcopy(centered_eight) idata_out = apply_test_function( idata, lambda y, theta: np.mean(y), group=group, var_names=var_names, pointwise=pointwise, out_name_data=out_name_data, out_data_shape=out_data_shape, out_pp_shape=out_pp_shape, ) if inplace: assert idata is idata_out if group == "both": test_dict = {"observed_data": ["T"], "posterior_predictive": ["T"]} else: test_dict = {group: [kwargs.get("out_name_data", "T")]} fails = check_multiple_attrs(test_dict, idata_out) assert not fails def test_apply_test_function_bad_group(centered_eight): """Test error when group is an invalid name.""" with pytest.raises(ValueError, match="Invalid group argument"): apply_test_function(centered_eight, lambda y, theta: y, group="bad_group") def test_apply_test_function_missing_group(): """Test error when InferenceData object is missing a required group. The function cannot work if group="both" but InferenceData object has no posterior_predictive group. """ idata = from_dict( posterior={"a": np.random.random((4, 500, 30))}, observed_data={"y": np.random.random(30)} ) with pytest.raises(ValueError, match="must have posterior_predictive"): apply_test_function(idata, lambda y, theta: np.mean, group="both") def test_apply_test_function_should_overwrite_error(centered_eight): """Test error when overwrite=False but out_name is already a present variable.""" with pytest.raises(ValueError, match="Should overwrite"): apply_test_function(centered_eight, lambda y, theta: y, out_name_data="obs")
[ 2, 279, 2645, 600, 25, 15560, 28, 445, 18156, 12, 39605, 12, 3672, 11, 645, 12, 19522, 198, 6738, 4866, 1330, 2769, 30073, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 6738, 299, 32152, 13, 33407, 1330, 6818,...
2.352751
4,326
import numpy as np def _ecdf(x): '''no frills empirical cdf used in fdrcorrection ''' nobs = len(x) return np.arange(1, nobs + 1) / float(nobs) def fdrcorrection(pvals, alpha=0.05, method='indep', is_sorted=False): '''pvalue correction for false discovery rate This covers Benjamini/Hochberg for independent or positively correlated and Benjamini/Yekutieli for general or negatively correlated tests. Both are available in the function multipletests, as method=`fdr_bh`, resp. `fdr_by`. Parameters ---------- pvals : array_like set of p-values of the individual tests. alpha : float error rate method : {'indep', 'negcorr') Returns ------- rejected : ndarray, bool True if a hypothesis is rejected, False if not pvalue-corrected : ndarray pvalues adjusted for multiple hypothesis testing to limit FDR Notes ----- If there is prior information on the fraction of true hypothesis, then alpha should be set to alpha * m/m_0 where m is the number of tests, given by the p-values, and m_0 is an estimate of the true hypothesis. (see Benjamini, Krieger and Yekuteli) The two-step method of Benjamini, Krieger and Yekutiel that estimates the number of false hypotheses will be available (soon). Method names can be abbreviated to first letter, 'i' or 'p' for fdr_bh and 'n' for fdr_by. ''' pvals = np.asarray(pvals) if not is_sorted: pvals_sortind = np.argsort(pvals) pvals_sorted = np.take(pvals, pvals_sortind) else: pvals_sorted = pvals # alias if method in ['i', 'indep', 'p', 'poscorr']: ecdffactor = _ecdf(pvals_sorted) elif method in ['n', 'negcorr']: cm = np.sum(1. / np.arange(1, len(pvals_sorted) + 1)) # corrected this ecdffactor = _ecdf(pvals_sorted) / cm ## elif method in ['n', 'negcorr']: ## cm = np.sum(np.arange(len(pvals))) ## ecdffactor = ecdf(pvals_sorted)/cm else: raise ValueError('only indep and negcorr implemented') pvals_corrected_raw = pvals_sorted / ecdffactor pvals_corrected = np.minimum.accumulate(pvals_corrected_raw[::-1])[::-1] del pvals_corrected_raw pvals_corrected[pvals_corrected > 1] = 1 if not is_sorted: pvals_corrected_ = np.empty_like(pvals_corrected) pvals_corrected_[pvals_sortind] = pvals_corrected del pvals_corrected return pvals_corrected_ else: return pvals_corrected
[ 11748, 299, 32152, 355, 45941, 628, 198, 4299, 4808, 721, 7568, 7, 87, 2599, 198, 220, 220, 220, 705, 7061, 3919, 1216, 2171, 21594, 269, 7568, 973, 287, 277, 67, 6015, 273, 8243, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, ...
2.448607
1,041
from django.conf import settings from django.conf.urls import url from .views import * branch_mode_urls = [ url(r'^merge_request/create/$', CreateMergeRequest.as_view(), name="create_merge_request"), url(r'^merge_request/list/$', MergeRequestList.as_view(), name="merge_requests_list"), url(r'^merge_request/(?P<merge_request_id>\d+)/$', MergeRequestDiscussionView.as_view(), name="merge_request"), url(r'^merge_request/(?P<merge_request_id>\d+)/$', MergeRequestDiscussionView.as_view(), name="merge_request_discussion"), url(r'^merge_request/(?P<merge_request_id>\d+)/changes/$', MergeRequestChangesView.as_view(), name="merge_request_changes"), url(r'^merge_request/(?P<merge_request_id>\d+)/reopen/$', MergeRequestReopenView.as_view(), name="merge_request_reopen"), url(r'^merge_request/(?P<merge_request_id>\d+)/follow/$', FollowMergeRequestView.as_view(), name="merge_request_follow"), url(r'^merge_request/(?P<merge_request_id>\d+)/unfollow/$', UnfollowMergeRequestView.as_view(), name="merge_request_unfollow"), url(r'^branch/list/$', BranchesListView.as_view(), name="branches_list"), url(r'^branch/create/$', CreateBranchView.as_view(), name="create_branch"), url(r'^delete/$', DeleteBranchView.as_view(), name="delete_branch"), ] problem_urls = ([ url(r'^analysis/$', AnalysisView.as_view(), name="analysis"), url(r'^analysis/generate/$', AnalysisGenerateView.as_view(), name="analysis_generate"), url(r'^analysis/analyze/$', AnalyzeView.as_view(), name="analyze"), url(r'^export/$', ExportView.as_view(), name="export"), url(r'export/(?P<export_id>\d+)/download/$', ExportDownloadView.as_view(), name="export_download"), url(r'export/(?P<export_id>\d+)/start/$', ExportPackageStarterView.as_view(), name="export_start"), url(r'statement/$', EditStatement.as_view(), name="statement"), url(r'statement/(?P<attachment_id>.+)$', DownloadStatementAttachment.as_view(), name="statement"), url(r'^history/$', HistoryView.as_view(), name="history"), url(r'^diff/(?P<other_slug>\w{1,40})/$', DiffView.as_view(), name="diff"), url(r'^$', Overview.as_view(), name="overview"), url(r'^discussions/$', DiscussionsListView.as_view(), name="discussions"), url(r'^discussion/add/$', DiscussionAddView.as_view(), name="add_discussion"), url(r'^discussion/(?P<discussion_id>\d+)/comments$', CommentListView.as_view(), name="comments"), url(r'^invocations/$', InvocationsListView.as_view(), name="invocations"), url(r'^invocation/add/$', InvocationAddView.as_view(), name="add_invocation"), url(r'^invocation/(?P<invocation_id>\d+)/run/$', InvocationRunView.as_view(), name="run_invocation"), url(r'^invocation/(?P<invocation_id>\d+)/clone/$', InvocationCloneView.as_view(), name="clone_invocation"), url(r'^invocation/(?P<invocation_id>\d+)/view/$', InvocationDetailsView.as_view(), name="view_invocation"), url(r'^invocation/(?P<invocation_id>\d+)/invocation_result/(?P<result_id>\d+)/view/$', InvocationResultView.as_view(), name="view_invocation_result"), url(r'^invocation/(?P<invocation_id>\d+)/invocation_result/(?P<result_id>\d+)/view/download/output/$', InvocationOutputDownloadView.as_view(), name="download_output"), url(r'^invocation/(?P<invocation_id>\d+)/invocation_result/(?P<result_id>\d+)/view/download/input/$', InvocationInputDownloadView.as_view(), name="download_input"), url(r'^invocation/(?P<invocation_id>\d+)/invocation_result/(?P<result_id>\d+)/view/download/answer/$', InvocationAnswerDownloadView.as_view(), name="download_answer"), url(r'^resource/add/$', ResourceAddView.as_view(), name="add_resource"), url(r'^resource/(?P<resource_id>\d+)/edit/$', ResourceEditView.as_view(), name="edit_resource"), url(r'^resource/(?P<object_id>\d+)/delete/$', ResourceDeleteView.as_view(), name="delete_resource"), url(r'^resource/(?P<object_id>\d+)/download/$', ResourceDownloadView.as_view(), name="download_resource"), url(r'^solutions/$', SolutionsListView.as_view(), name="solutions"), url(r'^solution/add/$', SolutionAddView.as_view(), name="add_solution"), url(r'^solution/(?P<solution_id>.+)/edit/$', SolutionEditView.as_view(), name="edit_solution"), url(r'^solution/(?P<solution_id>.+)/delete/$', SolutionDeleteView, name="delete_solution"), url(r'^solution/(?P<solution_id>.+)/source/$', SolutionShowSourceView.as_view(), name="solution_source"), url(r'^solution/(?P<solution_id>.+)/download/$', SolutionDownloadView.as_view(), name="download_solution"), url(r'^graders/$', GradersListView.as_view(), name="graders"), url(r'^grader/add/$', GraderAddView.as_view(), name="add_grader"), url(r'^grader/(?P<grader_id>.+)/edit/$', GraderEditView.as_view(), name="edit_grader"), url(r'^grader/(?P<grader_id>.+)/delete/$', GraderDeleteView, name="delete_grader"), url(r'^grader/(?P<grader_id>.+)/source/$', GraderShowSourceView.as_view(), name="grader_source"), url(r'^grader/(?P<grader_id>.+)/download/$', GraderDownloadView.as_view(), name="download_grader"), url(r'^testcases/$', TestCasesListView.as_view(), name="testcases"), url(r'^testcase/add/$', TestCaseAddView.as_view(), name="add_testcase"), url(r'^testcase/(?P<testcase_id>.+)/edit/$', TestCaseEditView.as_view(), name="edit_testcase"), url(r'^testcase/(?P<testcase_id>.+)/delete/$', TestCaseDeleteView, name="delete_testcase"), url(r'^testcase/(?P<testcase_id>.+)/input/$', TestCaseInputDownloadView.as_view(), name="testcase_input"), url(r'^testcase/(?P<testcase_id>.+)/output/$', TestCaseOutputDownloadView.as_view(), name="testcase_output"), url(r'^testcase/(?P<testcase_id>.+)/generate/$', TestCaseGenerateView.as_view(), name="generate_testcase"), url(r'^testcase/generate/all/$', TestCaseGenerateView.as_view(), name="generate_testcase"), url(r'^testcase/(?P<testcase_id>.+)/details/$', TestCaseDetailsView.as_view(), name="testcase_details"), url(r'^subtasks/$', SubtasksListView.as_view(), name="subtasks"), url(r'^subtask/add/$', SubtaskAddView.as_view(), name="add_subtask"), url(r'^subtask/(?P<subtask_id>.+)/details/$', SubtaskDetailsView.as_view(), name="subtask_details"), url(r'^subtask/(?P<subtask_id>.+)/delete/$', SubtaskDeleteView, name="delete_subtask"), url(r'^subtask/(?P<subtask_id>.+)/edit/$', SubtaskEditView.as_view(), name="edit_subtask"), url(r'^validators/$', ValidatorsListView.as_view(), name="validators"), url(r'^validator/(?P<validator_id>.+)/edit/$', ValidatorEditView.as_view(), name="edit_validator"), url(r'^validator/(?P<validator_id>.+)/delete/$', ValidatorDeleteView, name="delete_validator"), url(r'^validator/(?P<validator_id>.+)/source/$', ValidatorShowSourceView.as_view(), name="validator_source"), url(r'^validator/add/$', ValidatorAddView.as_view(), name="add_validator"), url(r'^validator/(?P<validator_id>.+)/download/$', ValidatorDownloadView.as_view(), name="download_validator"), url(r'^generators/$', GeneratorsListView.as_view(), name="generators"), url(r'^generator/(?P<generator_id>.+)/edit/$', GeneratorEditView.as_view(), name="edit_generator"), url(r'^generator/(?P<generator_id>.+)/delete/$', GeneratorDeleteView, name="delete_generator"), url(r'^generator/(?P<generator_id>.+)/source/$', GeneratorShowSourceView.as_view(), name="generator_source"), url(r'^generator/add/$', GeneratorAddView.as_view(), name="add_generator"), url(r'^generator/(?P<generator_id>.+)/generate-testcases/$', GeneratorEnableView.as_view(), name="enable_generator"), url(r'^generator/(?P<generator_id>.+)/delete-testcases/$', GeneratorDisableView.as_view(), name="disable_generator"), url(r'^checkers/$', CheckerListView.as_view(), name="checkers"), url(r'^checker/add/$$', CheckerAddView.as_view(), name="add_checker"), url(r'^checker/(?P<checker_id>.+)/activate/$$', CheckerActivateView.as_view(), name="activate_checker"), url(r'^checker/(?P<checker_id>.+)/delete/$$', CheckerDeleteView, name="delete_checker"), url(r'^checker/(?P<checker_id>.+)/edit/$$', CheckerEditView.as_view(), name="edit_checker"), url(r'^checker/(?P<checker_id>.+)/source/$$', CheckerShowSourceView.as_view(), name="checker_source"), url(r'^checker/(?P<checker_id>.+)/download/$$', CheckerDownloadView.as_view(), name="download_checker"), url(r'^pull/$', PullBranchView.as_view(), name="pull_branch"), url(r'^commit/$', CommitWorkingCopy.as_view(), name="commit"), url(r'^discard/$', DiscardWorkingCopy.as_view(), name="discard"), url(r'^conflicts/$', ConflictsListView.as_view(), name="conflicts"), url(r'^conflict/(?P<conflict_id>\d+)/$', ResolveConflictView.as_view(), name="resolve_conflict"), url(r'files/list/$', ProblemFilesView.as_view(), name="files"), url(r'files/add/$', ProblemFileAddView.as_view(), name="add_file"), url(r'^files/(?P<file_id>\d+)/edit/$', ProblemFileEditView.as_view(), name="edit_file"), url(r'^files/(?P<file_id>\d+)/delete/$', ProblemFileDeleteView.as_view(), name="delete_file"), url(r'^files/(?P<file_id>\d+)/source/$', ProblemFileShowSourceView.as_view(), name="file_source"), url(r'^files/(?P<file_id>\d+)/download/$', ProblemFileDownloadView.as_view(), name="download_file"), ] + (branch_mode_urls if not settings.DISABLE_BRANCHES else []) , None, None) urlpatterns = [ url(r'^$', ProblemsListView.as_view(), name="problems"), url(r'^problem/(?P<problem_code>[^\/]+)/(?P<revision_slug>\w{1,40})/', problem_urls), url(r'^problem/add/$', ProblemAddView.as_view(), name="add_problem"), ]
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 198, 6738, 764, 33571, 1330, 1635, 628, 198, 1671, 3702, 62, 14171, 62, 6371, 82, 796, 685, 198, 220, 220, 220, 19016, 7, ...
2.45011
4,079
""" Model collection from first batch of experiments Notes ----- Note that all models collected here are designed for fixed 256x256 patch normalization. Predifined shape helps theano to build more computationally efficient graph, so highly recommended to use this during training time. For testing, it is of course better to have undefined spatial dimensions, however this is (right now) not the primary goal of this code collections and hence not implemented. Contributing ------------ For later comparison of approaches, please continue with numbering and *do not* rename existing functions, as this will confuse loading of stored weights. Whereever datasets and/or weight files are used, a suitable hash has to be provided. Ressources ---------- - VGG16 weights : [["https://s3.amazonaws.com/lasagne/recipes/pretrained/imagenet/vgg16.pkl"]] License : Non-commercial use only md5sum : 57858ec9bb7435e99c78a0520e6c5d3e - VGG19 weights : [["https://s3.amazonaws.com/lasagne/recipes/pretrained/imagenet/vgg19_normalized.pkl"]] License : Non-commercial use only md5sum : cb8ee699c50a64f8fef2a82bfbb307c5 Changelog --------- v0.3 (..-01-2017) - Added bilinear upsampling, especially used in the feature path v0.2 (09-12-2016) - Added the Feature-Aware Normalization (FAN) layer, replacing the final batch norm layer in Baseline 1 - The model is up and running, however learning the FAN parameters is rather slow and not yet evaluated, but it seems to work :-) v0.1 (05-12-2016) - Added four baseline models with varying amount of model complexity - Baselines 1 and 2 confirm that the batch norm layer on the output alone has a huge impact on system performance - Baseline 3 is the old approach using the first VGG block """ __author__ = "sschneider" __email__ = "steffen.schneider@rwth-aachen.de" from collections import OrderedDict import pickle import lasagne as nn from lasagne.layers import InputLayer, NonlinearityLayer, BatchNormLayer try: from lasagne.layers.dnn import Pool2DDNNLayer as PoolLayer from lasagne.layers.dnn import Conv2DDNNLayer as ConvLayer except: print("Failed to use GPU implementations of Conv and Pool Layers") from lasagne.layers import Pool2DLayer as PoolLayer from lasagne.layers import Conv2DLayer as ConvLayer from lasagne.layers import Upscale2DLayer from lasagne.layers import ExpressionLayer, TransposedConv2DLayer from lasagne.nonlinearities import rectify, linear from lasagne.layers import get_output_shape from . import layers, tools from .layers import fan_module_simple, fan_module_improved from .layers import get_features, normalize, transpose from .featurenorm import FeatureAwareNormLayer __all__ = ['build_baseline1_small', 'build_baseline2_feats', 'build_baseline3_vgg', 'build_baseline4_fan', 'build_baseline5_fan', 'build_baseline6_fan_fan', 'build_resnet7_fan', 'build_baseline8_fan_bilinear', 'build_baseline9_fan_fan_bilinear', 'build_finetuned1_fan', 'build_finetuned2_fan', 'build_big_fan', 'build_fan_reworked'] ### # Small Baseline Model def build_baseline1_small(input_var): """ Most simplistic model possible. Effectively only uses last batch norm layer """ net = OrderedDict() # Input, standardization last = net['input'] = InputLayer((None, 3, tools.INP_PSIZE, tools.INP_PSIZE), input_var=input_var) last = net['norm'] = ExpressionLayer(last, lambda x: normalize(x)) last = net["middle"] = ConvLayer(last, 3, 1, nonlinearity=linear) last = net["bn"] = BatchNormLayer(last, beta=nn.init.Constant(128.), gamma=nn.init.Constant(25.)) return last, net def build_baseline2_feats(input_var, nb_filter=96): """ Slightly more complex model. Transform x to a feature space first """ net = OrderedDict() # Input, standardization last = net['input'] = InputLayer((None, 3, tools.INP_PSIZE, tools.INP_PSIZE), input_var=input_var) last = net['norm'] = ExpressionLayer(last, lambda x: normalize(x)) # Pretrained Encoder as before last = net["conv1_1"] = ConvLayer(last, nb_filter, 1, pad=0, flip_filters=False, nonlinearity=linear) last = net["bn1_1"] = BatchNormLayer(last) last = net["relu1_1"] = NonlinearityLayer(last, nonlinearity=rectify) last = net["conv1_2"] = ConvLayer(last, nb_filter, 1, pad=0, flip_filters=False, nonlinearity=linear) last = net["bn1_2"] = BatchNormLayer(last) last = net["relu1_2"] = NonlinearityLayer(last, nonlinearity=rectify) # Modified Middle Part last = net["middle"] = ConvLayer(last, nb_filter, 1, nonlinearity=linear) # Decoder as before last = net["deconv1_2"] = TransposedConv2DLayer(last, net["conv1_2"].input_shape[1], net["conv1_2"].filter_size, stride=net["conv1_2"].stride, crop=net["conv1_2"].pad, W=net["conv1_2"].W, flip_filters=not net["conv1_2"].flip_filters, nonlinearity=None) last = net["deconv1_1"] = TransposedConv2DLayer(last, net["conv1_1"].input_shape[1], net["conv1_1"].filter_size, stride=net["conv1_1"].stride, crop=net["conv1_1"].pad, W=net["conv1_1"].W, flip_filters=not net["conv1_1"].flip_filters, nonlinearity=None) last = net["bn"] = BatchNormLayer(last, beta=nn.init.Constant(128.), gamma=nn.init.Constant(25.)) return last, net ### # VGG + LSTM Model ### # FULL LSTM Model ### # Model with new Feature Norm Layer ### # FULL LSTM Model with Bilinar upsampling ### # FULL LSTM Model ### # FULL LSTM Model ### # FULL LSTM Model ### # FULL Feature Aware Normalization Model
[ 37811, 9104, 4947, 422, 717, 15458, 286, 10256, 198, 198, 16130, 198, 30934, 198, 198, 6425, 326, 477, 4981, 7723, 994, 389, 3562, 329, 5969, 17759, 87, 11645, 8529, 3487, 1634, 13, 198, 39156, 361, 1389, 5485, 5419, 262, 5733, 284, 1...
2.428685
2,524
""" Contains Feed, which handles parsing the rss feed and User, which handles messaging """ from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib from bs4 import BeautifulSoup import feedparser as fp from jinja2 import Environment, PackageLoader, select_autoescape from requests import get from configuration import Config from database import Database class Feed(Database): """ Uses Database's methods in conjunction with its own to parse feed url, fetching and parsing page to plain text, searching each text for specific terms and email the correct users if the terms are found. """ URL = 'feed://www.scotcourts.gov.uk/feeds/court-of-session-court-rolls' def new_urls(self): """ Gets new URLs, adds to database then yields url :yield: str, url """ page = fp.parse(self.URL)['entries'] return [item['link'] for item in page if item['link'] not in self.get_urls()] def refresh(self): """ Iterates through new_urls, downloading then searching through resulting text. Note: text and search terms are upper case, to simplify things. """ new_urls = self.new_urls() for url in new_urls: print(f'Adding {url}') html, text = self._downloader(url) self.add_url_html(url, html) for user in self.users(): hits = self._text_search(text.upper(), user, url) if hits: print(f'Sending alert to {user.name}') user.send_email(hits, url) def users(self): """ :yield: User obj containing name, email address and list of search_terms """ users = self.get_users() for user in users: name, email_address = user search_terms = self.get_search_terms(email_address) yield User(name, email_address, search_terms) def _text_search(self, text, user, url): """ Searches through text for any of the user's search terms, if found, sends email. :param text: str, block of text from Court Roll Issue :param user: User obj :param url: str Court Roll Issue URL :return: search term hits """ search_term_hits = [] for term in user.search_terms: if term in text: search_term_hits.append(term) self.add_user_issue(user.email_address, url) return search_term_hits @staticmethod def _downloader(url): """ Uses BeautifulSoup to extract a block of text through which to search :param url: str :return: tuple, html and plain text of Court Roll issue downloaded """ soup = BeautifulSoup(get(url).content, 'html.parser') selection = soup.select('.courtRollContent')[0] html, text = selection.prettify(), selection.get_text() return html, text class User: """ Object containing a person's name, email address and list of search terms associated with them, As well as a methods used to send an email to them """ __slots__ = ['name', 'email_address', 'search_terms'] def __init__(self, name, email_address, search_terms): """ :param name: str person's name :param email_address: str person's email address :param search_terms: list, search terms associated with this person """ self.name = name self.email_address = email_address self.search_terms = search_terms def send_email(self, search_term_hits, url): """ Sends email message to a user.email_address containing the url & search term hits :param search_term_hits: list of search terms that were present in the issue searched :param url: str, url to a court roll issue :return: None """ msg = MIMEMultipart('alternative') msg['Subject'] = 'Court Roll Notification' msg['From'] = Config.sender msg['To'] = self.email_address msg.attach(MIMEText(self._render_text(search_term_hits, url), 'plain')) msg.attach(MIMEText(self._render_html(search_term_hits, url), 'html')) server = smtplib.SMTP(host=Config.host, port=Config.port) server.starttls() server.login(user=Config.sender, password=Config.pw) server.sendmail(Config.sender, self.email_address, msg.as_string()) server.quit() def _render_text(self, search_term_hits, url): """ Renders Text message for email :param search_term_hits: list of search_terms :param url: str :return: text-formatted email message """ env = Environment( loader=PackageLoader('message', 'templates'), autoescape=select_autoescape(['.txt']) ) template = env.get_template('base.txt') return template.render(name=self.name, search_terms=search_term_hits, url=url) def _render_html(self, search_term_hits, url): """ Renders HTML message for email :param search_term_hits: list of search_terms :param url: str :return: HTML-formatted email message """ env = Environment( loader=PackageLoader('message', 'templates'), autoescape=select_autoescape(['html', 'xml']) ) template = env.get_template('base.html') return template.render(name=self.name, search_terms=search_term_hits, url=url)
[ 37811, 198, 4264, 1299, 18272, 11, 543, 17105, 32096, 262, 374, 824, 3745, 290, 11787, 11, 543, 17105, 19925, 198, 37811, 198, 6738, 3053, 13, 76, 524, 13, 16680, 541, 433, 1330, 337, 3955, 3620, 586, 541, 433, 198, 6738, 3053, 13, ...
2.33279
2,455
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE # ############################################################################## """Presentation Traverser Tests """ import unittest from zope.testing.cleanup import CleanUp from zope.interface import Interface, implementer from zope.publisher.browser import TestRequest from zope.traversing.namespace import view, resource from zope.traversing.testing import browserView, browserResource @implementer(IContent)
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 198, 2, 15069, 357, 66, 8, 5878, 11, 6244, 1168, 3008, 5693, 290, 25767, 669, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 770, 3788, 318, 2426, 284, 262, 8617, 286, 262, 1168, 3008, ...
4.00823
243
# flake8: noqa from .LivescoreBase import NoOverlayFoundException from .Livescore2017 import Livescore2017 from .Livescore2018 import Livescore2018 from .Livescore2019 import Livescore2019
[ 2, 781, 539, 23, 25, 645, 20402, 198, 6738, 764, 43, 1083, 7295, 14881, 1330, 1400, 5886, 10724, 21077, 16922, 198, 6738, 764, 43, 1083, 7295, 5539, 1330, 18965, 7295, 5539, 198, 6738, 764, 43, 1083, 7295, 7908, 1330, 18965, 7295, 790...
3.5
54
from dqn_globals import * import numpy as np import random # Fast and NOT random
[ 198, 6738, 288, 80, 77, 62, 4743, 672, 874, 1330, 1635, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 628, 220, 220, 220, 220, 220, 220, 220, 220, 198, 220, 220, 220, 220, 220, 220, 220, 220, 628, 220, 220, 220, 220, 220, ...
1.634409
93
""" # Copyright 2022 Red Hat # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ from unittest import TestCase from unittest.mock import Mock from cibyl.models.ci.zuul.test import Test, TestKind, TestStatus class TestTest(TestCase): """Tests for :class:`Test`. """ def test_attributes(self): """Checks that the model has the desired attributes. """ kind = TestKind.ANSIBLE name = 'test' status = TestStatus.SUCCESS duration = 1.2 url = 'url-to-test' data = Test.Data() data.name = name data.status = status data.duration = duration data.url = url model = Test(kind, data) self.assertEqual(kind, model.kind.value) self.assertEqual(name, model.name.value) self.assertEqual(status.name, model.result.value) self.assertEqual(duration, model.duration.value) self.assertEqual(url, model.url.value) def test_equality_by_type(self): """Checks that two models are no the same if they are of different type. """ model = Test() other = Mock() self.assertNotEqual(other, model) def test_equality_by_reference(self): """Checks that a model is equal to itself. """ model = Test() self.assertEqual(model, model) def test_equality_by_contents(self): """Checks that two models are equal if they hold the same data. """ kind = TestKind.ANSIBLE data = Test.Data() data.name = 'test' data.status = TestStatus.SUCCESS data.duration = 1.2 data.url = 'url-to-test' model1 = Test(kind, data) model2 = Test(kind, data) self.assertEqual(model2, model1) def test_status(self): """Checks that the correct status is returned for different results. """ model = Test() model.result.value = TestStatus.UNKNOWN.name self.assertEqual(TestStatus.UNKNOWN, model.status) model.result.value = TestStatus.SUCCESS.name self.assertEqual(TestStatus.SUCCESS, model.status) model.result.value = TestStatus.FAILURE.name self.assertEqual(TestStatus.FAILURE, model.status) model.result.value = TestStatus.SKIPPED.name self.assertEqual(TestStatus.SKIPPED, model.status)
[ 37811, 198, 2, 220, 220, 220, 15069, 33160, 2297, 10983, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 284...
2.477778
1,170
# Copyright (c) Lawrence Livermore National Security, LLC and other VisIt # Project developers. See the top-level LICENSE file for dates and other # details. No copyright assignment is required to contribute to VisIt. """ file: qplot/scene.py author: Cyrus Harrison <cyrush@llnl.gov> description: Qt based offscreen Curve Rendering lib. """ import sys import time import math from visit_utils.property_tree import PropertyTree from visit_utils import ult from visit_utils.property_tree import PropertyTree from visit_utils import ult from visit_utils.qannote import * from .plots import *
[ 2, 15069, 357, 66, 8, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 6911, 1026, 198, 2, 4935, 6505, 13, 220, 4091, 262, 1353, 12, 5715, 38559, 24290, 2393, 329, 9667, 290, 584, 198, 2, 3307, 13, 220, 1400, 6634, 16237, 318, ...
3.619048
168
# ########################################################## # FlatCAM: 2D Post-processing for Manufacturing # # File Author: Marius Adrian Stanciu (c) # # Date: 1/10/2020 # # MIT Licence # # ########################################################## from PyQt5 import QtWidgets, QtCore, QtGui from appTool import AppTool from appGUI.GUIElements import RadioSet, FCDoubleSpinner, FCCheckBox, FCComboBox from shapely.geometry import Point import logging import gettext import appTranslation as fcTranslate import builtins fcTranslate.apply_language('strings') if '_' not in builtins.__dict__: _ = gettext.gettext log = logging.getLogger('base')
[ 2, 1303, 29113, 14468, 7804, 2, 198, 2, 21939, 34, 2390, 25, 362, 35, 2947, 12, 36948, 329, 32760, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1303, 198, 2, 9220, 6434, 25, 1526, 3754, 21462, 7299, 979, 84, 357, 66, 8...
2.503247
308
""" This file contains all image database (imdb) functionality, such as loading and reading information from a dataset. Generally, this file is meant to read in a dataset from disk into a simple custom format for the detetive framework. """ # ----------------------------------------- # modules # ----------------------------------------- import torch import torch.utils.data as data import sys import re from PIL import Image from copy import deepcopy sys.dont_write_bytecode = True # ----------------------------------------- # custom # ----------------------------------------- from lib.rpn_util import * from lib.util import * from lib.augmentations import * from lib.core import * class Dataset(torch.utils.data.Dataset): """ A single Dataset class is used for the whole project, which implements the __init__ and __get__ functions from PyTorch. """ def __init__(self, conf, root, cache_folder=None): """ This function reads in all datasets to be used in training and stores ANY relevant information which may be needed during training as a list of edict() (referred to commonly as 'imobj'). The function also optionally stores the image database (imdb) file into a cache. """ imdb = [] self.video_det = False if not ('video_det' in conf) else conf.video_det self.video_count = 1 if not ('video_count' in conf) else conf.video_count self.use_3d_for_2d = ('use_3d_for_2d' in conf) and conf.use_3d_for_2d # use cache? if (cache_folder is not None) and os.path.exists(os.path.join(cache_folder, 'imdb.pkl')): logging.info('Preloading imdb.') imdb = pickle_read(os.path.join(cache_folder, 'imdb.pkl')) else: print("here") # cycle through each dataset for dbind, db in enumerate(conf.datasets_train): logging.info('Loading imdb {}'.format(db['name'])) # single imdb imdb_single_db = [] # kitti formatting if db['anno_fmt'].lower() == 'kitti_det': train_folder = os.path.join(root, db['name'], 'training') ann_folder = os.path.join(train_folder, 'label_2', '') cal_folder = os.path.join(train_folder, 'calib', '') im_folder = os.path.join(train_folder, 'image_2', '') # get sorted filepaths annlist = sorted(glob(ann_folder + '*.txt')) imdb_start = time() self.affine_size = None if not ('affine_size' in conf) else conf.affine_size for annind, annpath in enumerate(annlist): # get file parts base = os.path.basename(annpath) id, ext = os.path.splitext(base) calpath = os.path.join(cal_folder, id + '.txt') impath = os.path.join(im_folder, id + db['im_ext']) impath_pre = os.path.join(train_folder, 'prev_2', id + '_01' + db['im_ext']) impath_pre2 = os.path.join(train_folder, 'prev_2', id + '_02' + db['im_ext']) impath_pre3 = os.path.join(train_folder, 'prev_2', id + '_03' + db['im_ext']) # read gts p2 = read_kitti_cal(calpath) p2_inv = np.linalg.inv(p2) gts = read_kitti_label(annpath, p2, self.use_3d_for_2d) if not self.affine_size is None: # filter relevant classes gts_plane = [deepcopy(gt) for gt in gts if gt.cls in conf.lbls and not gt.ign] if len(gts_plane) > 0: KITTI_H = 1.65 # compute ray traces for default projection for gtind in range(len(gts_plane)): gt = gts_plane[gtind] #cx2d = gt.bbox_3d[0] #cy2d = gt.bbox_3d[1] cy2d = gt.bbox_full[1] + gt.bbox_full[3] cx2d = gt.bbox_full[0] + gt.bbox_full[2] / 2 z2d, coord3d = projection_ray_trace(p2, p2_inv, cx2d, cy2d, KITTI_H) gts_plane[gtind].center_in = coord3d[0:3, 0] gts_plane[gtind].center_3d = np.array(gt.center_3d) prelim_tra = np.array([gt.center_in for gtind, gt in enumerate(gts_plane)]) target_tra = np.array([gt.center_3d for gtind, gt in enumerate(gts_plane)]) if self.affine_size == 4: prelim_tra = np.pad(prelim_tra, [(0, 0), (0, 1)], mode='constant', constant_values=1) target_tra = np.pad(target_tra, [(0, 0), (0, 1)], mode='constant', constant_values=1) affine_gt, err = solve_transform(prelim_tra, target_tra, compute_error=True) a = 1 obj = edict() # did not compute transformer if (self.affine_size is None) or len(gts_plane) < 1: obj.affine_gt = None else: obj.affine_gt = affine_gt # store gts obj.id = id obj.gts = gts obj.p2 = p2 obj.p2_inv = p2_inv # im properties im = Image.open(impath) obj.path = impath obj.path_pre = impath_pre obj.path_pre2 = impath_pre2 obj.path_pre3 = impath_pre3 obj.imW, obj.imH = im.size # database properties obj.dbname = db.name obj.scale = db.scale obj.dbind = dbind # store imdb_single_db.append(obj) if (annind % 1000) == 0 and annind > 0: time_str, dt = compute_eta(imdb_start, annind, len(annlist)) logging.info('{}/{}, dt: {:0.4f}, eta: {}'.format(annind, len(annlist), dt, time_str)) # concatenate single imdb into full imdb imdb += imdb_single_db imdb = np.array(imdb) # cache off the imdb? if cache_folder is not None: pickle_write(os.path.join(cache_folder, 'imdb.pkl'), imdb) # store more information self.datasets_train = conf.datasets_train self.len = len(imdb) self.imdb = imdb # setup data augmentation transforms self.transform = Augmentation(conf) # setup sampler and data loader for this dataset self.sampler = torch.utils.data.sampler.WeightedRandomSampler(balance_samples(conf, imdb), self.len) self.loader = torch.utils.data.DataLoader(self, conf.batch_size, sampler=self.sampler, collate_fn=self.collate) # check classes cls_not_used = [] for imobj in imdb: for gt in imobj.gts: cls = gt.cls if not(cls in conf.lbls or cls in conf.ilbls) and (cls not in cls_not_used): cls_not_used.append(cls) if len(cls_not_used) > 0: logging.info('Labels not used in training.. {}'.format(cls_not_used)) def __getitem__(self, index): """ Grabs the item at the given index. Specifically, - read the image from disk - read the imobj from RAM - applies data augmentation to (im, imobj) - converts image to RGB and [B C W H] """ if not self.video_det: # read image im = cv2.imread(self.imdb[index].path) else: # read images im = cv2.imread(self.imdb[index].path) video_count = 1 if self.video_count is None else self.video_count if video_count >= 2: im_pre = cv2.imread(self.imdb[index].path_pre) if not im_pre.shape == im.shape: im_pre = cv2.resize(im_pre, (im.shape[1], im.shape[0])) im = np.concatenate((im, im_pre), axis=2) if video_count >= 3: im_pre2 = cv2.imread(self.imdb[index].path_pre2) if im_pre2 is None: im_pre2 = im_pre if not im_pre2.shape == im.shape: im_pre2 = cv2.resize(im_pre2, (im.shape[1], im.shape[0])) im = np.concatenate((im, im_pre2), axis=2) if video_count >= 4: im_pre3 = cv2.imread(self.imdb[index].path_pre3) if im_pre3 is None: im_pre3 = im_pre2 if not im_pre3.shape == im.shape: im_pre3 = cv2.resize(im_pre3, (im.shape[1], im.shape[0])) im = np.concatenate((im, im_pre3), axis=2) # transform / data augmentation im, imobj = self.transform(im, deepcopy(self.imdb[index])) for i in range(int(im.shape[2]/3)): # convert to RGB then permute to be [B C H W] im[:, :, (i*3):(i*3) + 3] = im[:, :, (i*3+2, i*3+1, i*3)] im = np.transpose(im, [2, 0, 1]) return im, imobj @staticmethod def collate(batch): """ Defines the methodology for PyTorch to collate the objects of a batch together, for some reason PyTorch doesn't function this way by default. """ imgs = [] imobjs = [] # go through each batch for sample in batch: # append images and object dictionaries imgs.append(sample[0]) imobjs.append(sample[1]) # stack images imgs = np.array(imgs) imgs = torch.from_numpy(imgs).cuda() return imgs, imobjs def __len__(self): """ Simply return the length of the dataset. """ return self.len def read_kitti_cal(calfile): """ Reads the kitti calibration projection matrix (p2) file from disc. Args: calfile (str): path to single calibration file """ text_file = open(calfile, 'r') p2pat = re.compile(('(P2:)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)' + '\s+(fpat)\s+(fpat)\s+(fpat)\s*\n').replace('fpat', '[-+]?[\d]+\.?[\d]*[Ee](?:[-+]?[\d]+)?')) for line in text_file: parsed = p2pat.fullmatch(line) # bbGt annotation in text format of: # cls x y w h occ x y w h ign ang if parsed is not None: p2 = np.zeros([4, 4], dtype=float) p2[0, 0] = parsed.group(2) p2[0, 1] = parsed.group(3) p2[0, 2] = parsed.group(4) p2[0, 3] = parsed.group(5) p2[1, 0] = parsed.group(6) p2[1, 1] = parsed.group(7) p2[1, 2] = parsed.group(8) p2[1, 3] = parsed.group(9) p2[2, 0] = parsed.group(10) p2[2, 1] = parsed.group(11) p2[2, 2] = parsed.group(12) p2[2, 3] = parsed.group(13) p2[3, 3] = 1 text_file.close() return p2 def read_kitti_label(file, p2, use_3d_for_2d=False): """ Reads the kitti label file from disc. Args: file (str): path to single label file for an image p2 (ndarray): projection matrix for the given image """ gts = [] text_file = open(file, 'r') ''' Values Name Description ---------------------------------------------------------------------------- 1 type Describes the type of object: 'Car', 'Van', 'Truck', 'Pedestrian', 'Person_sitting', 'Cyclist', 'Tram', 'Misc' or 'DontCare' 1 truncated Float from 0 (non-truncated) to 1 (truncated), where truncated refers to the object leaving image boundaries 1 occluded Integer (0,1,2,3) indicating occlusion state: 0 = fully visible, 1 = partly occluded 2 = largely occluded, 3 = unknown 1 alpha Observation angle of object, ranging [-pi..pi] 4 bbox 2D bounding box of object in the image (0-based index): contains left, top, right, bottom pixel coordinates 3 dimensions 3D object dimensions: height, width, length (in meters) 3 location 3D object location x,y,z in camera coordinates (in meters) 1 rotation_y Rotation ry around Y-axis in camera coordinates [-pi..pi] 1 score Only for results: Float, indicating confidence in detection, needed for p/r curves, higher is better. ''' pattern = re.compile(('([a-zA-Z\-\?\_]+)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+' + '(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s+(fpat)\s*((fpat)?)\n') .replace('fpat', '[-+]?\d*\.\d+|[-+]?\d+')) for line in text_file: parsed = pattern.fullmatch(line) # bbGt annotation in text format of: # cls x y w h occ x y w h ign ang if parsed is not None: obj = edict() ign = False cls = parsed.group(1) trunc = float(parsed.group(2)) occ = float(parsed.group(3)) alpha = float(parsed.group(4)) x = float(parsed.group(5)) y = float(parsed.group(6)) x2 = float(parsed.group(7)) y2 = float(parsed.group(8)) width = x2 - x + 1 height = y2 - y + 1 h3d = float(parsed.group(9)) w3d = float(parsed.group(10)) l3d = float(parsed.group(11)) cx3d = float(parsed.group(12)) # center of car in 3d cy3d = float(parsed.group(13)) # bottom of car in 3d cz3d = float(parsed.group(14)) # center of car in 3d rotY = float(parsed.group(15)) # actually center the box cy3d -= (h3d / 2) elevation = (1.65 - cy3d) if use_3d_for_2d and h3d > 0 and w3d > 0 and l3d > 0: # re-compute the 2D box using 3D (finally, avoids clipped boxes) verts3d, corners_3d = project_3d(p2, cx3d, cy3d, cz3d, w3d, h3d, l3d, rotY, return_3d=True) # any boxes behind camera plane? if np.any(corners_3d[2, :] <= 0): ign = True else: x = min(verts3d[:, 0]) y = min(verts3d[:, 1]) x2 = max(verts3d[:, 0]) y2 = max(verts3d[:, 1]) width = x2 - x + 1 height = y2 - y + 1 # project cx, cy, cz coord3d = p2.dot(np.array([cx3d, cy3d, cz3d, 1])) # store the projected instead cx3d_2d = coord3d[0] cy3d_2d = coord3d[1] cz3d_2d = coord3d[2] cx = cx3d_2d / cz3d_2d cy = cy3d_2d / cz3d_2d # encode occlusion with range estimation # 0 = fully visible, 1 = partly occluded # 2 = largely occluded, 3 = unknown if occ == 0: vis = 1 elif occ == 1: vis = 0.66 elif occ == 2: vis = 0.33 else: vis = 0.0 while rotY > math.pi: rotY -= math.pi * 2 while rotY < (-math.pi): rotY += math.pi * 2 # recompute alpha alpha = convertRot2Alpha(rotY, cz3d, cx3d) obj.elevation = elevation obj.cls = cls obj.occ = occ > 0 obj.ign = ign obj.visibility = vis obj.trunc = trunc obj.alpha = alpha obj.rotY = rotY # is there an extra field? (assume to be track) if len(parsed.groups()) >= 16 and parsed.group(16).isdigit(): obj.track = int(parsed.group(16)) obj.bbox_full = np.array([x, y, width, height]) obj.bbox_3d = [cx, cy, cz3d_2d, w3d, h3d, l3d, alpha, cx3d, cy3d, cz3d, rotY] obj.center_3d = [cx3d, cy3d, cz3d] gts.append(obj) text_file.close() return gts def balance_samples(conf, imdb): """ Balances the samples in an image dataset according to the given configuration. Basically we check which images have relevant foreground samples and which are empty, then we compute the sampling weights according to a desired fg_image_ratio. This is primarily useful in datasets which have a lot of empty (background) images, which may cause instability during training if not properly balanced against. """ sample_weights = np.ones(len(imdb)) if conf.fg_image_ratio >= 0: empty_inds = [] valid_inds = [] for imind, imobj in enumerate(imdb): valid = 0 scale = conf.test_scale / imobj.imH igns, rmvs = determine_ignores(imobj.gts, conf.lbls, conf.ilbls, conf.min_gt_vis, conf.min_gt_h, conf.max_gt_h, scale) for gtind, gt in enumerate(imobj.gts): if (not igns[gtind]) and (not rmvs[gtind]): valid += 1 sample_weights[imind] = valid if valid>0: valid_inds.append(imind) else: empty_inds.append(imind) if not (conf.fg_image_ratio == 2): fg_weight = len(imdb) * conf.fg_image_ratio / len(valid_inds) bg_weight = len(imdb) * (1 - conf.fg_image_ratio) / len(empty_inds) sample_weights[valid_inds] = fg_weight sample_weights[empty_inds] = bg_weight logging.info('weighted respectively as {:.2f} and {:.2f}'.format(fg_weight, bg_weight)) logging.info('Found {} foreground and {} empty images'.format(np.sum(sample_weights > 0), np.sum(sample_weights <= 0))) # force sampling weights to sum to 1 sample_weights /= np.sum(sample_weights) return sample_weights
[ 37811, 198, 1212, 2393, 4909, 477, 2939, 6831, 357, 320, 9945, 8, 11244, 11, 198, 10508, 355, 11046, 290, 3555, 1321, 422, 257, 27039, 13, 198, 198, 37058, 11, 428, 2393, 318, 4001, 284, 1100, 287, 257, 27039, 422, 11898, 656, 257, ...
1.862882
10,057
from . import BaseMeninggal
[ 6738, 764, 1330, 7308, 44, 3101, 13528, 628 ]
3.625
8
''' Permuted multiples It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. ''' def st2set(n): '''stevke da v mnozico''' assert n >= 0 #zakaj pa ne stevke = set() while n != 0: stevke.add(n % 10) n //= 10 return stevke import itertools for i in itertools.count(1): if st2set(i) == st2set(2*i) == st2set(3*i) == st2set(4*i) == st2set(5*i) == st2set(6*i): print(f'tole iščemo: {i}') break #tole iščemo: 142857
[ 7061, 6, 201, 198, 5990, 76, 7241, 5021, 2374, 201, 198, 201, 198, 1026, 460, 307, 1775, 326, 262, 1271, 11, 1105, 3365, 4524, 11, 290, 663, 4274, 11, 201, 198, 1495, 1558, 2780, 11, 3994, 3446, 262, 976, 19561, 11, 475, 287, 257,...
2.052632
323
''' fasta2nj.py - convert fasta file to nj input ============================================ :Author: Andreas Heger :Release: $Id$ :Date: |today| :Tags: Python Purpose ------- convert a fasta file to NJ input. This script translates identifiers like species|transcripts|gene|class to transcript_species GENEID=gene Usage ----- Example:: python fasta2nj.py --help Type:: python fasta2nj.py --help for command line help. Command line options -------------------- ''' import sys import re import CGAT.Experiment as E import CGAT.IOTools as IOTools def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv parser = E.OptionParser( version="%prog version: $Id: fasta2nj.py 2781 2009-09-10 11:33:14Z andreas $") parser.add_option("-m", "--map", dest="filename_map", type="string", help="filename with mapping of species ids to swissprot species ids.") parser.set_defaults( separator="|", filename_map=None, ) (options, args) = E.Start(parser) if options.filename_map: map_species2sp = IOTools.ReadMap(open(options.filename_map, "r")) ninput, noutput, nerrors = 0, 0, 0 for line in sys.stdin: if line[0] == ">": ninput += 1 id = re.match(">([^/ \t]+)", line[:-1]).groups()[0] data = id.split(options.separator) species = data[0] if len(data) == 2: gene = data[1] transcript = None elif len(data) >= 3: gene = data[2] transcript = data[1] if map_species2sp: try: species = map_species2sp[species] except IndexError: nerrors += 1 if options.loglevel >= 1: options.stdlog.write( "# could not map species %s\n" % species) if transcript: options.stdout.write( ">%s_%s GENEID=%s\n" % (transcript, species, gene)) else: options.stdout.write(">%s_%s\n" % (species, gene)) noutput += 1 else: options.stdout.write(line) if options.loglevel >= 1: options.stdlog.write( "# ninput=%i, noutput=%i, nerrors=%i\n" % (ninput, noutput, nerrors)) E.Stop() if __name__ == "__main__": sys.exit(main(sys.argv))
[ 7061, 6, 198, 7217, 64, 17, 77, 73, 13, 9078, 532, 10385, 3049, 64, 2393, 284, 299, 73, 5128, 198, 10052, 25609, 198, 198, 25, 13838, 25, 33728, 679, 1362, 198, 25, 26362, 25, 720, 7390, 3, 198, 25, 10430, 25, 930, 40838, 91, 19...
2.05314
1,242
import runner1c
[ 11748, 17490, 16, 66, 628, 198 ]
3
6
#mcandrew import sys import numpy as np import pandas as pd if __name__ == "__main__": # SURVEY1 (2020-02-17) survey1 = truth() survey1.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF-1-0','QF-1-1_1','QF-2-0','QF-2-0_1','QF-2-2_1','QF-2-2_2','QF-2-2_3','QF-3-0']) survey1.addTruths([np.nan,np.nan,np.nan,1,1,1,1,35,35,35,np.nan]) survey1DB = survey1.export2DB('2020-02-17') # SURVEY2 (2020-02-24) survey2 = truth() survey2.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1','QF2_1','QF3','QF4_1','QF5_1','QF5_2','QF5_3','QF6_1','QF6_2','QF6_3','QF7']) survey2.addTruths([np.nan,np.nan,np.nan,1,1,1,1,62,62,62,7,7,7,np.nan]) survey2DB = survey2.export2DB('2020-02-24') # SURVEY3 (2020-03-02) survey3 = truth() survey3.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1_1','QF1_2','QF1_3','QF2_1','QF2_2','QF2_3','QF3_1','QF3_2','QF3_3','QF4_1','QF4_2','QF4_3','QF5_1','QF5_2','QF5_3','QF6_1','QF6_2','QF6_3','QF7']) survey3.addTruths([np.nan,np.nan,np.nan,423,423,423,3487,3487,3487,35,35,35,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,17,17,17,np.nan]) survey3DB = survey3.export2DB('2020-03-02') # SURVEY4 (2020-03-09) survey4 = truth() survey4.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1_1','QF1_2','QF1_3','QF2_1','QF2_2','QF2_3','QF3','QF4_1','QF4_2','QF4_3','QF6_1','QF6_2','QF6_3','QF7','QF8','QF9']) survey4.addTruths([np.nan,np.nan,np.nan,3487,3487,3487,49,49,49,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]) survey4DB = survey4.export2DB('2020-03-09') # SURVEY5 (2020-03-16) survey5 = truth() survey5.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1_1','QF1_2','QF1_3','QF2_1','QF2_2','QF2_3','QF3_1','QF3_2','QF3_3','QF4_1','QF4_2','QF4_3','QF5_1','QF5_2','QF5_3','QF6_1','QF7','QF8']) survey5.addTruths([np.nan,np.nan,np.nan,33404,33404,33404,139061,139061,139061,32,32,32,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]) survey5DB = survey5.export2DB('2020-03-16') # SURVEY6 (2020-03-23) survey6 = truth() survey6.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1_1','QF1_2','QF1_3','QF2_1','QF2_2','QF2_3','QF3_1','QF3_2','QF3_3','QF4_1','QF4_2','QF4_3','QF5_1','QF5_2','QF5_3','QF6_1','QF6_4','QF6_5','QF6_6','QF6_7','QF6_8','QF7','QF8']) survey6.addTruths([np.nan,np.nan,np.nan,139061,139061,139061,332308,332308,332308,49,49,49,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]) survey6DB = survey6.export2DB('2020-03-23') # SURVEY7 (2020-03-30) survey7 = truth() survey7.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1_1','QF1_2','QF1_3','QF2_1','QF2_2','QF2_3','QF3_1','QF3_2','QF3_3','QF4_1','QF4_2','QF4_3','QF5_1','QF5_4','QF5_5','QF5_6','QF5_7','QF5_8','QF6_1','QF6_2','QF6_3','QF7_1','QF8','QF9']) survey7.addTruths([np.nan,np.nan,np.nan,332308,332308,332308,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]) survey7DB = survey7.export2DB('2020-03-30') # SURVEY8 (2020-04-06) survey8 = truth() survey8.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1_1','QF1_2','QF1_3','QF2_1','QF2_2','QF2_3','QF3_1','QF3_4','QF3_5','QF3_6','QF3_7','QF3_8','QF3_10','Q4_1','Q4_2','Q4_3','Q4_4','Q4_5','QF5_1','QF5_2','QF5_3','QF6','QF7']) survey8.addTruths([np.nan,np.nan,np.nan,576774,576774,576774,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,2,2,2,2,2,np.nan,np.nan,np.nan,np.nan,np.nan]) survey8DB = survey8.export2DB('2020-04-06') # SURVEY9 (2020-04-13) # true number of cases was 751,646 and corresponds to bin the 3rd bin which is labeled "3" survey9 = truth() survey9.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1_1','QF1_2','QF1_3','QF1_5','QF1_6','QF1_7','QF1_8','QF1_9','QF2_1','QF2_2','QF2_3','QF2_4','QF2_5','QF3_1','QF3_2','QF3_3','QF3_4','QF3_5','QF3_6','Q4_1','Q4_2','Q4_3','QF5_1','QF5_2','QF5_3','QF6_1','QF7','QF8']) survey9.addTruths([np.nan,np.nan,np.nan,3,3,3,3,3,3,3,3,5,5,5,5,5,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]) survey9DB = survey9.export2DB('2020-04-13') # SURVEY10 (2020-04-20) # true number of cases was 960,343 and corresponds to the fourth bin which is labeled "5" survey10 = truth() survey10.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1_1','QF1_2','QF1_3','QF1_5','QF1_6','QF1_7','QF2_1','QF2_2','QF2_3','QF3_1','QF3_2','QF3_3','Q4_1','Q4_2','Q4_3','QF5_1','QF5_2','QF5_3','QF6_1','QF6_2' ,'QF6_3','QF6_4','QF6_5','QF7','QF8']) survey10.addTruths([np.nan,np.nan,np.nan,5,5,5,5,5,5,73291,73291,73291,3349,3349,3349,2267,2267,2267,np.nan,np.nan,np.nan,1,1,1,1,1,np.nan,np.nan]) survey10DB = survey10.export2DB('2020-04-20') # SURVEY11 (2020-04-27) # 1,152,006 reported survey11 = truth() survey11.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1_1','QF1_2','QF1_3','QF1_4','QF1_5','QF2_1','QF2_2','QF2_3','QF3_1','QF3_2','QF3_3','QF3_4','QF3_5','QF4_1','QF4_2','QF4_3','QF5_1','QF5_2','QF5_3']) survey11.addTruths([np.nan,np.nan,np.nan,4,4,4,4,4,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]) survey11DB = survey11.export2DB('2020-04-27') # SURVEY12 (2020-05-04) survey12 = truth() survey12.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1_1','QF1_2','QF1_3','QF1_4','QF1_5','QF1_6','QF1_7','QF2_1','QF2_2','QF2_3','QF2_4','QF2_5','QF2_6','QF2_7','QF3_1','QF3_2','QF3_3','QF3_4','QF3_5','QF4_1','QF4_2','QF4_3','QF4_4','QF4_5','QF5_1','QF5_2','QF5_3']) survey12.addTruths([np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]) survey12DB = survey12.export2DB('2020-05-04') #SURVEY13 - 2020-05-12 survey13 = truth() survey13.addQuestionLabels(['Q0-1','QR-1-0','QR-2-0','QF1_1','QF1_2','QF1_3','QF1_4','QF1_5','QF1_6','QF1_7','QF2_1','QF2_2','QF2_3','QF3_1','QF3_2','QF3_3','QF4_1','QF4_2','QF4_3','QF5_1']) survey13.addTruths([np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]) survey13DB = survey13.export2DB('2020-05-11') entiredb = pd.DataFrame() for db in [survey1DB,survey2DB,survey3DB,survey4DB,survey5DB ,survey6DB,survey7DB,survey8DB,survey9DB,survey10DB ,survey11DB,survey12DB,survey13DB]: entiredb = entiredb.append(db) entiredb.to_csv('./database/truthDatabase.csv',index=False)
[ 2, 23209, 392, 1809, 198, 198, 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 628, 220, 220, 220, 1303, 41016, 6089, 56, 16, ...
1.691847
4,011
from math import factorial
[ 6738, 10688, 1330, 1109, 5132, 628 ]
4.666667
6
import open3d as o3d import os import logging import numpy as np from util.trajectory import CameraPose from util.pointcloud import compute_overlap_ratio, \ make_open3d_point_cloud, make_open3d_feature_from_numpy from scipy import spatial #######################################################################
[ 11748, 1280, 18, 67, 355, 267, 18, 67, 198, 11748, 28686, 198, 11748, 18931, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 7736, 13, 9535, 752, 652, 1330, 20432, 47, 577, 198, 6738, 7736, 13, 4122, 17721, 1330, 24061, 62, 2502, ...
3.468085
94
import os from typing import Dict, Tuple import hydra import pandas as pd import torch import wandb from omegaconf import DictConfig from pl_bolts.datamodules.kitti_datamodule import KittiDataModule from pytorch_lightning import Trainer, seed_everything from pytorch_lightning.loggers import WandbLogger from tqdm.auto import tqdm # isort:imports-firstparty from trackseg.datamodules import UnsupervisedSingleImageDataModule from trackseg.model import UnsupervisedSemSegment PROJECT_ROOT = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir)) @hydra.main(config_path="../config", config_name="config") if __name__ == "__main__": my_app()
[ 11748, 28686, 198, 6738, 19720, 1330, 360, 713, 11, 309, 29291, 198, 198, 11748, 25039, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 28034, 198, 11748, 11569, 65, 198, 6738, 267, 28917, 7807, 69, 1330, 360, 713, 16934, 198, 6738, ...
2.907489
227
# -*- coding: utf-8 -*- """Tests for the ``calculation launch matdyn`` command.""" from aiida_quantumespresso.cli.calculations.matdyn import launch_calculation def test_command_base(run_cli_process_launch_command, fixture_code, generate_force_constants_data): """Test invoking the calculation launch command with only required inputs.""" code = fixture_code('quantumespresso.matdyn').store() force_constants = generate_force_constants_data.store() options = ['-X', code.full_label, '-D', force_constants.pk] run_cli_process_launch_command(launch_calculation, options=options)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 51, 3558, 329, 262, 7559, 9948, 14902, 4219, 2603, 67, 2047, 15506, 3141, 526, 15931, 198, 6738, 257, 72, 3755, 62, 40972, 8139, 18302, 568, 13, 44506, 13, 9948, ...
3.035533
197
""" MIT License Copyright (c) 2020 Christoph Kreisl Copyright (c) 2021 Lukas Ruppert 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. """ from core.pyside2_uic import loadUi from PySide2.QtCore import Slot from PySide2.QtWidgets import QWidget from PySide2.QtWidgets import QApplication import os import logging from typing import TYPE_CHECKING if TYPE_CHECKING: from controller.controller import Controller else: from typing import Any as Controller class ViewDetectorSettings(QWidget): """ ViewDetectorSettings Handles the settings of the detector. The view will trigger the detector which will detect outliers based on the final estimate data. """ def set_controller(self, controller : Controller): """ Sets the connection to the controller :param controller: Controller :return: """ self._controller = controller def init_values(self, detector): """ Initialise the values of the view from the detector :param detector: :return: """ self.dsb_m.setValue(detector.m) self.dsb_alpha.setValue(detector.alpha) self.dsb_k.setValue(detector.k) self.dsb_pre_filter.setValue(detector.pre_filter) self.cb_default.setChecked(detector.is_default_active) @Slot(bool, name='toggle_esd') def toggle_esd(self, clicked): """ Toggles the checkbox of the ESD detector, only one detector can be active :param clicked: boolean :return: """ if self.cb_default.isChecked(): self.cb_esd.setChecked(False) if not self.cb_default.isChecked() and not self.cb_esd.isChecked(): self.cb_esd.setChecked(True) @Slot(bool, name='toggle_default') def toggle_default(self, clicked): """ Toggles the checkbox of the default detector, only one detector can be active :param clicked: boolean :return: """ if self.cb_esd.isChecked(): self.cb_default.setChecked(False) if not self.cb_esd.isChecked() and not self.cb_default.isChecked(): self.cb_default.setChecked(True) @Slot(bool, name='apply') def apply(self, clicked): """ Informs the controller to apply the current detector settings :param clicked: boolean :return: """ self._controller.detector.update_and_run_detector( self.dsb_m.value(), self.dsb_alpha.value(), self.dsb_k.value(), self.dsb_pre_filter.value(), self.cb_default.isChecked(), self.cb_is_active.isChecked()) @Slot(bool, name='apply_close') def apply_close(self, clicked): """ Applies the current detector by informing the controller and closes the view. :param clicked: boolean :return: """ self.apply(clicked) self.close()
[ 37811, 198, 220, 220, 220, 17168, 13789, 628, 220, 220, 220, 15069, 357, 66, 8, 12131, 1951, 2522, 25732, 3044, 198, 220, 220, 220, 15069, 357, 66, 8, 33448, 28102, 292, 371, 7211, 861, 628, 220, 220, 220, 2448, 3411, 318, 29376, 75...
2.605195
1,540
# Machine Learning Search Techniques # # Base classes for search techniques that use machine-learning models # # Author: Hans Giesen (giesen@seas.upenn.edu) ####################################################################################################################### import abc, logging from opentuner.search.bandittechniques import AUCBanditMetaTechnique from opentuner.search.differentialevolution import DifferentialEvolutionAlt from opentuner.search.evolutionarytechniques import NormalGreedyMutation, UniformGreedyMutation from opentuner.search.simplextechniques import RandomNelderMead from opentuner.search.technique import SearchTechnique from .modeltuner import ModelTuner log = logging.getLogger(__name__) ####################################################################################################################### class LearningTechnique(SearchTechnique): """Abstract base class for machine-learning search techniques""" __metaclass__ = abc.ABCMeta def __init__(self, models, *pargs, **kwargs): """ Initialize the machine learning search technique object. Parameters ---------- models : list of Model objects """ super(LearningTechnique, self).__init__(*pargs, **kwargs) self._models = models self._data_set = [] self._pending_cfgs = set() def handle_requested_result(self, result): """This callback is invoked by the search driver to report new results. Parameters ---------- result : Result Result """ self._data_set.append(result) data_set = [result for result in self._data_set if result.state == 'OK'] if data_set: cfgs = [result.configuration.data for result in data_set] for model in self._models: results = [getattr(result, model.metric) for result in data_set] model.train(cfgs, results) self._pending_cfgs.discard(result.configuration) def desired_configuration(self): """Suggest a new configuration to evaluate. Returns ------- Configuration Suggested configuration """ for model in self._models: cfg = model.select_configuration() if cfg != None: break if cfg == None: cfg = self.select_configuration() if cfg is not None: self._pending_cfgs.add(cfg) return cfg @abc.abstractmethod def select_configuration(self): """Callback that should be implemented by a subclass to suggest a new configuration to evaluate. Returns ------- Configuration Suggested configuration """ def set_driver(self, driver): """Set the search driver. Parameters ---------- driver : SearchDriver """ super(LearningTechnique, self).set_driver(driver) for model in self._models: model.set_driver(driver) class Model(object): """Abstract base class for machine-learning models""" __metaclass__ = abc.ABCMeta def __init__(self, metric = None): """Constructor Parameters ---------- metric : str Metric that is modeled """ self.metric = metric def train(self, cfgs, results): """Train the model with the provided dataset. Parameters ---------- cfgs : list of dict Configurations results : list of float Measurements """ pass def set_driver(self, driver): """Set the search driver. Parameters ---------- driver : SearchDriver """ self._driver = driver self._manipulator = driver.manipulator @abc.abstractmethod def predict(self, cfg): """Make a prediction for the given configuration. Parameters ---------- cfg : dict Configuration Returns ------- float Mean of prediction float Standard deviation of prediction """ def select_configuration(self): """Suggest a new configuration to evaluate to initialize the model. Returns ------- Configuration Suggested configuration. None is returned if initialization has completed. """ return None class GreedyLearningTechnique(LearningTechnique): """Configuration selector that tries the optimal configuration according to the model unless it has already been tried, in which case a random configuration is chosen. """ def select_configuration(self): """Suggest a new configuration to evaluate. If the configuration that the model thinks is best has not been tried yet, we will suggest it. Otherwise, we suggest a random configuration. Returns ------- Configuration Suggested configuration """ if len(self._data_set) == 0: return self._driver.get_configuration(self._manipulator.random()) technique = AUCBanditMetaTechnique([ DifferentialEvolutionAlt(), UniformGreedyMutation(), NormalGreedyMutation(mutation_rate = 0.3), RandomNelderMead(), ]) tuner = ModelTuner(self._models, technique, self._objective, self._manipulator) cfg = self._driver.get_configuration(tuner.tune()) if (cfg in [result.configuration for result in self._data_set]) or (cfg in self._pending_cfgs): log.info("Subtechnique suggests already evaluated point. Falling back to random point."); cfg = self._driver.get_configuration(self._manipulator.random()) return cfg
[ 2, 10850, 18252, 11140, 49686, 198, 2, 198, 2, 7308, 6097, 329, 2989, 7605, 326, 779, 4572, 12, 40684, 4981, 198, 2, 198, 2, 6434, 25, 13071, 402, 444, 268, 357, 70, 444, 268, 31, 325, 292, 13, 929, 1697, 13, 15532, 8, 198, 2911...
3.006121
1,797
# source: https://github.com/PyTorchLightning/pytorch-lightning-bolts (Apache2) import logging from collections import Counter from typing import Any, Dict, Optional, Tuple import segmentation_models_pytorch as smp import pandas as pd import pytorch_lightning as pl import torch from deadtrees.loss.losses import ( BoundaryLoss, class2one_hot, FocalLoss, GeneralizedDice, ) from deadtrees.network.extra import EfficientUnetPlusPlus, ResUnet, ResUnetPlusPlus from deadtrees.visualization.helper import show from omegaconf import DictConfig from torch import Tensor logger = logging.getLogger(__name__)
[ 2, 2723, 25, 3740, 1378, 12567, 13, 785, 14, 20519, 15884, 354, 15047, 768, 14, 9078, 13165, 354, 12, 2971, 768, 12, 28984, 912, 357, 25189, 4891, 17, 8, 198, 198, 11748, 18931, 198, 6738, 17268, 1330, 15034, 198, 6738, 19720, 1330, ...
2.97619
210
''' The pathExecutor is to use NetworkX as algorithm support to run path finding operations. After getting results from NetworkX, the pathExecutor will transform the results into a temp table in PostgreSQL @author: keshan ''' import os import networkx as nx #based on the path expression, choose different methods to run the operations import QueryParser #Create graphs in NetworkX #for example: dealing with V1/./V2/./V3, separate it into two paths. #get the graph from materialised graph dir or tmp graph dir #create temp table in the relational DB to store the results (without middle node condition, e.g. V1/././V2) #create temp table in the relational DB to store the results (with middle node conditions, e.g. V1/.V2/.V3) def createMTable(pathCommands, Graph, columnList, pathLenList, conn, cur): ''' for debug for each in rowsList: print each for each in pathLenList: print each print "enter MTable" ''' tableName = pathCommands[-1] Col1 = "PathId" Col2 = "Length" Col3 = "Path" #print "create temp table " + graphCommand[3] + " (" + graphCommand[1] + " int not null primary key, " + graphCommand[2] + " int);" cur.execute("create temp table " + tableName + " (" + Col1 + " int not null primary key, " + Col2 + " int , " + Col3 + " integer[] );") conn.commit() pathId = 0 srcCols = columnList[-1] desCols = columnList[-2] pathLen = pathLenList[0] for i in range(0,len(srcCols)): for j in range(0, len(desCols)): if (srcCols[i][0] != desCols[j][0]): #print "enter path1" try: pathList = findPaths(Graph, srcCols[i][0], desCols[j][0], pathLen) except (nx.exception.NetworkXError, nx.exception.NetworkXNoPath, KeyError) as reasons: #print reasons continue tempPathList = [] #this is the first path e.g. V1/./V2 for path in pathList: #Here starts the next several paths for pl in range(1, len(pathLenList)): sCols = columnList[-pl-1] dCols = columnList[-pl-2] #Here is for the last path e.g. V2/./V3 #only for the last path, we start to insert values into table if pl == len(pathLenList) - 1: for a in range(0, len(sCols)): for b in range(0, len(dCols)): #make sure the first node not equals to the last node if (srcCols[i][0] != dCols[b][0]) and (sCols[a][0] != dCols[b][0]): try: lastPathList = findPaths(Graph, sCols[a][0], dCols[b][0], pathLenList[pl]) except (nx.exception.NetworkXError, nx.exception.NetworkXNoPath, KeyError) as reasons: #print reasons continue #print "enter update:", pathId if len(tempPathList) == 0: for lastPath in lastPathList: pathId += 1 cpPath = path[:] cpPath.extend(lastPath[1:]) cur.execute("INSERT INTO " + tableName + " VALUES(%s, %s, array %s)" % (pathId, len(cpPath)-1, cpPath)) #cur.execute("UPDATE " + tableName + " SET %s = %s || ARRAY%s WHERE %s = %s" % (Col3, Col3, path[1:], Col1, pathId)) #cur.execute("UPDATE " + tableName + " SET %s = %s + %s WHERE %s = %s" % (Col2, Col2, pathLenList[pl], Col1, pathId)) conn.commit() else: for each in tempPathList: for lastPath in lastPathList: pathId += 1 cpPath = each[:] cpPath.extend(lastPath[1:]) cur.execute("INSERT INTO " + tableName + " VALUES(%s, %s, array %s)" % (pathId, len(cpPath)-1, cpPath)) conn.commit() #Here is the paths between first path and last path #We only expand the result list and store the new results into a tempPathList else: for a in range(0, len(sCols)): for b in range(0, len(dCols)): #the source and the des must be different if (sCols[a][0] != dCols[b][0]): try: conPathList = findPaths(Graph, sCols[a][0], dCols[b][0], pathLenList[pl]) except (nx.exception.NetworkXError, nx.exception.NetworkXNoPath, KeyError) as reasons: #print reasons continue if len(tempPathList) == 0: for conPath in conPathList: cpPath = path[:] cpPath.extend(conPath[1:]) tempPathList.append(cpPath) else: cpTempPathList = tempPathList[:] for each in tempPathList: tempPathList.remove(each) for each in cpTempPathList: for conPath in conPathList: cpPath = each[:] cpPath.extend(conPath[1:]) tempPathList.append(cpPath) print "complete the paths temp Mtable" #use networkx to find paths
[ 7061, 6, 198, 464, 3108, 23002, 38409, 318, 284, 779, 7311, 55, 355, 11862, 1104, 284, 1057, 3108, 4917, 4560, 13, 198, 3260, 1972, 2482, 422, 7311, 55, 11, 262, 3108, 23002, 38409, 481, 6121, 262, 2482, 656, 257, 20218, 3084, 287, ...
1.625295
4,238
# coding: utf-8 import sys sys.path.append('../beta_code') import unittest import beta_code if __name__ == '__main__': unittest.main()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 10786, 40720, 31361, 62, 8189, 11537, 198, 198, 11748, 555, 715, 395, 198, 11748, 12159, 62, 8189, 198, 198, 361, 11593, 3672, 834, 6624, 705, ...
2.545455
55
import json from unittest import TestCase from unittest.mock import MagicMock from tornado import gen from tornado.concurrent import Future import app from application_repository import ApplicationRepository __author__ = 'adrian'
[ 11748, 33918, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 6139, 44, 735, 198, 6738, 33718, 1330, 2429, 198, 6738, 33718, 13, 1102, 14421, 1330, 10898, 198, 11748, 598, 198, 6738, 3586, 62,...
3.85
60
import os import re import rollbar import rollbar.contrib.flask from flask import Flask, render_template, Response from flask import got_request_exception from werkzeug.exceptions import NotFound app = Flask(__name__) MIN_PAGE_NAME_LENGTH = 2 @app.before_first_request @app.route("/<string:page>/") if __name__ == "__main__": app.run(debug=True)
[ 11748, 28686, 198, 11748, 302, 198, 11748, 4836, 5657, 198, 11748, 4836, 5657, 13, 3642, 822, 13, 2704, 2093, 198, 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 18261, 198, 6738, 42903, 1330, 1392, 62, 25927, 62, 1069, 4516, 198, ...
2.887097
124
# ------------------------------------------------------------------- # # Copyright (c) 2007-2008 Hanzo Archives Limited. # # # # 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. # # # # You may find more information about Hanzo Archives at # # # # http://www.hanzoarchives.com/ # # # # You may find more information about the WARC Tools project at # # # # http://code.google.com/p/warc-tools/ # # ------------------------------------------------------------------- # import wpath import web from web import cheetah from urllib import unquote_plus from index.keypath import keypath from index.timetools import getDisplayTime from warcutils import getRecord from rewrite import makeAccessible index = None def getparams( s ): ret = {} items = s.split('&') for item in items: if '=' in item: bits = item.split('=') key = bits[0] value = unquote_plus( ''.join( bits[1: ] )) ret[key] = value return ret urls = ( '/' , 'frontpage' , '/archive/(.*?)/(.*)' , 'archive' ) class frontpage(object): def GET( self ): cheetah.render( 'index.tmpl' ) class query(object): def GET(self): print 'there' def POST( self ): print 'here' , print getparams(web.data()) def doSearchResults( url ): r = index.search( keypath( url )) if len(r): results = [ x.split()[1] for x in r ] years = [] yearresults = {} for res in results: year = res[:4] if year not in years: years.append( year ) yearresults[ year ] = [ ( res , getDisplayTime(res )) ] else: yearresults[ year ].append(( res , getDisplayTime(res ))) yearresults["years"] = years cheetah.render( 'searchresults.tmpl' , { 'url': url , 'results': yearresults } ) else: cheetah.render( 'nosearchresults.tmpl' ); class archive( object ): def GET( self , timestamp , url ): r = web.ctx['fullpath'] url = r[ r.find('archive') + len('archive') + 2 + len( timestamp ) :] if index is not None: if '*' in timestamp: doSearchResults( url ) else: item = index.get( timestamp , keypath( url )) if item is not None: bits = [x for x in item.split(' ' ) if x.strip() != '' ] mimetype = bits[2] status = bits[3] offset = bits[4] redirect = bits[5] warcn = bits[6] ( headers , content ) = getRecord( warcn , offset ) print makeAccessible( mimetype , url , timestamp , content ) def my_notfound(): cheetah.render( '404.tmpl' ); def browse( idx ): global index index = idx fn = web.webpyfunc( urls , globals() ) web.webapi.notfound = my_notfound web.runsimple( web.wsgifunc(fn ))
[ 201, 2, 16529, 6329, 220, 1303, 201, 2, 15069, 357, 66, 8, 4343, 12, 11528, 9530, 10872, 22275, 15302, 13, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1303, 201, 2, 22...
1.873824
2,338
import calendar hc = calendar.HTMLCalendar() print(hc.formatmonth(2019, 1, withyear=False)) # <table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">January</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="noday">&nbsp;</td><td class="tue">1</td><td class="wed">2</td><td class="thu">3</td><td class="fri">4</td><td class="sat">5</td><td class="sun">6</td></tr> # <tr><td class="mon">7</td><td class="tue">8</td><td class="wed">9</td><td class="thu">10</td><td class="fri">11</td><td class="sat">12</td><td class="sun">13</td></tr> # <tr><td class="mon">14</td><td class="tue">15</td><td class="wed">16</td><td class="thu">17</td><td class="fri">18</td><td class="sat">19</td><td class="sun">20</td></tr> # <tr><td class="mon">21</td><td class="tue">22</td><td class="wed">23</td><td class="thu">24</td><td class="fri">25</td><td class="sat">26</td><td class="sun">27</td></tr> # <tr><td class="mon">28</td><td class="tue">29</td><td class="wed">30</td><td class="thu">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> # </table> # print(type(hc.formatmonth(2019, 1))) # <class 'str'> print(hc.formatyear(2019, width=4)) # <table border="0" cellpadding="0" cellspacing="0" class="year"> # <tr><th colspan="4" class="year">2019</th></tr><tr><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">January</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="noday">&nbsp;</td><td class="tue">1</td><td class="wed">2</td><td class="thu">3</td><td class="fri">4</td><td class="sat">5</td><td class="sun">6</td></tr> # <tr><td class="mon">7</td><td class="tue">8</td><td class="wed">9</td><td class="thu">10</td><td class="fri">11</td><td class="sat">12</td><td class="sun">13</td></tr> # <tr><td class="mon">14</td><td class="tue">15</td><td class="wed">16</td><td class="thu">17</td><td class="fri">18</td><td class="sat">19</td><td class="sun">20</td></tr> # <tr><td class="mon">21</td><td class="tue">22</td><td class="wed">23</td><td class="thu">24</td><td class="fri">25</td><td class="sat">26</td><td class="sun">27</td></tr> # <tr><td class="mon">28</td><td class="tue">29</td><td class="wed">30</td><td class="thu">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> # </table> # </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">February</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="fri">1</td><td class="sat">2</td><td class="sun">3</td></tr> # <tr><td class="mon">4</td><td class="tue">5</td><td class="wed">6</td><td class="thu">7</td><td class="fri">8</td><td class="sat">9</td><td class="sun">10</td></tr> # <tr><td class="mon">11</td><td class="tue">12</td><td class="wed">13</td><td class="thu">14</td><td class="fri">15</td><td class="sat">16</td><td class="sun">17</td></tr> # <tr><td class="mon">18</td><td class="tue">19</td><td class="wed">20</td><td class="thu">21</td><td class="fri">22</td><td class="sat">23</td><td class="sun">24</td></tr> # <tr><td class="mon">25</td><td class="tue">26</td><td class="wed">27</td><td class="thu">28</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> # </table> # </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">March</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="fri">1</td><td class="sat">2</td><td class="sun">3</td></tr> # <tr><td class="mon">4</td><td class="tue">5</td><td class="wed">6</td><td class="thu">7</td><td class="fri">8</td><td class="sat">9</td><td class="sun">10</td></tr> # <tr><td class="mon">11</td><td class="tue">12</td><td class="wed">13</td><td class="thu">14</td><td class="fri">15</td><td class="sat">16</td><td class="sun">17</td></tr> # <tr><td class="mon">18</td><td class="tue">19</td><td class="wed">20</td><td class="thu">21</td><td class="fri">22</td><td class="sat">23</td><td class="sun">24</td></tr> # <tr><td class="mon">25</td><td class="tue">26</td><td class="wed">27</td><td class="thu">28</td><td class="fri">29</td><td class="sat">30</td><td class="sun">31</td></tr> # </table> # </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">April</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="mon">1</td><td class="tue">2</td><td class="wed">3</td><td class="thu">4</td><td class="fri">5</td><td class="sat">6</td><td class="sun">7</td></tr> # <tr><td class="mon">8</td><td class="tue">9</td><td class="wed">10</td><td class="thu">11</td><td class="fri">12</td><td class="sat">13</td><td class="sun">14</td></tr> # <tr><td class="mon">15</td><td class="tue">16</td><td class="wed">17</td><td class="thu">18</td><td class="fri">19</td><td class="sat">20</td><td class="sun">21</td></tr> # <tr><td class="mon">22</td><td class="tue">23</td><td class="wed">24</td><td class="thu">25</td><td class="fri">26</td><td class="sat">27</td><td class="sun">28</td></tr> # <tr><td class="mon">29</td><td class="tue">30</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> # </table> # </td></tr><tr><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">May</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="wed">1</td><td class="thu">2</td><td class="fri">3</td><td class="sat">4</td><td class="sun">5</td></tr> # <tr><td class="mon">6</td><td class="tue">7</td><td class="wed">8</td><td class="thu">9</td><td class="fri">10</td><td class="sat">11</td><td class="sun">12</td></tr> # <tr><td class="mon">13</td><td class="tue">14</td><td class="wed">15</td><td class="thu">16</td><td class="fri">17</td><td class="sat">18</td><td class="sun">19</td></tr> # <tr><td class="mon">20</td><td class="tue">21</td><td class="wed">22</td><td class="thu">23</td><td class="fri">24</td><td class="sat">25</td><td class="sun">26</td></tr> # <tr><td class="mon">27</td><td class="tue">28</td><td class="wed">29</td><td class="thu">30</td><td class="fri">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> # </table> # </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">June</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="sat">1</td><td class="sun">2</td></tr> # <tr><td class="mon">3</td><td class="tue">4</td><td class="wed">5</td><td class="thu">6</td><td class="fri">7</td><td class="sat">8</td><td class="sun">9</td></tr> # <tr><td class="mon">10</td><td class="tue">11</td><td class="wed">12</td><td class="thu">13</td><td class="fri">14</td><td class="sat">15</td><td class="sun">16</td></tr> # <tr><td class="mon">17</td><td class="tue">18</td><td class="wed">19</td><td class="thu">20</td><td class="fri">21</td><td class="sat">22</td><td class="sun">23</td></tr> # <tr><td class="mon">24</td><td class="tue">25</td><td class="wed">26</td><td class="thu">27</td><td class="fri">28</td><td class="sat">29</td><td class="sun">30</td></tr> # </table> # </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">July</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="mon">1</td><td class="tue">2</td><td class="wed">3</td><td class="thu">4</td><td class="fri">5</td><td class="sat">6</td><td class="sun">7</td></tr> # <tr><td class="mon">8</td><td class="tue">9</td><td class="wed">10</td><td class="thu">11</td><td class="fri">12</td><td class="sat">13</td><td class="sun">14</td></tr> # <tr><td class="mon">15</td><td class="tue">16</td><td class="wed">17</td><td class="thu">18</td><td class="fri">19</td><td class="sat">20</td><td class="sun">21</td></tr> # <tr><td class="mon">22</td><td class="tue">23</td><td class="wed">24</td><td class="thu">25</td><td class="fri">26</td><td class="sat">27</td><td class="sun">28</td></tr> # <tr><td class="mon">29</td><td class="tue">30</td><td class="wed">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> # </table> # </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">August</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="thu">1</td><td class="fri">2</td><td class="sat">3</td><td class="sun">4</td></tr> # <tr><td class="mon">5</td><td class="tue">6</td><td class="wed">7</td><td class="thu">8</td><td class="fri">9</td><td class="sat">10</td><td class="sun">11</td></tr> # <tr><td class="mon">12</td><td class="tue">13</td><td class="wed">14</td><td class="thu">15</td><td class="fri">16</td><td class="sat">17</td><td class="sun">18</td></tr> # <tr><td class="mon">19</td><td class="tue">20</td><td class="wed">21</td><td class="thu">22</td><td class="fri">23</td><td class="sat">24</td><td class="sun">25</td></tr> # <tr><td class="mon">26</td><td class="tue">27</td><td class="wed">28</td><td class="thu">29</td><td class="fri">30</td><td class="sat">31</td><td class="noday">&nbsp;</td></tr> # </table> # </td></tr><tr><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">September</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="sun">1</td></tr> # <tr><td class="mon">2</td><td class="tue">3</td><td class="wed">4</td><td class="thu">5</td><td class="fri">6</td><td class="sat">7</td><td class="sun">8</td></tr> # <tr><td class="mon">9</td><td class="tue">10</td><td class="wed">11</td><td class="thu">12</td><td class="fri">13</td><td class="sat">14</td><td class="sun">15</td></tr> # <tr><td class="mon">16</td><td class="tue">17</td><td class="wed">18</td><td class="thu">19</td><td class="fri">20</td><td class="sat">21</td><td class="sun">22</td></tr> # <tr><td class="mon">23</td><td class="tue">24</td><td class="wed">25</td><td class="thu">26</td><td class="fri">27</td><td class="sat">28</td><td class="sun">29</td></tr> # <tr><td class="mon">30</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> # </table> # </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">October</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="noday">&nbsp;</td><td class="tue">1</td><td class="wed">2</td><td class="thu">3</td><td class="fri">4</td><td class="sat">5</td><td class="sun">6</td></tr> # <tr><td class="mon">7</td><td class="tue">8</td><td class="wed">9</td><td class="thu">10</td><td class="fri">11</td><td class="sat">12</td><td class="sun">13</td></tr> # <tr><td class="mon">14</td><td class="tue">15</td><td class="wed">16</td><td class="thu">17</td><td class="fri">18</td><td class="sat">19</td><td class="sun">20</td></tr> # <tr><td class="mon">21</td><td class="tue">22</td><td class="wed">23</td><td class="thu">24</td><td class="fri">25</td><td class="sat">26</td><td class="sun">27</td></tr> # <tr><td class="mon">28</td><td class="tue">29</td><td class="wed">30</td><td class="thu">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> # </table> # </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">November</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="fri">1</td><td class="sat">2</td><td class="sun">3</td></tr> # <tr><td class="mon">4</td><td class="tue">5</td><td class="wed">6</td><td class="thu">7</td><td class="fri">8</td><td class="sat">9</td><td class="sun">10</td></tr> # <tr><td class="mon">11</td><td class="tue">12</td><td class="wed">13</td><td class="thu">14</td><td class="fri">15</td><td class="sat">16</td><td class="sun">17</td></tr> # <tr><td class="mon">18</td><td class="tue">19</td><td class="wed">20</td><td class="thu">21</td><td class="fri">22</td><td class="sat">23</td><td class="sun">24</td></tr> # <tr><td class="mon">25</td><td class="tue">26</td><td class="wed">27</td><td class="thu">28</td><td class="fri">29</td><td class="sat">30</td><td class="noday">&nbsp;</td></tr> # </table> # </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">December</th></tr> # <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> # <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="sun">1</td></tr> # <tr><td class="mon">2</td><td class="tue">3</td><td class="wed">4</td><td class="thu">5</td><td class="fri">6</td><td class="sat">7</td><td class="sun">8</td></tr> # <tr><td class="mon">9</td><td class="tue">10</td><td class="wed">11</td><td class="thu">12</td><td class="fri">13</td><td class="sat">14</td><td class="sun">15</td></tr> # <tr><td class="mon">16</td><td class="tue">17</td><td class="wed">18</td><td class="thu">19</td><td class="fri">20</td><td class="sat">21</td><td class="sun">22</td></tr> # <tr><td class="mon">23</td><td class="tue">24</td><td class="wed">25</td><td class="thu">26</td><td class="fri">27</td><td class="sat">28</td><td class="sun">29</td></tr> # <tr><td class="mon">30</td><td class="tue">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> # </table> # </td></tr></table> print(hc.cssclasses) # ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] hc.cssclasses = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat blue', 'sun red'] print(hc.cssclass_month) # month print(hc.cssclass_year) # year print(hc.cssclass_noday) # noday hc_sun = calendar.HTMLCalendar(firstweekday=6) print(hc_sun.formatmonth(2019, 1)) # <table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">January 2019</th></tr> # <tr><th class="sun">Sun</th><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th></tr> # <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="tue">1</td><td class="wed">2</td><td class="thu">3</td><td class="fri">4</td><td class="sat">5</td></tr> # <tr><td class="sun">6</td><td class="mon">7</td><td class="tue">8</td><td class="wed">9</td><td class="thu">10</td><td class="fri">11</td><td class="sat">12</td></tr> # <tr><td class="sun">13</td><td class="mon">14</td><td class="tue">15</td><td class="wed">16</td><td class="thu">17</td><td class="fri">18</td><td class="sat">19</td></tr> # <tr><td class="sun">20</td><td class="mon">21</td><td class="tue">22</td><td class="wed">23</td><td class="thu">24</td><td class="fri">25</td><td class="sat">26</td></tr> # <tr><td class="sun">27</td><td class="mon">28</td><td class="tue">29</td><td class="wed">30</td><td class="thu">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> # </table> # lhc = calendar.LocaleHTMLCalendar(firstweekday=6, locale='ja_jp') print(lhc.formatmonth(2019, 1)) # <table border="0" cellpadding="0" cellspacing="0" class="month"> # <tr><th colspan="7" class="month">1月 2019</th></tr> # <tr><th class="sun">日</th><th class="mon">月</th><th class="tue">火</th><th class="wed">水</th><th class="thu">木</th><th class="fri">金</th><th class="sat">土</th></tr> # <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="tue">1</td><td class="wed">2</td><td class="thu">3</td><td class="fri">4</td><td class="sat">5</td></tr> # <tr><td class="sun">6</td><td class="mon">7</td><td class="tue">8</td><td class="wed">9</td><td class="thu">10</td><td class="fri">11</td><td class="sat">12</td></tr> # <tr><td class="sun">13</td><td class="mon">14</td><td class="tue">15</td><td class="wed">16</td><td class="thu">17</td><td class="fri">18</td><td class="sat">19</td></tr> # <tr><td class="sun">20</td><td class="mon">21</td><td class="tue">22</td><td class="wed">23</td><td class="thu">24</td><td class="fri">25</td><td class="sat">26</td></tr> # <tr><td class="sun">27</td><td class="mon">28</td><td class="tue">29</td><td class="wed">30</td><td class="thu">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> # </table> #
[ 11748, 11845, 198, 198, 71, 66, 796, 11845, 13, 6535, 44, 5639, 282, 9239, 3419, 198, 198, 4798, 7, 71, 66, 13, 18982, 8424, 7, 23344, 11, 352, 11, 351, 1941, 28, 25101, 4008, 198, 2, 1279, 11487, 4865, 2625, 15, 1, 2685, 39231, ...
2.361179
8,140
import sys, os import xml.etree.ElementTree as ET import json import textbase from tqdm import tqdm CIT_data = {} for x in textbase.parse("CIT.dmp"): CIT_data[x["ID.INV"][0]] = x # We only want to add image items for images that we also actually have on disk at time of import. # Read in a list of current filenames from disk CURRENT_JPGS = set(open("all_jpg.txt").read().split("\n")) HIM_CODES = ("VANDA", "MET", "NPM", "CMA") data_list = [] for HIM_CODE in HIM_CODES: if not os.path.exists(HIM_CODE): print(f"Directory named {HIM_CODE} not found") continue for filename in os.listdir(HIM_CODE): if filename.lower().endswith(".xml"): filepath = os.path.join(HIM_CODE, filename) data_list.extend(parse(filepath, HIM_CODE)) dump("CATALOG.dmp", data_list)
[ 11748, 25064, 11, 28686, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 198, 11748, 33918, 198, 11748, 2420, 8692, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 34, 2043, 62, 7890, 796, 23884, 198, 1640, 2...
2.351429
350
__all__ = ['pipeline'] import asyncio from .task_tui import start_tui import frunner as fr from asyncio.subprocess import PIPE from frunner import State from collections import deque
[ 198, 834, 439, 834, 796, 37250, 79, 541, 4470, 20520, 198, 11748, 30351, 952, 198, 6738, 764, 35943, 62, 83, 9019, 1330, 923, 62, 83, 9019, 198, 11748, 1216, 403, 1008, 355, 1216, 198, 6738, 30351, 952, 13, 7266, 14681, 1330, 350, 4...
3.152542
59
"""Flask application core logic.""" import os from dotenv import load_dotenv from flask import Flask, url_for from twitoff.models import db, migrate from twitoff.routes.home_routes import home_routes from twitoff.routes.twitter_routes import twitter_routes assert load_dotenv(), 'falied to initialize environment' SECRET_KEY = os.getenv('SECRET_KEY') DATABASE_URL = os.getenv('DATABASE_URL') def create_app(): """Create and configure a Flask application instance. Returns: Flask application instance. """ app = Flask(__name__) app.config['SECRET_KEY'] = SECRET_KEY # configure database app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) migrate.init_app(app, db) # configure routes app.register_blueprint(home_routes) app.register_blueprint(twitter_routes) return app
[ 37811, 7414, 2093, 3586, 4755, 9156, 526, 15931, 198, 198, 11748, 28686, 198, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 6738, 42903, 1330, 46947, 11, 19016, 62, 1640, 198, 198, 6738, 665, 270, 2364, 13, 27530, 1330, 20...
2.700297
337
# Copyright (c) 2016 Hewlett-Packard Enterprise Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. from tempest.lib.services.network.agents_client import AgentsClient from tempest.lib.services.network.extensions_client import ExtensionsClient from tempest.lib.services.network.floating_ips_client import FloatingIPsClient from tempest.lib.services.network.floating_ips_port_forwarding_client import \ FloatingIpsPortForwardingClient from tempest.lib.services.network.log_resource_client import LogResourceClient from tempest.lib.services.network.loggable_resource_client import \ LoggableResourceClient from tempest.lib.services.network.metering_label_rules_client import \ MeteringLabelRulesClient from tempest.lib.services.network.metering_labels_client import \ MeteringLabelsClient from tempest.lib.services.network.networks_client import NetworksClient from tempest.lib.services.network.ports_client import PortsClient from tempest.lib.services.network.qos_client import QosClient from tempest.lib.services.network.qos_limit_bandwidth_rules_client import \ QosLimitBandwidthRulesClient from tempest.lib.services.network.qos_minimum_bandwidth_rules_client import \ QosMinimumBandwidthRulesClient from tempest.lib.services.network.quotas_client import QuotasClient from tempest.lib.services.network.routers_client import RoutersClient from tempest.lib.services.network.security_group_rules_client import \ SecurityGroupRulesClient from tempest.lib.services.network.security_groups_client import \ SecurityGroupsClient from tempest.lib.services.network.segments_client import SegmentsClient from tempest.lib.services.network.service_providers_client import \ ServiceProvidersClient from tempest.lib.services.network.subnetpools_client import SubnetpoolsClient from tempest.lib.services.network.subnets_client import SubnetsClient from tempest.lib.services.network.tags_client import TagsClient from tempest.lib.services.network.trunks_client import TrunksClient from tempest.lib.services.network.versions_client import NetworkVersionsClient __all__ = ['AgentsClient', 'ExtensionsClient', 'FloatingIPsClient', 'FloatingIpsPortForwardingClient', 'MeteringLabelRulesClient', 'MeteringLabelsClient', 'NetworksClient', 'NetworkVersionsClient', 'PortsClient', 'QosClient', 'QosMinimumBandwidthRulesClient', 'QosLimitBandwidthRulesClient', 'QuotasClient', 'RoutersClient', 'SecurityGroupRulesClient', 'SecurityGroupsClient', 'SegmentsClient', 'ServiceProvidersClient', 'SubnetpoolsClient', 'SubnetsClient', 'TagsClient', 'TrunksClient', 'LogResourceClient', 'LoggableResourceClient']
[ 2, 15069, 357, 66, 8, 1584, 30446, 15503, 12, 11869, 446, 14973, 7712, 5834, 11, 406, 13, 47, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 407, 198, 2, 779, 4...
3.34891
963
try: # importlib.metadata is present in Python 3.8 and later import importlib.metadata as importlib_metadata except ImportError: # use the shim package importlib-metadata pre-3.8 import importlib_metadata as importlib_metadata # type: ignore import pathlib for distribution_name in [__package__, __name__, pathlib.Path(__file__).parent.name]: try: _DISTRIBUTION_METADATA = importlib_metadata.metadata( distribution_name=distribution_name, ) break except importlib_metadata.PackageNotFoundError: continue else: pass author = _DISTRIBUTION_METADATA["Author"] project = _DISTRIBUTION_METADATA["Name"] version = _DISTRIBUTION_METADATA["Version"] version_info = tuple([int(d) for d in version.split("-")[0].split(".")])
[ 28311, 25, 198, 220, 220, 220, 1303, 1330, 8019, 13, 38993, 318, 1944, 287, 11361, 513, 13, 23, 290, 1568, 198, 220, 220, 220, 1330, 1330, 8019, 13, 38993, 355, 1330, 8019, 62, 38993, 198, 16341, 17267, 12331, 25, 198, 220, 220, 220...
2.765734
286
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = [ 'GetQuotaAlarmsResult', 'AwaitableGetQuotaAlarmsResult', 'get_quota_alarms', ] @pulumi.output_type class GetQuotaAlarmsResult: """ A collection of values returned by getQuotaAlarms. """ @property @pulumi.getter @property @pulumi.getter(name="enableDetails") @property @pulumi.getter def id(self) -> str: """ The provider-assigned unique ID for this managed resource. """ return pulumi.get(self, "id") @property @pulumi.getter @property @pulumi.getter(name="nameRegex") @property @pulumi.getter @property @pulumi.getter(name="outputFile") @property @pulumi.getter(name="productCode") @property @pulumi.getter(name="quotaActionCode") @property @pulumi.getter(name="quotaAlarmName") @property @pulumi.getter(name="quotaDimensions") # pylint: disable=using-constant-test def get_quota_alarms(enable_details: Optional[bool] = None, ids: Optional[Sequence[str]] = None, name_regex: Optional[str] = None, output_file: Optional[str] = None, product_code: Optional[str] = None, quota_action_code: Optional[str] = None, quota_alarm_name: Optional[str] = None, quota_dimensions: Optional[Sequence[pulumi.InputType['GetQuotaAlarmsQuotaDimensionArgs']]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetQuotaAlarmsResult: """ This data source provides the Quotas Quota Alarms of the current Alibaba Cloud user. > **NOTE:** Available in v1.116.0+. ## Example Usage Basic Usage ```python import pulumi import pulumi_alicloud as alicloud example = alicloud.quotas.get_quota_alarms(ids=["5VR90-421F886-81E9-xxx"], name_regex="tf-testAcc") pulumi.export("firstQuotasQuotaAlarmId", example.alarms[0].id) ``` :param bool enable_details: Default to `false`. Set it to `true` can output more details about resource attributes. :param Sequence[str] ids: A list of Quota Alarm IDs. :param str name_regex: A regex string to filter results by Quota Alarm name. :param str product_code: The Product Code. :param str quota_action_code: The Quota Action Code. :param str quota_alarm_name: The name of Quota Alarm. :param Sequence[pulumi.InputType['GetQuotaAlarmsQuotaDimensionArgs']] quota_dimensions: The Quota Dimensions. """ __args__ = dict() __args__['enableDetails'] = enable_details __args__['ids'] = ids __args__['nameRegex'] = name_regex __args__['outputFile'] = output_file __args__['productCode'] = product_code __args__['quotaActionCode'] = quota_action_code __args__['quotaAlarmName'] = quota_alarm_name __args__['quotaDimensions'] = quota_dimensions if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('alicloud:quotas/getQuotaAlarms:getQuotaAlarms', __args__, opts=opts, typ=GetQuotaAlarmsResult).value return AwaitableGetQuotaAlarmsResult( alarms=__ret__.alarms, enable_details=__ret__.enable_details, id=__ret__.id, ids=__ret__.ids, name_regex=__ret__.name_regex, names=__ret__.names, output_file=__ret__.output_file, product_code=__ret__.product_code, quota_action_code=__ret__.quota_action_code, quota_alarm_name=__ret__.quota_alarm_name, quota_dimensions=__ret__.quota_dimensions)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 24118, 687, 10290, 357, 27110, 5235, 8, 16984, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760...
2.393743
1,694
# !/usr/bin/env python # -*- coding: utf-8 -*- # # Filename: peewee_factory.py # Project: pwdbs # Author: Brian Cherinka # Created: Monday, 23rd March 2020 4:32:17 pm # License: BSD 3-clause "New" or "Revised" License # Copyright (c) 2020 Brian Cherinka # Last Modified: Monday, 23rd March 2020 5:34:56 pm # Modified By: Brian Cherinka from __future__ import print_function, division, absolute_import import peewee from factory import base # # This code, copied from https://github.com/cam-stitt/factory_boy-peewee, # implements a factory_boy Model Factory for Peewee ORM models since # factory_boy does not support the peewee ORM # class PeeweeModelFactory(base.Factory): """Factory for peewee models. """ _options_class = PeeweeOptions @classmethod def _setup_next_sequence(cls, *args, **kwargs): """Compute the next available PK, based on the 'pk' database field.""" db = cls._meta.database model = cls._meta.model pk = getattr(model, model._meta.primary_key.name) max_pk = (model.select(peewee.fn.Max(pk).alias('maxpk')) .limit(1).order_by().execute()) max_pk = [mp.maxpk for mp in max_pk][0] if isinstance(max_pk, int): return max_pk + 1 if max_pk else 1 else: return 1 @classmethod def _create(cls, target_class, *args, **kwargs): """Create an instance of the model, and save it to the database.""" db = cls._meta.database obj = target_class.create(**kwargs) return obj
[ 2, 5145, 14, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 220, 198, 2, 7066, 12453, 25, 613, 413, 1453, 62, 69, 9548, 13, 9078, 198, 2, 4935, 25, 279, 16993, 1443, 1...
2.440439
638
##TO DO Consider adding in 'not suitable for test' """ Score population according to: 0: Number of hospitals 1: Mean time to thrombolysis 2: Max time to thrombolysis 3: Mean time to thrombectomy 4: Maximum time to thrombectomy 5: Minimum thrombolysis admissions to any one hospital 6: Maximum thrombolysis admissions to any one hospital 7: Minimum thrombectomy admissions to any one hospital 8: Maximum thrombectomy admissions to any one hospital 9: Proportion patients within target thrombolysis time 10: Proportion patients attending unit with target first admissions 11: Proportion patients meeting both thrombolysis targets 12: Proportion patients within target thrombectomy time 13: Proportion patients attending unit with target thrombectomy 14: Proportion patients meeting targets both thrombectomy targets 15: Proportion patients meeting all thrombolysis + thrombectomy targets 16: 95th percentile time for thrombolysis 17: 95th percentile time for thrombectomy 18: Total transfers 19: Total transfer time 20: Clinical outcome (good outcomes) with no treatment 21: Clinical outcome (good outcomes) with treatment 22: Additional good outcomes per 1000 admissions 23: Median time to thrombolysis 24: Median time to thrombectomy 25: Minimum clinical outcome 26: 5th percentile clinical outcome 27: 95th percentile clinical outcome 28: Maximum clinical outcome """ import numpy as np import pandas as pd from classes.clinical_outcome import Clinical_outcome
[ 2235, 10468, 8410, 12642, 4375, 287, 705, 1662, 11080, 329, 1332, 6, 198, 198, 37811, 198, 26595, 3265, 1864, 284, 25, 198, 220, 220, 220, 220, 657, 25, 7913, 286, 11301, 198, 220, 220, 220, 220, 352, 25, 22728, 640, 284, 294, 398, ...
3.403846
468
#!/usr/bin/env python from __future__ import division #from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import import os, sys from os.path import join # We require Python v2.7 or newer if sys.version_info[:2] < (2,7): raise RuntimeError("This requires Python v2.7 or newer") # Prepare for compiling the source code from distutils.ccompiler import get_default_compiler import numpy compiler_name = get_default_compiler() # TODO: this isn't the compiler that will necessarily be used, but is a good guess... compiler_opt = { 'msvc' : ['/D_SCL_SECURE_NO_WARNINGS','/EHsc','/O2','/DNPY_NO_DEPRECATED_API=7','/bigobj','/openmp'], # TODO: older versions of gcc need -std=c++0x instead of -std=c++11 'unix' : ['-std=c++11','-O3','-DNPY_NO_DEPRECATED_API=7','-fopenmp'], # gcc/clang (whatever is system default) 'mingw32' : ['-std=c++11','-O3','-DNPY_NO_DEPRECATED_API=7','-fopenmp'], 'cygwin' : ['-std=c++11','-O3','-DNPY_NO_DEPRECATED_API=7','-fopenmp'], } linker_opt = { 'msvc' : [], 'unix' : ['-fopenmp'], # gcc/clang (whatever is system default) 'mingw32' : ['-fopenmp'], 'cygwin' : ['-fopenmp'], } np_inc = numpy.get_include() import pysegtools cy_inc = join(os.path.dirname(pysegtools.__file__), 'general', 'cython') # TODO: better way to get this src_ext = '.cpp' # Find and use Cython if available try: from distutils.version import StrictVersion import Cython.Build if StrictVersion(Cython.__version__) >= StrictVersion('0.22'): src_ext = '.pyx' except ImportError: # Finally we get to run setup try: from setuptools import setup except ImportError: from distutils.core import setup setup(name='glia', version='0.1', author='Jeffrey Bush', author_email='jeff@coderforlife.com', packages=['glia'], setup_requires=['numpy>=1.7'], install_requires=['numpy>=1.7','scipy>=0.16','pysegtools>=0.1'], use_2to3=True, # the code *should* support Python 3 once run through 2to3 but this isn't tested zip_safe=False, package_data = { '': ['*.pyx', '*.pyxdep', '*.pxi', '*.pxd', '*.h', '*.txt'], }, # Make sure all Cython files are wrapped up with the code ext_modules = cythonize([ create_ext('glia.__contours_around_labels'), create_ext('glia.__count_pairs'), ]) )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 2, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443,...
2.452577
970
OntCversion = '2.0.0' #!/usr/bin/env python3 from ontology.builtins import print
[ 45984, 34, 9641, 796, 705, 17, 13, 15, 13, 15, 6, 198, 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 39585, 1435, 13, 18780, 1040, 1330, 3601, 198 ]
2.612903
31
from setuptools import setup setup() # Note: Everything should be in the local setup.cfg
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 3419, 220, 1303, 5740, 25, 11391, 815, 307, 287, 262, 1957, 9058, 13, 37581, 198 ]
3.791667
24
from aws_cdk import core, aws_dynamodb as dynamodb from . import names
[ 6738, 3253, 82, 62, 10210, 74, 1330, 4755, 11, 3253, 82, 62, 67, 4989, 375, 65, 355, 6382, 375, 65, 198, 6738, 764, 1330, 3891, 628 ]
2.769231
26
#%% # always check the input carefully after opening and splitting # split r and c indices for simplicity (instead of combining them into a tuple) # when using re, be sure to thing if greedy or nongreedy parsing is necessary # don't use re when split() suffices, whitespaces can be casted to int # make sure to experiment with one item from a list instead of and immediate for loop # !when there is a clear test case available, test it! # scan over the input a bit more carefully, it may be different than the test examples # when plotting, use plt.imshow (not plt.show) # i should look into itertools more # when refractoring a test case into the real code, check the indices are not hardcoded! # use better descriptive names. also unpack if it makes code more readable for example in list of tuples # with regex you can numbers pretty easily in a line. and -? to add possible negatives # sometimes its easier to brute force bfs than to figure out an insane algo yourself # at beginning look at example first and highlighted texts # use the easiest way to calculate solution (is set A is asked, dont calc set total - set B) # when defining multiple functions, but an assert testcase below it that closely resembles input # use a class with __hash__ to store mutable objects # with assembly analysis make sure to print registers at important jump points # don't implement an algo if you are pretty sure it isnt going to work # %% f = open('input.txt','r') lines = [list(line.rstrip()) for line in f] print(f'len lines {len(lines)} first item {lines[0]}') import numpy as np grid = np.array(lines) grid import networkx as nx G = nx.Graph() for cell,value in np.ndenumerate(grid): G.add_node(cell) for cell,value in np.ndenumerate(grid): if value != '#': for delta in [[0,1],[1,0],[0,-1],[-1,0]]: r2 = cell[0]+delta[0] c2 = cell[1]+delta[1] if 0<= r2 < grid.shape[0] and 0<= c2 < grid.shape[1] and grid[r2,c2]!='#': G.add_edge(cell,(r2,c2)) # %% poi = {} for cell,value in np.ndenumerate(grid): if value.isdigit(): poi[cell] = value start = [k for k,v in poi.items() if v == '0'][0] total_dis = 0 for fromcell in poi: distances = {} for tocell in poi: if fromcell != tocell: distances[tocell]= nx.shortest_path_length(G, source=fromcell, target=tocell) poi[fromcell]=distances poi best = 9999 from itertools import permutations for p in permutations(poi,len(poi)): if p[0]== start: dis = 0 p = list(p) p.append(start) for i,j in zip(p,p[1:]): dis+=poi[i][j] if dis < best: best = dis best
[ 2, 16626, 198, 2, 1464, 2198, 262, 5128, 7773, 706, 4756, 290, 26021, 198, 2, 6626, 374, 290, 269, 36525, 329, 21654, 357, 38070, 286, 19771, 606, 656, 257, 46545, 8, 198, 2, 618, 1262, 302, 11, 307, 1654, 284, 1517, 611, 31828, 3...
2.813559
944
# MobileInsight Recipe for python-for-android # Authors: Zengwen Yuan, Jiayao Li, # Update for py3: Yunqi Guo, 2020.04 import glob from os.path import exists, join, isdir, split import sh from pythonforandroid.logger import info, shprint, warning from pythonforandroid.toolchain import Recipe, current_directory LOCAL_DEBUG = False recipe = MobileInsightRecipe()
[ 2, 12173, 818, 18627, 26694, 329, 21015, 12, 1640, 12, 19411, 198, 2, 46665, 25, 1168, 1516, 21006, 34071, 11, 29380, 323, 5488, 7455, 11, 198, 2, 10133, 329, 12972, 18, 25, 20757, 40603, 1962, 78, 11, 12131, 13, 3023, 198, 198, 117...
3.324324
111
from ...utils import docval, getargs from ...build import ObjectMapper, BuildManager from ...spec import Spec from ..table import DynamicTable, VectorIndex from .. import register_map @register_map(DynamicTable)
[ 6738, 2644, 26791, 1330, 2205, 2100, 11, 651, 22046, 198, 6738, 2644, 11249, 1330, 9515, 44, 11463, 11, 10934, 13511, 198, 6738, 2644, 16684, 1330, 18291, 198, 6738, 11485, 11487, 1330, 26977, 10962, 11, 20650, 15732, 198, 6738, 11485, 13...
3.962963
54
# ====================================================================================== # # Minimal innovation model implementations and solutions. # # Author : Eddie Lee, edlee@csh.ac.at # ====================================================================================== # from numba import njit, jit from numba.typed import List from scipy.optimize import minimize, root from cmath import sqrt from workspace.utils import save_pickle from .utils import * def L_1ode(G, ro, re, rd, I, alpha=1., Q=2, return_denom=False): """Calculate stationary lattice width accounting the first order correction (from Firms II pg. 140, 238). This is equivalent to (np.exp((1-rd_bar)/(1-ro_bar)) - 1) / np.exp((1-rd_bar)/(1-ro_bar)) * -G_bar * I / ro_bar / (1-rd_bar) This matches numerical solution to first-order equation with x=-1 boundary condition. Parameters ---------- G : float ro : float re : float rd : float I : float alpha : float, 1. Q : float 2. return_denom : bool, False Returns ------- float Estimated lattice width. float (optional) Denominator for L calculation. """ G_bar = G/re ro_bar = ro/re rd_bar = rd/re assert not hasattr(G_bar, '__len__') z = -(1 - rd_bar*(Q-1)) / (1 - ro_bar*(Q-1)) if not hasattr(z, '__len__'): is_ndarray = False z = np.array([z]) else: is_ndarray = True C = np.zeros_like(z) # handle numerical precision problems with z # analytic limit zeroix = z==0 # large z approximation largeix = z < -200 C[largeix] = np.inf remainix = (~zeroix) & (~largeix) C[remainix] = (np.exp(-z[remainix]) - 1 + z[remainix]) / z[remainix] denom = ro_bar/I * ((1+1/(1-C))/(Q-1) - rd_bar - ro_bar/(1-C)) L = -G_bar / denom # analytic form #L = G_bar / (1-rd_bar) * I/ro_bar * (np.exp(-(1-rd_bar)/(1-ro_bar)) - 1) if return_denom: if is_ndarray: return L, denom return L[0], denom if is_ndarray: return L return L[0] def match_length(y1, y2, side1='l', side2='r'): """Fill zeros to match two vectors. Pad zeros on either left or right sides. Parameters ---------- y1 : ndarray y2 : ndarray side1 : str, 'l' side2 : str, 'r' Returns ------- ndarray ndarray """ if side1=='l': y1 = y1[::-1] if side2=='l': y2 = y2[::-1] if y1.size > y2.size: y2 = np.concatenate((y2, np.zeros(y1.size-y2.size))) elif y2.size > y1.size: y1 = np.concatenate((y1, np.zeros(y2.size-y1.size))) if side1=='l': y1 = y1[::-1] if side2=='l': y2 = y2[::-1] return y1, y2 def _solve_G(G0, L, ro, re, rd, I): """Solve for G that return appropriate L.""" z = (re - rd) / (re * (ro/re-1)) C = (np.exp(-z)-1+z) / z soln = minimize(cost, np.log(G0)) return np.exp(soln['x']), soln def fit_dmft(data, L, dt, initial_params, **params_kw): """Best fit of dmft model at stationarity. Parameters ---------- dt : float initial_params : list G shouldn't be specified. **params_kw Returns ------- dict """ soln = minimize(cost, np.log(initial_params)) return np.exp(soln['x']), soln def _fit_dmft(data, dt, initial_params, **params_kw): """Best fit of dmft model at stationarity. Parameters ---------- dt : float initial_params **params_kw Returns ------- dict """ soln = minimize(cost, np.log(initial_params)) return np.exp(soln['x']), soln def fit_flow(x, data, initial_params, full_output=False, reverse=False, **params_kw): """Best fit of ODE model at stationarity. Parameters ---------- x : ndarray data : ndarray initial_params : list full_output : bool, False If True, return soln dict. reverse : bool, False **params_kw Returns ------- ndarray Estimates for (G, ro, re, rd, I). dict If full_output is True. From scipy.optimize.minimize. """ from scipy.interpolate import interp1d data_fun = interp1d(x, data, bounds_error=False, fill_value=0) soln = minimize(cost, initial_params, bounds=[(0,np.inf),(0,np.inf),(1e-3, np.inf)]+[(1e-3,30)]*3, method='SLSQP', constraints=({'type':'ineq', 'fun':lambda args: args[3] - 2 + args[4] - 1e-3, 'jac':lambda args: np.array([0,0,0,1,0,1])},)) if full_output: return soln['x'], soln return soln['x'] def fit_ode(x, data, initial_params, full_output=False, **params_kw): """Best fit of ODE model at stationarity. Parameters ---------- x : ndarray data : ndarray initial_params : list full_output : bool, False If True, return soln dict. **params_kw Returns ------- ndarray Estimates for (G, ro, re, rd, I). dict If full_output is True. From scipy.optimize.minimize. """ soln = minimize(cost, initial_params, bounds=[(1e-3, np.inf)]*4, method='SLSQP', constraints=({'type':'ineq', 'fun':lambda args: args[1] - 2 + args[2] - 1e-3, 'jac':lambda args: np.array([0,1,0,1])},)) if full_output: return soln['x'], soln return soln['x'] def fit_piecewise_ode(x, y, initial_guess, full_output=False): """Heuristic algorithm for fitting to density function. Parameters ---------- full_output : bool, False """ # convert parameters to log space to handle cutoff at 0 soln = minimize(cost, [initial_guess[0]]+np.log(initial_guess[1:]).tolist(), method='powell') if full_output: return np.exp(soln['x']), soln return np.exp(soln['x']) def _fit_piecewise_ode(peakx, peaky, n0, s0, initial_guess, full_output=False): """Heuristic algorithm for fitting to density function. Parameters ---------- full_output : bool, False """ # convert parameters to log space to handle cutoff at 0 soln = minimize(cost, [initial_guess[0]]+np.log(initial_guess[1:]).tolist(), method='powell') if full_output: return np.exp(soln['x']), soln return np.exp(soln['x']) def solve_min_rd(G, ro, re, I, Q=2, a=1., tol=1e-10, initial_guess=None, full_output=False, return_neg=False): """Solve for minimum rd that leads to divergent lattice, i.e. when denominator for L goes to 0 for a fixed re. Parameters ---------- G : float ro : float re : float I : float Q : float, 2 a : float, 1. tol : float, 1e-10 initial_guess : float, None full_output : bool, False return_neg : bool, False Returns ------- float dict (optional) """ # use linear guess as default starting point initial_guess = initial_guess or (2*re+ro) # analytic continuation from the collapsed curve if re==0: if full_output: return 0., {} return 0. soln = minimize(cost, initial_guess) # if it didn't converge, return nan if soln['fun'] > tol: if full_output: return np.nan, soln return np.nan # neg values should be rounded up to 0 elif not return_neg and soln['x'][0] < 0: if full_output: return 0., soln return 0. if full_output: return soln['x'][0], soln return soln['x'][0] def solve_max_rd(G, ro, re, I, Q=2, a=1., tol=1e-10, initial_guess=None, full_output=False, return_neg=False): """Solve for max rd that precedes collapsed lattice, i.e. when we estimate L~1. Parameters ---------- G : float ro : float re : float I : float Q : float, 2 a : float, 1. tol : float, 1e-10 initial_guess : float, None full_output : bool, False return_neg : bool, False Returns ------- float dict (optional) """ # use linear guess as default starting point initial_guess = initial_guess or (G * (ro/re/I)**(-1/a) - ro + 2*re) # analytic continuation from the collapsed curve if re==0: if full_output: return 0., {} return 0. soln = minimize(cost, initial_guess) # if it didn't converge, return nan if soln['fun'] > tol: if full_output: return np.nan, soln return np.nan # neg values should be rounded up to 0 elif not return_neg and soln['x'][0] < 0: if full_output: return 0., soln return 0. if full_output: return soln['x'][0], soln return soln['x'][0] def flatten_phase_boundary(G, ro, re, I, Q, a, re_data, rd_data, poly_order=5): """Fit polynomial to min rd growth curve and use inverse transform to map relative to 1:1 line. Parameters ---------- G: float ro : float re : ndarray I : float Q : float a : float re_data : ndarray rd_data : ndarray poly_order : int, 5 Returns ------- float float """ if not hasattr(re_data, '__len__'): re_data = np.array([re_data]) if not hasattr(rd_data, '__len__'): rd_data = np.array([rd_data]) y = np.array([solve_min_rd(G, ro, re_, I, Q=Q, return_neg=True) for re_ in re]) y = y[1:] x = re[1:][~np.isnan(y)] y = y[~np.isnan(y)] # rescale x to interval [0,1] newx = re_data / x[-1] x /= x[-1] p = np.poly1d(np.polyfit(x, y, poly_order)) newy = np.zeros_like(rd_data) for i, y_ in enumerate(rd_data): roots = (p-y_).roots ny = roots[np.abs(roots-y_).argmin()] if not ny.imag==0: newy[i] = np.nan else: newy[i] = ny return newx, newy.real def L_denominator(ro, rd, Q=2): """Denominator for 2nd order calculation of L at stationarity. Parameters are rescaled rates. When denom goes negative, we have no physical solution for L, i.e. it is either non-stationary or it diverges there is a weird boundary at ro=1. Parameters ---------- ro : float or ndarray ro/re rd : float or ndarray rd/re Q : float, 2 Returns ------- ndarray """ if not hasattr(ro, '__len__'): ro = np.array([ro]) assert (ro>=0).all() if not hasattr(rd, '__len__'): rd = np.array([rd]) assert (rd>=0).all() assert Q>=2 z = -(1/(Q-1) - rd) / (1/(Q-1) - ro) C = np.zeros_like(z) # handle numberical precision problems with z # analytic limit zeroix = z==0 # large z approximation largeix = z < -200 C[largeix] = np.inf remainix = (~zeroix) & (~smallix) & (~largeix) C[remainix] = (np.exp(-z[remainix]) - 1 + z[remainix]) / z[remainix] return ro/(1-C) + rd - (1+1/(1-C)) / (Q-1) def collapse_condition(ro, rd, G, I, Q=2, allow_negs=False): """When this goes to 0, we are at a collapsed boundary. Coming from first order ODE approximation. Parameters ---------- ro : float or ndarray ro/re rd : float or ndarray rd/re G : float G/re I : float Q : float, 2 allow_negs : bool, False Returns ------- ndarray """ if not hasattr(ro, '__len__'): ro = np.array([ro]) if not hasattr(rd, '__len__'): rd = np.array([rd]) if not allow_negs: assert (ro>=0).all() assert (rd>=0).all() assert Q>=2 z = -(1/(Q-1) - rd) / (1/(Q-1) - ro) C = np.zeros_like(z) # handle numerical precision problems with z # analytic limit zeroix = z==0 # large z approximation largeix = z < -200 C[largeix] = np.inf remainix = (~zeroix) & (~smallix) & (~largeix) C[remainix] = (np.exp(-z[remainix]) - 1 + z[remainix]) / z[remainix] return rd + ro / (1-C) - (1+1/(1-C)) / (Q-1) - G*I/ro # ======= # # Classes # # ======= # #end IterativeMFT #end FlowMFT #end ODE2 #end UnitSimulator @njit def jit_unit_sim_loop(T, dt, G, ro, re, rd, I, a): """ Parameters ---------- occupancy : numba.typed.ListType[int64] T : int dt : float ro : float G : float re : float rd : float I : float a : float """ counter = 0 occupancy = [0] while (counter * dt) < T: # innov innov = False if occupancy[-1] and np.random.rand() < (re * I * occupancy[-1]**a * dt): occupancy.append(1) innov = True # obsolescence if len(occupancy) > 1 and np.random.rand() < (ro * dt): occupancy.pop(0) # from right to left b/c of expansion for x in range(len(occupancy)-1, -1, -1): # expansion (fast approximation) if x < (len(occupancy)-1-innov): if occupancy[x] and np.random.rand() < (occupancy[x] * re * dt): occupancy[x+1] += 1 # death (fast approximation) if occupancy[x] and np.random.rand() < (occupancy[x] * rd * dt): occupancy[x] -= 1 # start up (remember that L is length of lattice on x-axis, s.t. L=0 means lattice has one site) if np.random.rand() < (G / len(occupancy) * dt): occupancy[x] += 1 counter += 1 return occupancy @njit def jit_unit_sim_loop_with_occupancy(occupancy, T, dt, G, ro, re, rd, I, a): """ Parameters ---------- occupancy : numba.typed.ListType[int64] T : int dt : float ro : float G : float re : float rd : float I : float a : float """ counter = 0 while (counter * dt) < T: # innov innov = False if occupancy[-1] and np.random.rand() < (re * I * occupancy[-1]**a * dt): occupancy.append(1) innov = True # from right to left b/c of expansion for x in range(len(occupancy)-1, -1, -1): # death (fast approximation) if occupancy[x] and np.random.rand() < (occupancy[x] * rd * dt): occupancy[x] -= 1 # expansion (fast approximation) if x < (len(occupancy)-1-innov): if occupancy[x] and np.random.rand() < (occupancy[x] * re * dt): occupancy[x+1] += 1 # start up if np.random.rand() < (G / len(occupancy) * dt): occupancy[x] += 1 # obsolescence if len(occupancy) > 1 and np.random.rand() < (ro * dt): occupancy.pop(0) counter += 1 return occupancy @njit def jit_unit_sim_loop_no_expand(T, dt, G, ro, re, rd, I, a): """Special case for testing. Without expansion. Parameters ---------- occupancy : numba.typed.ListType[int64] T : int dt : float ro : float G : float re : float rd : float I : float a : float """ counter = 0 occupancy = [0] while (counter * dt) < T: # innov innov = False if occupancy[-1] and np.random.rand() < (re * I * occupancy[-1]**a * dt): occupancy.append(1) innov = True # obsolescence if len(occupancy) > 1 and np.random.rand() < (ro * dt): occupancy.pop(0) # from right to left b/c of expansion for x in range(len(occupancy)-1, -1, -1): # death (fast approximation) if occupancy[x] and np.random.rand() < (occupancy[x] * rd * dt): occupancy[x] -= 1 # start up (remember that L is length of lattice on x-axis, s.t. L=0 means lattice has one site) if len(occupancy)==1: occupancy[x] += 1 elif np.random.rand() < (G / (len(occupancy)-1) * dt): occupancy[x] += 1 counter += 1 return occupancy
[ 2, 38093, 4770, 1421, 28, 1303, 198, 2, 1855, 4402, 11044, 2746, 25504, 290, 8136, 13, 198, 2, 220, 198, 2, 6434, 1058, 19478, 5741, 11, 1225, 7197, 31, 66, 1477, 13, 330, 13, 265, 198, 2, 38093, 4770, 1421, 28, 1303, 198, 6738, ...
2.087224
7,796
import unittest from pyqt2waybinding import BindingEndpoint from PyQt4.QtCore import QObject, pyqtSignal class RealPropertyModel(QObject): """ A simple model class for testing """ valueChanged = pyqtSignal(int) @property @value.setter if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 12972, 39568, 17, 1014, 30786, 1330, 38904, 12915, 4122, 198, 6738, 9485, 48, 83, 19, 13, 48, 83, 14055, 1330, 1195, 10267, 11, 12972, 39568, 11712, 282, 628, 198, 4871, 6416, 21746, 17633, 7, 48, 1026...
2.515385
130
from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from .models import Post
[ 6738, 42625, 14208, 1330, 5107, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 23914, 1330, 11787, 12443, 341, 8479, 11, 48191, 8479, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 198, 6738...
3.73913
46
# Lists the assets' ID, hostname and note for active and inactive assets. # Displays the first 500 assets, because there is no pagination code. import os import sys import requests status_opt = "both" if len(sys.argv) > 1: opt = sys.argv[1] if (opt == "active") or (opt == "inactive"): status_opt = opt else: print(sys.argv[0] + " [active | inactive]") print("If option not specified that both active and inactive stati are displayed.") sys.exit(1) print("List Assets") # KENNA_API_KEY is an environment variable. api_key = os.getenv('KENNA_API_KEY') if api_key is None: print("Environment variable KENNA_API_KEY is non-existent") sys.exit(1) # HTTP header. headers = {'Accept': 'application/json', 'X-Risk-Token': api_key} # List assests depending on the URL. Context is displayed. # List active assets. list_active_assets_url = "https://api.kennasecurity.com/assets" if (status_opt == "both") or (status_opt == "active"): list_assets(list_active_assets_url, "Active Assets") print("") # List inactive assets. if (status_opt == "both") or (status_opt == "inactive"): list_inactive_assets_url = list_active_assets_url + "?filter=inactive" list_assets(list_inactive_assets_url, "Inactive Assets")
[ 2, 44968, 262, 6798, 6, 4522, 11, 2583, 3672, 290, 3465, 329, 4075, 290, 28621, 6798, 13, 198, 2, 3167, 26024, 262, 717, 5323, 6798, 11, 780, 612, 318, 645, 42208, 1883, 2438, 13, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 1174...
2.728238
471
import yfinance as yf from maxpain import max_pain, get_current_price import warnings warnings.simplefilter(action='ignore', category=FutureWarning) if __name__ == "__main__": get_index_maxpain()
[ 11748, 331, 69, 14149, 355, 331, 69, 198, 6738, 3509, 35436, 1330, 3509, 62, 35436, 11, 651, 62, 14421, 62, 20888, 198, 11748, 14601, 198, 40539, 654, 13, 36439, 24455, 7, 2673, 11639, 46430, 3256, 6536, 28, 29783, 20361, 8, 628, 198,...
3.190476
63
from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ User = settings.AUTH_USER_MODEL
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, 4808, 198, 198, 12982, 796, 6460, 13, 32, 24318, 62, 2...
3.282609
46
#funcion con parametros funcion_arg("Josaphat","Lopez")
[ 2, 20786, 295, 369, 5772, 316, 4951, 198, 220, 220, 220, 220, 198, 198, 20786, 295, 62, 853, 7203, 41, 418, 499, 5183, 2430, 43, 20808, 4943 ]
2.259259
27
# -*- coding: utf-8 -*- # Copyright 2018-2021 releng-tool from releng_tool.util.log import err import sys def platform_exit(msg=None, code=None): """ exit out of the releng-tool process Provides a convenience method to help invoke a system exit call without needing to explicitly use ``sys``. A caller can provide a message to indicate the reason for the exit. The provide message will output to standard error. The exit code, if not explicit set, will vary on other arguments. If a message is provided to this call, the default exit code will be ``1``. If no message is provided, the default exit code will be ``0``. In any case, if the caller explicitly sets a code value, the provided code value will be used. An example when using in the context of script helpers is as follows: .. code-block:: python releng_exit('there was an error performing this task') Args: msg (optional): error message to print code (optional): exit code; defaults to 0 if no message or defaults to 1 if a message is set Raises: SystemExit: always raised """ if msg: err(msg) if code is None: code = 1 elif code is None: code = 0 sys.exit(code)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 2864, 12, 1238, 2481, 823, 1516, 12, 25981, 198, 198, 6738, 823, 1516, 62, 25981, 13, 22602, 13, 6404, 1330, 11454, 198, 11748, 25064, 198, 198, 4299, 3859, ...
2.938215
437
import torch import math import unittest from pvae.distributions import HypersphericalUniform if __name__ == '__main__': unittest.main()
[ 11748, 28034, 198, 11748, 10688, 198, 11748, 555, 715, 395, 198, 198, 6738, 279, 33353, 13, 17080, 2455, 507, 1330, 21209, 364, 17042, 605, 3118, 6933, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, ...
2.807692
52
from typing import Union from pyrogram import Client, filters from pyrogram.types import ( CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message, ) import alisu from alisu.config import prefix from alisu.utils import commands from alisu.utils.localization import use_chat_lang bot_repo_link: str = "https://github.com/iiiiii1wepfj/alisurobot" bot_chat: str = "@AlisuChat" # Using a low priority group so deeplinks will run before this and stop the propagation. @Client.on_message( filters.command("start", prefix) & ~filters.regex("^/start rules_"), group=2 ) @Client.on_callback_query(filters.regex("^start_back$")) @use_chat_lang() @Client.on_callback_query(filters.regex("^infos$")) @use_chat_lang() commands.add_command("start", "general")
[ 6738, 19720, 1330, 4479, 198, 198, 6738, 12972, 39529, 1330, 20985, 11, 16628, 198, 6738, 12972, 39529, 13, 19199, 1330, 357, 198, 220, 220, 220, 4889, 1891, 20746, 11, 198, 220, 220, 220, 554, 1370, 9218, 3526, 21864, 11, 198, 220, 2...
2.879121
273
import os import sys if __name__ == '__main__': params = sys.argv[1] print(params) all_files(params)
[ 11748, 28686, 198, 11748, 25064, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 42287, 796, 25064, 13, 853, 85, 58, 16, 60, 198, 220, 220, 220, 3601, 7, 37266, 8, 198, 220, 220, 220, 477, 6...
2.354167
48
import tensorflow as tf def make_skip_gram_for_image(images_captions_pairs): ''' images_captions_pairs: [[image, captions], ...] image: [width, height, [channel]] captions: [[word1, word2, word3], [word1, word2, word3, word4], ...] return: [(image, word1), (image, word2), ....] ''' image_word_pairs = [] for image, captions in images_captions_pairs: for word in captions: images_captions_pairs.append((image, word)) return image_word_pairs
[ 11748, 11192, 273, 11125, 355, 48700, 198, 198, 4299, 787, 62, 48267, 62, 4546, 62, 1640, 62, 9060, 7, 17566, 62, 27144, 507, 62, 79, 3468, 2599, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 4263, 62, 27144, 507, 62, 79, 346...
2.415459
207
# -*- coding: utf-8 -*- # Generated by Django 1.11.26 on 2020-01-25 23:47 from __future__ import unicode_literals from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 2075, 319, 12131, 12, 486, 12, 1495, 2242, 25, 2857, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198,...
2.885417
96
from .base import Filth
[ 6738, 764, 8692, 1330, 7066, 400, 628 ]
3.571429
7
import graphing import random from flask import Flask, abort, request from imgurpython import ImgurClient from linebot import ( LineBotApi, WebhookHandler ) from linebot.exceptions import ( InvalidSignatureError ) from linebot.models import * import tempfile, os from config import client_id, client_secret, album_id, access_token, refresh_token, line_channel_access_token, line_channel_secret ###above for import package app = Flask(__name__) line_bot_api = LineBotApi(line_channel_access_token) handler = WebhookHandler(line_channel_secret) static_tmp_path = os.path.join(os.path.dirname(__file__), 'static', 'tmp') @app.route("/callback", methods=['POST']) @handler.add(MessageEvent, message=(ImageMessage, TextMessage)) if __name__ == '__main__': app.run()
[ 11748, 23360, 722, 220, 201, 198, 11748, 4738, 201, 198, 6738, 42903, 1330, 46947, 11, 15614, 11, 2581, 201, 198, 6738, 33705, 333, 29412, 1330, 1846, 45073, 11792, 201, 198, 6738, 1627, 13645, 1330, 357, 201, 198, 220, 220, 220, 6910, ...
2.817869
291
from django.shortcuts import render, redirect from django.views import View from django.http import HttpResponse from django.contrib import messages, auth
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 18941, 198, 6738, 42625, 14208, 13, 33571, 1330, 3582, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 6218, 11, 6284 ]
3.948718
39
import sys import os import json testCasesFileName = parseInputArgs(sys.argv) test = Test("dummy_app") test.loadFile(testCasesFileName) test.run()
[ 11748, 25064, 198, 11748, 28686, 198, 11748, 33918, 628, 198, 9288, 34, 1386, 8979, 5376, 796, 21136, 20560, 42035, 7, 17597, 13, 853, 85, 8, 198, 198, 9288, 796, 6208, 7203, 67, 13513, 62, 1324, 4943, 198, 9288, 13, 2220, 8979, 7, ...
2.777778
54
import json import shlex, subprocess import re train_file = open('updated_train_nuro.txt').readlines() uuid_file = open('updated_uuid_nuro.txt').readlines() qa_reports = open('qa_reports.txt').read().split() subtasks = [] for report in qa_reports: # adding try except since some reports differ in structure i.e. # TODO: why the difference? # NOTE: reading out subtasks from here since the qa_reports file doesn't have the subtask ID # https://s3-us-west-1.amazonaws.com/6876.qa.report.linking/20190115_160816_00023_2646.0_2676.0_linking/qa_report.json # https://scale.ai/corp/compare_attempts?subtask=5cfe774faaf51a0e1c8570a7&customerTaskResponse=https://s3-us-west-1.amazonaws.com/6876.qa.report.linking/20190115_160816_00023_2646.0_2676.0_linking/qa_report.json try: subtask_idx = report.split('?')[1].split('&')[0].split('=')[1] # extract subtask id's from qa_reports list subtasks.append(subtask_idx) except: continue for subtask_idx in subtasks[:1]: SUBTASK_ID = subtask_idx data = grepper(train_file, SUBTASK_ID) fn_train = 'filtered_subtask/subtask_'+SUBTASK_ID+'_train.txt' write_filtered(data, fn_train) fn_uuid = 'filtered_subtask/subtask_'+SUBTASK_ID+'_uuid.txt' data = grepper(uuid_file, SUBTASK_ID) write_filtered(data, fn_uuid) # extract object id from qa reports file # grep uuid file for subtask id containing the object # extract train + uuid lines from this subtask i: # run model on the filtered subtask # extract frames corresponding to matching object id # grep SUBTASK_ID updated_train_nuro.txt > filtered_subtask/subtask_SUBTASK_ID_train.txt # grep SUBTASK_ID updated_uuid_nuro.txt > filtered_subtask/subtask_SUBTASK_ID_uuid.txt # f['nuro_labels'][0]['frames'][0]['annotations'][0]['scale_id']
[ 11748, 33918, 198, 11748, 427, 2588, 11, 850, 14681, 220, 198, 11748, 302, 198, 198, 27432, 62, 7753, 796, 1280, 10786, 43162, 62, 27432, 62, 77, 1434, 13, 14116, 27691, 961, 6615, 3419, 198, 12303, 312, 62, 7753, 796, 1280, 10786, 43...
2.46049
734
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 628, 198 ]
3.444444
9
# Desafio 031: Dado uma distancia da viagem, calcule o valor, 0.50$ pra cada # quilometro até 200km e 0.45 para viagens acima de 200km. from cores import cor d = float(input('Digite a distância da viagem: ')) print('O custo será de R$ {}{:.2f}{} reais.'.format( cor.verde, d * 0.50 if d <= 200 else d * 0.45, cor.reset))
[ 2, 2935, 1878, 952, 657, 3132, 25, 360, 4533, 334, 2611, 1233, 1192, 544, 12379, 25357, 363, 368, 11, 2386, 23172, 267, 1188, 273, 11, 657, 13, 1120, 3, 7201, 269, 4763, 220, 198, 2, 627, 346, 908, 305, 379, 2634, 939, 13276, 304,...
2.261745
149
import os import re import sys import math import spacy import codecs import tarfile import logging import requests import collections import progressbar import torch as th import numpy as np from sklearn.cluster.k_means_ import k_means import bhabana.utils as utils import bhabana.utils.generic_utils as gu from bhabana.utils import wget from bhabana.utils import constants from torch.autograd import Variable logger = logging.getLogger(__name__) spacy_nlp_collection = {} def get_spacy(lang='en', model=None): """ Returns the spaCy pipeline for the specified language. Keyword arguments: lang -- the language whose pipeline will be returned. """ if model is not None: if lang not in model: raise ValueError("There is no correspondence between the Languge " "({})and the Model ({}) provided.".format(lang, model)) global spacy_nlp_collection spacy_model_name = model if model is not None else lang model_key = "{}_{}".format(lang, spacy_model_name) if model_key not in spacy_nlp_collection: spacy_nlp_collection[model_key] = spacy.load(spacy_model_name) return spacy_nlp_collection[model_key] def pad_sentences(data_batch, pad=0, raw=False): """ Given a sentence, returns the sentence padded with the 'PAD' string. If `pad` is smaller than the size of the sentence, the sentence is trimmed to `pad` elements. If `pad` is 0, the function just returns the original `data`. If raw is False, then the sentence is padded with 0 instead of the 'PAD' string. Keyword arguments: pad -- The number of elements to which the sentence should be padded. raw -- If True, the padding character will be a string 'PAD'; else, 0. """ padded_batch = [] for data in data_batch: if pad == 0: return data if pad <= len(data): return data[:pad] pad_vec = [0 if not raw else 'PAD' for _ in range(len(data[-1]))] for i in range(pad - len(data)): padded_batch.append(pad_vec) return padded_batch def pad_int_sequences(sequences, maxlen=None, dtype='int32', padding='post', truncating='post', value=0.): """ pad_sequences. Pad each sequence to the same length: the length of the longest sequence. If maxlen is provided, any sequence longer than maxlen is truncated to maxlen. Truncation happens off either the beginning or the end (default) of the sequence. Supports pre-padding and post-padding (default). Arguments: sequences: list of lists where each element is a sequence. maxlen: int, maximum length. dtype: type to cast the resulting sequence. padding: 'pre' or 'post', pad either before or after each sequence. truncating: 'pre' or 'post', remove values from sequences larger than maxlen either in the beginning or in the end of the sequence value: float, value to pad the sequences to the desired value. Returns: x: `numpy array` with dimensions (number_of_sequences, maxlen) Credits: From Keras `pad_sequences` function. """ lengths = [len(s) for s in sequences] nb_samples = len(sequences) if maxlen is None: maxlen = np.max(lengths) x = (np.ones((nb_samples, maxlen)) * value).astype(dtype) for idx, s in enumerate(sequences): if len(s) == 0: continue # empty list was found if truncating == 'pre': trunc = s[-maxlen:] elif truncating == 'post': trunc = s[:maxlen] else: raise ValueError("Truncating type '%s' not understood" % padding) if padding == 'post': x[idx, :len(trunc)] = trunc elif padding == 'pre': x[idx, -len(trunc):] = trunc else: raise ValueError("Padding type '%s' not understood" % padding) return x def pad_1dconv_input(input, kernel_size, mode="same"): """ This method pads the input for "same" and "full" convolutions. Currently just Same and full padding modes have been implemented :param input: Input Tensor with shape BATCH_SIZE X TIME_STEPS X FEATURES :param mode: :return: Padded Input Tensor with shape BATCH_SIZE X TIME_STEPS X FEATURES """ input_size = list(input.size()) if len(input_size) != 3: raise ValueError("The Shape of the input is invalid." " The Shape of the current input is {}, but ideally a 3D " "vector is expected with shape in the following format:" " BATCH_SIZE X TIME_STEPS X FEATURES".format(input_size)) n_time_steps = input_size[1] if mode == "same": n_padding = n_time_steps - (n_time_steps - kernel_size + 1) elif mode == "full": n_padding = 2 * (kernel_size -1) else: raise NotImplementedError("Other modes for padding have not been " "implemented. Valid and Full are coming " "soon") if n_padding == 0: padded_input = input elif (n_padding % 2) == 0: pad_len = int(n_padding / 2) if input.data.is_cuda: pad_tensor = Variable(th.zeros(input_size[0], pad_len, input_size[-1]).cuda()).cuda() else: pad_tensor = Variable(th.zeros(input_size[0], pad_len, input_size[-1])) padded_input = th.cat([pad_tensor, input, pad_tensor], dim=1) else: pad_len = n_padding / 2 l_pad = int(math.ceil(pad_len)) r_pad = int(math.floor(pad_len)) if not input.data.is_cuda: l_pad_tensor = Variable(th.zeros(input_size[0], l_pad, input_size[-1])) r_pad_tensor = Variable(th.zeros(input_size[0], r_pad, input_size[-1])) else: l_pad_tensor = Variable(th.zeros(input_size[0], l_pad, input_size[-1]).cuda()).cuda() r_pad_tensor = Variable(th.zeros(input_size[0], r_pad, input_size[-1]).cuda()).cuda() padded_input = th.cat([l_pad_tensor, input, r_pad_tensor], dim=1) return padded_input def id2seq(data, i2w): """ `data` is a list of sequences. Each sequence is a list of numbers. For example, the following could be an example of data: [[1, 10, 4, 1, 6], [1, 2, 5, 1, 3], [1, 8, 4, 1, 2]] Each number represents the ID of a word in the vocabulary `i2w`. This function transforms each list of numbers into the corresponding list of words. For example, the list above could be transformed into: [['the', 'dog', 'chased', 'the', 'cat' ], ['the', 'boy', 'kicked', 'the', 'girl'], ['the', 'girl', 'chased', 'the', 'boy' ]] For a function that transforms the abovementioned list of words back into IDs, see `seq2id`. """ buff = [] for seq in data: w_seq = [] for term in seq: if term in i2w: w_seq.append(i2w[term]) sent = ' '.join(w_seq) buff.append(sent) return buff def id2charseq(data, i2w): """ `data` is a list of sequences. Each sequence is a list of numbers. For example, the following could be an example of data: [[1, 10, 4, 1, 6], [1, 2, 5, 1, 3], [1, 8, 4, 1, 2]] Each number represents the ID of a word in the vocabulary `i2w`. This function transforms each list of numbers into the corresponding list of words. For example, the list above could be transformed into: [['the', 'dog', 'chased', 'the', 'cat' ], ['the', 'boy', 'kicked', 'the', 'girl'], ['the', 'girl', 'chased', 'the', 'boy' ]] For a function that transforms the abovementioned list of words back into IDs, see `seq2id`. """ buff = [] for seq in data: w_seq = [] for term in seq: if term in i2w: w_seq.append(i2w[term]) sent = ''.join(w_seq) buff.append(sent) return buff def id2semhashseq(data, i2w): """ `data` is a list of sequences. Each sequence is a list of numbers. For example, the following could be an example of data: [[1, 10, 4, 1, 6], [1, 2, 5, 1, 3], [1, 8, 4, 1, 2]] Each number represents the ID of a word in the vocabulary `i2w`. This function transforms each list of numbers into the corresponding list of words. For example, the list above could be transformed into: [['the', 'dog', 'chased', 'the', 'cat' ], ['the', 'boy', 'kicked', 'the', 'girl'], ['the', 'girl', 'chased', 'the', 'boy' ]] For a function that transforms the abovementioned list of words back into IDs, see `seq2id`. """ buff = [] for seq in data: w_seq = [] for term in seq: term_seq = [] trigram_indexes = np.where(term > 0) for index in trigram_indexes: if index in i2w: term_seq.append(i2w[term].replace("#", "")) w_seq.append("".join(term_seq)) sent = ' '.join(w_seq) buff.append(sent) return buff def seq2id(data, w2i, seq_begin=False, seq_end=False): """ `data` is a list of sequences. Each sequence is a list of words. For example, the following could be an example of data: [['the', 'dog', 'chased', 'the', 'cat' ], ['the', 'boy', 'kicked', 'the', 'girl'], ['the', 'girl', 'chased', 'the', 'boy' ]] Each number represents the ID of a word in the vocabulary `i2w`. This function transforms each list of numbers into the corresponding list of words. For example, the list above could be transformed into: [[1, 10, 4, 1, 6], [1, 2, 5, 1, 3], [1, 8, 4, 1, 2]] For a function that transforms the abovementioned list of IDs back into words, see `id2seq`. Keyword arguments: seq_begin -- If True, insert the ID corresponding to 'SEQ_BEGIN' in the beginning of each sequence seq_end -- If True, insert the ID corresponding to 'SEQ_END' in the end of each sequence """ buff = [] for seq in data: id_seq = [] if seq_begin: id_seq.append(w2i[constants.BOS_WORD]) for term in seq: try: id_seq.append(w2i[term] if term in w2i else w2i[constants.UNK_WORD]) except Exception as e: print(str(e)) if seq_end: id_seq.append(w2i[constants.EOS_WORD]) buff.append(id_seq) return buff def append_seq_markers(data, seq_begin=True, seq_end=True): """ `data` is a list of sequences. Each sequence is a list of numbers. For example, the following could be an example of data: [[1, 10, 4, 1, 6], [1, 2, 5, 1, 3], [1, 8, 4, 1, 2]] Assume that 0 and 11 are IDs corresponding to 'SEQ_BEGIN' and 'SEQ_END', respectively. This function adds 'SEQ_BEGIN' and 'SEQ_END' to all lists, depending on the values of `seq_begin` and `seq_end`. For example, if both are true, then, for the input above, this function will return: [[0, 1, 10, 4, 1, 6, 11], [0, 1, 2, 5, 1, 3, 11], [0, 1, 8, 4, 1, 2, 11]] Keyword arguments: seq_begin -- If True, add the ID corresponding to 'SEQ_BEGIN' to each sequence seq_end -- If True, add the ID corresponding to 'SEQ_END' to each sequence """ data_ = [] for d in data: if seq_begin: d = ['SEQ_BEGIN'] + d if seq_end: d = d + ['SEQ_END'] data_.append(d) return data_ def mark_entities(data, lang='en'): """ `data` is a list of text lines. Each text line is a string composed of one or more words. For example: [['the dog chased the cat' ], ['the boy kicked the girl'], ['John kissed Mary']] The function uses the spaCy pipeline in each line of text, finds Named Entities, and tags them with their type. For example, for the example above, the output will be: [['the dog chased the cat' ], ['the boy kicked the girl'], ['BOE John PERSON EOE kissed BOE Mary PERSON EOE']] where: BOE indicates the beginning of an Entity PERSON indicates the type of the Entity EOE indicates the beginning of an Entity Keyword arguments: lang -- The language in which the sentences are (used to choose which spaCy pipeline to call). """ marked_data = [] spacy_nlp = get_spacy(lang=lang) for line in data: marked_line = [] for token in line: tok = spacy_nlp(token)[0] if tok.ent_type_ != '': marked_line.append('BOE') marked_line.append(token) marked_line.append(tok.ent_type_) marked_line.append('EOE') else: marked_line.append(token) marked_data.append(marked_line) return marked_data def sentence_tokenize(line, lang='en'): """ `line` is a string containing potentially multiple sentences. For each sentence, this function produces a list of tokens. The output of this function is a list containing the lists of tokens produced. For example, say line is: 'I ate chocolate. She ate cake.' This function produces: [['I', 'ate', 'chocolate'], ['She', 'ate', 'cake']] """ sentences = [] doc = get_spacy(lang=lang)(line) for sent in doc.sents: sentence_tokens = [] for token in sent: if token.ent_type_ == '': sentence_tokens.append(token.text.lower()) else: sentence_tokens.append(token.text) sentences.append(sentence_tokens) return sentences def default_tokenize(sentence): """ Returns a list of strings containing each token in `sentence` """ return [i for i in re.split(r"([-.\"',:? !\$#@~()*&\^%;\[\]/\\\+<>\n=])", sentence) if i != '' and i != ' ' and i != '\n'] def tokenize(line, tokenizer='spacy', lang='en', spacy_model=None): """ Returns a list of strings containing each token in `line`. Keyword arguments: tokenizer -- Possible values are 'spacy', 'split' and 'other'. lang -- Possible values are 'en' and 'de' """ tokens = [] if tokenizer == 'spacy': doc = get_spacy(lang=lang, model=spacy_model).tokenizer(line) for token in doc: if token.ent_type_ == '': if lang == 'de': text = token.text else: text = token.text.lower() tokens.append(text) else: tokens.append(token.text) elif tokenizer == 'split': tokens = line.split(' ') else: tokens = default_tokenize(line) return tokens def load_classes(classes_path): """ Loads the classes from file `classes_path`. """ c2i = {} i2c = {} c_id = 0 with codecs.open(classes_path, 'r', 'utf-8') as cf: for line in cf: label = line.strip() c2i[label] = c_id i2c[c_id] = label c_id += 1 return c2i, i2c def load_vocabulary(vocab_path): """ Loads the vocabulary from file `vocab_path`. """ w2i = {constants.PAD_WORD: constants.PAD, constants.UNK_WORD: constants.UNK, constants.BOS_WORD: constants.BOS, constants.EOS_WORD: constants.EOS, constants.SPACE_WORD: constants.SPACE} i2w = {constants.PAD: constants.PAD_WORD, constants.UNK: constants.UNK_WORD, constants.BOS: constants.BOS_WORD, constants.EOS: constants.EOS_WORD, constants.SPACE: constants.SPACE_WORD} with codecs.open(vocab_path, 'r', 'utf-8') as vf: wid = 5 dup_id = 0 for line in vf: term = line.strip().split('\t')[0] if term == " " or len(term) == 0: continue if term not in w2i: w2i[term] = wid i2w[wid] = term wid += 1 #else: # w2i["{}{}".format(term, dup_id)] = wid # i2w[wid] = "{}{}".format(term, dup_id) # wid += 1 # dup_id += 1 return w2i, i2w def preload_w2v(w2i, lang='en', model=None): ''' Loads the vocabulary based on spaCy's vectors. Keyword arguments: initialize -- Either 'random' or 'zeros'. Indicate the value of the new vectors to be created (if a word is not found in spaCy's vocabulary lang -- Either 'en' or 'de'. ''' logger.info('Preloading a w2v matrix') spacy_nlp = get_spacy(lang, model) vec_size = get_spacy_vector_size(lang, model) w2v = np.zeros((len(w2i), vec_size)) bar = progressbar.ProgressBar(max_value=len(w2i), redirect_stdout=True) for i_t, term in enumerate(w2i): if spacy_nlp(term).has_vector: w2v[w2i[term]] = spacy_nlp(term).vector bar.update(i_t) bar.finish() return w2v def rescale(values, new_range, original_range): """ `values` is a list of numbers. Rescale the numbers in `values` so that they are always between `new_range` and `original_range`. """ if new_range is None: return values if new_range == original_range: return values rescaled_values = [] for value in values: original_range_size = (original_range[1] - original_range[0]) if (original_range_size == 0): new_value = new_range[0] else: new_range_size = (new_range[1] - new_range[0]) new_value = (((value - original_range[ 0]) * new_range_size) / original_range_size) + \ new_range[0] rescaled_values.append(new_value) return rescaled_values if __name__ == '__main__': data_1 = [[[1, 2, 3], [2, 2, 3], [2, 3], [2, 3, 4, 5]], [[1, 2, 3], [2, 2, 3], [2, 3]]] data_2 = [[1, 2, 3, 4, 5 ,6], [1, 2, 3, 4]] padded_data2 = pad_sequences(data_2, 2) padded_data1 = pad_sequences(data_1, 2) print(np.array(padded_data1)) print(padded_data2)
[ 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 11748, 10688, 198, 11748, 599, 1590, 198, 11748, 40481, 82, 198, 11748, 13422, 7753, 198, 11748, 18931, 198, 11748, 7007, 198, 11748, 17268, 198, 11748, 4371, 5657, 198, 198, 11748, 2...
2.239478
8,268
#!/usr/bin/env python2 import json import re import numpy as np START = "<" STOP = ">" SEP = "@" random = np.random.RandomState(0) N_EX = 5 with open("data.json") as data_f: data = json.load(data_f) with open("templates.json") as template_f: templates = json.load(template_f) with open("hints.json") as hint_f: hints = json.load(hint_f) hints = {int(k): v for k, v in hints.items()} annotations = [] for i, example in enumerate(data): t_before = example["before"] t_before = t_before.replace("[aeiou]", "V").replace("[^aeiou]", "C") re_before = t_before letters_before = t_before.split(")(")[1].replace(".", "").replace("V", "").replace("C", "") letters_before = " ".join(letters_before) t_before = re.sub("[a-z]+", "l", t_before) t_after = example["after"][2:-2] re_after = t_after letters_after = t_after.replace("\\2", "") letters_after = " ".join(letters_after) t_after = re.sub("[a-z]+", "l", t_after) template_key = t_before + SEP + t_after if template_key not in templates: continue aug_hints = [] for template in templates[template_key]: aug_hint = template.replace("BEFORE", letters_before).replace("AFTER", letters_after) aug_hint = [START] + aug_hint.split() + [STOP] aug_hints.append(aug_hint) if i in hints: hint = hints[i] else: hint = "" hint = [START] + hint.split() + [STOP] re_hint = START + re_before + SEP + re_after + STOP ex = [] for inp, out in example["examples"]: inp = START + inp + STOP out = START + out + STOP ex.append((inp, out)) annotations.append({ "examples": ex, "re": re_hint, "hint": hint, "hints_aug": aug_hints }) train = annotations[:3000] val = annotations[3000:3500] test = annotations[3500:4000] for datum in val: del datum["examples"][N_EX+1:] for datum in test: del datum["examples"][N_EX+1:] corpus = { "train": train, "val": val, "test": test } with open("corpus.json", "w") as corpus_f: json.dump(corpus, corpus_f)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 198, 11748, 33918, 198, 11748, 302, 198, 11748, 299, 32152, 355, 45941, 198, 198, 2257, 7227, 796, 33490, 1, 198, 2257, 3185, 796, 366, 24618, 198, 5188, 47, 796, 44212, 1, 198, ...
2.256656
939
print(ackermann(2,2))
[ 198, 4798, 7, 441, 2224, 77, 7, 17, 11, 17, 4008 ]
2
11
# Copyright 2016 The TensorFlow 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. # ============================================================================== """BigQuery reading support for TensorFlow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.cloud.python.ops import gen_bigquery_reader_ops from tensorflow.python.framework import ops from tensorflow.python.ops import io_ops class BigQueryReader(io_ops.ReaderBase): """A Reader that outputs keys and tf.Example values from a BigQuery table. Example use: ```python # Assume a BigQuery has the following schema, # name STRING, # age INT, # state STRING # Create the parse_examples list of features. features = dict( name=tf.FixedLenFeature([1], tf.string), age=tf.FixedLenFeature([1], tf.int32), state=tf.FixedLenFeature([1], dtype=tf.string, default_value="UNK")) # Create a Reader. reader = bigquery_reader_ops.BigQueryReader(project_id=PROJECT, dataset_id=DATASET, table_id=TABLE, timestamp_millis=TIME, num_partitions=NUM_PARTITIONS, features=features) # Populate a queue with the BigQuery Table partitions. queue = tf.training.string_input_producer(reader.partitions()) # Read and parse examples. row_id, examples_serialized = reader.read(queue) examples = tf.parse_example(examples_serialized, features=features) # Process the Tensors examples["name"], examples["age"], etc... ``` Note that to create a reader a snapshot timestamp is necessary. This will enable the reader to look at a consistent snapshot of the table. For more information, see 'Table Decorators' in BigQuery docs. See ReaderBase for supported methods. """ def __init__(self, project_id, dataset_id, table_id, timestamp_millis, num_partitions, features=None, columns=None, test_end_point=None, name=None): """Creates a BigQueryReader. Args: project_id: GCP project ID. dataset_id: BigQuery dataset ID. table_id: BigQuery table ID. timestamp_millis: timestamp to snapshot the table in milliseconds since the epoch. Relative (negative or zero) snapshot times are not allowed. For more details, see 'Table Decorators' in BigQuery docs. num_partitions: Number of non-overlapping partitions to read from. features: parse_example compatible dict from keys to `VarLenFeature` and `FixedLenFeature` objects. Keys are read as columns from the db. columns: list of columns to read, can be set iff features is None. test_end_point: Used only for testing purposes (optional). name: a name for the operation (optional). Raises: TypeError: - If features is neither None nor a dict or - If columns is is neither None nor a list or - If both features and columns are None or set. """ if (features is None) == (columns is None): raise TypeError("exactly one of features and columns must be set.") if features is not None: if not isinstance(features, dict): raise TypeError("features must be a dict.") self._columns = list(features.keys()) elif columns is not None: if not isinstance(columns, list): raise TypeError("columns must be a list.") self._columns = columns self._project_id = project_id self._dataset_id = dataset_id self._table_id = table_id self._timestamp_millis = timestamp_millis self._num_partitions = num_partitions self._test_end_point = test_end_point reader = gen_bigquery_reader_ops.big_query_reader( name=name, project_id=self._project_id, dataset_id=self._dataset_id, table_id=self._table_id, timestamp_millis=self._timestamp_millis, columns=self._columns, test_end_point=self._test_end_point) super(BigQueryReader, self).__init__(reader) def partitions(self, name=None): """Returns serialized BigQueryTablePartition messages. These messages represent a non-overlapping division of a table for a bulk read. Args: name: a name for the operation (optional). Returns: `1-D` string `Tensor` of serialized `BigQueryTablePartition` messages. """ return gen_bigquery_reader_ops.generate_big_query_reader_partitions( name=name, project_id=self._project_id, dataset_id=self._dataset_id, table_id=self._table_id, timestamp_millis=self._timestamp_millis, num_partitions=self._num_partitions, test_end_point=self._test_end_point, columns=self._columns) ops.NotDifferentiable("BigQueryReader")
[ 2, 15069, 1584, 383, 309, 22854, 37535, 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, ...
2.592287
2,178
# -*- coding: utf-8 -*- from django.db import models # from documents.models import Languages class WikiTexts(models.Model): """ Текст для вики """ nazv = models.CharField( max_length=255, blank=True, default='', verbose_name="Название" ) red_zag = models.CharField( max_length=255, blank=True, default='', verbose_name="редакционный заголовок" ) author = models.CharField( max_length=255, blank=True, default='', verbose_name="Автор" ) translator = models.CharField( max_length=255, blank=True, default='', verbose_name="Переводчик" ) editor = models.CharField( max_length=255, blank=True, default='', verbose_name="Редактор" ) data_n = models.CharField( max_length=255, blank=True, default='', verbose_name="Название" ) place_n = models.CharField( max_length=255, blank=True, default='', verbose_name="Название" ) data_i = models.CharField( max_length=255, blank=True, default='', verbose_name="Название" ) place_i = models.CharField( max_length=255, blank=True, default='', verbose_name="Название" ) zhanr = models.CharField( max_length=255, blank=True, default='', verbose_name="Жанр" ) picture = models.CharField( max_length=255, blank=True, default='', verbose_name="Изображение" ) samizdat = models.CharField( max_length=255, blank=True, default='', verbose_name="Название" ) categories = models.CharField( max_length=255, blank=True, default='', verbose_name="Категории" ) title = models.CharField( max_length=255, blank=True, default='', verbose_name="Название" ) link = models.CharField( max_length=255, blank=True, default='', verbose_name="Ссылка" ) user = models.CharField( max_length=255, blank=True, default='', verbose_name="Пользователь" ) ruwiki = models.CharField( max_length=255, blank=True, default='', verbose_name="RU wiki" ) enwiki = models.CharField( max_length=255, blank=True, default='', verbose_name="EN wiki" ) timestamp = models.DateTimeField( auto_now_add=True, null=True, verbose_name="Дата") oborotka = models.TextField( blank=True, default='', verbose_name="Оборотка" ) class TXTC(models.Model): """ TXTC """ t_type = models.CharField( max_length=50, blank=True, default='', verbose_name="Тип" ) class XTC(models.Model): """ XTC """ number = models.CharField( max_length=10, blank=True, default='', verbose_name="Номер ХТС" ) pages = models.CharField( max_length=50, verbose_name="Номера страниц", help_text="Номера страниц хроники, на которых упомянут документ" ) pages_from = models.IntegerField( blank=True, null=True, verbose_name="Начальная страница диапазона") pages_to = models.IntegerField( blank=True, null=True, verbose_name="Последняя страница диапазона") profile = models.CharField( max_length=20, blank=True, verbose_name="Профиль упоминания", default="упом." ) notes = models.CharField( max_length=255, blank=True, default='', verbose_name="Примечания" ) catalog = models.ForeignKey("Catalog", verbose_name="Документ") operator = models.CharField( max_length=8, blank=True, default='', verbose_name="Оператор" ) date = models.DateField( auto_now_add=True, null=True, verbose_name="Дата ввода") class Catalog(models.Model): """ Основной каталог ?? """ ACNumber = models.CharField( max_length=28, blank=True, default='', verbose_name="Номер АС" ) language = models.CharField( max_length=2, blank=True, default='', verbose_name="Язык" ) # language = models.ForeignKey( # "documents.Languages", # db_column="language", # null=True) translated = models.CharField( max_length=2, blank=True, default='', verbose_name="Переведено" ) author = models.CharField( max_length=255, blank=True, default='', verbose_name="Автор" ) auth_notes = models.CharField( max_length=255, blank=True, default='', verbose_name="Примечания к автору" ) auth_group = models.CharField( max_length=100, blank=True, default='', verbose_name="Группа авторов" ) # auth_group_notes = models.CharField( # max_length=255, # blank=True, default='', # verbose_name="Примечания к группе авторов" # ) group_members = models.CharField( max_length=255, blank=True, default='', verbose_name="Состав группы" ) # members_notes = models.CharField( # max_length=255, # blank=True, default='', # verbose_name="Примечания к составу группы" # ) signers = models.CharField( max_length=255, blank=True, default='', verbose_name="Подписанты" ) signers_notes = models.CharField( max_length=255, blank=True, default='', verbose_name="Примечания о подписантах" ) complie_editors = models.CharField( max_length=255, blank=True, default='', verbose_name="Редакторы_составители" ) ce_notes = models.CharField( max_length=255, blank=True, default='', verbose_name="Примечания о редакторах-составителях" ) selfname = models.CharField( max_length=255, blank=True, default='', verbose_name="Самоназвание" ) name1 = models.CharField( max_length=255, blank=True, default='', verbose_name="name1" ) #XXX Possible foreign key to TypeDoc typedoc = models.CharField( max_length=25, blank=True, default='', verbose_name="Тип документа" ) name = models.TextField(blank=True, verbose_name="Название") name2 = models.CharField( max_length=255, blank=True, default='', verbose_name="Name2" ) place = models.CharField( max_length=100, blank=True, null=True, default='', verbose_name="Место" ) m_ind = models.CharField( max_length=100, blank=True, default='', verbose_name="m-ind" ) place_prim = models.CharField( max_length=255, blank=True, null=True, default='', verbose_name="PlacePrim" ) date = models.CharField( max_length=125, blank=True, default='', verbose_name="Дата" ) date_prim = models.CharField( max_length=255, blank=True, default='', verbose_name="DatePrim" ) date1 = models.DateTimeField(blank=True, null=True, verbose_name="date1") date2 = models.DateTimeField(blank=True, null=True, verbose_name="date2") reproducing = models.CharField( max_length=15, blank=True, default='', verbose_name="Способ воспроизведения" ) authencity = models.CharField( max_length=10, blank=True, default='', verbose_name="Подлинность" ) num_copies = models.CharField( max_length=10, blank=True, null=True, verbose_name="Число экземпляров" ) correction = models.CharField( max_length=255, blank=True, null=True, verbose_name="Правка" ) medium = models.CharField( max_length=35, blank=True, null=True, verbose_name="Носитель" ) pages = models.CharField( max_length=50, blank=True, null=True, verbose_name="Страниц" ) archive_notes = models.CharField( max_length=50, blank=True, null=True, verbose_name="Архивные примечания" ) notes = models.TextField( blank=True, null=True, verbose_name="Примечания" ) published = models.TextField( blank=True, null=True, verbose_name="Опубликовано" ) tome = models.CharField( max_length=15, blank=True, null=True, verbose_name="Том" ) number_mc = models.CharField( max_length=10, blank=True, null=True, verbose_name="Номер МС" ) year = models.CharField( max_length=20, blank=True, null=True, verbose_name="Год" ) fund = models.CharField( max_length=70, blank=True, null=True, verbose_name="Фонд" ) register = models.CharField( max_length=70, blank=True, null=True, verbose_name="Опись" ) folder = models.CharField( max_length=10, blank=True, null=True, verbose_name="Дело" ) sheets = models.CharField( max_length=50, blank=True, null=True, verbose_name="Листы" ) annotation = models.TextField( blank=True, null=True, verbose_name="Аннотация" ) web_address = models.CharField( max_length=255, blank=True, null=True, verbose_name="Адрес документа" ) nas = models.IntegerField( blank=True, null=True, verbose_name="NAS" ) nas_ind = models.CharField( max_length=28, blank=True, null=True, verbose_name="NAS-ind" ) troubles = models.NullBooleanField(verbose_name="Troubles") hr = models.NullBooleanField( verbose_name="В хронике", help_text="Отметка о том, что документ упоминается в Хронике" ) hr_search = models.NullBooleanField( verbose_name="hr_poisk", help_text="Отметка для фильтра по номеру ХТС" ) operator = models.CharField( max_length=10, blank=True, null=True, verbose_name="Оператор", help_text="Имя оператора, вводящего запись" ) registration_date = models.DateTimeField( blank=True, null=True, verbose_name="Дата ввода", help_text="Дата ввода оператором(проставляется автоматически)", auto_now_add=True ) ready = models.NullBooleanField( verbose_name="Ready", help_text="Отметка для записей, обработанных на авторство по Именнику" ) belles_lettres = models.NullBooleanField( verbose_name="Художка", ) link = models.CharField( max_length=255, blank=True, null=True, verbose_name="Ссылка", ) aka_name = models.CharField( max_length=255, blank=True, null=True, verbose_name="AKA_name", )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 2, 422, 4963, 13, 27530, 1330, 42860, 628, 198, 4871, 13078, 8206, 82, 7, 27530, 13, 17633, 2599, 198, 220, 22...
1.783674
6,162
from django.core.urlresolvers import reverse from website.apps.core.models import Source from website.testutils import WithEditor class Test_View_SourceEdit_NotLoggedIn(WithEditor): """Tests the source_edit view""" class Test_View_SourceEdit_LoggedIn(WithEditor): """Tests the source_edit view"""
[ 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, 690, 1330, 9575, 198, 6738, 3052, 13, 18211, 13, 7295, 13, 27530, 1330, 8090, 198, 6738, 3052, 13, 9288, 26791, 1330, 2080, 17171, 628, 198, 4871, 6208, 62, 7680, 62, 7416, 18378, 62, ...
3.287234
94
import csv import json import threading import time import psutil import pygame from common import record_metadata, request_clients_end from config import UPDATE_RATE from network import receive, send from .config_finger_tapping_task import (COUNT_DOWN_MESSAGE, SECONDS_COUNT_DOWN, SECONDS_PER_SESSION, SESSION, SQUARE_WIDTH) from .utils import TAPPED, UNTAPPED
[ 11748, 269, 21370, 198, 11748, 33918, 198, 11748, 4704, 278, 198, 11748, 640, 198, 11748, 26692, 22602, 198, 198, 11748, 12972, 6057, 198, 6738, 2219, 1330, 1700, 62, 38993, 11, 2581, 62, 565, 2334, 62, 437, 198, 6738, 4566, 1330, 35717...
2.033333
240
import urllib.request import requests from requests import auth import json # def getRows(userID): # me = auth.HTTPDigestAuth("admin", "admin") # row = [] # transactionAttributes = ["BookingDateTime", "TransactionInformation", "Amount", "Currency"] # id = str(userID) # res = requests.get("http://51.11.48.127:8060/v1/documents?uri=/documents/"+id+".json", auth = me) # if (res.status_code == 404): # return False # a = json.loads(res.text) # for transaction in a['Data']['Transaction']: # collecting = { # 'BookingDateTime': '', # 'TransactionInformation': '', # 'Amount': '', # 'Currency': '' # } # for attribute in transactionAttributes: # if ((attribute == "Amount") or (attribute == "Currency")) : # collecting[attribute] = transaction['Amount'][str(attribute)] # else: # collecting[attribute] = transaction[str(attribute)] # row.append(collecting) # return row main()
[ 11748, 2956, 297, 571, 13, 25927, 201, 198, 11748, 7007, 201, 198, 6738, 7007, 1330, 6284, 201, 198, 11748, 33918, 201, 198, 201, 198, 201, 198, 2, 825, 651, 49, 1666, 7, 7220, 2389, 2599, 201, 198, 2, 220, 220, 220, 220, 502, 796...
2.20284
493
""" Converting test folders into modules allows to use similar file names within structure:: test/ __init__.py integration/ __init__.py test_something.py unit/ __init__.py test_something.py .. seealso:: https://docs.pytest.org/en/latest/goodpractices.html#tests-outside-application-code """
[ 37811, 198, 3103, 48820, 1332, 24512, 656, 13103, 3578, 284, 779, 2092, 2393, 3891, 1626, 198, 301, 5620, 3712, 628, 220, 220, 220, 1332, 14, 198, 220, 220, 220, 220, 220, 220, 220, 11593, 15003, 834, 13, 9078, 198, 220, 220, 220, 2...
2.259036
166
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model
[ 2, 19617, 28, 40477, 12, 23, 201, 198, 2, 16529, 35937, 201, 198, 2, 6127, 7560, 416, 5413, 357, 49, 8, 11160, 19452, 6127, 35986, 352, 13, 15, 13, 16, 13, 15, 201, 198, 2, 19179, 743, 2728, 11491, 4069, 290, 481, 307, 2626, 611...
5
74
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.891892
37