content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
from transformers import EvalPrediction from utils_qa import postprocess_qa_predictions
[ 6738, 6121, 364, 1330, 26439, 39156, 2867, 198, 6738, 3384, 4487, 62, 20402, 1330, 1281, 14681, 62, 20402, 62, 28764, 9278, 628 ]
4.045455
22
import numpy as np def dice(Seg, G): """ compute dice coefficient """ if (np.sum(G) + np.sum(Seg)) == 0: dice = 1.0 else: dice = (2.0 * np.sum(Seg[G == 1])) / (np.sum(Seg) + np.sum(G)) return dice
[ 198, 11748, 299, 32152, 355, 45941, 628, 198, 4299, 17963, 7, 41030, 11, 402, 2599, 198, 220, 220, 220, 37227, 24061, 17963, 35381, 37227, 628, 220, 220, 220, 611, 357, 37659, 13, 16345, 7, 38, 8, 1343, 45941, 13, 16345, 7, 41030, 4...
2.070796
113
#Write a Python program to test whether a number is within 100 of 1000 or 2000 print(test(120)) print(test(0)) print(test(80)) print(test(999)) print(test(1000))
[ 2, 16594, 257, 11361, 1430, 284, 1332, 1771, 257, 1271, 318, 1626, 1802, 286, 8576, 393, 4751, 198, 198, 4798, 7, 9288, 7, 10232, 4008, 198, 4798, 7, 9288, 7, 15, 4008, 198, 4798, 7, 9288, 7, 1795, 4008, 198, 4798, 7, 9288, 7, 1...
3.056604
53
import time import vk
[ 11748, 640, 198, 11748, 410, 74, 198 ]
3.142857
7
import urllib2 import sys #Simple Class Color BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) has_colours = has_colours(sys.stdout) # Resolver: printout("*\-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\*\r\n" , RED) printout("Python ~ Skype Resolver By Phobia\r\n" , CYAN) printout(" Skype: classified \r\n" , YELLOW) printout("*\-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\*\r\n" , RED) SKYPEAPI = "https://www.hackthatapi.com/?command=7&username=" printout("> Skype Username: " , BLUE) SKYPEUSERNAME = raw_input() SKYPEAPI = SKYPEAPI + SKYPEUSERNAME webFile = urllib2.urlopen(SKYPEAPI).read() #if webFile == ("Invalid Key"): # printout("Error", RED) #else: printout(webFile, GREEN) print('\r\n')
[ 11748, 2956, 297, 571, 17, 198, 11748, 25064, 198, 220, 198, 2, 26437, 5016, 5315, 198, 9148, 8120, 11, 23848, 11, 47606, 11, 575, 23304, 3913, 11, 9878, 8924, 11, 28263, 3525, 32, 11, 30440, 1565, 11, 44925, 796, 2837, 7, 23, 8, ...
2.39375
320
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University # Berlin, 14195 Berlin, Germany. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import absolute_import import numpy as np from pyemma.util.annotators import deprecated from six.moves import zip __author__ = 'Fabian Paul' __all__ = ['histogram'] @deprecated("Please use pyemma.coordinates.histogram()") def histogram(transform, dimensions, nbins): '''Computes the N-dimensional histogram of the transformed data. Parameters ---------- transform : pyemma.coordinates.transfrom.Transformer object transform that provides the input data dimensions : tuple of indices indices of the dimensions you want to examine nbins : tuple of ints number of bins along each dimension Returns ------- counts : (bins[0],bins[1],...) ndarray of ints counts compatible with pyplot.pcolormesh and pyplot.bar edges : list of (bins[i]) ndarrays bin edges compatible with pyplot.pcolormesh and pyplot.bar, see below. Examples -------- >>> import matplotlib.pyplot as plt # doctest: +SKIP Only for ipython notebook >> %matplotlib inline # doctest: +SKIP >>> counts, edges=histogram(transform, dimensions=(0,1), nbins=(20, 30)) # doctest: +SKIP >>> plt.pcolormesh(edges[0], edges[1], counts.T) # doctest: +SKIP >>> counts, edges=histogram(transform, dimensions=(1,), nbins=(50,)) # doctest: +SKIP >>> plt.bar(edges[0][:-1], counts, width=edges[0][1:]-edges[0][:-1]) # doctest: +SKIP ''' maximum = np.ones(len(dimensions)) * (-np.inf) minimum = np.ones(len(dimensions)) * np.inf # compute min and max for _, chunk in transform: maximum = np.max( np.vstack(( maximum, np.max(chunk[:, dimensions], axis=0))), axis=0) minimum = np.min( np.vstack(( minimum, np.min(chunk[:, dimensions], axis=0))), axis=0) # define bins bins = [np.linspace(m, M, num=n) for m, M, n in zip(minimum, maximum, nbins)] res = np.zeros(np.array(nbins) - 1) # compute actual histogram for _, chunk in transform: part, _ = np.histogramdd(chunk[:, dimensions], bins=bins) res += part return res, bins
[ 2, 15069, 357, 66, 8, 1853, 11, 1946, 22476, 864, 38275, 24698, 4912, 11, 3232, 2059, 198, 2, 11307, 11, 1478, 22186, 11307, 11, 4486, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2297, 396, 3890, 290, 779, 287, 2723, 290, ...
2.76753
1,312
from starlette.authentication import SimpleUser from starlette_auth_toolkit.base.backends import BaseTokenAuth from ..utils import get_base_app TOKEN = "s3kr3t_t0k3n"
[ 6738, 3491, 21348, 13, 41299, 3299, 1330, 17427, 12982, 198, 198, 6738, 3491, 21348, 62, 18439, 62, 25981, 15813, 13, 8692, 13, 1891, 2412, 1330, 7308, 30642, 30515, 198, 198, 6738, 11485, 26791, 1330, 651, 62, 8692, 62, 1324, 198, 198,...
2.915254
59
__version__ = "0.1.dev39" version = "0.1.dev39" version_tuple = (0, 1)
[ 834, 9641, 834, 796, 366, 15, 13, 16, 13, 7959, 2670, 1, 198, 9641, 796, 366, 15, 13, 16, 13, 7959, 2670, 1, 198, 9641, 62, 83, 29291, 796, 357, 15, 11, 352, 8, 198 ]
2.028571
35
import os import fps as fps_mod if __name__ == "__main__": main(**fps_mod.collect_args())
[ 11748, 28686, 198, 198, 11748, 32977, 355, 32977, 62, 4666, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 7, 1174, 29647, 62, 4666, 13, 33327, 62, 22046, 28955 ]
2.552632
38
from django.urls import include, path from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic.base import RedirectView # Uncomment the next two lines to enable the admin: admin.autodiscover() admin.site.enable_nav_sidebar = False admin.site.site_header = 'Software de Historias Clinicas' admin.site.site_title = 'Historias Clinicas' admin.site.index_title = "Bienvenido al Software de Historias Clinicas" urlpatterns = i18n_patterns( # Examples: # url(r'^$', 'hist.views.home', name='home'), # url(r'^hist/', include('hist.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: path('', RedirectView.as_view(url='/admin')), path('admin/historias/', include('historias.urls')), path('admin/', admin.site.urls), ) if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 2291, 11, 3108, 198, 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 13, 72, 1507, 77, 1330, 1312, 1507, 77, 62, 33279, 82, 220, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, ...
2.7543
407
# encode image of shape (n<=24, 1080, 1920) with Enhanced Run-Length Encoding (ERLE) described in http://www.ti.com/lit/pdf/dlpu018 import numpy as np import struct pack32be = struct.Struct('>I').pack # uint32 big endian def get_header(): ''' generate header defined in section 2.4.2 ''' header = bytearray(0) # signature header += bytearray([0x53, 0x70, 0x6c, 0x64]) # width header += bytearray([1920 % 256, 1920//256]) # height header += bytearray([1080 % 256, 1080//256]) # number of bytes, will be overwritten later header += bytearray(4) # reserved header += bytearray([0xff]*8) # background color (BB GG RR 00) header += bytearray(4) # reserved header.append(0) # compression, 0=Uncompressed, 1=RLE, 2=Enhanced RLE header.append(2) # reserved header.append(1) header += bytearray(21) return header header_template = get_header() def merge(images): ''' merge up to 24 binary images into a single 24-bit image, each pixel is an uint32 of format 0x00BBGGRR ''' image32 = np.zeros((1080, 1920), dtype=np.uint32) n_img = len(images) batches = [8]*(n_img//8) if n_img % 8: batches.append(n_img % 8) for i, batch_size in enumerate(batches): image8 = np.zeros((1080, 1920), dtype=np.uint8) for j in range(batch_size): image8 += images[i*8+j]*(1 << j) image32 += image8*(1 << (i*8)) return image32 def bgr(pixel): ''' convert an uint32 pixel into [B, G, R] bytes ''' return pack32be(pixel)[1:4] def enc128(num): ''' encode num (up to 32767) into 1 or 2 bytes ''' return bytearray([(num & 0x7f) | 0x80, num >> 7]) if num >= 128 else bytearray([num]) def run_len(row, idx): ''' find the length of the longest run starting from idx in row ''' stride = 128 length = len(row) j = idx while j < length and row[j]: if j % stride == 0 and np.all(row[j:j+stride]): j += min(stride, length-j) else: j += 1 return j-idx def encode_row(row, same_prev): ''' encode a row of length 1920 with the format described in section 2.4.3.2 ''' # bool array indicating if same as previous row, shape = (1920, ) # same_prev = np.zeros(1920, dtype=bool) if i==0 else image[i]==image[i-1] # bool array indicating if same as next element, shape = (1919, ) same = np.logical_not(np.diff(row)) # same as previous row or same as next element, shape = (1919, ) same_either = np.logical_or(same_prev[:1919], same) j = 0 compressed = bytearray(0) while j < 1920: # copy n pixels from previous line if same_prev[j]: r = run_len(same_prev, j+1) + 1 j += r compressed += b'\x00\x01' + enc128(r) # repeat single pixel n times elif j < 1919 and same[j]: r = run_len(same, j+1) + 2 j += r compressed += enc128(r) + bgr(row[j-1]) # single uncompressed pixel elif j > 1917 or same_either[j+1]: compressed += b'\x01' + bgr(row[j]) j += 1 # multiple uncompressed pixels else: j_start = j pixels = bgr(row[j]) + bgr(row[j+1]) j += 2 while j == 1919 or not same_either[j]: pixels += bgr(row[j]) j += 1 compressed += b'\x00' + enc128(j-j_start) + pixels return compressed + b'\x00\x00' def encode(images): ''' encode image with the format described in section 2.4.3.2.1 ''' # header encoded = bytearray(header_template) # uint32 array, shape = (1080, 1920) image = merge(images) # image content for i in range(1080): # bool array indicating if same as previous row, shape = (1920, ) same_prev = np.zeros(1920, dtype=bool) if i == 0 else image[i] == image[i-1] encoded += encode_row(image[i], same_prev) # end of image encoded += b'\x00\x01\x00' # pad to 4-byte boundary encoded += bytearray((-len(encoded)) % 4) # overwrite number of bytes in header # uint32 little endian, offset=8 struct.pack_into('<I', encoded, 8, len(encoded)) return encoded
[ 2, 37773, 2939, 286, 5485, 357, 77, 27, 28, 1731, 11, 17729, 11, 14062, 8, 351, 22104, 5660, 12, 24539, 14711, 7656, 357, 1137, 2538, 8, 3417, 287, 2638, 1378, 2503, 13, 20259, 13, 785, 14, 18250, 14, 12315, 14, 25404, 19944, 29159,...
2.230689
1,929
import os.path from setuptools import setup setup( name="costBuddy", license="MIT", description="Taming AWS cost proactively", long_description=get_long_description(), author="A lot of people", author_email="opensource@intuit.com", packages=["src"], python_requires='>=3.6', classifiers=[ "Development Status :: 6 - Mature", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development", "Topic :: Utilities", ], install_requires=['boto3', 'pytest'])
[ 11748, 28686, 13, 6978, 198, 6738, 900, 37623, 10141, 1330, 9058, 628, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 15805, 33, 21584, 1600, 198, 220, 220, 220, 5964, 2625, 36393, 1600, 198, 220, 220, 220, 6764, 2625, 51, 3723, 30865...
2.751381
362
author_special_cases = { "Jeanette Hellgren Kotaleski": ("Jeanette", "Hellgren Kotaleski"), "Hellgren Kotaleski J": ("Jeanette", "Hellgren Kotaleski"), "João Pedro Santos": ("João Pedro", "Santos"), "Yi Ming Lai": ("Yi Ming", "Lai"), "Luis Georg Romundstad": ("Luis Georg", "Romundstad"), "Johanna Frost Nylen": ("Johanna", "Frost Nylen"), "Pål Gunnar Larsson": ("Pål Gunnar", "Larsson"), "André Sevenius Nilsen": ("André Sevenius", "Nilsen"), "Gabriel Andrés Fonseca Guerra": ("Gabriel Andrés", "Fonseca Guerra"), "Pier Stanislao Paolucci": ("Pier Stanislao", "Paolucci"), "Werner Van Geit": ("Werner", "Van Geit"), "Sacha van Albada": ("Sacha", "van Albada"), "Paolo Del Giudice": ("Paolo", "Del Giudice"), "Ignazio De Blasi": ("Ignazio", "De Blasi"), "Marc de Kamps": ("Marc", "de Kamps"), "José Francisco Gómez González": ("José Francisco", "Gómez González"), "Ivilin Peev Stoianov": ("Ivilin Peev", "Stoianov"), "BBP-team": ("BBP", "team") }
[ 198, 198, 9800, 62, 20887, 62, 33964, 796, 1391, 198, 220, 220, 220, 366, 38248, 5857, 5783, 32762, 21702, 2040, 4106, 1298, 5855, 38248, 5857, 1600, 366, 28254, 32762, 21702, 2040, 4106, 12340, 198, 220, 220, 220, 366, 28254, 32762, 21...
2.343249
437
from modeltranslation.translator import register, TranslationOptions from .models import AgeGroup, Compensation, Recruitment, Trait @register(AgeGroup) @register(Compensation) @register(Recruitment) @register(Trait)
[ 6738, 953, 2120, 26084, 7592, 13, 7645, 41880, 1330, 7881, 11, 33322, 29046, 198, 198, 6738, 764, 27530, 1330, 7129, 13247, 11, 39059, 11, 3311, 4872, 434, 11, 4759, 270, 628, 198, 31, 30238, 7, 23396, 13247, 8, 628, 198, 31, 30238, ...
3.515625
64
import torch from torchvision import transforms, utils from PIL import Image import os import numpy as np
[ 11748, 28034, 198, 6738, 28034, 10178, 1330, 31408, 11, 3384, 4487, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 628 ]
3.962963
27
__author__ = "Lucas Ortega Venzel" __license__ = "The Unlicense" __version__ = "0.1" __maintainer__ = "Lucas Ortega Venzel" __email__ = "venzellucas@gmail.com" __status__ = "Testing" from itertools import product from tqdm import tqdm from sklearn.metrics import make_scorer from sklearn.model_selection import cross_val_score
[ 834, 9800, 834, 796, 366, 22946, 292, 1471, 660, 4908, 9932, 17396, 1, 198, 834, 43085, 834, 796, 366, 464, 791, 43085, 1, 198, 834, 9641, 834, 796, 366, 15, 13, 16, 1, 198, 834, 76, 2913, 10613, 834, 796, 366, 22946, 292, 1471, ...
2.811966
117
from django import forms from django.contrib.auth.models import User from dal import autocomplete from .models import BitByteActivity, OffChallenge
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 198, 6738, 288, 282, 1330, 1960, 42829, 6677, 198, 198, 6738, 764, 27530, 1330, 4722, 40778, 16516, 11, 3242, 41812, 3540, 6...
3.642857
42
# pylint: disable=too-few-public-methods, attribute-defined-outside-init """A tiny, async webframework written in Python3.""" import re import cgi from io import BytesIO from urllib.parse import parse_qs from types import FunctionType async def default404(_, error=''): """Default 404 handler.""" return Response(str(error), status=404) async def default500(_, error=''): """Default 404 handler.""" return Response(str(error), status=500) class UploadedFile: """A file uploaded through a multipart/form POST request.""" class Router: """Route different matching string patterns to different urls.""" def add_route(self, route: str, view: FunctionType): """Add a route. Compiles a regex string and stores it with a tuple. Eventually, this should use prefixes so we can more effectively search through paths. As it stands, finding a path will be O(n).""" self.routes[route] = [re.compile(route), view] def route(self, route: str): """Decorator for adding a route to the router. This lets the user add routes pretty easily from Python code like this: @router.route(r'^/mypath$') def mypath(request): ... return response """ return decorator def dispatch(self, path: str) -> FunctionType: """Search for a stored route that matches the given path.""" for route in self.routes: regex = self.routes[route][0] match = regex.search(path) if match: view = self.routes[route][1] return view, match.groupdict() return self.handler404, {"error": "Path {} Not Found".format(path)} class Request: """Represents an incoming HTTP request from the ASGI server. Handles storing get parameters, the request body, and giving view function informations on the context they are being called. """ @classmethod async def create(cls, scope, receive): """Async factory method for creating a request object.""" self = Request() self._scope = scope self.body = await self.receive_body(receive) self.path = scope['path'] self.method = scope.get('method', 'GET') self.headers = {} for key, value in scope['headers']: key = key.decode('utf-8') self.headers[key] = value.decode('utf-8') self.content_type = self.headers.get( 'content-type', 'application/x-www-form-urlencoded' ) if self.method == 'GET': self.GET = self.build_get_params() # pylint: disable=invalid-name elif self.method == 'POST': self.POST = self.build_post_params() # pylint: disable=invalid-name return self async def receive_body(self, receive): """Load all of the body contained in the request and store it. This is based off a similar example from the Uvicorn documentation. """ body = b'' more_body = True while more_body: message = await receive() body += message.get('body', b'') more_body = message.get('more_body', False) return body def build_get_params(self): """Construction of more advanced parts of a request.""" get = {} query_string = parse_qs(self._scope['query_string'].decode('utf-8')) get.update(query_string) return get def build_post_params(self): """Construction of POST parameters and content""" post = {} # Using the CGI module to parse multipart form data. # This section is inspired by similar bottle code. if self.content_type.startswith('multipart/'): safe_env = {'QUERY_STRING': '', 'REQUEST_METHOD': 'POST'} if self.content_type: safe_env.update({'CONTENT_TYPE': self.content_type}) if self.headers.get('content-length'): safe_env.update({'CONTENT_LENGTH': self.headers['content-length']}) cgi_args = dict( fp=BytesIO(self.body), environ=safe_env, keep_blank_values=True ) data = cgi.FieldStorage(**cgi_args) data = data.list or [] for item in data: if item.filename: post[item.name] = UploadedFile(item.file, item.name, item.filename, item.headers) else: post[item.name] = item.value return post class Response: """A response object. Returned by a view.""" async def send_response(self, send): """Send an http response.""" await send({ 'type': 'http.response.start', 'status': self.status, 'headers': [ [b'content_type', self.content_type], *self.headers ], }) await send({ 'type': 'http.response.body', 'body': self.body, }) class Phial: """A Phial webserver class. When called, returns a callback function that the ASGI server can use, while still having access to the parent Phial class. Arguments: router: a Router instance """ def __call__(self, scope): """The ASGI callback handler.""" return callback async def handle_http(self, receive, send, scope): """HTTP Handler.""" request = await Request.create(scope, receive) view, url_params = self.router.dispatch(request.path) try: response = await view(request, **url_params) except Exception as error: # pylint: disable=broad-except response = await self.router.handler500(request, error=error) await response.send_response(send)
[ 2, 279, 2645, 600, 25, 15560, 28, 18820, 12, 32146, 12, 11377, 12, 24396, 82, 11, 11688, 12, 23211, 12, 43435, 12, 15003, 198, 37811, 32, 7009, 11, 30351, 3992, 30604, 3194, 287, 11361, 18, 526, 15931, 198, 11748, 302, 198, 11748, 2...
2.331225
2,530
import os import time import numpy as np import fitsio catalog_dir = '_catalogs' box_data_fn = os.path.join(catalog_dir, 'box_data.fits') data_fn = os.path.join(catalog_dir, 'data.fits') randoms_fn = os.path.join(catalog_dir, 'randoms.fits') bias = 2.0
[ 11748, 28686, 198, 11748, 640, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11414, 952, 628, 198, 9246, 11794, 62, 15908, 796, 705, 62, 9246, 11794, 82, 6, 198, 3524, 62, 7890, 62, 22184, 796, 28686, 13, 6978, 13, 22179, 7, ...
2.407407
108
"""MoneroPy - A python toolbox for Monero Copyright (C) 2016 The MoneroPy Developers. MoneroPy is released under the BSD 3-Clause license. Use and redistribution of this software is subject to the license terms in the LICENSE file found in the top-level directory of this distribution. Modified by emesik and rooterkyberian: + optimized + proper exceptions instead of returning errors as results """ from typing import List ALPHABET: List[int] = [ ord(s) for s in ("123456789ABCDEFGHJKLMNPQRSTUVWXYZ" "abcdefghijkmnopqrstuvwxyz") ] B58_BASE: int = 58 UINT64_MAX: int = 2 ** 64 ENCODED_BLOCK_SIZES: List[int] = [0, 2, 3, 5, 6, 7, 9, 10, 11] FULL_BLOCK_SIZE: int = 8 FULL_ENCODED_BLOCK_SIZE: int = 11 def encode(data: bytes) -> str: """Encode data bytes as base58 (ex: encoding a Monero address).""" l_data: int = len(data) if l_data == 0: return "" full_block_count: int = l_data // FULL_BLOCK_SIZE last_block_size: int = l_data % FULL_BLOCK_SIZE res_size: int = (full_block_count * FULL_ENCODED_BLOCK_SIZE + ENCODED_BLOCK_SIZES[last_block_size]) res: bytearray = bytearray([ALPHABET[0]] * res_size) for i in range(full_block_count): # type: int res = encode_block( data[(i * FULL_BLOCK_SIZE):(i * FULL_BLOCK_SIZE + FULL_BLOCK_SIZE)], res, i * FULL_ENCODED_BLOCK_SIZE ) if last_block_size > 0: begin: int = full_block_count * FULL_BLOCK_SIZE end: int = full_block_count * FULL_BLOCK_SIZE + last_block_size res = encode_block(data[begin:end], res, full_block_count * FULL_ENCODED_BLOCK_SIZE) return bytes(res).decode("ascii") def decode(encoded_value: str) -> str: """Decode a base58 string (ex: a Monero address) into hexidecimal form.""" data_encoded: bytearray = bytearray(encoded_value, encoding="ascii") l_enc: int = len(data_encoded) if l_enc == 0: return "" full_block_count: int = l_enc // FULL_ENCODED_BLOCK_SIZE last_block_size: int = l_enc % FULL_ENCODED_BLOCK_SIZE try: last_block_decoded_size: int = ENCODED_BLOCK_SIZES.index(last_block_size) except ValueError: raise ValueError(f"Invalid encoded length: {l_enc}") data_size: int = (full_block_count * FULL_BLOCK_SIZE + last_block_decoded_size) data: bytearray = bytearray(data_size) begin: int end: int for i in range(full_block_count): # type: int begin = i * FULL_ENCODED_BLOCK_SIZE end = i * FULL_ENCODED_BLOCK_SIZE + FULL_ENCODED_BLOCK_SIZE data = decode_block(data_encoded[begin:end], data, i * FULL_BLOCK_SIZE) if last_block_size > 0: begin = full_block_count * FULL_ENCODED_BLOCK_SIZE end = full_block_count * FULL_ENCODED_BLOCK_SIZE + last_block_size data = decode_block(data_encoded[begin:end], data, full_block_count * FULL_BLOCK_SIZE) return bin_to_hex(data)
[ 37811, 9069, 3529, 20519, 532, 317, 21015, 2891, 3524, 329, 2892, 3529, 198, 15269, 357, 34, 8, 1584, 383, 2892, 3529, 20519, 34152, 13, 198, 198, 9069, 3529, 20519, 318, 2716, 739, 262, 347, 10305, 513, 12, 2601, 682, 5964, 13, 5765,...
2.129161
1,502
import sys from setuptools import setup, find_packages sys.path.insert(0, 'AWSIoTPythonSDK') import AWSIoTPythonSDK currentVersion = AWSIoTPythonSDK.__version__ setup( name='AWSIoTPythonSDK', packages=find_packages(exclude=('tests', )), version=currentVersion, description='SDK for connecting to AWS IoT using Python.', author='Amazon Web Service', author_email='', url='https://github.com/aws/aws-iot-device-sdk-python.git', download_url='https://s3.amazonaws.com/aws-iot-device-sdk-python/aws-iot-device-sdk-python-latest.zip', keywords=['aws', 'iot', 'mqtt'], classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Natural Language :: English", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5" ] )
[ 11748, 25064, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 705, 12298, 11584, 78, 7250, 7535, 10305, 42, 11537, 198, 11748, 14356, 11584, 78, 7250, 7535, 10305, 42, 198, 14...
2.661871
417
""" Module: resources/__init__.py """ from mercadopago.resources.advanced_payment import AdvancedPayment from mercadopago.resources.card_token import CardToken from mercadopago.resources.card import Card from mercadopago.resources.customer import Customer from mercadopago.resources.disbursement_refund import DisbursementRefund from mercadopago.resources.identification_type import IdentificationType from mercadopago.resources.merchant_order import MerchantOrder from mercadopago.resources.payment_methods import PaymentMethods from mercadopago.resources.payment import Payment from mercadopago.resources.preference import Preference from mercadopago.resources.preapproval import PreApproval from mercadopago.resources.refund import Refund from mercadopago.resources.user import User from mercadopago.config.request_options import RequestOptions from mercadopago.http.http_client import HttpClient
[ 37811, 198, 26796, 25, 4133, 14, 834, 15003, 834, 13, 9078, 198, 37811, 198, 6738, 11991, 324, 404, 3839, 13, 37540, 13, 32225, 2903, 62, 37301, 1330, 13435, 19197, 434, 198, 6738, 11991, 324, 404, 3839, 13, 37540, 13, 9517, 62, 30001...
3.75
240
# 数码问题 initial_mat = []
[ 2, 10545, 243, 108, 163, 254, 223, 29785, 106, 165, 95, 246, 198, 198, 36733, 62, 6759, 796, 17635 ]
1.263158
19
#!/usr/bin/env python """ # By: Charles Brandt [code at contextiskey dot com] # On: 2014.07.09 14:56:09 # License: MIT # Requires: moments # based off of: # /c/templates/scripts/diff_directories.py # Description: # # takes two directory paths as input # looks at the contents of both directories # and recursively finds json files with differences between the two of them be very careful if merging automatically... this is not a version control system. more like copy contents of directories over one another and keeping the newer version. potential for data loss there, but shouldn't be a big deal with one primary location. few different approaches for the diff part: 1. read in json as actual object then compare that way: http://stackoverflow.com/questions/11141644/how-to-compare-2-json-in-python 2. use dedicated library for the task: https://pypi.python.org/pypi/json_tools https://bitbucket.org/vadim_semenov/json_tools/src/75cc15381188c760badbd5b66aef9941a42c93fa?at=default https://bitbucket.org/vadim_semenov/json_tools/wiki/Home it employs json-patch: http://tools.ietf.org/html/draft-ietf-appsawg-json-patch-02 3. diff textually: http://stackoverflow.com/questions/4599456/textually-diffing-json python3 sync_jsons.py /path/to/d1 /path/to/d2 it is best if d1 is a subset of d2 (pruned collection derived from bigger one) If d2 does not yet have any data, use rsync or copy to get the initial set (nothing to synchronize in that case): rsync -av /d1/*.json /d2/ """ from __future__ import print_function from builtins import str # skelton for command line interaction: import os, sys import re import subprocess, shutil from datetime import datetime import json, codecs #http://docs.python.org/release/2.5.2/lib/module-difflib.html from difflib import Differ, unified_diff from pprint import pprint #from moments.path import Path from sortable.path import Path from moments.filters import unaccented_map #from __future__ import print_function def diff_json(local, other): """ Calculates the difference between two JSON documents. All resulting changes are relative to @a local. Returns diff formatted in form of extended JSON Patch (see IETF draft). via: https://bitbucket.org/vadim_semenov/json_tools/src/75cc15381188c760badbd5b66aef9941a42c93fa/lib/diff.py?at=default """ result = [] _recursive_diff(local, other, result) return result def print_reduced(diff, pretty=True): """ Prints JSON diff in reduced format (similar to plain diffs). """ print(diff) for action in diff: if 'add' in action: print('+', action['add'], action['value']) elif 'remove' in action: print('-', action['remove'], action['prev']) if __name__ == '__main__': if len (sys.argv) > 1: if sys.argv[1] in ['--help','help'] or len(sys.argv) < 2: usage() d1 = sys.argv[1] d2 = sys.argv[2] #go through each directory #look for matching .json files in both d1 and d2 #if they're exactly the same, skip #if they're the same filename, but different contents: # - check which one has newer content (timestamp) # - if newer is larger, use it # - if newer is smaller, show visual diff (or an alert at minimum) #debug mode to show what the differences are #(diff, added, skipped) = diff_dirs(d1, d2) #when ready to really sync, uncomment: (diff, added, skipped) = diff_dirs(d1, d2, sync=True) print("ADDED:") print('\n'.join(added)) print("\nSKIPPED:") print('\n'.join(skipped))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 2, 2750, 25, 7516, 13512, 83, 685, 8189, 379, 4732, 271, 2539, 16605, 401, 60, 198, 2, 1550, 25, 1946, 13, 2998, 13, 2931, 1478, 25, 3980, 25, 2931, 198, 2, 13789, 25, ...
2.695525
1,363
import numpy as np def _get_chain_recursive(begin,end,sizes): #print((begin,end,sizes)) """ Get chain starting with bead of size sizes[begin] and ending with bead sizes[end-1] """ if begin == end: return np.array([[]]) elif begin == end-1: return np.array([[0,0,0]]) else: margin = 0.001 # allow 0.1% intersections intersecting = True while intersecting: midpoint = (begin+end)//2 left_chain = _get_chain_recursive(begin,midpoint,sizes) right_chain = _get_chain_recursive(midpoint,end,sizes) chain_offset = (sizes[midpoint] + sizes[midpoint-1])*get_spherical() right_chain_shifted = right_chain + chain_offset squared_distances = np.sum((left_chain[:,np.newaxis] - right_chain_shifted[np.newaxis,:])**2, axis = -1) left_sizes = sizes[begin:midpoint] right_sizes = sizes[midpoint:end] shortcuts = (1-margin)*(left_sizes[:,np.newaxis]+right_sizes[np.newaxis,:])**2 - squared_distances if np.all(shortcuts < 0): return np.vstack([left_chain,right_chain_shifted]) else: #print(end-begin) intersecting = True if __name__ == "__main__": print(get_chains(np.ones(17),1))
[ 11748, 299, 32152, 355, 45941, 198, 198, 4299, 4808, 1136, 62, 7983, 62, 8344, 30753, 7, 27471, 11, 437, 11, 82, 4340, 2599, 198, 220, 220, 220, 1303, 4798, 19510, 27471, 11, 437, 11, 82, 4340, 4008, 198, 220, 220, 220, 37227, 198, ...
1.931544
745
## -*- coding: utf-8 -*- ## ## Jonathan Salwan - 2014-05-12 - ROPgadget tool ## ## http://twitter.com/JonathanSalwan ## http://shell-storm.org/project/ROPgadget/ ## import ropgadget.args import ropgadget.binary import ropgadget.core import ropgadget.gadgets import ropgadget.options import ropgadget.rgutils import ropgadget.updateAlert import ropgadget.version import ropgadget.loaders import ropgadget.ropchain
[ 2235, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2235, 198, 2235, 220, 11232, 4849, 8149, 532, 1946, 12, 2713, 12, 1065, 532, 371, 3185, 70, 324, 1136, 2891, 198, 2235, 198, 2235, 220, 2638, 1378, 6956, 13, 785, 1...
2.656051
157
# coding=utf-8 # Copyright 2018 The TF-Agents Authors. # # 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. """A neural network based agent that implements Thompson sampling via dropout. Implements an agent based on a neural network that predicts arm rewards. The neural network internally uses dropout to approximate Thompson sampling. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import gin import tensorflow as tf from tf_agents.bandits.agents import greedy_reward_prediction_agent from tf_agents.networks import q_network @gin.configurable class DropoutThompsonSamplingAgent( greedy_reward_prediction_agent.GreedyRewardPredictionAgent): """A neural network based Thompson sampling agent. This agent receives parameters for a neural network and trains it to predict rewards. The action is chosen greedily with respect to the prediction. The neural network implements dropout for exploration. """ def __init__( self, time_step_spec, action_spec, optimizer, # Network params. dropout_rate, network_layers, dropout_only_top_layer=True, observation_and_action_constraint_splitter=None, # Params for training. error_loss_fn=tf.compat.v1.losses.mean_squared_error, gradient_clipping=None, # Params for debugging. debug_summaries=False, summarize_grads_and_vars=False, enable_summaries=True, expose_predicted_rewards=False, train_step_counter=None, name=None): """Creates a Dropout Thompson Sampling Agent. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. optimizer: The optimizer to use for training. dropout_rate: Float in `(0, 1)`, the dropout rate. network_layers: Tuple of ints determining the sizes of the network layers. dropout_only_top_layer: Boolean parameter determining if dropout should be done only in the top layer. True by default. observation_and_action_constraint_splitter: A function used for masking valid/invalid actions with each state of the environment. The function takes in a full observation and returns a tuple consisting of 1) the part of the observation intended as input to the bandit agent and policy, and 2) the boolean mask. This function should also work with a `TensorSpec` as input, and should output `TensorSpec` objects for the observation and mask. error_loss_fn: A function for computing the error loss, taking parameters labels, predictions, and weights (any function from tf.losses would work). The default is `tf.losses.mean_squared_error`. gradient_clipping: A float representing the norm length to clip gradients (or None for no clipping.) debug_summaries: A Python bool, default False. When True, debug summaries are gathered. summarize_grads_and_vars: A Python bool, default False. When True, gradients and network variable summaries are written during training. enable_summaries: A Python bool, default True. When False, all summaries (debug or otherwise) should not be written. expose_predicted_rewards: (bool) Whether to expose the predicted rewards in the policy info field under the name 'predicted_rewards'. train_step_counter: An optional `tf.Variable` to increment every time the train op is run. Defaults to the `global_step`. name: Python str name of this agent. All variables in this module will fall under that name. Defaults to the class name. Raises: ValueError: If the action spec contains more than one action or or it is not a bounded scalar int32 spec with minimum 0. """ fc_layer_params = network_layers dropout_param = {'rate': dropout_rate, 'permanent': True} if dropout_only_top_layer: dropout_layer_params = [None] * (len(fc_layer_params) - 1) dropout_layer_params.append(dropout_param) else: dropout_layer_params = [dropout_param] * len(fc_layer_params) if observation_and_action_constraint_splitter: input_tensor_spec, _ = observation_and_action_constraint_splitter( time_step_spec.observation) else: input_tensor_spec = time_step_spec.observation reward_network = q_network.QNetwork( input_tensor_spec=input_tensor_spec, action_spec=action_spec, fc_layer_params=fc_layer_params, dropout_layer_params=dropout_layer_params) super(DropoutThompsonSamplingAgent, self).__init__( time_step_spec=time_step_spec, action_spec=action_spec, reward_network=reward_network, optimizer=optimizer, observation_and_action_constraint_splitter=( observation_and_action_constraint_splitter), error_loss_fn=error_loss_fn, gradient_clipping=gradient_clipping, debug_summaries=debug_summaries, summarize_grads_and_vars=summarize_grads_and_vars, enable_summaries=enable_summaries, expose_predicted_rewards=expose_predicted_rewards, train_step_counter=train_step_counter, name=name)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 2864, 383, 24958, 12, 10262, 658, 46665, 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, ...
2.874317
2,013
from ..entity import TypeEntity from ..list import List from ..map import Map from ..reference import Reference from ..string import String from .attribute_definition import AttributeDefinition from .interface_definition_for_type import InterfaceDefinitionForType from .property_definition import PropertyDefinition
[ 6738, 11485, 26858, 1330, 5994, 32398, 198, 6738, 11485, 4868, 1330, 7343, 198, 6738, 11485, 8899, 1330, 9347, 198, 6738, 11485, 35790, 1330, 20984, 198, 6738, 11485, 8841, 1330, 10903, 198, 198, 6738, 764, 42348, 62, 46758, 1330, 3460, 4...
4.818182
66
# coding: utf-8 """ Xero Finance API The Finance API is a collection of endpoints which customers can use in the course of a loan application, which may assist lenders to gain the confidence they need to provide capital. # noqa: E501 Contact: api@xero.com Generated by: https://openapi-generator.tech """ import re # noqa: F401 from xero_python.models import BaseModel class PnlAccountClass(BaseModel): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = {"total": "float", "account_types": "list[PnlAccountType]"} attribute_map = {"total": "total", "account_types": "accountTypes"} def __init__(self, total=None, account_types=None): # noqa: E501 """PnlAccountClass - a model defined in OpenAPI""" # noqa: E501 self._total = None self._account_types = None self.discriminator = None if total is not None: self.total = total if account_types is not None: self.account_types = account_types @property def total(self): """Gets the total of this PnlAccountClass. # noqa: E501 Total revenue/expense value # noqa: E501 :return: The total of this PnlAccountClass. # noqa: E501 :rtype: float """ return self._total @total.setter def total(self, total): """Sets the total of this PnlAccountClass. Total revenue/expense value # noqa: E501 :param total: The total of this PnlAccountClass. # noqa: E501 :type: float """ self._total = total @property def account_types(self): """Gets the account_types of this PnlAccountClass. # noqa: E501 Contains trading income and other income for revenue section / operating expenses and direct cost for expense section if the data is available for each section. Refer to the account type element below # noqa: E501 :return: The account_types of this PnlAccountClass. # noqa: E501 :rtype: list[PnlAccountType] """ return self._account_types @account_types.setter def account_types(self, account_types): """Sets the account_types of this PnlAccountClass. Contains trading income and other income for revenue section / operating expenses and direct cost for expense section if the data is available for each section. Refer to the account type element below # noqa: E501 :param account_types: The account_types of this PnlAccountClass. # noqa: E501 :type: list[PnlAccountType] """ self._account_types = account_types
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 1395, 3529, 15007, 7824, 628, 220, 220, 220, 383, 15007, 7824, 318, 257, 4947, 286, 886, 13033, 543, 4297, 460, 779, 287, 262, 1781, 286, 257, 8063, 3586, 11, 54...
2.701627
1,106
from flask import Flask, render_template, redirect from flask_pymongo import PyMongo import scrape_mars # Create an instance of Flask app = Flask(__name__) # Use flask_pymongo to set up mongo connection mongo = PyMongo(app, uri="mongodb://localhost:27017/mars_db") # Route to render index.html template using data from Mongo @app.route("/") @app.route("/scrape") if __name__ == "__main__": app.run(debug=True)
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 18941, 198, 6738, 42903, 62, 79, 4948, 25162, 1330, 9485, 44, 25162, 198, 11748, 42778, 62, 76, 945, 198, 198, 2, 13610, 281, 4554, 286, 46947, 198, 1324, 796, 46947, 7, 834, 3672, ...
2.864865
148
{ 'targets': [ { 'target_name': 'node-minizip', 'sources': [ 'src/zip.cc', 'src/zip.h', 'src/zip_api.cc', 'src/zip_async_worker.cc', 'src/zip_async_worker.h', 'src/zip_internal.cc', 'src/zip_internal.h', 'src/zip_reader.cc', 'src/zip_reader.h', 'src/zip_utils.cc', 'src/zip_utils.h', ], 'dependencies': [ 'deps/zlib/zlib.gyp:zlib' ], 'include_dirs': [ 'deps/', '<!(node -e "require(\'nan\')")' ], 'conditions': [ ['OS=="win"', { 'defines': [ 'OS_WIN', # _HAS_EXCEPTIONS must match ExceptionHandling in msvs_settings. '_HAS_EXCEPTIONS=0', ], }], ['OS=="mac" or OS=="linux"', { 'defines': [ 'OS_POSIX', ], }], ['OS=="linux"', { 'cflags':[ # Don't warn about the "struct foo f = {0};" initialization pattern. '-Wno-missing-field-initializers', ], }], ], }, ] }
[ 90, 198, 220, 705, 83, 853, 1039, 10354, 685, 198, 220, 220, 220, 1391, 198, 220, 220, 220, 220, 220, 705, 16793, 62, 3672, 10354, 705, 17440, 12, 1084, 528, 541, 3256, 198, 220, 220, 220, 220, 220, 705, 82, 2203, 10354, 685, 198,...
1.674772
658
import pydash import json import maya import logging from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import get_object_or_404 from django.apps import apps from rest_framework.viewsets import GenericViewSet from rest_framework.views import APIView from rest_framework import mixins from rest_framework.response import Response from rest_framework import status from rest_framework.permissions import IsAuthenticated from talentmap_api.common.mixins import FieldLimitableSerializerMixin from talentmap_api.user_profile.models import UserProfile from talentmap_api.messaging.models import Notification from talentmap_api.bidding.models import BidHandshakeCycle from talentmap_api.messaging.filters import NotificationFilter from talentmap_api.messaging.serializers import NotificationSerializer logger = logging.getLogger(__name__) class NotificationView(FieldLimitableSerializerMixin, GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): ''' partial_update: Edits a saved notification retrieve: Retrieves a specific notification list: Lists all notifications destroy: Deletes a specified notification ''' serializer_class = NotificationSerializer filter_class = NotificationFilter permission_classes = (IsAuthenticated,)
[ 11748, 279, 5173, 1077, 198, 11748, 33918, 198, 11748, 743, 64, 198, 11748, 18931, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 651, 62, 15...
2.976048
501
from app import db from werkzeug.security import generate_password_hash, check_password_hash from datetime import datetime from flask_login import UserMixin, AnonymousUserMixin users_privileges = db.Table('users_privileges', db.Model.metadata, db.Column('id_privilege', db.Integer, db.ForeignKey('privilege_groups.id')), db.Column('id_user', db.Integer, db.ForeignKey('users.id')) ) article_collaborators = db.Table('article_collaborators', db.Model.metadata, db.Column('id_article', db.Integer, db.ForeignKey('articles.id')), db.Column('id_collaborator', db.Integer, db.ForeignKey('users.id')) ) article_tags = db.Table('article_tags', db.Model.metadata, db.Column('id_article', db.Integer, db.ForeignKey('articles.id')), db.Column('id_tag', db.Integer, db.ForeignKey('tags.id')) ) from app import login @login.user_loader login.anonymous_user = AnonymousUser
[ 6738, 598, 1330, 20613, 198, 6738, 266, 9587, 2736, 1018, 13, 12961, 1330, 7716, 62, 28712, 62, 17831, 11, 2198, 62, 28712, 62, 17831, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 42903, 62, 38235, 1330, 11787, 35608, 259, 11, ...
2.915858
309
''' ========================================================================== connect_bits2bitstruct.py ========================================================================== A connect function that connects a bits signal and a bitsrtuct signal that has the same width. Author : Yanghui Ou Date : Feb 24, 2020 ''' from pymtl3 import Bits, connect, get_nbits from pymtl3.datatypes.bitstructs import _FIELDS, is_bitstruct_class #------------------------------------------------------------------------- # _connect_bits2bitstruct_h #------------------------------------------------------------------------- # Helper function for connect_bits2bitstruct. #------------------------------------------------------------------------- # connect_bits2bitstruct #-------------------------------------------------------------------------
[ 7061, 6, 198, 23926, 2559, 855, 198, 8443, 62, 9895, 17, 2545, 7249, 13, 9078, 198, 23926, 2559, 855, 198, 32, 2018, 2163, 326, 20417, 257, 10340, 6737, 290, 257, 10340, 17034, 4782, 6737, 326, 198, 10134, 262, 976, 9647, 13, 198, 1...
5.493421
152
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys sys.path.insert(1, '../') import tools BOOT_CONFIG_FILE = "/boot/config.txt" if __name__ == "__main__": x= main() print( x )
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 28463, 7, 16, 11, 705, 40720, 11537, 198, 11748, 4899, 198, ...
2.208791
91
"""Graph export/import utilities.""" from typing import List, Union import networkx as nx from rpasdt.algorithm.taxonomies import GraphDataFormatEnum GRAPH_EXPORTER = { GraphDataFormatEnum.MULTILINE_ADJLIST: lambda graph: list( nx.generate_multiline_adjlist(graph) ) } GRAPH_IMPORTER = { GraphDataFormatEnum.MULTILINE_ADJLIST: lambda data: nx.parse_multiline_adjlist( iter(_fetch_lines(data)) ) }
[ 37811, 37065, 10784, 14, 11748, 20081, 526, 15931, 198, 6738, 19720, 1330, 7343, 11, 4479, 198, 198, 11748, 3127, 87, 355, 299, 87, 198, 198, 6738, 374, 44429, 28664, 13, 282, 42289, 13, 19290, 6326, 444, 1330, 29681, 6601, 26227, 4834,...
2.471591
176
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt data = pd.read_csv("kc_house_data.csv") data.drop('id',axis=1,inplace=True) data.drop('date',axis=1,inplace=True) plt.figure(figsize=(15,15)) sns.heatmap(data.corr(),annot=True) plt.show()
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 7890, 796, 279, 67, 13, 961, 62, 40664, 7203, 74, 66, 62, 4803, 62, 7890, 13, 4066...
2.318966
116
import copy,math import numpy as np import pandas as pd # ---------------------------------------------------------------------------- # pre-defined models # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # pre-defined models # ---------------------------------------------------------------------------- # class two_state_constant_probability_model(bellman_harris_model_base): # def __init__(self,f,f0,beta): # self.beta = beta # type_names = ['ng','broken','gfp'] # # p = lambda gt:1-np.exp(-beta*gt) # Q = lambda gt,t: np.array([[np.exp(-beta*gt),1-np.exp(-beta*gt)],[0,1]]) # bellman_harris_model_base.__init__(self,f,f0,Q,type_names)
[ 11748, 4866, 11, 11018, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 628, 628, 198, 2, 16529, 10541, 198, 2, 662, 12, 23211, 4981, 198, 2, 16529, 10541, 628, 198, 2, 16529, 10541, 198, 2, 662, 12, 23211,...
3.265306
245
import discord from discord.ext import commands import pyowm class WeatherCog: """ControlCog""" global debuglv debuglv = 0 @commands.command() @commands.guild_only() @commands.command() @commands.guild_only()
[ 11748, 36446, 201, 198, 6738, 36446, 13, 2302, 1330, 9729, 201, 198, 11748, 12972, 322, 76, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 4871, 15615, 34, 519, 25, 201, 198, 220, 220, 220, 37227, 15988, 34, 519, 37811, 201, 198,...
2.15873
126
import tensorflow as tf import numpy as np import cv2 import re import os import random from Data_utils import preprocessing from functools import partial def readPFM(file): """ Load a pfm file as a numpy array Args: file: path to the file to be loaded Returns: content of the file as a numpy array """ file = open(file, 'rb') color = None width = None height = None scale = None endian = None header = file.readline().rstrip() if header == b'PF': color = True elif header == b'Pf': color = False else: raise Exception('Not a PFM file.') dims = file.readline() try: width, height = list(map(int, dims.split())) except: raise Exception('Malformed PFM header.') scale = float(file.readline().rstrip()) if scale < 0: # little-endian endian = '<' scale = -scale else: endian = '>' # big-endian data = np.fromfile(file, endian + 'f') shape = (height, width, 3) if color else (height, width, 1) data = np.reshape(data, shape) data = np.flipud(data) return data, scale def read_list_file(path_file): """ Read dataset description file encoded as left;right;disp;conf Args: path_file: path to the file encoding the database Returns: [left,right,gt,conf] 4 list containing the images to be loaded """ with open(path_file,'r') as f_in: lines = f_in.readlines() lines = [x for x in lines if not x.strip()[0] == '#'] left_file_list = [] right_file_list = [] gt_file_list = [] conf_file_list = [] for l in lines: to_load = re.split(',|;',l.strip()) left_file_list.append(to_load[0]) right_file_list.append(to_load[1]) if len(to_load)>2: gt_file_list.append(to_load[2]) if len(to_load)>3: conf_file_list.append(to_load[3]) return left_file_list,right_file_list,gt_file_list,conf_file_list def read_image_from_disc(image_path,shape=None,dtype=tf.uint8): """ Create a queue to hoold the paths of files to be loaded, then create meta op to read and decode image Args: image_path: metaop with path of the image to be loaded shape: optional shape for the image Returns: meta_op with image_data """ image_raw = tf.read_file(image_path) if dtype==tf.uint8: image = tf.image.decode_image(image_raw) else: image = tf.image.decode_png(image_raw,dtype=dtype) if shape is None: image.set_shape([None,None,3]) else: image.set_shape(shape) return tf.cast(image, dtype=tf.float32) class dataset(): """ Class that reads a dataset for deep stereo """ ################# PUBLIC METHOD ####################### ########################################################################################à class task_library(): """ Support class to handle definition and generation of adaptation tasks """ def _load_sequence(self, filename): """ Add a sequence to self._task_dictionary, saving the paths to the different files from filename """ assert(os.path.exists(filename)) left_files, right_files, gt_files,_ = read_list_file(filename) self._task_dictionary[filename] = { 'left': left_files, 'right': right_files, 'gt': gt_files, 'num_frames': len(left_files) } def get_task(self): """ Generate a task encoded as a 3 X num_frames matrix of path to load to get the respective frames First row contains paths to left frames, Second row contains paths to right frames, Third row contains paths to gt frams """ #fetch a random task picked_task = random.choice(list(self._task_dictionary.keys())) #fetch all the samples from the current sequence left_frames = self._task_dictionary[picked_task]['left'] right_frames = self._task_dictionary[picked_task]['right'] gt_frames = self._task_dictionary[picked_task]['gt'] num_frames = self._task_dictionary[picked_task]['num_frames'] max_start_frame = num_frames-self._frame_per_task-1 start_frame_index = random.randint(0,max_start_frame) task_left = left_frames[start_frame_index:start_frame_index+self._frame_per_task] task_right = right_frames[start_frame_index:start_frame_index+self._frame_per_task] gt_frames = gt_frames[start_frame_index:start_frame_index+self._frame_per_task] result = np.array([task_left,task_right,gt_frames]) return result def __call__(self): """ Generator that returns a number of tasks equal to the number of different seuqences in self._taskLibrary """ for i in range(len(self._task_dictionary)): yield self.get_task() def __len__(self): """ Number of tasks/sequences defined in the library """ return len(self._task_dictionary) class metaDataset(): """ Class that reads a dataset for deep stereo """ def _load_task(self, files): """ Load all the image and return them as three lists, [left_files], [right_files], [gt_files] """ #from 3xk to kx3 left_files = files[0] right_files = files[1] gt_files = files[2] #read images left_task_samples = tf.map_fn(read_image_from_disc,left_files,dtype = tf.float32, parallel_iterations=self._sequence_length) left_task_samples.set_shape([self._sequence_length, None, None, 3]) right_task_samples = tf.map_fn(read_image_from_disc,right_files,dtype = tf.float32, parallel_iterations=self._sequence_length) right_task_samples.set_shape([self._sequence_length, None, None, 3]) gt_task_samples = tf.map_fn(self._decode_gt, gt_files, dtype=tf.float32, parallel_iterations=self._sequence_length) gt_task_samples.set_shape([self._sequence_length, None, None, 1]) #alligned image resize if self._resize_shape[0] is not None: scale_factor = tf.cast(tf.shape(left_task_samples)[1]//self._resize_shape[1], tf.float32) left_task_samples = preprocessing.rescale_image(left_task_samples,self._resize_shape) right_task_samples = preprocessing.rescale_image(right_task_samples,self._resize_shape) gt_task_samples = tf.image.resize_nearest_neighbor(gt_task_samples,self._resize_shape)/scale_factor #alligned random crop if self._crop_shape[0] is not None: left_task_samples,right_task_samples,gt_task_samples = preprocessing.random_crop(self._crop_shape, [left_task_samples,right_task_samples,gt_task_samples]) #augmentation if self._augment: left_task_samples,right_task_samples=preprocessing.augment(left_task_samples,right_task_samples) return [left_task_samples, right_task_samples, gt_task_samples] ################# PUBLIC METHOD ####################### ########################################################àà
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 302, 198, 11748, 28686, 198, 11748, 4738, 198, 198, 6738, 6060, 62, 26791, 1330, 662, 36948, 198, 6738, 1257, 310, 10141, 133...
2.390139
3,022
from rest_framework import serializers from words.models import Word class WordSerializer(serializers.ModelSerializer): """单词使用这个Serializer""" class WordCloudSerializer(serializers.ModelSerializer): """词云使用这个Serializer""" class WordTrainSerializer(serializers.ModelSerializer): """专项训练->单词测验->组卷用这个Serializer"""
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 198, 6738, 2456, 13, 27530, 1330, 9678, 628, 198, 4871, 9678, 32634, 7509, 7, 46911, 11341, 13, 17633, 32634, 7509, 2599, 198, 220, 220, 220, 37227, 39355, 243, 46237, 235, 45635, 18796, 1...
2.381295
139
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from mephisto.abstractions.blueprint import TaskBuilder class EmptyStaticTaskBuilder(TaskBuilder): """ Abstract class for a task builder for static tasks """ def build_in_dir(self, build_dir: str): """Build the frontend if it doesn't exist, then copy into the server directory""" raise AssertionError( "Classes that extend the abstract StaticBlueprint must define a custom " "TaskBuilder class that pulls the correct frontend together. Examples " "can be seen in the static_react_task and static_html_task folders. " "Note that extra static content will be provided in `args.blueprint.extra_source_dir` " )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287,...
3.075342
292
import numpy as np from torch.autograd import Variable import torch import torch.nn as nn from torch.nn import MSELoss import torch.optim as optim from torch.utils.data import DataLoader import math from sklearn.metrics import mean_squared_error, mean_absolute_error import argparse import logging import time import torch.nn.functional as F import sys
[ 11748, 299, 32152, 355, 45941, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 13, 20471, 1330, 6579, 3698, 793, 198, 11748, 28034, 13, 40085, 355, 643...
3.639175
97
from cyaron import * for i in range(0, 10): io = IO(file_prefix="a", data_id=i + 1) n = randint(2, 1001) m = randint(1, 2001) io.input_writeln(n, m) graph = Graph.graph(n, m) io.input_writeln(graph.to_str(output=Edge.unweighted_edge, shuffle=True)) io.output_gen("../../bin/a")
[ 6738, 3075, 8045, 1330, 1635, 198, 198, 1640, 1312, 287, 2837, 7, 15, 11, 838, 2599, 198, 220, 220, 220, 33245, 796, 24418, 7, 7753, 62, 40290, 2625, 64, 1600, 1366, 62, 312, 28, 72, 1343, 352, 8, 628, 220, 220, 220, 299, 796, 4...
2.197183
142
import yaml import os.path import shutil if __name__ == '__main__': config = yaml.load(open('config.yml', 'r')) directories = config['directories'] default_analyzed_dirs_path = os.path.join(directories['mri_analysis_scripts'], 'default_dirs.yml') default_analyzed_dirs = yaml.load(open(default_analyzed_dirs_path, 'r')) dir_map = { 'localizerDir': 'localizer', 'mprageDir': 'mprage', 't219Dir': 't2_19', 't215Dir': 't2_15', 'run1Dir': 'run1', 'run2Dir': 'run2', 'run3Dir': 'run3', 'run4Dir': 'run4', 'run5Dir': 'run5', 'run6Dir': 'run6', 'fieldmap1Dir': 'fieldmap1', 'fieldmap2Dir': 'fieldmap2', 'segmentedpartialDir': 'ep_seg_partial', 'segmentedwholeDir': 'ep_seg_wholebrain' } for d in os.listdir(directories['analyzed_mri']): dirname = os.path.relpath(d) if dirname.startswith('s'): print("executing " + dirname) analyzed_dirs = default_analyzed_dirs.copy() # If there is a yaml file with overwrite directories, # we will merge anything that exists there with the existing defaults # The overwrite file will only contain entries that have changed, # so merging is necessary - otherwise we will clobber any defaults # that haven't changed. overwrite_analyzed_dirs_path = os.path.join(directories['raw_behavioral'], dirname, dirname + '.yml') if os.path.exists(overwrite_analyzed_dirs_path): print("found overwrite file " + overwrite_analyzed_dirs_path) overwrite_analyzed_dirs = yaml.load(open(overwrite_analyzed_dirs_path, 'r')) for k in overwrite_analyzed_dirs: analyzed_dirs[k] = overwrite_analyzed_dirs[k] # Move all of the files if they exist, whether they were defaults or overrides for k in dir_map: move_if_exists( os.path.join(directories['analyzed_mri'],dirname,analyzed_dirs[k]), os.path.join(directories['analyzed_mri'],dirname,dir_map[k]))
[ 11748, 331, 43695, 198, 11748, 28686, 13, 6978, 198, 11748, 4423, 346, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 4566, 796, 331, 43695, 13, 2220, 7, 9654, 10786, 11250, 13, 88, 4029, 3256,...
2.133333
1,020
import os import torch def save_model_w_condition(model, model_dir, model_name, accu, target_accu, rank=0, log=print): ''' model: this is not the multigpu model ''' if rank == 0: if accu > target_accu: log('\tabove {0:.2f}%'.format(target_accu * 100)) # torch.save(obj=model.state_dict(), f=os.path.join(model_dir, (model_name + '{0:.4f}.pth').format(accu))) torch.save(obj=model, f=os.path.join(model_dir, (model_name + '{0:.4f}.pth').format(accu)))
[ 11748, 28686, 198, 11748, 28034, 198, 198, 4299, 3613, 62, 19849, 62, 86, 62, 31448, 7, 19849, 11, 2746, 62, 15908, 11, 2746, 62, 3672, 11, 697, 84, 11, 2496, 62, 4134, 84, 11, 4279, 28, 15, 11, 2604, 28, 4798, 2599, 198, 220, 2...
2.124481
241
characters116 =['☺','☻','♥','♦','♣','♠','•','◘','○','◙','♂','♀','♪','♫','☼','►','◄','↕','‼','¶','§','▬','↨','↑','↓','→','←','∟','↔','▲','▼','space','!','"','#','$','%','&',"'",'(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] alpha =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] chars91u127 = ['[','\\',']','^','_','`','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','{','|','}','~','⌂'] chars128u255 = ['Ç','ü','é','â','ä','à','å','ç','ê','ê','è','ï','î','ì','Ä','Å','É','æ','Æ','ô','ö','ò','û','ù','ÿ','Ö','Ü','¢','£','¥','₧','ƒ','á','í','ó','ú','ñ','Ñ','ª','º','¿','⌐','¬','½','¼','¡','«','»','░','▒','▓','│','┤','╡','╢','╖','╕','╣','║','╗','╝','╜','╛','┐','└','┴','┬','├','─','┼','╞','╟','╚','╔','╩','╦','╠','═','╬','╧','╨','╤','╥','╙','╘','╒','╓','╫','╪','┘','┌','█','▄','▌','▐','▀','α','ß','Γ','π','Σ','σ','µ','τ','Φ','Θ','Ω','δ','∞','φ','ε','∩','≡','±','≥','≤','⌠','⌡','÷','≈','°','∙','·','√','ⁿ','²','■',' '] ##from AltCodesAlpha import alphacodes chars = chars128u255 altCode = LOGICchars128u255 with open("Output.txt" , 'w', encoding='utf8') as file: allChars()
[ 10641, 19858, 18298, 796, 17816, 24583, 118, 41707, 24583, 119, 41707, 39908, 41707, 41298, 41707, 17992, 96, 41707, 17992, 254, 41707, 3581, 41707, 15926, 246, 41707, 15926, 233, 41707, 15926, 247, 41707, 17992, 224, 41707, 17992, 222, 41707...
1.76822
837
from random import randint from .circle_class import CircleClass from .rectangle_class import RectangleClass from .triangle_class import TriangleClass
[ 6738, 4738, 1330, 43720, 600, 198, 198, 6738, 764, 45597, 62, 4871, 1330, 16291, 9487, 198, 6738, 764, 2554, 9248, 62, 4871, 1330, 48599, 9248, 9487, 198, 6738, 764, 28461, 9248, 62, 4871, 1330, 33233, 9487, 628 ]
4.135135
37
from typing import Optional, Dict, List, Any import pendulum from src.data_models import CalculatedFieldDescription from src.data_models import Configuration def add_calculated_fields(*, current_item: Dict[str, Any], initial_status, current_status, position_list, lap_list, total, charging_process_list, forecast, configuration: Configuration, current_item_index: Optional[int], now_dt: pendulum.DateTime): """ Add hardcoded calculated fields into current_item Note the prototype is the same for all calculated functions even if all inputs are not used :param current_item: :param initial_status: :param current_status: :param position_list: :param lap_list: :param total: :param charging_process_list: :param forecast: :param configuration: :param current_item_index: :param now_dt: time to calculate data for. :return: """ lap_start_time: pendulum.DateTime = current_item['lap_data'][0]['date'] \ if 'lap_data' in current_item and current_item['lap_data'] else None lap_end_time: pendulum.DateTime = current_item['lap_data'][-1]['date'] \ if 'lap_data' in current_item and current_item['lap_data'] else None pit_start_time: pendulum.DateTime = current_item['pit_data'][0]['date'] \ if 'pit_data' in current_item and current_item['pit_data'] else None pit_end_time: pendulum.DateTime = current_item['pit_data'][-1]['date'] \ if 'pit_data' in current_item and current_item['pit_data'] else None distance: float = current_item['lap_data'][-1]['odometer'] - current_item['lap_data'][0]['odometer'] \ if 'lap_data' in current_item and current_item['lap_data'] else None lap_duration: pendulum.Period = lap_end_time - lap_start_time if lap_end_time and lap_start_time else None pit_duration: pendulum.Period = pit_end_time - pit_start_time if pit_end_time and pit_start_time else None full_duration: pendulum.Period = None if lap_duration and pit_duration: full_duration = lap_duration + pit_duration elif lap_duration: full_duration = lap_duration else: full_duration = pit_duration lap_avg_speed: float = distance / lap_duration.total_seconds() * 3600 if distance is not None and lap_duration else None full_avg_speed: float = distance / full_duration.total_seconds() * 3600 if distance is not None and full_duration else None current_item['lap_start_time'] = lap_start_time current_item['lap_end_time'] = lap_end_time current_item['pit_start_time'] = pit_start_time current_item['pit_end_time'] = pit_end_time current_item['distance'] = distance current_item['lap_duration'] = lap_duration current_item['pit_duration'] = pit_duration current_item['full_duration'] = full_duration current_item['lap_avg_speed'] = lap_avg_speed current_item['full_avg_speed'] = full_avg_speed # try the magic d = pendulum.Duration(hours=configuration.hours) d += current_item['pit_duration'] current_item['total_using_lap'] = full_avg_speed * d.total_seconds() / 3600
[ 6738, 19720, 1330, 32233, 11, 360, 713, 11, 7343, 11, 4377, 198, 11748, 44017, 14452, 198, 198, 6738, 12351, 13, 7890, 62, 27530, 1330, 27131, 515, 15878, 11828, 198, 6738, 12351, 13, 7890, 62, 27530, 1330, 28373, 628, 198, 4299, 751, ...
2.466521
1,374
#!/usr/bin/env python import datetime import fcntl import logging import logging.config import os import re import tempfile from functools import update_wrapper, partial import click import yaml from ldsbde.core.bde import BDEProcessor from ldsbde.core.job import Job L = logging.getLogger("ldsbde") def with_config(func): """ Populate ctx.config with the parsed contents of the config file """ f = click.option( '--config-file', type=click.Path(), help="Config file location", is_eager=True, # do first expose_value=False, # don't pass parameter through to real command callback=callback ) return f(func) def singleton(wait): """ Prevent multiple lds-bde-loader processes fighting each other. wait should be a boolean whether to block/wait for the other process or not. """ return wrap def with_bde(func): """ Populate a ldsbde.core.BDEProcessor instance as the bde argument. Requires @with_config above. """ @click.pass_context return update_wrapper(wrapper, func) def save_job(ctx, job): """ Serialize the job out to a YAML file """ job_path = ctx.config["job_path"] job_file = os.path.join(job_path, '%s.yml' % job.id) with open(job_file, 'w') as fd: yaml.safe_dump(job.serialize(), fd, default_flow_style=False) def load_job(ctx, job_id): """ Load a Job from on-disk as a yaml file. """ job_path = ctx.config["job_path"] job_file = os.path.join(job_path, '%s.yml' % job_id) if not os.path.exists(job_file): raise Job.NotFound("Job %s (%s)" % (job_id, job_file)) with open(job_file, 'r') as fd: data = yaml.safe_load(fd) if not data: raise Job.NotFound("Job %s (%s) -- empty" % (job_id, job_file)) return Job.parse(data, job_id=job_id, save_func=partial(save_job, ctx)) def find_jobs(ctx, max_age=None): """ Find multiple Jobs from on-disk yaml files (N.yml). Returns a generator for Job objects in newest-first order. max_age: restrict the maximum age in days of jobs to return (based on Job.created_at). """ # find the existing Job IDs and YAML files job_ids = [] for fn in os.listdir(ctx.config["job_path"]): m = re.match(r'([0-9]+)\.yml$', fn) if m: job_ids.append(int(m.group(1))) job_ids.sort(reverse=True) oldest = None if max_age: oldest = datetime.date.today() - datetime.timedelta(days=max_age) for job_id in job_ids: job = load_job(ctx, job_id) if oldest and (job.created_at.date() < oldest): # stop, we'll only see older jobs from here break yield job def with_job(func): """ Populate a ldsbde.job.Job instance as the job argument Requires @with_config above. Requires @with_bde above if you want to use with create=True """ @click.argument('job_id', type=int, required=True) @click.pass_context return update_wrapper(wrapper, func)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 4818, 8079, 198, 11748, 277, 66, 429, 75, 198, 11748, 18931, 198, 11748, 18931, 13, 11250, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 20218, 7753, 198, 6738, 1257, 310, 10141...
2.450363
1,239
# Time: O(lgn) # Space: O(n) # NOT IMPLEMENTED
[ 2, 3862, 25, 220, 440, 7, 75, 4593, 8, 198, 2, 4687, 25, 440, 7, 77, 8, 198, 198, 2, 5626, 30023, 2538, 10979, 1961, 198 ]
1.884615
26
# Generated by Django 2.2.13 on 2021-05-05 20:58 from django.conf import settings from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 1485, 319, 33448, 12, 2713, 12, 2713, 1160, 25, 3365, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, ...
3.038462
52
import argparse import subprocess from examc.generator import generate_exam import sys if __name__ == "__main__": examc()
[ 11748, 1822, 29572, 198, 11748, 850, 14681, 198, 6738, 2814, 66, 13, 8612, 1352, 1330, 7716, 62, 1069, 321, 198, 11748, 25064, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 2814, 66, 3419,...
3
43
#!/usr/bin/python -u # force matplotlib agg backend import matplotlib matplotlib.use("agg") import matplotlib.pyplot as plt from scipy.ndimage.filters import gaussian_filter1d from scipy.interpolate import UnivariateSpline import os import numpy as np from argparse import ArgumentParser # %%%%%%%%%%%%%%%%%%%%%%%%%%% # PLOTTING-RELATED TWEAKABLES # %%%%%%%%%%%%%%%%%%%%%%%%%%% color_map = None print_title = None gaussian_enable = None gaussian_sigma = None interpolation_enable = None interpolation_segments = None interpolation_order = None # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # PLOTTING VALUES OF MULTIPLE MODELS # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 532, 84, 198, 198, 2, 2700, 2603, 29487, 8019, 4194, 30203, 198, 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 7203, 9460, 4943, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, ...
2.966102
236
import csv from itertools import chain import click from joblib import Parallel, delayed from tqdm import tqdm from docs.impc_header import header from utils import ( mousemine_api, europe_pmc_api, mongo_access, config, nlp, allele_importer, ) from utils.solr_access import resolve_allele @click.command() @click.option("--use-mousemine", "-m", is_flag=True, help="Use mousemine.") @click.option("--use-alleles", "-a", is_flag=True, help="Use alleles file.") @click.option( "--use-consortium-citations", "-c", is_flag=True, help="Use consortium citations." ) @click.option("--add-order-id", "-o", is_flag=True, help="Import order ids.") @click.option("--load-reviewed-pmids", "-p", is_flag=True, help="Load pmids from file.") @click.option("--import-alleles", "-i", is_flag=True, help="Import load alleles file.") def harvest( use_mousemine, use_alleles, use_consortium_citations, add_order_id, load_reviewed_pmids, import_alleles, ): """Command line application to harvest publications that cite or contain IMPC data resources""" existing_pmids = mongo_access.get_existing_pmids() click.secho(header, fg="yellow", bold=True) update_exisiting_papers = True update_papers = [] update_pmids = [] harvested_references = {} keyword_harvest_count = 0 citation_harvest_count = 0 mousemine_harvest_count = 0 if import_alleles: allele_importer.load_all() if load_reviewed_pmids: with open(config.get("DEFAULT", "LOAD_PMIDS_FILE")) as f: csv_orders = [ {k: v for k, v in row.items()} for row in csv.DictReader(f, skipinitialspace=True) ] for line in csv_orders: pmid = line["PubMed ID"] if update_exisiting_papers and pmid in existing_pmids: if pmid not in update_pmids: paper = mongo_access.get_by_pmid(pmid) paper["comment"] = line["comment"] update_papers.append(paper) update_pmids.append(pmid) continue elif pmid in harvested_references: continue bibliographic_data = europe_pmc_api.get_paper_by_pmid(pmid) reviewed_reference = dict( chain( { "alleles": [], "status": "reviewed", "datasource": "manual", "consortiumPaper": False, "citations": [], "cites": [], "alleleCandidates": [], "citedBy": [], "comment": line["comment"], "tags": [], }.items(), bibliographic_data.items(), ) ) harvested_references[pmid] = reviewed_reference if use_mousemine: click.secho("Execute Mousemine query", fg="blue") alleles = mousemine_api.get_mousemine_references_from_webservice() click.secho("Group results by PMID", fg="blue") grouped_alleles = mousemine_api.get_pmid2alleles_map(alleles) for pmid, alleles in grouped_alleles.items(): if update_exisiting_papers and pmid in existing_pmids: if pmid not in update_pmids: paper = mongo_access.get_by_pmid(pmid) update_papers.append(paper) update_pmids.append(pmid) continue elif pmid in harvested_references: continue bibliographic_data = europe_pmc_api.get_paper_by_pmid(pmid) mousemine_reference = dict( chain( { "alleles": alleles, "status": "reviewed", "datasource": "mousemine", "consortiumPaper": False, "citations": [], "cites": [], "alleleCandidates": [], "citedBy": [], "comment": "", "tags": [], }.items(), bibliographic_data.items(), ) ) harvested_references[pmid] = mousemine_reference mousemine_harvest_count += 1 if use_consortium_citations: consortium_papers = mongo_access.get_impc_papers() for paper in consortium_papers: for citing_paper in europe_pmc_api.get_citing_papers(paper["pmid"]): if update_exisiting_papers and citing_paper["pmid"] in existing_pmids: if citing_paper["pmid"] not in update_pmids: citing_paper = mongo_access.get_by_pmid(citing_paper["pmid"]) update_papers.append(citing_paper) update_pmids.append(citing_paper["pmid"]) continue if citing_paper["pmid"] not in harvested_references: harvested_references[citing_paper["pmid"]] = dict( chain( { "alleles": [], "status": "pending", "datasource": "europepmc", "consortiumPaper": False, "citations": [], "citedBy": [], "alleleCandidates": [], "comment": "", "tags": [], }.items(), citing_paper.items(), ) ) else: harvested_references[citing_paper["pmid"]]["cites"].append( paper["pmid"] ) citation_harvest_count += 1 search_results = [] alleles = None for keyword in config.get("DEFAULT", "TARGET_KEYWORDS").split(","): search_results.extend(europe_pmc_api.get_papers_by_keyword(keyword)) if use_alleles: with open(config.get("DEFAULT", "TARGET_ALLELE_FILE")) as f: alleles = f.read().splitlines() click.secho( "Found {} alleles to use".format(len(alleles)), fg="green", bold=True, ) # for keyword in alleles: # try: # search_results.extend(europe_pmc_api.get_papers_by_keyword(keyword)) # except Exception as e: # print('[ERROR] Encountered exception: {}'.format(e.__class__)) for index, paper in enumerate(search_results): if update_exisiting_papers and paper["pmid"] in existing_pmids: if paper["pmid"] not in update_pmids: paper = mongo_access.get_by_pmid(paper["pmid"]) update_papers.append(paper) update_pmids.append(paper["pmid"]) continue elif paper["pmid"] in harvested_references: continue else: harvested_references[paper["pmid"]] = dict( chain( { "alleles": [], "datasource": "europepmc", "status": "pending", "citations": [], "cites": [], "citedBy": [], "alleleCandidates": [], "comment": "", "tags": [], }.items(), paper.items(), ) ) keyword_harvest_count += 1 click.secho( "Found {} new references in Mousemine".format(mousemine_harvest_count), fg="green", bold=True, ) click.secho( "Found {} new references in EuroPMC".format(keyword_harvest_count), fg="green", bold=True, ) click.secho( "Found {} new references in EuroPMC citing Consortium papers".format( citation_harvest_count ), fg="green", bold=True, ) all_raw_references = harvested_references.values() for reference in all_raw_references: existing_reference = mongo_access.get_by_pmid(reference["pmid"]) if existing_reference: if ( existing_reference["datasource"] in ["manual", "europepmc"] and reference["datasource"] == "mousemine" ): try: mongo_access.update_by_pmid( existing_reference["pmid"], {"alleles": reference["alleles"], "datasource": "mousemine"}, ) except Exception as e: print('[ERROR] Encountered exception: {}'.format(e.__class__)) if add_order_id: click.secho("Updating allele info using provided order ids file", fg="blue") with open(config.get("DEFAULT", "ORDER_ID_FILE"), encoding="utf-8-sig") as f: csv_orders = [ {k: v for k, v in row.items()} for row in csv.DictReader(f, skipinitialspace=True) ] pmid_vs_alleles = dict() for c in csv_orders: allele = ( resolve_allele(c["allele"]) if "allele" in c else resolve_allele("") ) allele["_class"] = "org.impc.publications.models.AlleleRef" allele["orderId"] = c["order ID"] if c["PubMed ID"] not in pmid_vs_alleles: pmid_vs_alleles[c["PubMed ID"]] = [] pmid_vs_alleles[c["PubMed ID"]].append(allele) for ref in all_raw_references: ref["alleles"] = ( pmid_vs_alleles[ref["pmid"]] if ref["pmid"] in pmid_vs_alleles else [] ) for ref in update_papers: ref["alleles"] = ( pmid_vs_alleles[ref["pmid"]] if ref["pmid"] in pmid_vs_alleles and len(ref["alleles"]) == 0 else ref["alleles"] ) all_papers = mongo_access.get_all() for ref in [paper for paper in all_papers if paper["pmid"] not in update_pmids]: ref["alleles"] = ( pmid_vs_alleles[ref["pmid"]] if ref["pmid"] in pmid_vs_alleles and len(ref["alleles"]) == 0 else ref["alleles"] ) update_papers.append(ref) update_pmids.append(ref["pmid"]) click.secho("NLP Processing", fg="blue") all_references_processed = Parallel(n_jobs=8)( delayed(nlp.get_fragments)(reference, alleles) for reference in tqdm(all_raw_references) ) if len(all_references_processed) > 0: mongo_access.insert_all(all_references_processed) click.secho("Update NLP Processing for existing papers", fg="blue") if len(update_papers) == 0: click.secho(" Updating all", fg="blue") update_papers = mongo_access.get_all() else: for paper in mongo_access.get_all(): if paper["pmid"] not in update_pmids: update_papers.append(paper) update_pmids.append(paper["pmid"]) update_references_processed = Parallel(n_jobs=8)( delayed(nlp.get_fragments)(reference, alleles) for reference in tqdm(update_papers) ) click.secho( f"Update existing papers in Mongodb: {len(update_references_processed)}", fg="blue", ) for reference in tqdm(update_references_processed): try: mongo_access.update_by_pmid( reference["pmid"], { "fragments": reference["fragments"], "comment": reference["comment"] if "comment" in reference and reference["comment"] is not None else "", "tags": reference["tags"] if "tags" in reference and reference["tags"] is not None else [], "citations": reference["citations"] if "citations" in reference else [], "alleleCandidates": reference["alleleCandidates"], "alleles": reference["alleles"] if "alleles" in reference else [], "correspondence": reference["correspondence"] if "correspondence" in reference else [], }, ) except Exception as e: print('[ERROR] Encountered exception: {}'.format(e.__class__)) click.secho("Update existing papers in Mongodb", fg="blue") click.secho("Finished", fg="blue") if __name__ == "__main__": harvest()
[ 11748, 269, 21370, 198, 6738, 340, 861, 10141, 1330, 6333, 198, 198, 11748, 3904, 198, 6738, 1693, 8019, 1330, 42945, 11, 11038, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 6738, 34165, 13, 11011, 66, 62, 25677, 1330, 1...
1.843195
7,098
# Generated by Django 2.1 on 2018-09-15 13:51 from django.db import migrations, models import django.db.models.deletion import uuid
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 319, 2864, 12, 2931, 12, 1314, 1511, 25, 4349, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, 198, 11748...
2.913043
46
# -*- encoding: utf-8 -*- # python 2.7 import argparse from GmailServiceWrap import GmailServiceWrap import datetime import pdfkit import os from UberSlip import UberSlipType # FILL THIS GMAIL_USER_ID = None def stapleAndPrintSlips(slips, year, month) : ''' Staple matching slips toghter and print to pdf Returns: void ''' # dictionary{plate_date:UberSlip}, eg: 30(int):RBS3913 rentalSlips = {} mainSlips = {} for us in slips : if us.slipType == UberSlipType.OldMain or us.slipType == UberSlipType.NewMain: mainSlips['{}_{}'.format(us.plateNumber, us.date)] = us else : rentalSlips['{}_{}'.format(us.plateNumber, us.date)] = us dirname = '{}-{}'.format(year, month) try : os.makedirs(dirname) except OSError, ose : pass if len(mainSlips) != len(rentalSlips) : # missing matching slip print ('There are {} main slips, but {} rental slips.'.format(len(mainSlips), len(rentalSlips))) if len(mainSlips) > len(rentalSlips) : # try find missing slip for platenumberAndDate, mainSlip in mainSlips.iteritems() : try : rslip = rentalSlips[platenumberAndDate] except KeyError, ke: print ('MISSING rental slip at {datetime} with plate number {plate} fare {fare}, check with uber app.'.format(datetime=mainSlip.startDatetime, plate=mainSlip.plateNumber, fare=mainSlip.fare)) else : for platenumberAndDate, rslip in rentalSlips.iteritems() : try : mslip = mainSlips[platenumberAndDate] except KeyError, ke: print ('MISSING main slip plate {plate}, check with uber app.'.format(plate=rslip.plateNumber)) for platenumberAndDate, mainSlip in mainSlips.iteritems() : #print platenumber try : rentalSlip = rentalSlips[platenumberAndDate] except KeyError, ke: continue filename = './{dir}/{datetime}-{drivername}-{plate}-{fare}'.format(dir=dirname, datetime=mainSlip.startDatetime, drivername=mainSlip.driverName, plate=mainSlip.plateNumber, fare=mainSlip.fare) htmlfileMainpath = '{filename}-main.html'.format(filename=filename) htmlfileRentalpath = '{filename}-rental.html'.format(filename=filename) # write html to file with open(htmlfileMainpath, 'w') as h1f : try : h1f.write(mainSlip.body) except UnicodeDecodeError, e: print ('UnicodeDecodeError at main slip, {} {} '.format( mainSlip.plateNumber, e)) pass with open(htmlfileRentalpath, 'w') as h2f : try : h2f.write(rentalSlip.body.encode('utf-8')) except UnicodeDecodeError, e: print ('UnicodeDecodeError at rental slip, {} {} '.format( rentalSlip.plateNumber, e)) pass # write to pdf pdffilepath = '{filename}.pdf'.format(filename=filename) try : pdfkit.from_file([htmlfileMainpath, htmlfileRentalpath], pdffilepath) except Exception, e: pass print 'main receipt:{}, rental slip:{}, output pdf: {}'.format(mainSlip, rentalSlip, pdffilepath) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-m", "--month", type=int, default=0, help="month to search in number, Jan=1, default: current month") parser.add_argument("-y", "--year", help="year to search, default: current year", type=int, default=0) #0=current year args = parser.parse_args() month = args.month year = args.year if month is 0 : month = datetime.datetime.now().month if year is 0 : year = datetime.datetime.now().year settingfile = './settings.py' if os.path.isfile(settingfile) : execfile(settingfile) print ('loading from settings file.') print ('Search for uber slips in {}/{}'.format(year, month)) gmailServiceWrap = GmailServiceWrap(GMAIL_USER_ID, args) ''' for us in gmailServiceWrap.getUberSlips(year, month) : print '{}'.format(us) ''' #print gmailServiceWrap.uberSlipsSearch(year, month) uberSlips = gmailServiceWrap.getUberSlips(year, month) print ('there are {} slips.'.format(len(uberSlips)) ) stapleAndPrintSlips(uberSlips, year, month)
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 21015, 362, 13, 22, 198, 198, 11748, 1822, 29572, 198, 6738, 33662, 16177, 54, 2416, 1330, 33662, 16177, 54, 2416, 198, 11748, 4818, 8079, 198, 11748, 37124, 15813, 1...
2.465728
1,634
# coding: utf-8 from datetime import date, datetime from typing import List, Dict, Type from openapi_server.models.base_model_ import Model from openapi_server.models.extent import Extent from openapi_server.models.observed_property import ObservedProperty from openapi_server.models.one_ofintegerarray import OneOfintegerarray from openapi_server.models.parameter_measurement_approach import ParameterMeasurementApproach from openapi_server.models.units import Units from openapi_server import util class Parameter(Model): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(self, type: object=None, description: str=None, label: str=None, data_type: object=None, unit: Units=None, observed_property: ObservedProperty=None, category_encoding: Dict[str, OneOfintegerarray]=None, extent: Extent=None, id: str=None, measurement_type: ParameterMeasurementApproach=None): """Parameter - a model defined in OpenAPI :param type: The type of this Parameter. :param description: The description of this Parameter. :param label: The label of this Parameter. :param data_type: The data_type of this Parameter. :param unit: The unit of this Parameter. :param observed_property: The observed_property of this Parameter. :param category_encoding: The category_encoding of this Parameter. :param extent: The extent of this Parameter. :param id: The id of this Parameter. :param measurement_type: The measurement_type of this Parameter. """ self.openapi_types = { 'type': object, 'description': str, 'label': str, 'data_type': object, 'unit': Units, 'observed_property': ObservedProperty, 'category_encoding': Dict[str, OneOfintegerarray], 'extent': Extent, 'id': str, 'measurement_type': ParameterMeasurementApproach } self.attribute_map = { 'type': 'type', 'description': 'description', 'label': 'label', 'data_type': 'data-type', 'unit': 'unit', 'observed_property': 'observedProperty', 'category_encoding': 'categoryEncoding', 'extent': 'extent', 'id': 'id', 'measurement_type': 'measurementType' } self._type = type self._description = description self._label = label self._data_type = data_type self._unit = unit self._observed_property = observed_property self._category_encoding = category_encoding self._extent = extent self._id = id self._measurement_type = measurement_type @classmethod def from_dict(cls, dikt: dict) -> 'Parameter': """Returns the dict as a model :param dikt: A dict. :return: The parameter of this Parameter. """ return util.deserialize_model(dikt, cls) @property def type(self): """Gets the type of this Parameter. type :return: The type of this Parameter. :rtype: object """ return self._type @type.setter def type(self, type): """Sets the type of this Parameter. type :param type: The type of this Parameter. :type type: object """ allowed_values = [Parameter] # noqa: E501 if type not in allowed_values: raise ValueError( "Invalid value for `type` ({0}), must be one of {1}" .format(type, allowed_values) ) self._type = type @property def description(self): """Gets the description of this Parameter. :return: The description of this Parameter. :rtype: str """ return self._description @description.setter def description(self, description): """Sets the description of this Parameter. :param description: The description of this Parameter. :type description: str """ self._description = description @property def label(self): """Gets the label of this Parameter. :return: The label of this Parameter. :rtype: str """ return self._label @label.setter def label(self, label): """Sets the label of this Parameter. :param label: The label of this Parameter. :type label: str """ self._label = label @property def data_type(self): """Gets the data_type of this Parameter. Data type of returned parameter :return: The data_type of this Parameter. :rtype: object """ return self._data_type @data_type.setter def data_type(self, data_type): """Sets the data_type of this Parameter. Data type of returned parameter :param data_type: The data_type of this Parameter. :type data_type: object """ allowed_values = [integer, float, string] # noqa: E501 if data_type not in allowed_values: raise ValueError( "Invalid value for `data_type` ({0}), must be one of {1}" .format(data_type, allowed_values) ) self._data_type = data_type @property def unit(self): """Gets the unit of this Parameter. :return: The unit of this Parameter. :rtype: Units """ return self._unit @unit.setter def unit(self, unit): """Sets the unit of this Parameter. :param unit: The unit of this Parameter. :type unit: Units """ self._unit = unit @property def observed_property(self): """Gets the observed_property of this Parameter. :return: The observed_property of this Parameter. :rtype: ObservedProperty """ return self._observed_property @observed_property.setter def observed_property(self, observed_property): """Sets the observed_property of this Parameter. :param observed_property: The observed_property of this Parameter. :type observed_property: ObservedProperty """ if observed_property is None: raise ValueError("Invalid value for `observed_property`, must not be `None`") self._observed_property = observed_property @property def category_encoding(self): """Gets the category_encoding of this Parameter. :return: The category_encoding of this Parameter. :rtype: Dict[str, OneOfintegerarray] """ return self._category_encoding @category_encoding.setter def category_encoding(self, category_encoding): """Sets the category_encoding of this Parameter. :param category_encoding: The category_encoding of this Parameter. :type category_encoding: Dict[str, OneOfintegerarray] """ self._category_encoding = category_encoding @property def extent(self): """Gets the extent of this Parameter. :return: The extent of this Parameter. :rtype: Extent """ return self._extent @extent.setter def extent(self, extent): """Sets the extent of this Parameter. :param extent: The extent of this Parameter. :type extent: Extent """ self._extent = extent @property def id(self): """Gets the id of this Parameter. Unique ID of the parameter, this is the value used for querying the data :return: The id of this Parameter. :rtype: str """ return self._id @id.setter def id(self, id): """Sets the id of this Parameter. Unique ID of the parameter, this is the value used for querying the data :param id: The id of this Parameter. :type id: str """ self._id = id @property def measurement_type(self): """Gets the measurement_type of this Parameter. :return: The measurement_type of this Parameter. :rtype: ParameterMeasurementApproach """ return self._measurement_type @measurement_type.setter def measurement_type(self, measurement_type): """Sets the measurement_type of this Parameter. :param measurement_type: The measurement_type of this Parameter. :type measurement_type: ParameterMeasurementApproach """ self._measurement_type = measurement_type
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 4818, 8079, 1330, 3128, 11, 4818, 8079, 198, 198, 6738, 19720, 1330, 7343, 11, 360, 713, 11, 5994, 198, 198, 6738, 1280, 15042, 62, 15388, 13, 27530, 13, 8692, 62, 19849, 62, 1330, 9...
2.421435
3,583
import datetime from abc import ABC from typing import List, Any, Dict import pyodbc import sortedcontainers from .. import constants, sql_queries from . import metrics from typing import TYPE_CHECKING if TYPE_CHECKING: from .. import clock_sync
[ 11748, 4818, 8079, 198, 6738, 450, 66, 1330, 9738, 198, 6738, 19720, 1330, 7343, 11, 4377, 11, 360, 713, 198, 198, 11748, 12972, 375, 15630, 198, 11748, 23243, 3642, 50221, 198, 198, 6738, 11485, 1330, 38491, 11, 44161, 62, 421, 10640, ...
3.445946
74
# inference import torch, torch.nn as nn, torch.nn.functional as F, random, numpy as np from torchvision import datasets, transforms test_batch_size = 100 saved_model_path = '0602-656377418-Garg.pt' device = torch.device("cuda" if torch.cuda.is_available() else "cpu") checkpoint = torch.load(saved_model_path, map_location=device) model = Net().to(device) model.load_state_dict(checkpoint) model.eval() transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) test_dataset = datasets.ImageFolder('test_original/', transform=transform) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=test_batch_size) tot_loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) output = model(data) tot_loss += torch.nn.CrossEntropyLoss()(output, target).item() # sum up batch loss pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability correct += pred.eq(target.view_as(pred)).sum().item() print('Test Loss: {:.6f}, Test Accuracy: {:.2f}%'.format( tot_loss/(len(test_loader)), 100.0*correct/(len(test_loader)*test_batch_size)))
[ 2, 32278, 198, 11748, 28034, 11, 28034, 13, 20471, 355, 299, 77, 11, 28034, 13, 20471, 13, 45124, 355, 376, 11, 4738, 11, 299, 32152, 355, 45941, 198, 6738, 28034, 10178, 1330, 40522, 11, 31408, 198, 198, 9288, 62, 43501, 62, 7857, ...
2.545635
504
idade = maior = menor = homens = 0 while True: sexo = contin = '' idade = int(input('Digite sua idade: ')) while sexo != 'F' and sexo != 'M': sexo = str(input('Digite o seu sexo: ')).upper()[0] if idade >= 18: maior += 1 if sexo == 'M': homens += 1 if sexo == 'F': if idade < 20: menor += 1 while contin != 'S' and contin != 'N': contin = str(input('Deseja continuar? [S/N]')).upper()[0] if contin == 'N': break print(f'A quantidade de pessoas maiores de 18 são {maior}') print(f'A quantidade de homens cadastrados são {homens}') print(f'A quantidade de meninas abaixo dos 20 anos são {menor}')
[ 312, 671, 796, 17266, 1504, 796, 1450, 273, 796, 3488, 641, 796, 657, 198, 4514, 6407, 25, 198, 220, 220, 220, 1714, 78, 796, 1261, 796, 10148, 198, 220, 220, 220, 4686, 671, 796, 493, 7, 15414, 10786, 19511, 578, 424, 64, 4686, 6...
2.008357
359
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-04-25 21:49 from __future__ import unicode_literals from django.db import migrations, models import uuid
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 22, 319, 2864, 12, 3023, 12, 1495, 2310, 25, 2920, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.754098
61
import numpy as np import pytest as pt from collections import OrderedDict
[ 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 355, 42975, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 628 ]
3.8
20
import torch from dreamer.carracing import ( DenseModel, Env, ObservationDecoder, ObservationEncoder, Policy, Posterior, Prior, ) from dreamer import Dreamer if __name__ == "__main__": use_cuda = torch.cuda.is_available() device = torch.device("cuda" if use_cuda else "cpu") weight_dir = "weight" env = Env(save_mp4="video") agent = Dreamer( device=device, encoder=ObservationEncoder, prior=Prior, posterior=Posterior, decoder=ObservationDecoder, reward=DenseModel, policy=Policy, value=DenseModel, ) agent.load_weight(weight_dir) score = 0.0 state = env.reset() while 1: action = agent(state, train=False) state_, reward, done = env.step(action) score += reward state = state_ env.render() if any(done): break print("Score:", score)
[ 11748, 28034, 198, 198, 6738, 4320, 263, 13, 66, 3258, 4092, 1330, 357, 198, 220, 220, 220, 360, 1072, 17633, 11, 198, 220, 220, 220, 2039, 85, 11, 198, 220, 220, 220, 11086, 13208, 10707, 12342, 11, 198, 220, 220, 220, 11086, 13208...
2.184149
429
"""Build Script for setuptools This build script must be executed outside of the source code directory. The version number will be generated using the most recent tag and the number of commits on the master branch. [TAG].[COMMIT_COUNT] See Also: https://packaging.python.org/tutorials/packaging-projects/ """ import setuptools import os package_name = "kube_api" package_description = "A simple Kubernetes Python API" package_url = "https://github.com/labdave/kube_api" with open(os.path.join(package_name, "README.md"), "r") as fh: long_description = fh.read() with open(os.path.join(package_name, "requirements.txt"), "r") as f: requirements = f.read().split("\n") requirements = [r.strip() for r in requirements if r.strip()] release_version = str(os.popen("cd %s && git tag | tail -1" % package_name).read()).strip() if not release_version: raise ValueError("Release version not found.") commit_version = str(os.popen("cd %s && git rev-list --count master" % package_name).read()).strip() setuptools.setup( name=package_name, version="%s.%s" % (release_version, commit_version), author="Qiu Qin", author_email="qiuosier@gmail.com", description=package_description, long_description=long_description, long_description_content_type="text/markdown", url=package_url, packages=setuptools.find_packages(), install_requires=requirements, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', )
[ 37811, 15580, 12327, 329, 900, 37623, 10141, 198, 198, 1212, 1382, 4226, 1276, 307, 10945, 2354, 286, 262, 2723, 2438, 8619, 13, 198, 464, 2196, 1271, 481, 307, 7560, 1262, 262, 749, 2274, 7621, 290, 262, 1271, 286, 23463, 319, 262, 4...
2.905455
550
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # # Ravi Krishna 07/23/21 # Various import statements. import torch import torch.nn as nn from nas_searchmanager import SearchManager from cnn_supernet import ConvSuperNet from dnas_cnn_data_utils import CNNDataset import argparse import pickle from utils import arch_sampling_str_to_dict, STR_TO_OPTIM import random import numpy as np import hashlib import time import os # Create argument parser. parser = argparse.ArgumentParser(description="Run DNAS CNN test.") # Training / search manager parameters. parser.add_argument("--experiment_id", type=str, default=None, help="Unique experiment ID used as a prefix for all files saved during the experiment, including sampled architectures and logfiles.") parser.add_argument("--weights_batch_size", type=int, default=256, help="Weights training batch size.") parser.add_argument("--arch_params_batch_size", type=int, default=256, help="Arch params training batch size.") parser.add_argument("--initial_temperature", type=float, default=1.0, help="Initial Gumbel Softmax temperature.") parser.add_argument("--temp_decay_rate", type=float, default=0.1, help="Decay rate of Gumbel Softmax temperature.") parser.add_argument("--architecture_sampling", type=str, default="4:4", help="Architecture sampling. To sample 4 architecture after 1 epoch of architecture parameters training, 4 after 2, etc. for all 4 epochs, one would write \"1:4,2:4,3:4,4:4\".") parser.add_argument("--n_warmup_epochs", type=float, default=None, help="Number (possibly float) of warmup epochs i.e. weights-only training before architecture parameters trained.") parser.add_argument("--n_total_s_net_training_epochs", type=float, default=None, help="Total (possibly float) number of supernet training epochs.") parser.add_argument("--n_alt_train_epochs", type=float, default=1.0, help="Every n_alt_train_epochs, we switch from training the weights to architecture parameters or vice versa.") parser.add_argument("--host_gpu_id", type=int, default=None, help="Host GPU ID.") parser.add_argument("--clip_grad_norm_value", type=float, default=100.0, help="L2 norm at which to clip gradients of supernet.") # Both weights and architecture parameters gradients. parser.add_argument("--weights_optim_type", type=str, choices=["sgd"], default="sgd", help="Weights optimizer type.") parser.add_argument("--arch_params_optim_type", type=str, choices=["sgd", "adam", "adagrad"], default="sgd", help="Architecture parameters optimizer type.") parser.add_argument("--weights_lr", type=float, default=None, help="Initial learning rate for architecture weights.") parser.add_argument("--arch_params_lr", type=float, default=None, help="Initial learning rate for architecture configuration parameters.") parser.add_argument("--weights_wd", type=float, default=0.0, help="Weight decay for architecture weights.") parser.add_argument("--arch_params_wd", type=float, default=0.0, help="Weight decay for architecture configuration parameters.") parser.add_argument("--use_hw_cost", action="store_true", help="Whether or not to use HW cost in the DNAS training.") parser.add_argument("--hw_cost_function", type=str, choices=["exponential", "linear"], default="linear", help="HW cost function type if --use_hw_cost.") parser.add_argument("--hw_cost_exp", type=float, default=None, help="HW cost function exponent, provided only if --use_hw_cost and --hw_cost_function=exponential.") parser.add_argument("--hw_cost_coef", type=float, default=0.001, help="HW cost linear coefficient, provided if --use_hw_cost.") parser.add_argument("--hw_cost_multiplier", type=float, default=1.0, help="Linear HW cost multiplier to e.g. convert latency numbers measured in seconds to milliseconds.") parser.add_argument("--weights_lr_base", type=float, default=0.9, help="Weights LR = weights_lr * ((weights_lr_base) ** (num_weights_epochs)). Note that this formula may be applied at every training step or every n_alt_train_epochs.") # Every epoch not currently an option - may be added later as an option. parser.add_argument("--arch_params_lr_base", type=float, default=0.9, help="Arch params LR = arch_params_lr * ((arch_params_lr_base) ** (num_arch_params_epochs)). Note that this formula may be applied at every training step or every n_alt_train_epochs.") # Every epoch not currenly an option - may be added later. parser.add_argument("--update_lrs_every_step", action="store_true", help="If set, LRs will be updated every step instead of every SearchManager \"epoch\" (usually args.n_alt_train_amt).") # Could update the weights and architecture parameters learning rates at different frequencies. # Seed. parser.add_argument("--seed", type=int, default=1, help="Random seed to ensure results can be replicated. This seed is used for random, numpy, and torch.") # Needed to interface with tuning script. parser.add_argument("--save_metrics_param", type=str, default="", help="Path at which to save a file to tell tuning.py that this script is done running.") # Parse arguments. args = parser.parse_args() # Set seed. random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) # Create the supernet. cnn_supernet = ConvSuperNet() # Get dataloaders. weights_dataloader, arch_params_dataloader = torch.utils.data.DataLoader(CNNDataset("train-weights"), batch_size=args.weights_batch_size), torch.utils.data.DataLoader(CNNDataset("train-archparams"), batch_size=args.arch_params_batch_size) # Function to deal with OOM errors. def write_oom_exit(oom_error): """ Writes the text of the OOM error to the file and then exit()s. """ # Write OOM error. oom_error_file = open(f"oom_error_{args.save_metrics_param}", "w") oom_error_file.write(str(oom_error)) oom_error_file.flush() # Remove job information file. os.system(f"rm {job_info_filename}") # Exit. exit() # Move DLRM supernet to GPU. # Writing OOM error allows for job restarting. try: host_device = torch.device(f"cuda:{args.host_gpu_id}" if torch.cuda.is_available() else "dpcpp") print(f"ATTEMPTING TO MOVE CNN SUPERNET TO GPU {args.host_gpu_id if torch.cuda.is_available() else 'dpcpp'}.") print(cnn_supernet) cnn_supernet.to(host_device) except RuntimeError as oom_error: write_oom_exit(oom_error) # Construct various inputs to SearchManager.__init__(): # Optimizer classes. weights_optim_class = STR_TO_OPTIM[args.weights_optim_type.lower()] arch_params_optim_class = STR_TO_OPTIM[args.arch_params_optim_type.lower()] # Optimizer initialization parameters. weights_optim_init_params = {"lr" : args.weights_lr, "weight_decay" : args.weights_wd} arch_params_optim_init_params = {"lr" : args.arch_params_lr, "weight_decay" : args.arch_params_wd} # Functions to fetch parameters that each optimizer should train. weights_parameters_function = lambda s_net: [param for param_name, param in s_net.named_parameters() if "theta_parameters" not in param_name] arch_params_parameters_function = lambda s_net : [param for param_name, param in s_net.named_parameters() if "theta_parameters" in param_name] # Functions which specify how the LR changes during training. Note that # these functions return the RATIO of the current learning rate to the # initial learning rate, and not the current learning rate itself. weights_optim_lr_lambdas = [lambda curr_epoch: (args.weights_lr_base ** curr_epoch)] arch_params_optim_lr_lambdas = [lambda curr_epoch: (args.arch_params_lr_base ** curr_epoch)] # Initial learning rates for the different parameters groups in each # optimizer. Currently there is only one parameter group used per optimizer, # however, the code supports multiple parameters groups, each with their own # initial learning rate and learning rate schedule. weights_initial_lrs = [args.weights_lr] arch_params_initial_lrs = [args.arch_params_lr] # CrossEntropyLoss for image classification. loss_function = nn.CrossEntropyLoss() # Create search_manager. search_manager = SearchManager(super_net=cnn_supernet, init_temp=args.initial_temperature, temp_decay_rate=args.temp_decay_rate, n_warmup_epochs=args.n_warmup_epochs, arch_sampling=arch_sampling_str_to_dict(args.architecture_sampling), n_total_s_net_train_epochs=args.n_total_s_net_training_epochs, n_alt_train_amt=args.n_alt_train_epochs, host_device=host_device, clip_grad_norm_value=args.clip_grad_norm_value, w_dataloader=weights_dataloader, m_dataloader=arch_params_dataloader, w_optim_class=weights_optim_class, weights_optim_init_params=weights_optim_init_params, w_optim_params_func=weights_parameters_function, m_optim_class=arch_params_optim_class, mask_optim_init_params=arch_params_optim_init_params, m_optim_params_func=arch_params_parameters_function, weights_lr_lambdas=weights_optim_lr_lambdas, mask_lr_lambdas=arch_params_optim_lr_lambdas, weights_initial_lrs=weights_initial_lrs, mask_initial_lrs=arch_params_initial_lrs, update_lrs_every_step=args.update_lrs_every_step, loss_function=loss_function, experiment_id=args.experiment_id, logfile=args.experiment_id.replace("save_file", "search_manager_logfile"), use_hw_cost=args.use_hw_cost, cost_exp=args.hw_cost_exp, cost_coef=args.hw_cost_coef, exponential_cost=(True if args.use_hw_cost and args.hw_cost_function == "exponential" else False), cost_multiplier=args.hw_cost_multiplier) # Start search process. try: search_manager.train_dnas() except RuntimeError as oom_error: write_oom_exit(oom_error) # Once the DNAS process is done, in order to tuning.py to know # that the script is done running, save a file at the save_metrics_param # location. with open(args.save_metrics_param, "wb") as save_metrics_writefile: pickle.dump({"info" : "SCRIPT COMPLETED"}, save_metrics_writefile)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, ...
2.183165
5,738
import json from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Optional from flask import request, redirect, render_template, Flask from flask_socketio import SocketIO from tool.pid_settings.forms import AllPIDForms, OrderForm FILE_NAME = 'pid_coef.json' @dataclass @dataclass
[ 11748, 33918, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 19720, 1330, 32233, 198, 198, 6738, 42903, 1330, 2581, 11, 18941, 11, 8543, 62, 28243, 11, 46947, 198, 6738,...
3.381443
97
import os
[ 11748, 28686, 201, 198 ]
2.75
4
# Copyright 2019 John Reese # Licensed under the MIT license import gc import sys from sys import stdin, stdout from time import monotonic from digitalio import DigitalInOut, Direction, Pull from supervisor import runtime from touchio import TouchIn from .serial import ALL_COMMANDS, VERSION try: from typing import Callable, Dict, List, Tuple except ImportError: pass NIB = "NIB" NIN = "NIN" NIF = "NIF" DEBOUNCE = 0.02 # how long to wait on up/down changes REPEAT = object() INTERVAL = 0.1
[ 2, 15069, 13130, 1757, 39929, 198, 2, 49962, 739, 262, 17168, 5964, 628, 198, 11748, 308, 66, 198, 11748, 25064, 198, 6738, 25064, 1330, 14367, 259, 11, 14367, 448, 198, 6738, 640, 1330, 937, 313, 9229, 198, 198, 6738, 4875, 952, 1330...
3.060241
166
#!/usr/bin/env python """Services for asset tracking """ import csv from xlwt import Workbook import binascii import uuid import re from ion.util.xlsparser import XLSParser from pyon.core import bootstrap from ooi.logging import log from pyon.core.exception import NotFound, BadRequest, Inconsistent from pyon.public import IonObject, RT, PRED, LCS, LCE, OT from interface.objects import EventCategoryEnum, ValueTypeEnum from interface.services.coi.iorg_management_service import OrgManagementServiceClient
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 31007, 329, 11171, 9646, 37227, 198, 198, 11748, 269, 21370, 198, 6738, 2124, 75, 46569, 1330, 5521, 2070, 198, 11748, 9874, 292, 979, 72, 198, 11748, 334, 27112, 198, 11748,...
3.337662
154
import feedparser from nose.tools import ( assert_raises, eq_, set_trace, ) from . import DatabaseTest from ..opds import ( ContentServerAnnotator, StaticFeedAnnotator, StaticCOPPANavigationFeed, ) from ..core.opds import UnfulfillableWork class MockStaticLane(object): """Empty, unobtrusive Lane class that gives any StaticFeedAnnotator a name to work with."""
[ 11748, 3745, 48610, 198, 198, 6738, 9686, 13, 31391, 1330, 357, 198, 220, 220, 220, 6818, 62, 430, 2696, 11, 198, 220, 220, 220, 37430, 62, 11, 198, 220, 220, 220, 900, 62, 40546, 11, 198, 8, 198, 6738, 764, 1330, 24047, 14402, 19...
2.836879
141
import mock from sms_directions.sms import send_sms from sms_directions import config
[ 11748, 15290, 198, 198, 6738, 895, 82, 62, 12942, 507, 13, 82, 907, 1330, 3758, 62, 82, 907, 198, 6738, 895, 82, 62, 12942, 507, 1330, 4566, 628 ]
3.142857
28
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Copyright (c) 2021, ICGC ARGO 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. Authors: Junjun Zhang """ import os import sys import argparse import subprocess from multiprocessing import cpu_count from glob import glob import json import tarfile if __name__ == '__main__': parser = argparse.ArgumentParser(description='Tool: samtools-stats') parser.add_argument('-s', '--aligned_seq', type=str, help='Input aligned seq', required=True) parser.add_argument('-r', '--reference', type=str, help='Reference genome', required=True) parser.add_argument('-t', '--threads', type=int, default=cpu_count(), help='Number of threads') args = parser.parse_args() if not os.path.isfile(args.aligned_seq): sys.exit('Error: specified aligned seq file %s does not exist or is not accessible!' % args.aligned_seq) if not os.path.isfile(args.reference): sys.exit('Error: specified reference file %s does not exist or is not accessible!' % args.reference) main(args.aligned_seq, args.reference, args.threads)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 220, 15069, 357, 66, 8, 33448, 11, 12460, 15916, 5923, 11230, 628, 220, 2448, 3411, 318, 29376, ...
3.137733
697
import plotly.figure_factory as ff import plotly.graph_objects as go import statistics import random import csv import pandas as pd df =pd.read_csv("studentMarks.csv") data = df["Math_score"].tolist() std_deviation = statistics.stdev(mean_list) mean = statistics.mean(mean_list) print("mean of sampling distribution",mean) fig = ff.create_distplot([data],["student_marks"],show_hist= False) fig.add_trace(go.Scatter(x=[mean,mean],y = [0,0.20],mode="lines",name= "MEAN")) fig.show()
[ 11748, 7110, 306, 13, 26875, 62, 69, 9548, 355, 31246, 220, 201, 198, 11748, 7110, 306, 13, 34960, 62, 48205, 355, 467, 220, 201, 198, 11748, 7869, 201, 198, 11748, 4738, 201, 198, 11748, 269, 21370, 201, 198, 11748, 19798, 292, 355, ...
2.626943
193
# This gets rid of NumPy FutureWarnings that occur at TF import import warnings warnings.filterwarnings('ignore',category=FutureWarning) # This gets rid of TF 2.0 related deprecation warnings import tensorflow as tf tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
[ 2, 770, 3011, 5755, 286, 31835, 20519, 10898, 54, 1501, 654, 326, 3051, 379, 24958, 1330, 201, 198, 11748, 14601, 201, 198, 40539, 654, 13, 24455, 40539, 654, 10786, 46430, 3256, 22872, 28, 29783, 20361, 8, 201, 198, 201, 198, 2, 770,...
3.021053
95
''' Python version of check_aqc_07_spike_check.f. Details of the original code are: c/ DATE: JANUARY 25 2016 c/ AUTHOR: Viktor Gouretski c/ AUTHOR'S AFFILIATION: Integrated Climate Data Center, University of Hamburg, Hamburg, Germany c/ PROJECT: International Quality Controlled Ocean DataBase (IQuOD) c/ TITLE: check_aqc_07_spike_check c/ PURPOSE: c to check temperature profile for spikes ''' from . import ICDC_aqc_01_level_order as ICDC import numpy as np def test(p, parameters): '''Return quality control decisions. ''' # The test is run on re-ordered data. nlevels, z, t = ICDC.reordered_data(p, parameters) qc = np.zeros(nlevels, dtype=bool) # Reordered data may be a subset of available levels. defaultqc = np.zeros(p.n_levels(), dtype=bool) # Default QC flags for full set of levels. if nlevels < 3: return defaultqc # Not enough levels to check. # Ignore any levels outside of limits. parminover = -2.3 parmaxover = 33.0 use = (t > parminover) & (t < parmaxover) nuse = np.count_nonzero(use) if nuse < 3: return defaultqc zuse = z[use] tuse = t[use] origlevels = (np.arange(nlevels))[use] # Extract sections of the arrays. We are QCing the values # in the z2 and v3 arrays. z1 = zuse[0:-2] z2 = zuse[1:-1] z3 = zuse[2:] v1 = tuse[0:-2] v2 = tuse[1:-1] v3 = tuse[2:] ol = origlevels[1:-1] # Calculate the level of 'spike'. z13 = z3 - z1 z12 = z2 - z1 z23 = z3 - z2 a = 0.5 * (v1 + v3) q1 = np.abs(v2 - a) q2 = np.abs(0.5 * (v3 - v1)) spike = q1 - q2 # Define the threshold at each level. spikemax = np.ndarray(nuse - 2) spikemax[:] = 4.0 spikemax[z2 > 1000.0] = 3.0 spikemax[z2 > 2000.0] = 2.0 # Set QC flags. qc[ol[spike > spikemax]] = True return ICDC.revert_qc_order(p, qc, parameters)
[ 7061, 6, 198, 37906, 2196, 286, 2198, 62, 30188, 66, 62, 2998, 62, 2777, 522, 62, 9122, 13, 69, 13, 220, 198, 24259, 286, 262, 2656, 2438, 389, 25, 198, 198, 66, 14, 360, 6158, 25, 220, 220, 220, 220, 220, 220, 449, 1565, 52, ...
2.283848
842
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ######################################################## # ____ _ __ # # ___ __ __/ / /__ ___ ______ ______(_) /___ __ # # / _ \/ // / / (_-</ -_) __/ // / __/ / __/ // / # # /_//_/\_,_/_/_/___/\__/\__/\_,_/_/ /_/\__/\_, / # # /___/ team # # # # nullscan # # A modular framework designed to chain and automate security tests # # # # FILE # # http.py # # # # AUTHOR # # noptrix@nullsecurity.net # # # ################################################################################ # sys imports import concurrent.futures as cf from collections import deque import json # own imports from modules.libs.base import Base, tool, timeout class HTTP(Base): """ HTTP module (tcp/80,8000,8080,8888) """ def __init__(self, target, opts): """ init """ Base.__init__(self, target, opts) return @tool def http_headers(self): """ DESCR: Dump HTTP headers via a single HTTP HEAD request. (ext) TOOLS: curl """ opts = f"--connect-timeout 3 -m 30 -s -X HEAD -I -A '{self.useragent}'" opts += f" --url http://{self.target['host']}:{self.target['port']}/" self._run_tool('curl', opts, nullscan_tool='http_headers', timeout=30) return @tool def http_reqs(self): """ DESCR: Send HTTP (head,get,post,options) requests with different HTTP versions (0.9,1.0,1.1,2). (ext) TOOLS: curl """ threads = 3 with cf.ThreadPoolExecutor(threads) as exe: for t in self.http_req_types: for v in self.http_versions: opts = f"-v --connect-timeout 3 -m 30 -s -A '{self.useragent}'" opts += f" -X {t.upper()} --http{v}" opts += f" --url http://{self.target['host']}:{self.target['port']}/" exe.submit(self._run_tool, 'curl', opts, nullscan_tool=f'http_reqs_{t}') return @tool def http_put(self): """ DESCR: Try to send HTTP PUT request with example data to /nullscan.html. (int) TOOLS: curl """ opts = f"-s --connect-timeout 3 -m 30 -X PUT -A '{self.useragent}'" opts += ' -D /dev/stdout --data pwned' opts += f" --url http://{self.target['host']}:" opts += f"{self.target['port']}/nullscan.html" self._run_tool('curl', opts, nullscan_tool='http_put') return @tool def proxy_check(self): """ DESCR: Check for open HTTP proxy. (int) TOOLS: curl """ opts = f"-I -s -x 'http://{self.target['host']}:{self.target['port']}/'" opts += f" -L https://www.blackarch.org/" self._run_tool('curl', opts, nullscan_tool='proxy_check') return @tool def davscan(self): """ DESCR: Scan webserver and test if WebDAV is enabled. (ext) TOOLS: davscan """ opts = f"-d -m -D 1 -o /tmp/{self.target['host']}" if self.opts['user'] and self.opts['pass']: opts += f" -a basic -u {self.opts['user']} -p {self.opts['pass']}" if self.opts['proxy']: opts += f" -P {self.opts['proxy']}" opts += f" http://{self.target['host']}:{self.target['port']}/" self._run_tool('davscan', opts, escape_codes=True) return @tool def lulzbuster_http(self): """ DESCR: Enumerate directories and files on webserver. (ext) TOOLS: lulzbuster """ host = self.target['host'] port = self.target['port'] # better try with hostname domain = self._read_log('domainname')[0] hostname = self._read_log('hostname')[0] if domain: host = domain if hostname and hostname in domain: host = hostname for f in self.opts['flists']: self._lulzbuster(host, port, flist=f) return @tool def dirsearch_http(self): """ DESCR: Enumerate directories and files on webserver. (ext) TOOLS: dirsearch """ host = self.target['host'] port = self.target['port'] # better try with hostname domain = self._read_log('domainname')[0] hostname = self._read_log('hostname')[0] if domain: host = domain if hostname and hostname in domain: host = hostname for f in self.opts['flists']: self._dirsearch(host, port, flist=f) return @tool def gobuster_http(self): """ DESCR: Enumerate directories and files on webserver. (ext) TOOLS: gobuster """ host = self.target['host'] port = self.target['port'] # better try with hostname domain = self._read_log('domainname')[0] hostname = self._read_log('hostname')[0] if domain: host = domain if hostname and hostname in domain: host = hostname for f in self.opts['flists']: self._gobuster(host, port, flist=f) return @tool def halberd_http(self): """ DESCR: Discover http load balancer. (ext) TOOLS: halberd """ self._halberd(self.target['host'], self.target['port']) return @tool def lbmap_http(self): """ DESCR: Fingerprint HTTP server. (ext) TOOLS: lbmap """ self._lbmap(self.target['host'], self.target['port']) return @tool def metoscan_http(self): """ DESCR: Scan available HTTP methods. (ext) TOOLS: metoscan """ self._metoscan(self.target['host'], self.target['port']) return @tool def httping_http(self): """ DESCR: Ping HTTP server. (ext) TOOLS: httping """ self._httping(self.target['host'], self.target['port']) return @tool def httprint_http(self): """ DESCR: Fingerprint the web-server. (ext) TOOLS: httprint """ self._httprint(self.target['host'], self.target['port']) return @tool def nikto_http(self): """ DESCR: Crawl the web-server for directories, files and vulnerabilities. (ext) TOOLS: nikto """ self._nikto(self.target['host'], self.target['port']) return @tool def crack_http_auth(self): """ DESCR: Check HTTP auth type (basic, realm, etc.) and crack login. (int) TOOLS: python3 """ with timeout(self.opts['timeout']): url = f"http://{self.target['host']}:{self.target['port']}/" self._crack_http_auth(url, 'crack_http_auth') return @tool def crack_tomcat_http(self): """ DESCR: Check for tomcat and crack logins using tomcat's default creds. (int) TOOLS: python3 """ with timeout(self.opts['timeout']): # default tomcat creds users = deque(('tomcat', 'both', 'role1', 'admin', 'manager', 'root')) pws = deque(('tomcat', 'both', 'role1', 'admin', 'manager', 'root', '')) threads = len(users) url = self._is_tomcat(self.target['host'], self.target['port']) if url: with cf.ThreadPoolExecutor(threads) as exe: for us in users: for pw in pws: exe.submit(self._crack_tomcat, url, us, pw, 'crack_tomcat_http') return @tool def jexboss_http(self): """ DESCR: Check for known java deserialization vulns against JBoss, Jenkins, and Apache Struts2. (ext) TOOLS: jexboss """ self._jexboss(self.target['host'], self.target['port'], log='jexboss_http') return @tool def snallygaster_http(self): """ DESCR: Scan for secret files on web-server. (ext) TOOLS: snallygaster """ target = f"{self.target['host']}:{self.target['port']}" self._snallygaster(target, 'snallygaster_http') return @tool def tomcatwardeployer_http(self): """ DESCR: Apache Tomcat auto WAR deployment & pwning. (ext) TOOLS: tomcatwardeployer """ opts = '-t 5' if self.opts['user'] and self.opts['pass']: opts += f" -U {self.opts['user']} -P {self.opts['pass']}" opts += f" http://{self.target['host']}:{self.target['port']}/" self._run_tool('tomcatwardeployer', opts, 'tomcatwardeployer_http', timeout=8) return @tool def findstr_http(self): """ DESCR: Find given string in HTTP responses. (int) TOOLS: curl """ url = f"http://{self.target['host']}:{self.target['port']}/" opts = f"--connect-timeout 2 -m 30 -s -L -A '{self.useragent}' {url}" cmd = f'curl {opts}' res = ' '.join(self._run_cmd(cmd)) if self.opts['searchstr'] in res: idx = res.index(self.opts['searchstr']) data = f"{url} ==> '{res[idx:idx+int(self.opts['resp_size'])]}'" self._log('findstr_http', data) return @tool def nmap_http(self): """ DESCR: Scan http service with corresponding NSE scripts. (ext) TOOLS: nmap """ nse = 'http-adobe*,http-aff*,http-apache*,http-asp*,http-avaya*,http-awst*,' nse += 'http-axis*,http-barra*,http-bigip*,http-cakephp*,http-chrono*,' nse += 'http-cisco-*,http-coldfus*,http-date,http-dlink*,http-drupal*,' nse += 'http-favicon,http-frontpage*,http-generator,http-git*,http-google*,' nse += 'http-headers,http-huawei*,http-iis*,http-internal-ip*,http-litesp*,' nse += 'http-majordomo2*,http-malware*,http-mcmp,http-methods,http-ntlm-*,' nse += 'http-open-proxy,http-phpmyadm*,http-qnap*,http-robots*,http-robte*,' nse += 'http-server-head*,http-shellsh*,http-svn*,http-title,http-tplink*,' nse += 'http-trace*,http-trane*,http-vhosts,http-vlc*,http-vmware*,' nse += 'http-vuln-*,http-waf*,http-webdav*' opts = f'-n -sS -Pn --open --nsock-engine epoll --script {nse}' opts += f" -p {self.target['port']} {self.target['host']}" self._run_tool('nmap', opts, nullscan_tool='nmap_http') return # EOF
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 1303, 29113, 14468, 4242, 21017, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.102116
4,916
import pkgutil import unittest
[ 11748, 279, 10025, 22602, 198, 11748, 555, 715, 395, 628 ]
3.2
10
import formatter import unittest from test import test_support htmllib = test_support.import_module('htmllib', deprecated=True) if __name__ == "__main__": test_main()
[ 11748, 1296, 1436, 201, 198, 11748, 555, 715, 395, 201, 198, 201, 198, 6738, 1332, 1330, 1332, 62, 11284, 201, 198, 19211, 297, 571, 796, 1332, 62, 11284, 13, 11748, 62, 21412, 10786, 19211, 297, 571, 3256, 39224, 28, 17821, 8, 201, ...
2.597222
72
# -*- coding: utf-8 -*- from django.contrib import admin
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 628 ]
2.521739
23
# Copyright 2004-2019 Tom Rothamel <pytom@bishoujo.us> # # 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 __future__ import print_function import renpy.display import pygame_sdl2 as pygame import math import weakref import time import os from renpy.display.render import blit_lock, IDENTITY, BLIT, DISSOLVE, IMAGEDISSOLVE, PIXELLATE, FLATTEN # A map from cached surface to rle version of cached surface. rle_cache = weakref.WeakKeyDictionary() class Clipper(object): """ This is used to calculate the clipping rectangle and update rectangles used for a particular draw of the screen. """ def compute(self, full_redraw): """ This returns a clipping rectangle, and a list of update rectangles that cover the changes between the old and new frames. """ # First, get things out of the fields, and update them. This # allows us to just return without having to do any cleanup # code. bl0 = self.old_blits bl1 = self.blits old_forced = self.old_forced forced = self.forced mutated = self.mutated self.old_blits = bl1 self.blits = [ ] self.old_forced = forced self.forced = set() self.mutated = set() sw = renpy.config.screen_width sh = renpy.config.screen_height sa = sw * sh # A tuple representing the size of the fullscreen. fullscreen = (0, 0, sw, sh) # Check to see if a full redraw has been forced, and return # early. if full_redraw: return fullscreen, [ fullscreen ] # Quick checks to see if a dissolve is happening, or something like # that. changes = forced | old_forced if fullscreen in changes: return fullscreen, [ fullscreen ] # Compute the differences between the two sets, and add those # to changes. i0 = 0 i1 = 0 bl1set = set(bl1) while True: if i0 >= len(bl0) or i1 >= len(bl1): break b0 = bl0[i0] b1 = bl1[i1] if b0 == b1: if id(b0[5]) in mutated: changes.add(b0[:5]) i0 += 1 i1 += 1 elif b0 not in bl1set: changes.add(b0[:5]) i0 += 1 else: changes.add(b1[:5]) i1 += 1 changes.update(i[:5] for i in bl0[i0:]) changes.update(i[:5] for i in bl1[i1:]) # No changes? Quit. if not changes: return None, [ ] # Compute the sizes of the updated rectangles. sized = [ ] for x0, y0, x1, y1, (sx0, sy0, sx1, sy1) in changes: # Round up by a pixel, to prevent visual artifacts when scaled down. x1 += 1 y1 += 1 if x0 < sx0: x0 = sx0 if y0 < sy0: y0 = sy0 if x1 > sx1: x1 = sx1 if y1 > sy1: y1 = sy1 w = x1 - x0 h = y1 - y0 if w <= 0 or h <= 0: continue area = w * h if area >= sa: return fullscreen, [ fullscreen ] sized.append((area, x0, y0, x1, y1)) sized.sort() # The list of non-contiguous updates. noncont = [ ] # The total area of noncont. nca = 0 # Pick the largest area, merge with all overlapping smaller areas, repeat # until no merge possible. while sized: area, x0, y0, x1, y1 = sized.pop() merged = False if nca + area >= sa: return (0, 0, sw, sh), [ (0, 0, sw, sh) ] i = 0 while i < len(sized): _iarea, ix0, iy0, ix1, iy1 = sized[i] if (x0 <= ix0 <= x1 or x0 <= ix1 <= x1) and \ (y0 <= iy0 <= y1 or y0 <= iy1 <= y1): merged = True x0 = min(x0, ix0) x1 = max(x1, ix1) y0 = min(y0, iy0) y1 = max(y1, iy1) area = (x1 - x0) * (y1 - y0) sized.pop(i) else: i += 1 if merged: sized.append((area, x0, y0, x1, y1)) else: noncont.append((x0, y0, x1, y1)) nca += area if not noncont: return None, [ ] x0, y0, x1, y1 = noncont.pop() x0 = int(x0) y0 = int(y0) x1 = int(math.ceil(x1)) y1 = int(math.ceil(y1)) # A list of (x, y, w, h) tuples for each update. updates = [ (x0, y0, x1 - x0, y1 - y0) ] for ix0, iy0, ix1, iy1 in noncont: ix0 = int(ix0) iy0 = int(iy0) ix1 = int(math.ceil(ix1)) iy1 = int(math.ceil(iy1)) x0 = min(x0, ix0) y0 = min(y0, iy0) x1 = max(x1, ix1) y1 = max(y1, iy1) updates.append((ix0, iy0, ix1 - ix0, iy1 - iy0)) return (x0, y0, x1 - x0, y1 - y0), updates clippers = [ Clipper() ] def surface(w, h, alpha): """ Creates a surface that shares a pixel format with the screen. The created surface will """ if alpha: rv = pygame.Surface((w + 4, h + 4), pygame.SRCALPHA) else: rv = pygame.Surface((w + 4, h + 4), 0) return rv.subsurface((2, 2, w, h)) def draw_special(what, dest, x, y): """ This handles the special drawing operations, such as dissolve and image dissolve. `x` and `y` are the offsets of the thing to be drawn relative to the destination rectangle, and are always negative. """ dw, dh = dest.get_size() w = min(dw, what.width + x) h = min(dh, what.height + y) if w <= 0 or h <= 0: return if what.operation == DISSOLVE: bottom = what.children[0][0].render_to_texture(True) top = what.children[1][0].render_to_texture(True) if what.operation_alpha: target = surface(w, h, True) else: target = dest.subsurface((0, 0, w, h)) renpy.display.module.blend( bottom.subsurface((-x, -y, w, h)), top.subsurface((-x, -y, w, h)), target, int(what.operation_complete * 255)) if what.operation_alpha: dest.blit(target, (0, 0)) elif what.operation == IMAGEDISSOLVE: image = what.children[0][0].render_to_texture(True) bottom = what.children[1][0].render_to_texture(True) top = what.children[2][0].render_to_texture(True) if what.operation_alpha: target = surface(w, h, True) else: target = dest.subsurface((0, 0, w, h)) ramplen = what.operation_parameter ramp = "\x00" * 256 for i in xrange(0, ramplen): ramp += chr(255 * i / ramplen) ramp += "\xff" * 256 step = int( what.operation_complete * (256 + ramplen) ) ramp = ramp[step:step+256] renpy.display.module.imageblend( bottom.subsurface((-x, -y, w, h)), top.subsurface((-x, -y, w, h)), target, image.subsurface((-x, -y, w, h)), ramp) if what.operation_alpha: dest.blit(target, (0, 0)) elif what.operation == PIXELLATE: surf = what.children[0][0].render_to_texture(dest.get_masks()[3]) px = what.operation_parameter renpy.display.module.pixellate( surf.subsurface((-x, -y, w, h)), dest.subsurface((0, 0, w, h)), px, px, px, px) elif what.operation == FLATTEN: surf = what.children[0][0].render_to_texture(dest.get_masks()[3]) dest.subsurface((0, 0, w, h)).blit(surf, (0, 0)) else: raise Exception("Unknown operation: %d" % what.operation) def draw(dest, clip, what, xo, yo, screen): """ This is the simple draw routine, which only works when alpha is 1.0 and the matrices are None. If those aren't the case, draw_complex is used instead. `dest` - Either a destination surface, or a clipper. `clip` - If None, we should draw. Otherwise we should clip, and this is the rectangle to clip to. `what` - The Render or Surface we're drawing to. `xo` - The X offset. `yo` - The Y offset. `screen` - True if this is a blit to the screen, False otherwise. """ if not isinstance(what, renpy.display.render.Render): # Pixel-Aligned blit. if isinstance(xo, int) and isinstance(yo, int): if screen: what = rle_cache.get(what, what) if clip: w, h = what.get_size() dest.blits.append((xo, yo, xo + w, yo + h, clip, what, None)) else: try: blit_lock.acquire() dest.blit(what, (xo, yo)) finally: blit_lock.release() # Subpixel blit. else: if clip: w, h = what.get_size() dest.blits.append((xo, yo, xo + w, yo + h, clip, what, None)) else: renpy.display.module.subpixel(what, dest, xo, yo) return if what.text_input: renpy.display.interface.text_rect = what.screen_rect(xo, yo, None) # Deal with draw functions. if what.operation != BLIT: xo = int(xo) yo = int(yo) if clip: dx0, dy0, dx1, dy1 = clip dw = dx1 - dx0 dh = dy1 - dy0 else: dw, dh = dest.get_size() if xo >= 0: newx = 0 subx = xo else: newx = xo subx = 0 if yo >= 0: newy = 0 suby = yo else: newy = yo suby = 0 if subx >= dw or suby >= dh: return # newx and newy are the offset of this render relative to the # subsurface. They can only be negative or 0, as otherwise we # would make a smaller subsurface. subw = min(dw - subx, what.width + newx) subh = min(dh - suby, what.height + newy) if subw <= 0 or subh <= 0: return if clip: dest.forced.add((subx, suby, subx + subw, suby + subh, clip)) else: newdest = dest.subsurface((subx, suby, subw, subh)) # what.draw_func(newdest, newx, newy) draw_special(what, newdest, newx, newy) return # Deal with clipping, if necessary. if what.xclipping or what.yclipping: if clip: cx0, cy0, cx1, cy1 = clip cx0 = max(cx0, xo) cy0 = max(cy0, yo) cx1 = min(cx1, xo + what.width) cy1 = min(cy1, yo + what.height) if cx0 > cx1 or cy0 > cy1: return clip = (cx0, cy0, cx1, cy1) dest.forced.add(clip + (clip,)) return else: # After this code, x and y are the coordinates of the subsurface # relative to the destination. xo and yo are the offset of the # upper-left corner relative to the subsurface. if xo >= 0: x = xo xo = 0 else: x = 0 # xo = xo if yo >= 0: y = yo yo = 0 else: y = 0 # yo = yo dw, dh = dest.get_size() width = min(dw - x, what.width + xo) height = min(dh - y, what.height + yo) if width < 0 or height < 0: return dest = dest.subsurface((x, y, width, height)) # Deal with alpha and transforms by passing them off to draw_transformed. if what.alpha != 1 or what.over != 1.0 or (what.forward is not None and what.forward is not IDENTITY): for child, cxo, cyo, _focus, _main in what.visible_children: draw_transformed(dest, clip, child, xo + cxo, yo + cyo, what.alpha * what.over, what.forward, what.reverse) return for child, cxo, cyo, _focus, _main in what.visible_children: draw(dest, clip, child, xo + cxo, yo + cyo, screen) def do_draw_screen(screen_render, full_redraw, swdraw): """ Draws the render produced by render_screen to the screen. """ yoffset = xoffset = 0 screen_render.is_opaque() clip = (xoffset, yoffset, xoffset + screen_render.width, yoffset + screen_render.height) clipper = clippers[0] draw(clipper, clip, screen_render, xoffset, yoffset, True) cliprect, updates = clipper.compute(full_redraw) if cliprect is None: return [ ] x, y, _w, _h = cliprect dest = swdraw.window.subsurface(cliprect) draw(dest, None, screen_render, -x, -y, True) return updates class SWDraw(object): """ This uses the software renderer to draw to the screen. """ # private def show_mouse(self, pos, info): """ Actually shows the mouse. """ self.mouse_location = pos self.mouse_info = info mxo, myo, tex = info mx, my = pos mw, mh = tex.get_size() bx = mx - mxo by = my - myo self.mouse_backing_pos = (bx, by) self.mouse_backing = surface(mw, mh, False) self.mouse_backing.blit(self.window, (0, 0), (bx, by, mw, mh)) self.screen.blit(tex, (bx, by)) return bx, by, mw, mh # private def hide_mouse(self): """ Actually hides the mouse. """ size = self.mouse_backing.get_size() self.screen.blit(self.mouse_backing, self.mouse_backing_pos) rv = self.mouse_backing_pos + size self.mouse_backing = None self.mouse_backing_pos = None self.mouse_location = None return rv # private def draw_mouse(self, show_mouse): """ This draws the mouse to the screen, if necessary. It uses the buffer to minimize the amount of the screen that needs to be drawn, and only redraws if the mouse has actually been moved. """ hardware, x, y, tex = renpy.game.interface.get_mouse_info() if self.mouse_old_visible != hardware: pygame.mouse.set_visible(hardware) self.mouse_old_visible = hardware # The rest of this is for the software mouse. if self.suppressed_blit: return [ ] if not show_mouse: tex = None info = (x, y, tex) pos = pygame.mouse.get_pos() if (pos == self.mouse_location and tex and info == self.mouse_info): return [ ] updates = [ ] if self.mouse_location: updates.append(self.hide_mouse()) if tex and pos and renpy.game.interface.mouse_focused: # @UndefinedVariable updates.append(self.show_mouse(pos, info)) return updates def update_mouse(self): """ Draws the mouse, and then updates the screen. """ updates = self.draw_mouse(True) if updates: pygame.display.update(updates) def screenshot(self, surftree, fullscreen_video): """ Returns a pygame surface containing a screenshot. """ return self.window def should_redraw(self, needs_redraw, first_pass, can_block): """ Uses the framerate to determine if we can and should redraw. """ if not needs_redraw: return False framerate = renpy.config.framerate if framerate is None: return True next_frame = self.next_frame now = pygame.time.get_ticks() frametime = 1000.0 / framerate # Handle timer rollover. if next_frame > now + frametime: next_frame = now # It's not yet time for the next frame. if now < next_frame and not first_pass: return False # Otherwise, it is. Schedule the next frame. # if next_frame + frametime < now: next_frame = now + frametime # else: # next_frame += frametime self.next_frame = next_frame return True def draw_screen(self, surftree, fullscreen_video): """ Draws the screen. """ if fullscreen_video: if not self.showing_video: self.window.fill((0, 0, 0, 255)) w, h = self.window.get_size() frame = renpy.display.video.render_movie("movie", w, h) if frame is not None: surftree = frame self.full_redraw = True self.showing_video = True else: self.showing_video = False updates = [ ] updates.extend(self.draw_mouse(False)) damage = do_draw_screen(surftree, self.full_redraw, self) if damage: updates.extend(damage) self.full_redraw = False if self.window is self.screen: updates.extend(self.draw_mouse(True)) pygame.display.update(updates) else: if self.scale_fast: pygame.transform.scale(self.window, self.screen.get_size(), self.screen) else: renpy.display.scale.smoothscale(self.window, self.screen.get_size(), self.screen) self.draw_mouse(True) pygame.display.flip() if fullscreen_video: self.full_redraw = True def mutated_surface(self, surf): """ Called to indicate that the given surface has changed. """ for i in clippers: i.mutated.add(id(surf)) if surf in rle_cache: del rle_cache[surf] def load_texture(self, surf, transient=False): """ Creates a texture from the surface. In the software implementation, the only difference between a texture and a surface is that a texture is in the RLE cache. """ if surf in rle_cache: return rle_cache[surf] rle_surf = copy_surface(surf) if not transient: rle_surf.set_alpha(255, pygame.RLEACCEL) self.mutated_surface(rle_surf) rle_cache[surf] = rle_surf return rle_surf def solid_texture(self, w, h, color): """ Creates a texture filled to the edges with color. """ surf = surface(w + 4, h + 4, True) surf.fill(color) self.mutated_surface(surf) surf = surf.subsurface((2, 2, w, h)) self.mutated_surface(surf) return surf def kill_textures(self): """ Kills all textures and caches of textures. """ rle_cache.clear() def quit(self): # @ReservedAssignment """ Shuts down the drawing system. """ pygame.display.quit() return def event_peek_sleep(self): """ Wait a little bit so the CPU doesn't speed up. """ time.sleep(.0001) def get_physical_size(self): """ Return the physical width and height of the screen. """ return renpy.config.screen_width, renpy.config.screen_height
[ 2, 15069, 5472, 12, 23344, 4186, 16131, 17983, 1279, 9078, 39532, 31, 31795, 280, 7639, 13, 385, 29, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 198, 2, 16727, 257, 4866, 286, 428, 3788, ...
2.036387
10,086
import logging import time import os import pytest from tests.common.utilities import wait_until from tests.common.config_reload import config_reload from tests.common.reboot import reboot DUT_THERMAL_POLICY_FILE = '/usr/share/sonic/device/{}/thermal_policy.json' DUT_THERMAL_POLICY_BACKUP_FILE = '/usr/share/sonic/device/{}/thermal_policy.json.bak' BASE_DIR = os.path.dirname(os.path.realpath(__file__)) FILES_DIR = os.path.join(BASE_DIR, 'files') class BaseMocker: """ @summary: Base class for thermal control data mocker This base class defines the basic interface to be provided by base mocker. Mockers implemented by each vendor must be a subclass of this base class. """ # Mocker type dictionary. Vendor must register their concrete mocker class to this dictionary. _mocker_type_dict = {} def __init__(self, dut): """ Constructor of a mocker. :param dut: DUT object representing a SONiC switch under test. """ self.dut = dut def mock_data(self): """ Generate mock data. :return: """ pass def check_result(self, actual_data): """ Check actual data with mocked data. :param actual_data: A dictionary contains actual command line data. Key of the dictionary is the unique id of a line of command line data. For 'show platform fan', the key is FAN name. Value of the dictionary is a list of field values for a line. :return: True if actual data match mocked data else False """ pass def deinit(self): """ Destructor. Vendor specific clean up work should do here. :return: """ pass @classmethod def register_mocker_type(cls, name, mocker_type): """ Register mocker type with its name. :param name: Name of a mocker type. For example: FanStatusMocker. :param mocker_type: Class of a mocker. :return: """ cls._mocker_type_dict[name] = mocker_type @classmethod def get_mocker_type(cls, name): """ Get mocker type by its name. :param name: Name of a mocker type. For example: FanStatusMocker. :return: Class of a mocker. """ return cls._mocker_type_dict[name] if name in cls._mocker_type_dict else None def mocker(type_name): """ Decorator for register mocker type. :param type_name: Name of a mocker type. :return: """ return wrapper @pytest.fixture def mocker_factory(localhost, duthosts, rand_one_dut_hostname): """ Fixture for thermal control data mocker factory. :return: A function for creating thermal control related data mocker. """ mockers = [] duthost = duthosts[rand_one_dut_hostname] def _create_mocker(dut, mocker_name): """ Create vendor specified mocker object by mocker name. :param dut: DUT object representing a SONiC switch under test. :param mocker_name: Name of a mocker type. :return: Created mocker instance. """ platform = dut.facts['platform'] mocker_object = None if 'mlnx' in platform: from tests.platform_tests.mellanox import mellanox_thermal_control_test_helper mocker_type = BaseMocker.get_mocker_type(mocker_name) if mocker_type: mocker_object = mocker_type(dut) mockers.append(mocker_object) else: pytest.skip("No mocker defined for this platform %s") return mocker_object yield _create_mocker try: for m in mockers: m.deinit() except Exception as e: reboot(duthost, localhost) assert 0, "Caught exception while recovering from mock - {}".format(repr(e)) class FanStatusMocker(BaseMocker): """ Fan status mocker. Vendor should implement this class to provide a FAN mocker. This class could mock speed, presence/absence and so on for all FANs and check the actual data equal to the mocked data. """ def check_all_fan_speed(self, expected_speed): """ Check all fan speed with a given expect value. :param expected_speed: Expect FAN speed percentage. :return: True if match else False. """ pass class SingleFanMocker(BaseMocker): """ Single FAN mocker. Vendor should implement this class to provide a FAN mocker. This class could mock speed, presence/absence for one FAN, check LED color and other information. """ def is_fan_removable(self): """ :return: True if FAN is removable else False """ pass def mock_normal(self): """ Change the mocked FAN status to 'Present' and normal speed. :return: """ pass def mock_absence(self): """ Change the mocked FAN status to 'Not Present'. :return: """ pass def mock_presence(self): """ Change the mocked FAN status to 'Present' :return: """ pass def mock_status(self, status): """ Change the mocked FAN status to good or bad :param status: bool value indicate the target status of the FAN. :return: """ pass def mock_normal_speed(self): """ Change the mocked FAN speed to a normal value. :return: """ pass def mock_under_speed(self): """ Change the mocked FAN speed to slower than target speed and exceed speed tolerance. :return: """ pass def mock_over_speed(self): """ Change the mocked FAN speed to faster than target speed and exceed speed tolerance. :return: """ pass class ThermalStatusMocker(BaseMocker): """ Thermal status mocker. Vendor should implement this class to provide a Thermal data mocker. This class could mock temperature, high threshold, high critical threshold and so on for all FANs and check the actual data equal to the mocked data. """ def check_thermal_algorithm_status(self, expected_status): """ Check thermal control algorithm status equal to the given value. :param expected_status: Expected thermal control status. True means enable, false means disable. :return: True if match else False. """ pass def check_cli_output_with_mocker(dut, mocker_object, command, max_wait_time, key_index=0): """ Check the command line output matches the mocked data. :param dut: DUT object representing a SONiC switch under test. :param mocker_object: A mocker instance. :param command: The command to be executed. E.g, 'show platform fan' :param max_wait_time: Max wait time. :return: True if the actual data matches the mocked data. """ time.sleep(max_wait_time) result = dut.show_and_parse(command) assert len(result) > 0, "Run and parse output of command '{}' failed".format(command) return mocker_object.check_result(result) def check_thermal_algorithm_status(dut, mocker_factory, expected_status): """ Check thermal control algorithm status. :param dut: DUT object representing a SONiC switch under test. :param mocker_factory: Mocker factory. :param expected_status: Expect thermal control algorithm status. :return: True if actual thermal control status match expect value. """ thermal_mocker = mocker_factory(dut, 'ThermalStatusMocker') if thermal_mocker is not None: return thermal_mocker.check_thermal_algorithm_status(expected_status) return True # if vendor doesn't provide a thermal mocker, ignore this check by return True. def restart_thermal_control_daemon(dut): """ Restart thermal control daemon by killing it and waiting supervisord to restart it automatically. :param dut: DUT object representing a SONiC switch under test. :return: """ logging.info('Restarting thermal control daemon...') find_thermalctld_pid_cmd = 'docker exec -i pmon bash -c \'pgrep -f thermalctld\' | sort' output = dut.shell(find_thermalctld_pid_cmd) assert output["rc"] == 0, "Run command '%s' failed" % find_thermalctld_pid_cmd assert len(output["stdout_lines"]) == 2, "There should be 2 thermalctld process" pid_0 = int(output["stdout_lines"][0].strip()) pid_1 = int(output["stdout_lines"][1].strip()) # find and kill the parent process pid_to_kill = pid_0 if pid_0 < pid_1 else pid_1 logging.info('Killing old thermal control daemon with pid: {}'.format(pid_to_kill)) kill_thermalctld_cmd = 'docker exec -i pmon bash -c \'kill {}\''.format(pid_to_kill) output = dut.command(kill_thermalctld_cmd) # kill thermalctld and wait supervisord auto reboot thermalctld assert output["rc"] == 0, "Run command '%s' failed" % kill_thermalctld_cmd # make sure thermalctld has restarted max_wait_time = 30 while max_wait_time > 0: max_wait_time -= 1 output = dut.shell(find_thermalctld_pid_cmd) assert output["rc"] == 0, "Run command '%s' failed" % find_thermalctld_pid_cmd if len(output["stdout_lines"]) != 2: time.sleep(1) continue new_pid_0 = int(output["stdout_lines"][0].strip()) new_pid_1 = int(output["stdout_lines"][1].strip()) parent_pid = new_pid_0 if new_pid_0 < new_pid_1 else new_pid_1 if parent_pid == pid_to_kill: logging.info('Old thermal control daemon is still alive, waiting...') time.sleep(1) continue else: logging.info('New pid of thermal control daemon is {}'.format(parent_pid)) return # try restore by config reload... config_reload(dut) assert 0, 'Wait thermal control daemon restart failed' class ThermalPolicyFileContext: """ Context class to help replace thermal control policy file and restore it automatically. """ def __init__(self, dut, src): """ Constructor of ThermalPolicyFileContext. :param dut: DUT object representing a SONiC switch under test. :param src: Local policy file path. """ self.dut = dut self.src = src platform_str = dut.facts['platform'] self.thermal_policy_file_path = DUT_THERMAL_POLICY_FILE.format(platform_str) self.thermal_policy_file_backup_path = DUT_THERMAL_POLICY_BACKUP_FILE.format(platform_str) def __enter__(self): """ Back up original thermal control policy file and replace it with the given one. Restart thermal control daemon to make it effect. :return: """ self.dut.command('mv -f {} {}'.format(self.thermal_policy_file_path, self.thermal_policy_file_backup_path)) self.dut.copy(src=os.path.join(FILES_DIR, self.src), dest=self.thermal_policy_file_path) restart_thermal_control_daemon(self.dut) def __exit__(self, exc_type, exc_val, exc_tb): """ Restore original thermal control policy file. Restart thermal control daemon to make it effect. :param exc_type: Not used. :param exc_val: Not used. :param exc_tb: Not used. :return: """ self.dut.command('mv -f {} {}'.format(self.thermal_policy_file_backup_path, self.thermal_policy_file_path)) restart_thermal_control_daemon(self.dut)
[ 11748, 18931, 198, 11748, 640, 198, 11748, 28686, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 5254, 13, 11321, 13, 315, 2410, 1330, 4043, 62, 28446, 198, 6738, 5254, 13, 11321, 13, 11250, 62, 260, 2220, 1330, 4566, 62, 260, 2220, 19...
2.515376
4,585
# coding=utf-8 # Copyright 2019 The Tensor2Tensor Authors. # # 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. """Diet variables are much more memory-efficient than regular variables. Using diet variables, we can reduce memory overhead per parameter from 16 bytes to 2 bytes, allowing for up to 4B parameters per GPU. Functions that build subgraphs with variables can be made to use diet variables by using the fn_with_diet_vars decorator. """ from collections import defaultdict import copy import math from tensor2tensor.layers import common_layers from tensor2tensor.utils.hparam import HParams import tensorflow as tf def diet_adam_optimizer_params(): """Default hyperparameters for a DietAdamOptimizer. Returns: a hyperparameters object. """ return HParams( quantize=True, # use 16-bit fixed-point quantization_scale=10.0 / tf.int16.max, optimizer="DietAdam", learning_rate=1.0, learning_rate_warmup_steps=2000, learning_rate_decay_scheme="noam", # "noam" or "none" epsilon=1e-10, beta1=0.0, # we can save memory if beta1=0 beta2=0.98, factored_second_moment_accumulator=True, # this saves memory ) def diet_expert(x, hidden_size, params): """A two-layer feed-forward network with relu activation on hidden layer. Uses diet variables. Recomputes hidden layer on backprop to save activation memory. Args: x: a Tensor with shape [batch, io_size] hidden_size: an integer params: a diet variable HParams object. Returns: a Tensor with shape [batch, io_size] """ @fn_with_diet_vars(params) return diet_expert_internal(x) class DietVariableOptimizer(object): """Base class for Diet variable optimizers.""" @property @property class DietAdamOptimizer(DietVariableOptimizer): """A memory efficient optimizer for memory-efficient variables. We employ the following techniques: - 16-bit fixed-point quantization - inline updates during backprop, instead of through the optimizer. This keeps the gradients from staying around in memory. - momentum is optional - saves a slot if it is off (beta1=0.0). - "factored second-moment accumulator" (keep row-wise and col-wise averages instead of full accumulator) - tighter control over operation ordering to make sure that only a small portion of the decompressed variables and of the variable gradients are resident in memory at any given time. All together these techniques reduce the memory footprint per parameter to a little over 2 bytes, allowing for roughly 4B parameters per GPU. This is roughly an 8x improvement over the naive version. Usage: Diet variables should be created with the DietAdamOptimizer.get_variable() method. The resulting variables have extra fields pointing to the optimizer and to the accumulator slots. The variable is kept in quantized form, so you need to call var.optimizer.dequantize(var) to get the value. The variables are created with trainable=False, so that they will not be optimized by an ordinary optimizer. Instead, the user is responsible for making sure that var.optimizer.update(var, grad) is called during backprop. The reason for this inline update is to avoid keeping around the gradients for all variables at once. This is done with the clever use of defuns and control dependencies. See diet_expert() for an example of how all of this is done. To facilitate fixed-point quantization and to make it easier to choose a learning rate, all variables are initialized with unit normal initialization. If you want smaller values, downscale on the outside. """ def create_slots(self, var): """Create the factorized Adam accumulators for diet variables.""" params = self.params shape = var.get_shape().as_list() if not hasattr(params, "slots"): params.slots = defaultdict(dict) name = var.op.name slots = params.slots[name] if params.factored_second_moment_accumulator and len(shape) == 2: slots["adam_vr"] = tf.get_variable( name + "_adam_vr", [shape[0], 1], trainable=False, initializer=tf.zeros_initializer()) slots["adam_vc"] = tf.get_variable( name + "_adam_vc", [1, shape[1]], trainable=False, initializer=tf.zeros_initializer()) else: slots["adam_v"] = tf.get_variable( name + "_adam_v", shape, trainable=False, initializer=tf.zeros_initializer()) if params.beta1 != 0.0: slots["adam_m"] = tf.get_variable( name + "_adam_m", shape, trainable=False, initializer=tf.zeros_initializer()) def update_variable(self, var, grad_var): """Update the variable and its slots.""" params = self.params global_step = tf.to_float(self.global_step) + 1 # compute learning rate lrate = params.learning_rate if params.learning_rate_decay_scheme == "noam": lrate *= tf.minimum(global_step * params.learning_rate_warmup_steps**-1.5, global_step**-0.5) else: assert params.learning_rate_decay_scheme == "none" lrate *= tf.minimum(global_step / params.learning_rate_warmup_steps, 1.0) # compute adjustment due to second moment slots = params.slots[var.op.name] grad_squared = tf.square(grad_var) beta2_pow = tf.pow(params.beta2, global_step) if params.factored_second_moment_accumulator and len(var.shape) == 2: vr_update = tf.assign(slots["adam_vr"], slots["adam_vr"] * params.beta2 + tf.reduce_mean(grad_squared, 1, keepdims=True) * (1.0 - params.beta2)) vc_update = tf.assign(slots["adam_vc"], slots["adam_vc"] * params.beta2 + tf.reduce_mean(grad_squared, 0, keepdims=True) * (1.0 - params.beta2)) with tf.control_dependencies([vr_update, vc_update]): vr = tf.sqrt(slots["adam_vr"] / (1.0 - beta2_pow)) + params.epsilon vc = tf.sqrt(slots["adam_vc"] / (1.0 - beta2_pow)) + params.epsilon vc /= tf.reduce_mean(vc) denom = vr * vc else: v_update = tf.assign(slots["adam_v"], slots["adam_v"] * params.beta2 + grad_squared * (1.0 - params.beta2)) with tf.control_dependencies([v_update]): denom = tf.sqrt(slots["adam_v"] / (1.0 - beta2_pow)) + params.epsilon # compute momentum if applicable if params.beta1 != 0.0: m_update = tf.assign(slots["adam_m"], slots["adam_m"] * params.beta1 + grad_var * (1.0 - params.beta1)) with tf.control_dependencies([m_update]): grad_var = slots["adam_m"] # update var subtrahend = lrate * grad_var / denom new_val = _quantize(_dequantize(var, params) - subtrahend, params) return tf.assign(var, new_val) def _quantize(x, params, randomize=True): """Quantize x according to params, optionally randomizing the rounding.""" if not params.quantize: return x if not randomize: return tf.bitcast( tf.cast(x / params.quantization_scale, tf.int16), tf.float16) abs_x = tf.abs(x) sign_x = tf.sign(x) y = abs_x / params.quantization_scale y = tf.floor(y + tf.random_uniform(common_layers.shape_list(x))) y = tf.minimum(y, tf.int16.max) * sign_x q = tf.bitcast(tf.cast(y, tf.int16), tf.float16) return q def _dequantize(q, params): """Dequantize q according to params.""" if not params.quantize: return q return tf.to_float(tf.bitcast(q, tf.int16)) * params.quantization_scale def make_diet_var_getter(params): """Create a custom variable getter for diet variables according to params.""" def diet_var_initializer(shape, dtype, partition_info=None): """Initializer for a diet variable.""" del dtype del partition_info with common_layers.fn_device_dependency("diet_init") as out_deps: float_range = math.sqrt(3) ret = tf.random_uniform(shape, -float_range, float_range) if params.quantize: ret = _quantize(ret, params, randomize=False) out_deps.append(ret) return ret def diet_var_getter(getter, **kwargs): """Get diet variable and return it dequantized.""" if params.quantize: kwargs["dtype"] = tf.float16 kwargs["initializer"] = diet_var_initializer kwargs["trainable"] = False base_var = getter(**kwargs) dequantized = _dequantize(base_var, params) if not hasattr(params, "dequantized"): params.dequantized = defaultdict(list) params.dequantized[base_var.name].append(dequantized) return dequantized return diet_var_getter def _fn_with_diet_vars(fn, args, params): """Call function with args; use diet variables according to params.""" vs_ctr = [] def grad_fn(inputs, variables, outputs, output_grads): """Custom gradient function.""" del outputs # recomputing below with common_layers.fn_device_dependency("diet_grad", output_grads[0].device) as out_dep: with tf.variable_scope(vs_ctr[0], reuse=True): outputs = fn(*inputs) variables = [common_layers.underlying_variable_ref(v) for v in variables] dequantized_variables = [ params.dequantized[v.name][-1] for v in variables ] grads = tf.gradients(outputs, inputs + dequantized_variables, output_grads) grad_inputs = grads[:len(inputs)] grad_variables = grads[len(inputs):] opt = _create_diet_optimizer(params) # Apply grad_variables here var_updates = [] for v, dv in zip(variables, grad_variables): with tf.variable_scope(vs_ctr[0].name): opt.create_slots(v) update_op = opt.update_variable(v, dv) var_updates.append(update_op) with tf.control_dependencies(var_updates): grad_inputs = [tf.identity(dx) for dx in grad_inputs] out_dep.append(grad_inputs) return grad_inputs, [None] * len(variables) @common_layers.fn_with_custom_grad(grad_fn, use_global_vars=True) with common_layers.fn_device_dependency("diet_forward", args[0].device) as out_dep: outputs = forward(*args) out_dep.append(outputs) return outputs def fn_with_diet_vars(params): """Decorator for graph-building function to use diet variables.""" params = copy.copy(params) return dec
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 13130, 383, 309, 22854, 17, 51, 22854, 46665, 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, ...
2.565328
4,309
import os import torch import argparse import numpy as np import nibabel as nib import utils_segmentation as utils from matplotlib import pyplot as plt from dipy.align.reslice import reslice from nets.localization_network import LocalizationNet from nets.labelling_network import LabellingNet from nets.segmentation_network import SegmentationNet from helper import reorient_nib if __name__ == '__main__': parser = argparse.ArgumentParser(description='Spine Segmentation Pipeline') parser.add_argument('--model_dir', default='models') parser.add_argument('--pat_dir', default='sub-kypho005/post_fracture/ct.nii.gz') parser.add_argument('--save_dir', default='sub-kypho005/post_fracture/mask_auto.nii.gz') args = parser.parse_args() args_dict = vars(args) segment = SpineSegmentation(args_dict['model_dir'], args_dict['pat_dir'], args_dict['save_dir']) _ = segment.apply()
[ 11748, 28686, 198, 11748, 28034, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 33272, 9608, 355, 33272, 198, 11748, 3384, 4487, 62, 325, 5154, 341, 355, 3384, 4487, 198, 6738, 2603, 29487, 8019, 1330, 12972, 294...
2.951299
308
# Copyright 2021 The FedLearner 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. # coding: utf-8 import tarfile
[ 2, 15069, 33448, 383, 10169, 14961, 1008, 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...
3.792899
169
# coding=utf-8 import os import re import codecs from utils import create_dico, create_mapping, zero_digits from utils import iob2, iob_iobes import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) import numpy as np def load_sentences(path, lower, zeros): """ Load sentences. A line must contain at least a word and its tag. Sentences are separated by empty lines. """ sentences = [] sentence = [] max_sentence_length = 0 max_word_length = 0 for line in codecs.open(path, 'r', 'utf8'): line = zero_digits(line.rstrip()) if zeros else line.rstrip() if not line: if len(sentence) > 0: if 'DOCSTART' not in sentence[0][0]: # print sentence # sys.exit() sentences.append(sentence) if len(sentence) > max_sentence_length: max_sentence_length = len(sentence) sentence = [] else: tokens = line.split() assert len(tokens) >= 2 sentence.append(tokens) if len(tokens[0]) > max_word_length: max_word_length = len(tokens[0]) if len(sentence) > 0: if 'DOCSTART' not in sentence[0][0]: sentences.append(sentence) if len(sentence) > max_sentence_length: max_sentence_length = len(sentence) return sentences, max_sentence_length, max_word_length def update_tag_scheme(sentences, tag_scheme): """ Check and update sentences tagging scheme to IOB2. Only IOB1 and IOB2 schemes are accepted. """ for i, s in enumerate(sentences): tags = [w[-1] for w in s] # Check that tags are given in the IOB format if not iob2(tags): s_str = '\n'.join(' '.join(w) for w in s) print s_str.encode("utf8") raise Exception('Sentences should be given in IOB format! ' + 'Please check sentence %i:\n%s' % (i, s_str)) if tag_scheme == 'iob': # If format was IOB1, we convert to IOB2 for word, new_tag in zip(s, tags): word[-1] = new_tag elif tag_scheme == 'iobes': new_tags = iob_iobes(tags) for word, new_tag in zip(s, new_tags): word[-1] = new_tag else: raise Exception('Unknown tagging scheme!') def word_mapping(sentences, lower): """ Create a dictionary and a mapping of words, sorted by frequency. """ # words = [[(" ".join(x[0:2])).lower() if lower else " ".join(x[0:2]) for x in s] for s in sentences] words = [[x[0].lower() if lower else x[0] for x in s] for s in sentences] # TODO: only roots version, but this effectively damages char embeddings. # words = [[x[1].split("+")[0].lower() if lower else x[1].split("+")[0] for x in s] for s in sentences] dico = create_dico(words) dico['<UNK>'] = 10000000 word_to_id, id_to_word = create_mapping(dico) print "Found %i unique words (%i in total)" % ( len(dico), sum(len(x) for x in words) ) return dico, word_to_id, id_to_word def char_mapping(sentences): """ Create a dictionary and mapping of characters, sorted by frequency. """ chars = ["".join([w[0] + "".join(w[2:-1]) for w in s]) for s in sentences] chars.append("+") chars.append("*") dico = create_dico(chars) char_to_id, id_to_char = create_mapping(dico) print "Found %i unique characters" % len(dico) return dico, char_to_id, id_to_char def tag_mapping(sentences): """ Create a dictionary and a mapping of tags, sorted by frequency. """ tags = [[word[-1] for word in s] for s in sentences] dico = create_dico(tags) tag_to_id, id_to_tag = create_mapping(dico) print "Found %i unique named entity tags" % len(dico) return dico, tag_to_id, id_to_tag def morpho_tag_mapping(sentences, morpho_tag_type='wo_root', morpho_tag_column_index=1, joint_learning=False): """ Create a dictionary and a mapping of tags, sorted by frequency. """ if morpho_tag_type == 'char': morpho_tags = ["".join([w[morpho_tag_column_index] for w in s]) for s in sentences] morpho_tags += [ww for ww in w[2:-1] for w in s for s in sentences] else: morpho_tags = extract_morpho_tags_ordered(morpho_tag_type, sentences, morpho_tag_column_index, joint_learning=joint_learning) ## TODO: xxx # print morpho_tags #morpho_tags = [[word[1].split("+") for word in s] for s in sentences] # print morpho_tags morpho_tags.append(["*UNKNOWN*"]) dico = create_dico(morpho_tags) # print dico morpho_tag_to_id, id_to_morpho_tag = create_mapping(dico) print morpho_tag_to_id print "Found %i unique morpho tags" % len(dico) return dico, morpho_tag_to_id, id_to_morpho_tag def cap_feature(s): """ Capitalization feature: 0 = low caps 1 = all caps 2 = first letter caps 3 = one capital (not first letter) """ if is_number(s): return 0 elif sum([(str(digit) in s) for digit in range(0, 10)]) > 0: if "'" in s: return 1 + cap_characterization(s) else: return 1 + 4 + cap_characterization(s) else: if "'" in s: return 1 + 8 + cap_characterization(s) else: return 1 + 12 + cap_characterization(s) def prepare_sentence(str_words, word_to_id, char_to_id, lower=False): """ Prepare a sentence for evaluation. """ words = [word_to_id[f(w) if f(w) in word_to_id else '<UNK>'] for w in str_words] chars = [[char_to_id[c] for c in w if c in char_to_id] for w in str_words] caps = [cap_feature(w) for w in str_words] return { 'str_words': str_words, 'words': words, 'chars': chars, 'caps': caps } def prepare_dataset(sentences, word_to_id, char_to_id, tag_to_id, morpho_tag_to_id, lower=False, morpho_tag_dimension=0, morpho_tag_type='wo_root', morpho_tag_column_index=1): """ Prepare the dataset. Return a list of lists of dictionaries containing: - word indexes - word char indexes - tag indexes """ data = [] for s in sentences: str_words = [w[0] for w in s] words = [word_to_id[f(w) if f(w) in word_to_id else '<UNK>'] for w in str_words] # Skip characters that are not in the training set chars = [[char_to_id[c] for c in w if c in char_to_id] for w in str_words] caps = [cap_feature(w) for w in str_words] tags = [tag_to_id[w[-1]] for w in s] if morpho_tag_dimension > 0: if morpho_tag_type == 'char': str_morpho_tags = [w[morpho_tag_column_index] for w in s] morpho_tags = [[morpho_tag_to_id[c] for c in str_morpho_tag if c in morpho_tag_to_id] for str_morpho_tag in str_morpho_tags] else: morpho_tags_in_the_sentence = \ extract_morpho_tags_from_one_sentence_ordered(morpho_tag_type, [], s, morpho_tag_column_index, joint_learning=False) morpho_tags = [[morpho_tag_to_id[morpho_tag] for morpho_tag in ww if morpho_tag in morpho_tag_to_id] for ww in morpho_tags_in_the_sentence] # for now we ignore different schemes we did in previous morph. tag parses. morph_analyzes_tags = [[map(f_morpho_tag_to_id, analysis.split("+")[1:]) if analysis.split("+")[1:] else [morpho_tag_to_id["*UNKNOWN*"]] for analysis in w[2:-1]] for w in s] morph_analyzes_roots = [[map(f_char_to_id, list(analysis.split("+")[0])) if list(analysis.split("+")[0]) else [char_to_id["+"]] for analysis in w[2:-1]] for w in s] morph_analysis_from_NER_data = [w[morpho_tag_column_index] for w in s] morph_analyzes_from_FST_unprocessed = [w[2:-1] for w in s] golden_analysis_indices = [] for w_idx, w in enumerate(s): found = False try: golden_analysis_idx = \ morph_analyzes_from_FST_unprocessed[w_idx]\ .index(morph_analysis_from_NER_data[w_idx]) found = True except ValueError as e: # step 1 pass if not found: try: golden_analysis_idx = \ map(remove_Prop_and_lower, morph_analyzes_from_FST_unprocessed[w_idx])\ .index(remove_Prop_and_lower(morph_analysis_from_NER_data[w_idx])) found = True except ValueError as e: pass if not found: if len(morph_analyzes_from_FST_unprocessed[w_idx]) == 1: golden_analysis_idx = 0 else: # WE expect that this never happens in gungor.ner.14.* files as they have been processed for unfound golden analyses import random golden_analysis_idx = random.randint(0, len(morph_analyzes_from_FST_unprocessed[w_idx])-1) if golden_analysis_idx >= len(morph_analyzes_from_FST_unprocessed[w_idx]) or \ golden_analysis_idx < 0 or \ golden_analysis_idx >= len(morph_analyzes_roots[w_idx]): logging.error("BEEP at golden analysis idx") golden_analysis_indices.append(golden_analysis_idx) data_item = { 'str_words': str_words, 'word_ids': words, 'char_for_ids': chars, 'char_lengths': [len(char) for char in chars], 'cap_ids': caps, 'tag_ids': tags, 'morpho_analyzes_tags': morph_analyzes_tags, 'morpho_analyzes_roots': morph_analyzes_roots, 'golden_morph_analysis_indices': golden_analysis_indices, 'sentence_lengths': len(s), 'max_word_length_in_this_sample': max([len(x) for x in chars]) } if morpho_tag_dimension > 0: data_item['morpho_tag_ids'] = morpho_tags data.append(data_item) logging.info("Sorting the dataset by sentence length..") data_sorted_by_sentence_length = sorted(data, key=lambda x: x['sentence_lengths']) stats = [[x['sentence_lengths'], x['max_word_length_in_this_sample'], x['char_lengths']] for x in data] n_unique_words = set() for x in data: for word_id in x['word_ids']: n_unique_words.add(word_id) n_unique_words = len(n_unique_words) n_buckets = min([9, len(sentences)]) print "n_sentences: %d" % len(sentences) n_samples_to_be_bucketed = len(sentences)/n_buckets print "n_samples_to_be_binned: %d" % n_samples_to_be_bucketed buckets = [] for bin_idx in range(n_buckets+1): logging.info("Forming bin %d.." % bin_idx) data_to_be_bucketed = data_sorted_by_sentence_length[n_samples_to_be_bucketed*(bin_idx):n_samples_to_be_bucketed*(bin_idx+1)] if len(data_to_be_bucketed) == 0: continue buckets.append(data_to_be_bucketed) return buckets, stats, n_unique_words, data def augment_with_pretrained(dictionary, ext_emb_path, words): """ Augment the dictionary with words that have a pretrained embedding. If `words` is None, we add every word that has a pretrained embedding to the dictionary, otherwise, we only add the words that are given by `words` (typically the words in the development and test sets.) """ print 'Loading pretrained embeddings from %s...' % ext_emb_path assert os.path.isfile(ext_emb_path) # Load pretrained embeddings from file pretrained = set([ line.split()[0].strip() for line in codecs.open(ext_emb_path, 'r', 'utf-8') if len(ext_emb_path) > 0 ]) # We either add every word in the pretrained file, # or only words given in the `words` list to which # we can assign a pretrained embedding if words is None: for word in pretrained: if word not in dictionary: dictionary[word] = 0 else: for word in words: if any(x in pretrained for x in [ word, word.lower(), re.sub('\d', '0', word.lower()) ]) and word not in dictionary: dictionary[word] = 0 word_to_id, id_to_word = create_mapping(dictionary) return dictionary, word_to_id, id_to_word
[ 2, 19617, 28, 40477, 12, 23, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 40481, 82, 198, 6738, 3384, 4487, 1330, 2251, 62, 67, 3713, 11, 2251, 62, 76, 5912, 11, 6632, 62, 12894, 896, 198, 6738, 3384, 4487, 1330, 1312, 672, 17, ...
2.048934
6,376
""" Utilities for fuzzing non-routing configuration. This is the counterpart to interconnect.py """ import threading import tiles import libpyprjoxide import fuzzconfig def fuzz_word_setting(config, name, length, get_sv_substs, desc=""): """ Fuzz a multi-bit setting, such as LUT initialisation :param config: FuzzConfig instance containing target device and tile of interest :param name: name of the setting to store in the database :param length: number of bits in the setting :param get_sv_substs: a callback function, that is called with an array of bits to create a design with that setting """ prefix = "thread{}_".format(threading.get_ident()) baseline = config.build_design(config.sv, get_sv_substs([False for _ in range(length)]), prefix) fz = libpyprjoxide.Fuzzer.word_fuzzer(fuzzconfig.db, baseline, set(config.tiles), name, desc, length, baseline) for i in range(length): i_bit = config.build_design(config.sv, get_sv_substs([(_ == i) for _ in range(length)]), prefix) fz.add_word_sample(fuzzconfig.db, i, i_bit) fz.solve(fuzzconfig.db) def fuzz_enum_setting(config, empty_bitfile, name, values, get_sv_substs, include_zeros=True, assume_zero_base=False, min_cover={}, desc=""): """ Fuzz a setting with multiple possible values :param config: FuzzConfig instance containing target device and tile of interest :param empty_bitfile: a baseline empty bitstream to diff against :param name: name of the setting to store in the database :param values: list of values taken by the enum :param get_sv_substs: a callback function, :param include_zeros: if set, bits set to zero are not included in db. Needed for settings such as CEMUX which share bits with routing muxes to prevent conflicts. :param assume_zero_base: if set, the baseline bitstream is considered the all-zero bitstream :param min_cover: for each setting in this, run with each value in the array that setting points to, to get a minimal bit set """ prefix = "thread{}_".format(threading.get_ident()) fz = libpyprjoxide.Fuzzer.enum_fuzzer(fuzzconfig.db, empty_bitfile, set(config.tiles), name, desc, include_zeros, assume_zero_base) for opt in values: if opt in min_cover: for c in min_cover[opt]: opt_bit = config.build_design(config.sv, get_sv_substs((opt, c)), prefix) fz.add_enum_sample(fuzzconfig.db, opt, opt_bit) else: opt_bit = config.build_design(config.sv, get_sv_substs(opt), prefix) fz.add_enum_sample(fuzzconfig.db, opt, opt_bit) fz.solve(fuzzconfig.db) def fuzz_ip_word_setting(config, name, length, get_sv_substs, desc="", default=None): """ Fuzz a multi-bit IP setting with an optimum number of bitstreams :param config: FuzzConfig instance containing target device and tile of interest :param name: name of the setting to store in the database :param length: number of bits in the setting :param get_sv_substs: a callback function, that is called with an array of bits to create a design with that setting """ prefix = "thread{}_".format(threading.get_ident()) inverted_mode = False if default is not None: for i in range(0, length.bit_length()): bits = [(j >> i) & 0x1 == 0 for j in range(length)] if default == bits: inverted_mode = True break baseline = config.build_design(config.sv, get_sv_substs([inverted_mode for _ in range(length)]), prefix) ipcore, iptype = config.tiles[0].split(":") fz = libpyprjoxide.IPFuzzer.word_fuzzer(fuzzconfig.db, baseline, ipcore, iptype, name, desc, length, inverted_mode) for i in range(0, length.bit_length()): bits = [(j >> i) & 0x1 == (1 if inverted_mode else 0) for j in range(length)] i_bit = config.build_design(config.sv, get_sv_substs(bits), prefix) fz.add_word_sample(fuzzconfig.db, bits, i_bit) fz.solve(fuzzconfig.db) def fuzz_ip_enum_setting(config, empty_bitfile, name, values, get_sv_substs, desc=""): """ Fuzz a multi-bit IP enum with an optimum number of bitstreams :param config: FuzzConfig instance containing target device and tile of interest :param empty_bitfile: a baseline empty bitstream to diff against :param name: name of the setting to store in the database :param values: list of values taken by the enum :param get_sv_substs: a callback function, """ prefix = "thread{}_".format(threading.get_ident()) ipcore, iptype = config.tiles[0].split(":") fz = libpyprjoxide.IPFuzzer.enum_fuzzer(fuzzconfig.db, empty_bitfile, ipcore, iptype, name, desc) for opt in values: opt_bit = config.build_design(config.sv, get_sv_substs(opt), prefix) fz.add_enum_sample(fuzzconfig.db, opt, opt_bit) fz.solve(fuzzconfig.db)
[ 37811, 198, 18274, 2410, 329, 26080, 278, 1729, 12, 81, 13660, 8398, 13, 770, 318, 262, 11283, 284, 987, 8443, 13, 9078, 198, 37811, 198, 198, 11748, 4704, 278, 198, 11748, 19867, 198, 11748, 9195, 9078, 1050, 73, 28885, 198, 11748, 2...
2.712548
1,809
import redis pool = redis.ConnectionPool(host='127.0.0.1', port=6379) redisCon = redis.Redis(connection_pool=pool, charset='utf-8')
[ 11748, 2266, 271, 201, 198, 201, 198, 7742, 796, 2266, 271, 13, 32048, 27201, 7, 4774, 11639, 16799, 13, 15, 13, 15, 13, 16, 3256, 2493, 28, 21, 29088, 8, 201, 198, 445, 271, 3103, 796, 2266, 271, 13, 7738, 271, 7, 38659, 62, 77...
2.403509
57
from pymote import * from networkx.generators.classic import star_graph,balanced_tree,barbell_graph from networkx.generators.social import florentine_families_graph from networkx import Graph, is_connected,draw from networkx.algorithms.operators import union_all, disjoint_union_all try: from matplotlib import pyplot as plt except ImportError: raise ImportError("Matplotlib required for show()") from pymote import energy en = energy.EnergyModel() en.TR_RATE = 200 print en.TR_RATE, en, en.energy, en.increase_energy(),\ en.decrease_tx_energy(100), en.decrease_rx_energy(100), en from pymote import mobility en = mobility.MobilityModel(mobile_type=1) #en.HEADING = -en.HEADING print en.VELOCITY, en.HEADING, en, en.drift(), en.have_moved() from pymote import propagation en = propagation.PropagationModel(propagation_type=1) en2 = propagation.PropagationModel(propagation_type=1) pr = en.get_power_ratio(d=405, p_tx=1) print en, pr, propagation.PropagationModel.pw_to_dbm(pr), en.is_rx_ok(), \ en.free_space_distance(p_rx=2.354466826905901e-09) print en2, en2.cross_over_distance(), en2.get_power_ratio(d=205), \ propagation.PropagationModel.dbm_to_pw(11.6), en2.two_ray_ground_distance() en2 = propagation.PropagationModel(propagation_type=2) pr = en2.shadowing(d=405) print en2, pr, propagation.PropagationModel.pw_to_dbm(pr), en2.shadowing_rssi(d=405) propagation.PropagationModel.P_TX = 0.0144 en2 = propagation.PropagationModel(propagation_type=2) pr = en2.shadowing(d=405) print en2, pr, propagation.PropagationModel.pw_to_dbm(pr), en2.shadowing_rssi(d=405)
[ 6738, 279, 4948, 1258, 1330, 1635, 198, 6738, 3127, 87, 13, 8612, 2024, 13, 49421, 1330, 3491, 62, 34960, 11, 27753, 62, 21048, 11, 5657, 7923, 62, 34960, 198, 6738, 3127, 87, 13, 8612, 2024, 13, 14557, 1330, 781, 382, 429, 500, 62,...
2.564388
629
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/devtools/cloudtrace_v2/proto/trace.proto import sys _b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2 from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name="google/devtools/cloudtrace_v2/proto/trace.proto", package="google.devtools.cloudtrace.v2", syntax="proto3", serialized_options=_b( "\n!com.google.devtools.cloudtrace.v2B\nTraceProtoP\001ZGgoogle.golang.org/genproto/googleapis/devtools/cloudtrace/v2;cloudtrace\252\002\025Google.Cloud.Trace.V2\312\002\025Google\\Cloud\\Trace\\V2" ), serialized_pb=_b( '\n/google/devtools/cloudtrace_v2/proto/trace.proto\x12\x1dgoogle.devtools.cloudtrace.v2\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/wrappers.proto\x1a\x17google/rpc/status.proto"\xc5\x0f\n\x04Span\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07span_id\x18\x02 \x01(\t\x12\x16\n\x0eparent_span_id\x18\x03 \x01(\t\x12\x46\n\x0c\x64isplay_name\x18\x04 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x12.\n\nstart_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x42\n\nattributes\x18\x07 \x01(\x0b\x32..google.devtools.cloudtrace.v2.Span.Attributes\x12>\n\x0bstack_trace\x18\x08 \x01(\x0b\x32).google.devtools.cloudtrace.v2.StackTrace\x12\x43\n\x0btime_events\x18\t \x01(\x0b\x32..google.devtools.cloudtrace.v2.Span.TimeEvents\x12\x38\n\x05links\x18\n \x01(\x0b\x32).google.devtools.cloudtrace.v2.Span.Links\x12"\n\x06status\x18\x0b \x01(\x0b\x32\x12.google.rpc.Status\x12?\n\x1bsame_process_as_parent_span\x18\x0c \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x35\n\x10\x63hild_span_count\x18\r \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x1a\xeb\x01\n\nAttributes\x12W\n\rattribute_map\x18\x01 \x03(\x0b\x32@.google.devtools.cloudtrace.v2.Span.Attributes.AttributeMapEntry\x12 \n\x18\x64ropped_attributes_count\x18\x02 \x01(\x05\x1a\x62\n\x11\x41ttributeMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12<\n\x05value\x18\x02 \x01(\x0b\x32-.google.devtools.cloudtrace.v2.AttributeValue:\x02\x38\x01\x1a\xdf\x04\n\tTimeEvent\x12(\n\x04time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12N\n\nannotation\x18\x02 \x01(\x0b\x32\x38.google.devtools.cloudtrace.v2.Span.TimeEvent.AnnotationH\x00\x12S\n\rmessage_event\x18\x03 \x01(\x0b\x32:.google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEventH\x00\x1a\x97\x01\n\nAnnotation\x12\x45\n\x0b\x64\x65scription\x18\x01 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x12\x42\n\nattributes\x18\x02 \x01(\x0b\x32..google.devtools.cloudtrace.v2.Span.Attributes\x1a\xdf\x01\n\x0cMessageEvent\x12M\n\x04type\x18\x01 \x01(\x0e\x32?.google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.Type\x12\n\n\x02id\x18\x02 \x01(\x03\x12\x1f\n\x17uncompressed_size_bytes\x18\x03 \x01(\x03\x12\x1d\n\x15\x63ompressed_size_bytes\x18\x04 \x01(\x03"4\n\x04Type\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x08\n\x04SENT\x10\x01\x12\x0c\n\x08RECEIVED\x10\x02\x42\x07\n\x05value\x1a\x98\x01\n\nTimeEvents\x12\x41\n\ntime_event\x18\x01 \x03(\x0b\x32-.google.devtools.cloudtrace.v2.Span.TimeEvent\x12!\n\x19\x64ropped_annotations_count\x18\x02 \x01(\x05\x12$\n\x1c\x64ropped_message_events_count\x18\x03 \x01(\x05\x1a\xf7\x01\n\x04Link\x12\x10\n\x08trace_id\x18\x01 \x01(\t\x12\x0f\n\x07span_id\x18\x02 \x01(\t\x12;\n\x04type\x18\x03 \x01(\x0e\x32-.google.devtools.cloudtrace.v2.Span.Link.Type\x12\x42\n\nattributes\x18\x04 \x01(\x0b\x32..google.devtools.cloudtrace.v2.Span.Attributes"K\n\x04Type\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x15\n\x11\x43HILD_LINKED_SPAN\x10\x01\x12\x16\n\x12PARENT_LINKED_SPAN\x10\x02\x1a\\\n\x05Links\x12\x36\n\x04link\x18\x01 \x03(\x0b\x32(.google.devtools.cloudtrace.v2.Span.Link\x12\x1b\n\x13\x64ropped_links_count\x18\x02 \x01(\x05"\x8e\x01\n\x0e\x41ttributeValue\x12H\n\x0cstring_value\x18\x01 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableStringH\x00\x12\x13\n\tint_value\x18\x02 \x01(\x03H\x00\x12\x14\n\nbool_value\x18\x03 \x01(\x08H\x00\x42\x07\n\x05value"\x89\x05\n\nStackTrace\x12K\n\x0cstack_frames\x18\x01 \x01(\x0b\x32\x35.google.devtools.cloudtrace.v2.StackTrace.StackFrames\x12\x1b\n\x13stack_trace_hash_id\x18\x02 \x01(\x03\x1a\x9e\x03\n\nStackFrame\x12G\n\rfunction_name\x18\x01 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x12P\n\x16original_function_name\x18\x02 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x12\x43\n\tfile_name\x18\x03 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x12\x13\n\x0bline_number\x18\x04 \x01(\x03\x12\x15\n\rcolumn_number\x18\x05 \x01(\x03\x12:\n\x0bload_module\x18\x06 \x01(\x0b\x32%.google.devtools.cloudtrace.v2.Module\x12H\n\x0esource_version\x18\x07 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x1ap\n\x0bStackFrames\x12\x43\n\x05\x66rame\x18\x01 \x03(\x0b\x32\x34.google.devtools.cloudtrace.v2.StackTrace.StackFrame\x12\x1c\n\x14\x64ropped_frames_count\x18\x02 \x01(\x05"\x8e\x01\n\x06Module\x12@\n\x06module\x18\x01 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x12\x42\n\x08\x62uild_id\x18\x02 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString"@\n\x11TruncatableString\x12\r\n\x05value\x18\x01 \x01(\t\x12\x1c\n\x14truncated_byte_count\x18\x02 \x01(\x05\x42\xaa\x01\n!com.google.devtools.cloudtrace.v2B\nTraceProtoP\x01ZGgoogle.golang.org/genproto/googleapis/devtools/cloudtrace/v2;cloudtrace\xaa\x02\x15Google.Cloud.Trace.V2\xca\x02\x15Google\\Cloud\\Trace\\V2b\x06proto3' ), dependencies=[ google_dot_api_dot_annotations__pb2.DESCRIPTOR, google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, google_dot_protobuf_dot_wrappers__pb2.DESCRIPTOR, google_dot_rpc_dot_status__pb2.DESCRIPTOR, ], ) _SPAN_TIMEEVENT_MESSAGEEVENT_TYPE = _descriptor.EnumDescriptor( name="Type", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.Type", filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name="TYPE_UNSPECIFIED", index=0, number=0, serialized_options=None, type=None, ), _descriptor.EnumValueDescriptor( name="SENT", index=1, number=1, serialized_options=None, type=None ), _descriptor.EnumValueDescriptor( name="RECEIVED", index=2, number=2, serialized_options=None, type=None ), ], containing_type=None, serialized_options=None, serialized_start=1632, serialized_end=1684, ) _sym_db.RegisterEnumDescriptor(_SPAN_TIMEEVENT_MESSAGEEVENT_TYPE) _SPAN_LINK_TYPE = _descriptor.EnumDescriptor( name="Type", full_name="google.devtools.cloudtrace.v2.Span.Link.Type", filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name="TYPE_UNSPECIFIED", index=0, number=0, serialized_options=None, type=None, ), _descriptor.EnumValueDescriptor( name="CHILD_LINKED_SPAN", index=1, number=1, serialized_options=None, type=None, ), _descriptor.EnumValueDescriptor( name="PARENT_LINKED_SPAN", index=2, number=2, serialized_options=None, type=None, ), ], containing_type=None, serialized_options=None, serialized_start=2023, serialized_end=2098, ) _sym_db.RegisterEnumDescriptor(_SPAN_LINK_TYPE) _SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY = _descriptor.Descriptor( name="AttributeMapEntry", full_name="google.devtools.cloudtrace.v2.Span.Attributes.AttributeMapEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="google.devtools.cloudtrace.v2.Span.Attributes.AttributeMapEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="google.devtools.cloudtrace.v2.Span.Attributes.AttributeMapEntry.value", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=_b("8\001"), is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=985, serialized_end=1083, ) _SPAN_ATTRIBUTES = _descriptor.Descriptor( name="Attributes", full_name="google.devtools.cloudtrace.v2.Span.Attributes", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="attribute_map", full_name="google.devtools.cloudtrace.v2.Span.Attributes.attribute_map", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="dropped_attributes_count", full_name="google.devtools.cloudtrace.v2.Span.Attributes.dropped_attributes_count", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[_SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY,], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=848, serialized_end=1083, ) _SPAN_TIMEEVENT_ANNOTATION = _descriptor.Descriptor( name="Annotation", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.Annotation", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="description", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.Annotation.description", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="attributes", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.Annotation.attributes", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1307, serialized_end=1458, ) _SPAN_TIMEEVENT_MESSAGEEVENT = _descriptor.Descriptor( name="MessageEvent", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="type", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.type", index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="id", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.id", index=1, number=2, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="uncompressed_size_bytes", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.uncompressed_size_bytes", index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="compressed_size_bytes", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.compressed_size_bytes", index=3, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[_SPAN_TIMEEVENT_MESSAGEEVENT_TYPE,], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1461, serialized_end=1684, ) _SPAN_TIMEEVENT = _descriptor.Descriptor( name="TimeEvent", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="time", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.time", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="annotation", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.annotation", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="message_event", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.message_event", index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[_SPAN_TIMEEVENT_ANNOTATION, _SPAN_TIMEEVENT_MESSAGEEVENT,], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name="value", full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.value", index=0, containing_type=None, fields=[], ), ], serialized_start=1086, serialized_end=1693, ) _SPAN_TIMEEVENTS = _descriptor.Descriptor( name="TimeEvents", full_name="google.devtools.cloudtrace.v2.Span.TimeEvents", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="time_event", full_name="google.devtools.cloudtrace.v2.Span.TimeEvents.time_event", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="dropped_annotations_count", full_name="google.devtools.cloudtrace.v2.Span.TimeEvents.dropped_annotations_count", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="dropped_message_events_count", full_name="google.devtools.cloudtrace.v2.Span.TimeEvents.dropped_message_events_count", index=2, number=3, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1696, serialized_end=1848, ) _SPAN_LINK = _descriptor.Descriptor( name="Link", full_name="google.devtools.cloudtrace.v2.Span.Link", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="trace_id", full_name="google.devtools.cloudtrace.v2.Span.Link.trace_id", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="span_id", full_name="google.devtools.cloudtrace.v2.Span.Link.span_id", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="type", full_name="google.devtools.cloudtrace.v2.Span.Link.type", index=2, number=3, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="attributes", full_name="google.devtools.cloudtrace.v2.Span.Link.attributes", index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[_SPAN_LINK_TYPE,], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1851, serialized_end=2098, ) _SPAN_LINKS = _descriptor.Descriptor( name="Links", full_name="google.devtools.cloudtrace.v2.Span.Links", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="link", full_name="google.devtools.cloudtrace.v2.Span.Links.link", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="dropped_links_count", full_name="google.devtools.cloudtrace.v2.Span.Links.dropped_links_count", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2100, serialized_end=2192, ) _SPAN = _descriptor.Descriptor( name="Span", full_name="google.devtools.cloudtrace.v2.Span", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="name", full_name="google.devtools.cloudtrace.v2.Span.name", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="span_id", full_name="google.devtools.cloudtrace.v2.Span.span_id", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="parent_span_id", full_name="google.devtools.cloudtrace.v2.Span.parent_span_id", index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="display_name", full_name="google.devtools.cloudtrace.v2.Span.display_name", index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="start_time", full_name="google.devtools.cloudtrace.v2.Span.start_time", index=4, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="end_time", full_name="google.devtools.cloudtrace.v2.Span.end_time", index=5, number=6, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="attributes", full_name="google.devtools.cloudtrace.v2.Span.attributes", index=6, number=7, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="stack_trace", full_name="google.devtools.cloudtrace.v2.Span.stack_trace", index=7, number=8, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="time_events", full_name="google.devtools.cloudtrace.v2.Span.time_events", index=8, number=9, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="links", full_name="google.devtools.cloudtrace.v2.Span.links", index=9, number=10, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="status", full_name="google.devtools.cloudtrace.v2.Span.status", index=10, number=11, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="same_process_as_parent_span", full_name="google.devtools.cloudtrace.v2.Span.same_process_as_parent_span", index=11, number=12, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="child_span_count", full_name="google.devtools.cloudtrace.v2.Span.child_span_count", index=12, number=13, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[ _SPAN_ATTRIBUTES, _SPAN_TIMEEVENT, _SPAN_TIMEEVENTS, _SPAN_LINK, _SPAN_LINKS, ], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=203, serialized_end=2192, ) _ATTRIBUTEVALUE = _descriptor.Descriptor( name="AttributeValue", full_name="google.devtools.cloudtrace.v2.AttributeValue", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="string_value", full_name="google.devtools.cloudtrace.v2.AttributeValue.string_value", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="int_value", full_name="google.devtools.cloudtrace.v2.AttributeValue.int_value", index=1, number=2, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="bool_value", full_name="google.devtools.cloudtrace.v2.AttributeValue.bool_value", index=2, number=3, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name="value", full_name="google.devtools.cloudtrace.v2.AttributeValue.value", index=0, containing_type=None, fields=[], ), ], serialized_start=2195, serialized_end=2337, ) _STACKTRACE_STACKFRAME = _descriptor.Descriptor( name="StackFrame", full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="function_name", full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.function_name", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="original_function_name", full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.original_function_name", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="file_name", full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.file_name", index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="line_number", full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.line_number", index=3, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="column_number", full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.column_number", index=4, number=5, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="load_module", full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.load_module", index=5, number=6, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="source_version", full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.source_version", index=6, number=7, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2461, serialized_end=2875, ) _STACKTRACE_STACKFRAMES = _descriptor.Descriptor( name="StackFrames", full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrames", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="frame", full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrames.frame", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="dropped_frames_count", full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrames.dropped_frames_count", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2877, serialized_end=2989, ) _STACKTRACE = _descriptor.Descriptor( name="StackTrace", full_name="google.devtools.cloudtrace.v2.StackTrace", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="stack_frames", full_name="google.devtools.cloudtrace.v2.StackTrace.stack_frames", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="stack_trace_hash_id", full_name="google.devtools.cloudtrace.v2.StackTrace.stack_trace_hash_id", index=1, number=2, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[_STACKTRACE_STACKFRAME, _STACKTRACE_STACKFRAMES,], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2340, serialized_end=2989, ) _MODULE = _descriptor.Descriptor( name="Module", full_name="google.devtools.cloudtrace.v2.Module", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="module", full_name="google.devtools.cloudtrace.v2.Module.module", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="build_id", full_name="google.devtools.cloudtrace.v2.Module.build_id", index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2992, serialized_end=3134, ) _TRUNCATABLESTRING = _descriptor.Descriptor( name="TruncatableString", full_name="google.devtools.cloudtrace.v2.TruncatableString", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="value", full_name="google.devtools.cloudtrace.v2.TruncatableString.value", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="truncated_byte_count", full_name="google.devtools.cloudtrace.v2.TruncatableString.truncated_byte_count", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3136, serialized_end=3200, ) _SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY.fields_by_name[ "value" ].message_type = _ATTRIBUTEVALUE _SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY.containing_type = _SPAN_ATTRIBUTES _SPAN_ATTRIBUTES.fields_by_name[ "attribute_map" ].message_type = _SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY _SPAN_ATTRIBUTES.containing_type = _SPAN _SPAN_TIMEEVENT_ANNOTATION.fields_by_name[ "description" ].message_type = _TRUNCATABLESTRING _SPAN_TIMEEVENT_ANNOTATION.fields_by_name["attributes"].message_type = _SPAN_ATTRIBUTES _SPAN_TIMEEVENT_ANNOTATION.containing_type = _SPAN_TIMEEVENT _SPAN_TIMEEVENT_MESSAGEEVENT.fields_by_name[ "type" ].enum_type = _SPAN_TIMEEVENT_MESSAGEEVENT_TYPE _SPAN_TIMEEVENT_MESSAGEEVENT.containing_type = _SPAN_TIMEEVENT _SPAN_TIMEEVENT_MESSAGEEVENT_TYPE.containing_type = _SPAN_TIMEEVENT_MESSAGEEVENT _SPAN_TIMEEVENT.fields_by_name[ "time" ].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP _SPAN_TIMEEVENT.fields_by_name["annotation"].message_type = _SPAN_TIMEEVENT_ANNOTATION _SPAN_TIMEEVENT.fields_by_name[ "message_event" ].message_type = _SPAN_TIMEEVENT_MESSAGEEVENT _SPAN_TIMEEVENT.containing_type = _SPAN _SPAN_TIMEEVENT.oneofs_by_name["value"].fields.append( _SPAN_TIMEEVENT.fields_by_name["annotation"] ) _SPAN_TIMEEVENT.fields_by_name[ "annotation" ].containing_oneof = _SPAN_TIMEEVENT.oneofs_by_name["value"] _SPAN_TIMEEVENT.oneofs_by_name["value"].fields.append( _SPAN_TIMEEVENT.fields_by_name["message_event"] ) _SPAN_TIMEEVENT.fields_by_name[ "message_event" ].containing_oneof = _SPAN_TIMEEVENT.oneofs_by_name["value"] _SPAN_TIMEEVENTS.fields_by_name["time_event"].message_type = _SPAN_TIMEEVENT _SPAN_TIMEEVENTS.containing_type = _SPAN _SPAN_LINK.fields_by_name["type"].enum_type = _SPAN_LINK_TYPE _SPAN_LINK.fields_by_name["attributes"].message_type = _SPAN_ATTRIBUTES _SPAN_LINK.containing_type = _SPAN _SPAN_LINK_TYPE.containing_type = _SPAN_LINK _SPAN_LINKS.fields_by_name["link"].message_type = _SPAN_LINK _SPAN_LINKS.containing_type = _SPAN _SPAN.fields_by_name["display_name"].message_type = _TRUNCATABLESTRING _SPAN.fields_by_name[ "start_time" ].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP _SPAN.fields_by_name[ "end_time" ].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP _SPAN.fields_by_name["attributes"].message_type = _SPAN_ATTRIBUTES _SPAN.fields_by_name["stack_trace"].message_type = _STACKTRACE _SPAN.fields_by_name["time_events"].message_type = _SPAN_TIMEEVENTS _SPAN.fields_by_name["links"].message_type = _SPAN_LINKS _SPAN.fields_by_name["status"].message_type = google_dot_rpc_dot_status__pb2._STATUS _SPAN.fields_by_name[ "same_process_as_parent_span" ].message_type = google_dot_protobuf_dot_wrappers__pb2._BOOLVALUE _SPAN.fields_by_name[ "child_span_count" ].message_type = google_dot_protobuf_dot_wrappers__pb2._INT32VALUE _ATTRIBUTEVALUE.fields_by_name["string_value"].message_type = _TRUNCATABLESTRING _ATTRIBUTEVALUE.oneofs_by_name["value"].fields.append( _ATTRIBUTEVALUE.fields_by_name["string_value"] ) _ATTRIBUTEVALUE.fields_by_name[ "string_value" ].containing_oneof = _ATTRIBUTEVALUE.oneofs_by_name["value"] _ATTRIBUTEVALUE.oneofs_by_name["value"].fields.append( _ATTRIBUTEVALUE.fields_by_name["int_value"] ) _ATTRIBUTEVALUE.fields_by_name[ "int_value" ].containing_oneof = _ATTRIBUTEVALUE.oneofs_by_name["value"] _ATTRIBUTEVALUE.oneofs_by_name["value"].fields.append( _ATTRIBUTEVALUE.fields_by_name["bool_value"] ) _ATTRIBUTEVALUE.fields_by_name[ "bool_value" ].containing_oneof = _ATTRIBUTEVALUE.oneofs_by_name["value"] _STACKTRACE_STACKFRAME.fields_by_name["function_name"].message_type = _TRUNCATABLESTRING _STACKTRACE_STACKFRAME.fields_by_name[ "original_function_name" ].message_type = _TRUNCATABLESTRING _STACKTRACE_STACKFRAME.fields_by_name["file_name"].message_type = _TRUNCATABLESTRING _STACKTRACE_STACKFRAME.fields_by_name["load_module"].message_type = _MODULE _STACKTRACE_STACKFRAME.fields_by_name[ "source_version" ].message_type = _TRUNCATABLESTRING _STACKTRACE_STACKFRAME.containing_type = _STACKTRACE _STACKTRACE_STACKFRAMES.fields_by_name["frame"].message_type = _STACKTRACE_STACKFRAME _STACKTRACE_STACKFRAMES.containing_type = _STACKTRACE _STACKTRACE.fields_by_name["stack_frames"].message_type = _STACKTRACE_STACKFRAMES _MODULE.fields_by_name["module"].message_type = _TRUNCATABLESTRING _MODULE.fields_by_name["build_id"].message_type = _TRUNCATABLESTRING DESCRIPTOR.message_types_by_name["Span"] = _SPAN DESCRIPTOR.message_types_by_name["AttributeValue"] = _ATTRIBUTEVALUE DESCRIPTOR.message_types_by_name["StackTrace"] = _STACKTRACE DESCRIPTOR.message_types_by_name["Module"] = _MODULE DESCRIPTOR.message_types_by_name["TruncatableString"] = _TRUNCATABLESTRING _sym_db.RegisterFileDescriptor(DESCRIPTOR) Span = _reflection.GeneratedProtocolMessageType( "Span", (_message.Message,), dict( Attributes=_reflection.GeneratedProtocolMessageType( "Attributes", (_message.Message,), dict( AttributeMapEntry=_reflection.GeneratedProtocolMessageType( "AttributeMapEntry", (_message.Message,), dict( DESCRIPTOR=_SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2" # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.Attributes.AttributeMapEntry) ), ), DESCRIPTOR=_SPAN_ATTRIBUTES, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""A set of attributes, each in the format ``[KEY]:[VALUE]``. Attributes: attribute_map: The set of attributes. Each attribute's key can be up to 128 bytes long. The value can be a string up to 256 bytes, an integer, or the Boolean values ``true`` and ``false``. For example: :: "/instance_id": "my-instance" "/http/user_agent": "" "/http/request_bytes": 300 "abc.com/myattribute": true dropped_attributes_count: The number of attributes that were discarded. Attributes can be discarded because their keys are too long or because there are too many attributes. If this value is 0 then all attributes are valid. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.Attributes) ), ), TimeEvent=_reflection.GeneratedProtocolMessageType( "TimeEvent", (_message.Message,), dict( Annotation=_reflection.GeneratedProtocolMessageType( "Annotation", (_message.Message,), dict( DESCRIPTOR=_SPAN_TIMEEVENT_ANNOTATION, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""Text annotation with a set of attributes. Attributes: description: A user-supplied message describing the event. The maximum length for the description is 256 bytes. attributes: A set of attributes on the annotation. You can have up to 4 attributes per Annotation. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.TimeEvent.Annotation) ), ), MessageEvent=_reflection.GeneratedProtocolMessageType( "MessageEvent", (_message.Message,), dict( DESCRIPTOR=_SPAN_TIMEEVENT_MESSAGEEVENT, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""An event describing a message sent/received between Spans. Attributes: type: Type of MessageEvent. Indicates whether the message was sent or received. id: An identifier for the MessageEvent's message that can be used to match SENT and RECEIVED MessageEvents. It is recommended to be unique within a Span. uncompressed_size_bytes: The number of uncompressed bytes sent or received. compressed_size_bytes: The number of compressed bytes sent or received. If missing assumed to be the same size as uncompressed. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent) ), ), DESCRIPTOR=_SPAN_TIMEEVENT, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""A time-stamped annotation or message event in the Span. Attributes: time: The timestamp indicating the time the event occurred. value: A ``TimeEvent`` can contain either an ``Annotation`` object or a ``MessageEvent`` object, but not both. annotation: Text annotation with a set of attributes. message_event: An event describing a message sent/received between Spans. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.TimeEvent) ), ), TimeEvents=_reflection.GeneratedProtocolMessageType( "TimeEvents", (_message.Message,), dict( DESCRIPTOR=_SPAN_TIMEEVENTS, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""A collection of ``TimeEvent``\ s. A ``TimeEvent`` is a time-stamped annotation on the span, consisting of either user-supplied key:value pairs, or details of a message sent/received between Spans. Attributes: time_event: A collection of ``TimeEvent``\ s. dropped_annotations_count: The number of dropped annotations in all the included time events. If the value is 0, then no annotations were dropped. dropped_message_events_count: The number of dropped message events in all the included time events. If the value is 0, then no message events were dropped. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.TimeEvents) ), ), Link=_reflection.GeneratedProtocolMessageType( "Link", (_message.Message,), dict( DESCRIPTOR=_SPAN_LINK, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""A pointer from the current span to another span in the same trace or in a different trace. For example, this can be used in batching operations, where a single batch handler processes multiple requests from different traces or when the handler receives a request from a different project. Attributes: trace_id: The [TRACE\_ID] for a trace within a project. span_id: The [SPAN\_ID] for a span within a trace. type: The relationship of the current span relative to the linked span. attributes: A set of attributes on the link. You have have up to 32 attributes per link. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.Link) ), ), Links=_reflection.GeneratedProtocolMessageType( "Links", (_message.Message,), dict( DESCRIPTOR=_SPAN_LINKS, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""A collection of links, which are references from this span to a span in the same or different trace. Attributes: link: A collection of links. dropped_links_count: The number of dropped links after the maximum size was enforced. If this value is 0, then no links were dropped. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.Links) ), ), DESCRIPTOR=_SPAN, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""A span represents a single operation within a trace. Spans can be nested to form a trace tree. Often, a trace contains a root span that describes the end-to-end latency, and one or more subspans for its sub-operations. A trace can also contain multiple root spans, or none at all. Spans do not need to be contiguous—there may be gaps or overlaps between spans in a trace. Attributes: name: The resource name of the span in the following format: :: projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] [TRACE\_ID] is a unique identifier for a trace within a project; it is a 32-character hexadecimal encoding of a 16-byte array. [SPAN\_ID] is a unique identifier for a span within a trace; it is a 16-character hexadecimal encoding of an 8-byte array. span_id: The [SPAN\_ID] portion of the span's resource name. parent_span_id: The [SPAN\_ID] of this span's parent span. If this is a root span, then this field must be empty. display_name: A description of the span's operation (up to 128 bytes). Stackdriver Trace displays the description in the {% dynamic print site\_values.console\_name %}. For example, the display name can be a qualified method name or a file name and a line number where the operation is called. A best practice is to use the same display name within an application and at the same call point. This makes it easier to correlate spans in different traces. start_time: The start time of the span. On the client side, this is the time kept by the local machine where the span execution starts. On the server side, this is the time when the server's application handler starts running. end_time: The end time of the span. On the client side, this is the time kept by the local machine where the span execution ends. On the server side, this is the time when the server application handler stops running. attributes: A set of attributes on the span. You can have up to 32 attributes per span. stack_trace: Stack trace captured at the start of the span. time_events: A set of time events. You can have up to 32 annotations and 128 message events per span. links: Links associated with the span. You can have up to 128 links per Span. status: An optional final status for this span. same_process_as_parent_span: (Optional) Set this parameter to indicate whether this span is in the same process as its parent. If you do not set this parameter, Stackdriver Trace is unable to take advantage of this helpful information. child_span_count: An optional number of child spans that were generated while this span was active. If set, allows implementation to detect missing child spans. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span) ), ) _sym_db.RegisterMessage(Span) _sym_db.RegisterMessage(Span.Attributes) _sym_db.RegisterMessage(Span.Attributes.AttributeMapEntry) _sym_db.RegisterMessage(Span.TimeEvent) _sym_db.RegisterMessage(Span.TimeEvent.Annotation) _sym_db.RegisterMessage(Span.TimeEvent.MessageEvent) _sym_db.RegisterMessage(Span.TimeEvents) _sym_db.RegisterMessage(Span.Link) _sym_db.RegisterMessage(Span.Links) AttributeValue = _reflection.GeneratedProtocolMessageType( "AttributeValue", (_message.Message,), dict( DESCRIPTOR=_ATTRIBUTEVALUE, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""The allowed types for [VALUE] in a ``[KEY]:[VALUE]`` attribute. Attributes: value: The type of the value. string_value: A string up to 256 bytes long. int_value: A 64-bit signed integer. bool_value: A Boolean value represented by ``true`` or ``false``. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.AttributeValue) ), ) _sym_db.RegisterMessage(AttributeValue) StackTrace = _reflection.GeneratedProtocolMessageType( "StackTrace", (_message.Message,), dict( StackFrame=_reflection.GeneratedProtocolMessageType( "StackFrame", (_message.Message,), dict( DESCRIPTOR=_STACKTRACE_STACKFRAME, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""Represents a single stack frame in a stack trace. Attributes: function_name: The fully-qualified name that uniquely identifies the function or method that is active in this frame (up to 1024 bytes). original_function_name: An un-mangled function name, if ``function_name`` is `mangled <http://www.avabodh.com/cxxin/namemangling.html>`__. The name can be fully-qualified (up to 1024 bytes). file_name: The name of the source file where the function call appears (up to 256 bytes). line_number: The line number in ``file_name`` where the function call appears. column_number: The column number where the function call appears, if available. This is important in JavaScript because of its anonymous functions. load_module: The binary module from where the code was loaded. source_version: The version of the deployed source code (up to 128 bytes). """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.StackTrace.StackFrame) ), ), StackFrames=_reflection.GeneratedProtocolMessageType( "StackFrames", (_message.Message,), dict( DESCRIPTOR=_STACKTRACE_STACKFRAMES, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""A collection of stack frames, which can be truncated. Attributes: frame: Stack frames in this call stack. dropped_frames_count: The number of stack frames that were dropped because there were too many stack frames. If this value is 0, then no stack frames were dropped. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.StackTrace.StackFrames) ), ), DESCRIPTOR=_STACKTRACE, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""A call stack appearing in a trace. Attributes: stack_frames: Stack frames in this stack trace. A maximum of 128 frames are allowed. stack_trace_hash_id: The hash ID is used to conserve network bandwidth for duplicate stack traces within a single trace. Often multiple spans will have identical stack traces. The first occurrence of a stack trace should contain both the ``stackFrame`` content and a value in ``stackTraceHashId``. Subsequent spans within the same request can refer to that stack trace by only setting ``stackTraceHashId``. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.StackTrace) ), ) _sym_db.RegisterMessage(StackTrace) _sym_db.RegisterMessage(StackTrace.StackFrame) _sym_db.RegisterMessage(StackTrace.StackFrames) Module = _reflection.GeneratedProtocolMessageType( "Module", (_message.Message,), dict( DESCRIPTOR=_MODULE, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""Binary module. Attributes: module: For example: main binary, kernel modules, and dynamic libraries such as libc.so, sharedlib.so (up to 256 bytes). build_id: A unique identifier for the module, usually a hash of its contents (up to 128 bytes). """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Module) ), ) _sym_db.RegisterMessage(Module) TruncatableString = _reflection.GeneratedProtocolMessageType( "TruncatableString", (_message.Message,), dict( DESCRIPTOR=_TRUNCATABLESTRING, __module__="google.devtools.cloudtrace_v2.proto.trace_pb2", __doc__="""Represents a string that might be shortened to a specified length. Attributes: value: The shortened string. For example, if the original string is 500 bytes long and the limit of the string is 128 bytes, then ``value`` contains the first 128 bytes of the 500-byte string. Truncation always happens on a UTF8 character boundary. If there are multi-byte characters in the string, then the length of the shortened string might be less than the size limit. truncated_byte_count: The number of bytes removed from the original string. If this value is 0, then the string was not shortened. """, # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.TruncatableString) ), ) _sym_db.RegisterMessage(TruncatableString) DESCRIPTOR._options = None _SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY._options = None # @@protoc_insertion_point(module_scope)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 23645, 14, 7959, 31391, 14, 17721, 40546, 62, 85, 17, 14, 1676, 1462, 14...
1.947311
34,998
"""Models for the Solis PV Inverter integration.""" from __future__ import annotations from dataclasses import dataclass from homeassistant.components.sensor import SensorEntityDescription @dataclass class SolisSensorEntityDescription(SensorEntityDescription): """Sensor entity description for Solis PV Inverter.""" api_key: str | None = None
[ 37811, 5841, 1424, 329, 262, 4294, 271, 31392, 554, 332, 353, 11812, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 198, 6738, 1363, 562, 10167, 13, 5589, 3906, 13, ...
3.708333
96
# yellowbrick.datasets.path # Helper functions for looking up dataset paths. # # Author: Benjamin Bengfort # Created: Thu Jul 26 14:10:51 2018 -0400 # # Copyright (C) 2018 The scikit-yb developers # For license information, see LICENSE.txt # # ID: path.py [7082742] benjamin@bengfort.com $ """ Helper functions for looking up dataset paths. """ ########################################################################## ## Imports ########################################################################## import os import shutil from .signature import sha256sum from yellowbrick.exceptions import DatasetsError ########################################################################## ## Fixtures ########################################################################## FIXTURES = os.path.join(os.path.dirname(__file__), "fixtures") ########################################################################## ## Dataset path utilities ########################################################################## def get_data_home(path=None): """ Return the path of the Yellowbrick data directory. This folder is used by dataset loaders to avoid downloading data several times. By default, this folder is colocated with the code in the install directory so that data shipped with the package can be easily located. Alternatively it can be set by the ``$YELLOWBRICK_DATA`` environment variable, or programmatically by giving a folder path. Note that the ``'~'`` symbol is expanded to the user home directory, and environment variables are also expanded when resolving the path. """ if path is None: path = os.environ.get("YELLOWBRICK_DATA", FIXTURES) path = os.path.expanduser(path) path = os.path.expandvars(path) if not os.path.exists(path): os.makedirs(path) return path def find_dataset_path(dataset, data_home=None, fname=None, ext=".csv.gz", raises=True): """ Looks up the path to the dataset specified in the data home directory, which is found using the ``get_data_home`` function. By default data home is colocated with the code, but can be modified with the YELLOWBRICK_DATA environment variable, or passing in a different directory. The file returned will be by default, the name of the dataset in compressed CSV format. Other files and extensions can be passed in to locate other data types or auxilliary files. If the dataset is not found a ``DatasetsError`` is raised by default. Parameters ---------- dataset : str The name of the dataset; should either be a folder in data home or specified in the yellowbrick.datasets.DATASETS variable. data_home : str, optional The path on disk where data is stored. If not passed in, it is looked up from YELLOWBRICK_DATA or the default returned by ``get_data_home``. fname : str, optional The filename to look up in the dataset path, by default it will be the name of the dataset. The fname must include an extension. ext : str, default: ".csv.gz" The extension of the data to look up in the dataset path, if the fname is specified then the ext parameter is ignored. If ext is None then the directory of the dataset will be returned. raises : bool, default: True If the path does not exist, raises a DatasetsError unless this flag is set to False, at which point None is returned (e.g. for checking if the path exists or not). Returns ------- path : str or None A path to the requested file, guaranteed to exist if an exception is not raised during processing of the request (unless None is returned). raises : DatasetsError If raise is True and the path does not exist, raises a DatasetsError. """ # Figure out the root directory of the datasets data_home = get_data_home(data_home) # Figure out the relative path to the dataset if fname is None: if ext is None: path = os.path.join(data_home, dataset) else: path = os.path.join(data_home, dataset, "{}{}".format(dataset, ext)) else: path = os.path.join(data_home, dataset, fname) # Determine if the path exists if not os.path.exists(path): # Suppress exceptions if required if not raises: return None raise DatasetsError( ("could not find dataset at {} - does it need to be downloaded?").format( path ) ) return path def dataset_exists(dataset, data_home=None): """ Checks to see if a directory with the name of the specified dataset exists in the data home directory, found with ``get_data_home``. Parameters ---------- dataset : str The name of the dataset; should either be a folder in data home or specified in the yellowbrick.datasets.DATASETS variable. data_home : str, optional The path on disk where data is stored. If not passed in, it is looked up from YELLOWBRICK_DATA or the default returned by ``get_data_home``. Returns ------- exists : bool If a folder with the dataset name is in the data home directory. """ data_home = get_data_home(data_home) path = os.path.join(data_home, dataset) return os.path.exists(path) and os.path.isdir(path) def dataset_archive(dataset, signature, data_home=None, ext=".zip"): """ Checks to see if the dataset archive file exists in the data home directory, found with ``get_data_home``. By specifying the signature, this function also checks to see if the archive is the latest version by comparing the sha256sum of the local archive with the specified signature. Parameters ---------- dataset : str The name of the dataset; should either be a folder in data home or specified in the yellowbrick.datasets.DATASETS variable. signature : str The SHA 256 signature of the dataset, used to determine if the archive is the latest version of the dataset or not. data_home : str, optional The path on disk where data is stored. If not passed in, it is looked up from YELLOWBRICK_DATA or the default returned by ``get_data_home``. ext : str, default: ".zip" The extension of the archive file. Returns ------- exists : bool True if the dataset archive exists and is the latest version. """ data_home = get_data_home(data_home) path = os.path.join(data_home, dataset + ext) if os.path.exists(path) and os.path.isfile(path): return sha256sum(path) == signature return False def cleanup_dataset(dataset, data_home=None, ext=".zip"): """ Removes the dataset directory and archive file from the data home directory. Parameters ---------- dataset : str The name of the dataset; should either be a folder in data home or specified in the yellowbrick.datasets.DATASETS variable. data_home : str, optional The path on disk where data is stored. If not passed in, it is looked up from YELLOWBRICK_DATA or the default returned by ``get_data_home``. ext : str, default: ".zip" The extension of the archive file. Returns ------- removed : int The number of objects removed from data_home. """ removed = 0 data_home = get_data_home(data_home) # Paths to remove datadir = os.path.join(data_home, dataset) archive = os.path.join(data_home, dataset + ext) # Remove directory and contents if os.path.exists(datadir): shutil.rmtree(datadir) removed += 1 # Remove the archive file if os.path.exists(archive): os.remove(archive) removed += 1 return removed
[ 2, 7872, 1671, 624, 13, 19608, 292, 1039, 13, 6978, 198, 2, 5053, 525, 5499, 329, 2045, 510, 27039, 13532, 13, 198, 2, 198, 2, 6434, 25, 220, 14533, 14964, 3319, 198, 2, 15622, 25, 26223, 5979, 2608, 1478, 25, 940, 25, 4349, 2864,...
3.006098
2,624
from .api import (Eth, Personal) from .callablecontract import CallableContract from .filter import Filter from .hextools import HexTools from .keccak import keccak from .poller import Poller from .soliditykeccak import solidityKeccak from .structs import Structs from .types import Types from .w3json import w3json from .wstransport import WSTransport from .channel import Channel import asyncio as aio from attrdict import AttrDict import logging from functools import partial log = logging.getLogger(__name__) combine = lambda L: { k: v for d in L for k, v in d.items() } pipe = lambda transport,api: combine([{method:partial(pipeline,transport,getattr(api,method))} for method in dir(api) if method[0] != '_'])
[ 6738, 764, 15042, 1330, 357, 40226, 11, 15644, 8, 198, 6738, 764, 13345, 540, 28484, 1330, 4889, 540, 45845, 198, 6738, 764, 24455, 1330, 25853, 198, 6738, 764, 258, 742, 10141, 1330, 22212, 33637, 198, 6738, 764, 365, 535, 461, 1330, ...
3.208889
225
import hashlib v19 = [0] * 28 B = [0x59, 0x59, 0x59, 0x45, 0x45, 0x45, 0x45, 0x41, 0x59, 0x59, 0x59, 0x45, 0x45, 0x45, 0x45, 0x49, 0x59, 0x59, 0x59, 0x45, 0x45, 0x45, 0x45, 0x53, 0x59, 0x59, 0x59, 0x45, 0x45, 0x45, 0x45, 0x33, 0x59, 0x59, 0x59, 0x59, 0x45, 0x45, 0x45, 0x7B, 0x59, 0x59, 0x59, 0x59, 0x45, 0x45, 0x45, 0x5F, 0x59, 0x59, 0x59, 0x59, 0x45, 0x45, 0x45, 0x5F, 0x59, 0x59, 0x59, 0x59, 0x45, 0x45, 0x45] C = [0xD4, 0xCF, 0x20, 0x44, 0x81, 0x13, 0xCF, 0x54, 0x6E, 0xD3, 0x50, 0xEF, 0x53, 0xD9, 0xD9, 0x18, 0xD3, 0xD1, 0x11, 0x64, 0xDA, 0xB8, 0x6C, 0x25, 0xFB, 0x08, 0x60, 0x52, 0xE9, 0x59, 0x5C, 0x52, 0x6B, 0xEA, 0x8F, 0x14, 0x44, 0xD9, 0xC8, 0xAE, 0x10, 0xC8, 0x9D, 0x7F, 0xCF, 0xC6, 0x3E, 0x3E, 0x91, 0xAA, 0xA3, 0x21, 0xD6, 0x7B, 0x40, 0xE6, 0x13, 0x4A, 0xBA, 0x0A, 0x10, 0x23, 0x50, 0x28] E = [0x20, 0x1, 0x2, 0x3, 0x4, 0x5, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x8, 0x9, 0x0A, 0x0B, 0x0C, 0x0D, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x1, 0x10] P = [0x10, 0x7, 0x14, 0x15, 0x1D, 0x0C, 0x1C, 0x11, 0x1, 0x0F, 0x17, 0x1A, 0x5, 0x12, 0x1F, 0x0A, 0x2, 0x8, 0x18, 0x0E, 0x20, 0x1B, 0x3, 0x9, 0x13, 0x0D, 0x1E, 0x6, 0x16, 0x0B, 0x4, 0x19] FP = [0x28, 0x8, 0x30, 0x10, 0x38, 0x18, 0x40, 0x20, 0x27, 0x7, 0x2F, 0x0F, 0x37, 0x17, 0x3F, 0x1F, 0x26, 0x6, 0x2E, 0x0E, 0x36, 0x16, 0x3E, 0x1E, 0x25, 0x5, 0x2D, 0x0D, 0x35, 0x15, 0x3D, 0x1D, 0x24, 0x4, 0x2C, 0x0C, 0x34, 0x14, 0x3C, 0x1C, 0x23, 0x3, 0x2B, 0x0B, 0x33, 0x13, 0x3B, 0x1B, 0x22, 0x2, 0x2A, 0x0A, 0x32, 0x12, 0x3A, 0x1A, 0x21, 0x1, 0x29, 0x9, 0x31, 0x11, 0x39, 0x19] PL = [0x39, 0x31, 0x29, 0x21, 0x19, 0x11, 0x9, 0x1, 0x3A, 0x32, 0x2A, 0x22, 0x1A, 0x12, 0x0A, 0x2, 0x3B, 0x33, 0x2B, 0x23, 0x1B, 0x13, 0x0B, 0x3, 0x3C, 0x34, 0x2C, 0x24, 0x4] PR = [0x3F, 0x37, 0x2F, 0x27, 0x1F, 0x17, 0x0F, 0x7, 0x3E, 0x36, 0x2E, 0x26, 0x1E, 0x16, 0x0E, 0x6, 0x3D, 0x35, 0x2D, 0x25, 0x1D, 0x15, 0x0D, 0x5, 0x1C, 0x14, 0x0C, 0x4, 0x4] P2 = [0x0E, 0x11, 0x0B, 0x18, 0x1, 0x5, 0x3, 0x1C, 0x0F, 0x6, 0x15, 0x0A, 0x17, 0x13, 0x0C, 0x4, 0x1A, 0x8, 0x10, 0x7, 0x1B, 0x14, 0x0D, 0x2, 0x29, 0x34, 0x1F, 0x25, 0x2F, 0x37, 0x1E, 0x28, 0x33, 0x2D, 0x21, 0x30, 0x2C, 0x31, 0x27, 0x38, 0x22, 0x35, 0x2E, 0x2A, 0x32, 0x24, 0x1D, 0x20, 0x10] byte_1900 = [0x3A, 0x32, 0x2A, 0x22, 0x1A, 0x12, 0x0A, 0x2, 0x3C, 0x34, 0x2C, 0x24, 0x1C, 0x14, 0x0C, 0x4, 0x3E, 0x36, 0x2E, 0x26, 0x1E, 0x16, 0x0E, 0x6, 0x40, 0x38, 0x30, 0x28, 0x20, 0x18, 0x10, 0x8, 0x39, 0x31, 0x29, 0x21, 0x19, 0x11, 0x9, 0x1, 0x3B, 0x33, 0x2B, 0x23, 0x1B, 0x13, 0x0B, 0x3, 0x3D, 0x35, 0x2D, 0x25, 0x1D, 0x15, 0x0D, 0x5, 0x3F, 0x37, 0x2F, 0x27, 0x1F, 0x17, 0x0F, 0x7] A = bytes(input(), 'utf-8') assert len(A) == 64 v23 = [letter + byte_1900[index] - 1 for index, letter in enumerate(A)] for j in range(28): # pre process v19[j] = B[PL[j] - 1] v19[j + 28] = B[PR[j] - 1] for k in range(16): # main loop for l in range(48): v31 = [letter + E[index] + 31 for index, letter in enumerate(A)] v4 = v19[0] v5 = 0 for m in range(28): v19[m] = v19[m + 1] v19[m + 28] = v19[m + 29] v20 = v4 v22 = v5 v31 = [v ^ v19[P2[index] - 1] for index, v in enumerate(v31)] v17 = hashlib.sha256(''.join(v31)) v18 = [v17[P[ii] - 1] for ii in range(32)] A = xor(A, v18) if k != 15: A = xor(A, v27) v27 = xor(v27, A) A = [A[FP[jj] - 1] for jj in range(64)] assert A == C
[ 11748, 12234, 8019, 198, 198, 85, 1129, 796, 685, 15, 60, 1635, 2579, 198, 33, 796, 685, 15, 87, 3270, 11, 657, 87, 3270, 11, 657, 87, 3270, 11, 657, 87, 2231, 11, 657, 87, 2231, 11, 657, 87, 2231, 11, 657, 87, 2231, 11, 657, ...
1.456922
2,333
# -*- coding: utf-8 -*- # # Copyright 2020 Google LLC. 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. """Abstract operation class that command operations will inherit from. Should typically be executed in a task iterator through googlecloudsdk.command_lib.storage.tasks.task_executor. Manual execution example: >>> class CopyTask(Task): ... def __init__(self, src, dest): ... ... >>> my_copy_task = new CopyTask('~/Desktop/memes.jpg', '/kernel/') >>> my_copy_task.Execute() """ from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import abc import collections import enum from googlecloudsdk.core.util import debug_output import six # Holds information to be passed between tasks. # # Attributes: # topic (Topic): The type of information this message holds. # payload (Any): The information itself. Message = collections.namedtuple( 'Message', ['topic', 'payload'] ) # Holds information returned from Task.Execute. # # Note that because information here is sent between processes, all data in this # class must be picklable. # # Attributes: # additional_task_iterators (Optional[Iterable[Iterable[Task]]]): Tasks to be # executed such that all tasks in each Iterable[Task] are executed before # any tasks in the next Iterable[Task]. Tasks within each Iterable[Task] are # unordered. For example, if this value were the following: # # [ # [UploadObjectTask(), UploadObjectTask(), UploadObjectTask()], # [ComposeObjectsTask()] # ] # # All UploadObjectTasks should be completed before the ComposeObjectTask # could begin, but the UploadObjectTasks could be executed in parallel. # messages (Optional[Iterable[Message]]): Information to be passed to all # dependent tasks. Output = collections.namedtuple( 'Output', ['additional_task_iterators', 'messages'] ) class Task(six.with_metaclass(abc.ABCMeta, object)): """Abstract class to represent one command operation. Attributes: parallel_processing_key (Optional[Hashable]): Identifies a task during execution. If this value is not None, the executor will skip this task if another task being executed is using the same key. If this value is None, the executor will not skip any tasks based on it. received_messages (Iterable[Message]): Messages sent to this task by its dependencies. report_error (bool): If True, failure of this task should be reported by updating the exit_code to non-zero. Defaults to True. """ @abc.abstractmethod def execute(self, task_status_queue=None): """Performs some work based on class attributes. Args: task_status_queue (multiprocessing.Queue): Used by task to report it progress to a central location. Returns: An Output instance, or None. """ pass
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 1303, 198, 2, 15069, 12131, 3012, 11419, 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...
3.295432
1,029
from django.conf.urls import url from . import views from rest_framework import routers urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^login/', views.login, name='login'), url(r'^logout/', views.logout, name='logout'), url(r'^avatar/(?P<profile_id>[0-9]+)/$', views.avatar, name='avatar'), url(r'^leagues/$', views.leagues_list, name='leagues_index'), url(r'^leagues/(?P<league_id>[0-9]+)/$', views.leagues_get, name='leagues_get'), url(r'^leagues/(?P<league_id>[0-9]+)/users/$', views.leagues_users_list, name='leagues_users_list'), url(r'^leagues/(?P<league_id>[0-9]+)/users/(?P<user_id>[0-9]+)/$', views.leagues_users_get, name='leagues_users_get'), ] # urlpatterns = [ # url(r'^$', views.index, name='index'), # ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 201, 198, 201, 198, 6738, 764, 1330, 5009, 201, 198, 6738, 1334, 62, 30604, 1330, 41144, 201, 198, 201, 198, 6371, 33279, 82, 796, 685, 201, 198, 220, 220, 220, 19016, 7, 81,...
2.186486
370
import h5py import pickle import numpy as np
[ 11748, 289, 20, 9078, 198, 11748, 2298, 293, 198, 11748, 299, 32152, 355, 45941 ]
3.142857
14
import random as rd
[ 11748, 4738, 355, 374, 67 ]
3.8
5
#!/usr/bin/env python3 # GBA FE Hack Manager by MinN # # To use: run this once to create a rom folder for your hack roms and a patch folder for your patches # Put FE6_clean.gba FE7_clean.gba FE8_clean.gba FE7J_clean.gba FE8J_clean.gba in the parent folder as patching targets # This tool will not verify your FE roms' checksum so do it yourself # Put your patches in the patch folder and # run this script to patch and/or update your hack roms import sys import ups import os import os.path import shutil import re import platform from distutils.version import LooseVersion INHERIT_SAVE = True # solves various issues # on macOS, click on a #! script, your cwd is still ~ # and .app bundles doesn't give you a good sys.argv[0] # This only accepts version number separated by . or - and does not support dates if __name__ == '__main__': cd_current() main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 402, 4339, 18630, 18281, 9142, 416, 1855, 45, 198, 2, 198, 2, 1675, 779, 25, 1057, 428, 1752, 284, 2251, 257, 9267, 9483, 329, 534, 8156, 374, 3150, 290, 257, 8529, 9483, 32...
3.221402
271
# __all__ = ["trzy_1", "trzy_2", "trzy_3"] __all__ = ["trzy_1"] print ("Init modulu ", __name__)
[ 2, 11593, 439, 834, 796, 14631, 2213, 7357, 62, 16, 1600, 366, 2213, 7357, 62, 17, 1600, 366, 2213, 7357, 62, 18, 8973, 198, 834, 439, 834, 796, 14631, 2213, 7357, 62, 16, 8973, 198, 198, 4798, 5855, 31768, 953, 15712, 33172, 11593,...
2.106383
47