content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import collections import time import heapq from horovod_simulator_config import SimulatorConfig, SchedulingDisc from utils.logger import get_logger import typing from queue import PriorityQueue # compute iteration time from records def compute_iteration_time(record, simulator): logger = get_logger("compute_iteration_time", "DEBUG") iteration_time_ms = 0 iteration_start_time = 0 for event in record["FP_computation_done"]: if event.layer == simulator.config.num_layers -1: if event.iteration == 0: iteration_start_time = event.time if event.iteration == 1: iteration_time_ms = event.time - iteration_start_time break logger.debug(f'iteration_time_ms: {iteration_time_ms}') return iteration_time_ms def compute_slack_time_FIFO(record, simulator): ''' compute slack per layer for FIFO Time difference between when gradients are computed to when gradients are needed Gradients computed timestamp @ layer i = BP computation time done @ layer i Gradients consumed timestamp @ layer i = FP computation start @ layer i = FP computation done @ layer i - FP computation duration @ layer i ''' logger = get_logger("compute_slack_time_FIFO", "DEBUG") slack_per_layer_in_ms = {layer: 0 for layer in range(simulator.config.num_layers)} BP_computation_done_timestamp = {layer: 0 for layer in range(simulator.config.num_layers)} for event in record["BP_computation_done"]: if event.iteration == 0: BP_computation_done_timestamp[event.layer] = event.time for event in record["FP_computation_done"]: if event.iteration == 1: # print(f'layer: {event.layer}, FP_computation_done, {event.time}, fp_layers, {fp_layers[event.layer]}, BP compute done: { BP_computation_done_timestamp[event.layer]}') slack_per_layer_in_ms[event.layer] = event.time - simulator.fp_layers[event.layer] - BP_computation_done_timestamp[event.layer] logger.debug(f'slack_per_layer_in_ms: {slack_per_layer_in_ms}') return slack_per_layer_in_ms def compute_iteration_and_slack(record, simulator): compute_iteration_time(record, simulator) compute_slack_time_FIFO(record, simulator) def test_run(config): horovod_simulator = HorovodSimulator(config) horovod_simulator.run() compute_iteration_and_slack(horovod_simulator.record, horovod_simulator) if __name__ == "__main__": # test1() test_ring_allreduce_fifo()
[ 11748, 17268, 198, 11748, 640, 198, 11748, 24575, 80, 198, 6738, 3076, 709, 375, 62, 14323, 8927, 62, 11250, 1330, 13942, 16934, 11, 27774, 16619, 15642, 198, 6738, 3384, 4487, 13, 6404, 1362, 1330, 651, 62, 6404, 1362, 198, 11748, 1972...
2.536204
1,022
__author__ = 'alejandroaguado' from xml.etree import ElementTree
[ 834, 9800, 834, 796, 705, 1000, 47983, 11433, 4533, 6, 198, 198, 6738, 35555, 13, 316, 631, 1330, 11703, 27660, 198 ]
3.142857
21
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/bigtable/admin/table/v1/bigtable_table_service_messages.proto 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 from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from gcloud.bigtable._generated import bigtable_table_data_pb2 as google_dot_bigtable_dot_admin_dot_table_dot_v1_dot_bigtable__table__data__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='google/bigtable/admin/table/v1/bigtable_table_service_messages.proto', package='google.bigtable.admin.table.v1', syntax='proto3', serialized_pb=b'\nDgoogle/bigtable/admin/table/v1/bigtable_table_service_messages.proto\x12\x1egoogle.bigtable.admin.table.v1\x1a\x38google/bigtable/admin/table/v1/bigtable_table_data.proto\"\x86\x01\n\x12\x43reateTableRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x10\n\x08table_id\x18\x02 \x01(\t\x12\x34\n\x05table\x18\x03 \x01(\x0b\x32%.google.bigtable.admin.table.v1.Table\x12\x1a\n\x12initial_split_keys\x18\x04 \x03(\t\"!\n\x11ListTablesRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"K\n\x12ListTablesResponse\x12\x35\n\x06tables\x18\x01 \x03(\x0b\x32%.google.bigtable.admin.table.v1.Table\"\x1f\n\x0fGetTableRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\"\n\x12\x44\x65leteTableRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"2\n\x12RenameTableRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06new_id\x18\x02 \x01(\t\"\x88\x01\n\x19\x43reateColumnFamilyRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x18\n\x10\x63olumn_family_id\x18\x02 \x01(\t\x12\x43\n\rcolumn_family\x18\x03 \x01(\x0b\x32,.google.bigtable.admin.table.v1.ColumnFamily\")\n\x19\x44\x65leteColumnFamilyRequest\x12\x0c\n\x04name\x18\x01 \x01(\tBI\n\"com.google.bigtable.admin.table.v1B!BigtableTableServiceMessagesProtoP\x01\x62\x06proto3' , dependencies=[google_dot_bigtable_dot_admin_dot_table_dot_v1_dot_bigtable__table__data__pb2.DESCRIPTOR,]) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _CREATETABLEREQUEST = _descriptor.Descriptor( name='CreateTableRequest', full_name='google.bigtable.admin.table.v1.CreateTableRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='google.bigtable.admin.table.v1.CreateTableRequest.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, options=None), _descriptor.FieldDescriptor( name='table_id', full_name='google.bigtable.admin.table.v1.CreateTableRequest.table_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, options=None), _descriptor.FieldDescriptor( name='table', full_name='google.bigtable.admin.table.v1.CreateTableRequest.table', 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, options=None), _descriptor.FieldDescriptor( name='initial_split_keys', full_name='google.bigtable.admin.table.v1.CreateTableRequest.initial_split_keys', index=3, number=4, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=163, serialized_end=297, ) _LISTTABLESREQUEST = _descriptor.Descriptor( name='ListTablesRequest', full_name='google.bigtable.admin.table.v1.ListTablesRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='google.bigtable.admin.table.v1.ListTablesRequest.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, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=299, serialized_end=332, ) _LISTTABLESRESPONSE = _descriptor.Descriptor( name='ListTablesResponse', full_name='google.bigtable.admin.table.v1.ListTablesResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='tables', full_name='google.bigtable.admin.table.v1.ListTablesResponse.tables', 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, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=334, serialized_end=409, ) _GETTABLEREQUEST = _descriptor.Descriptor( name='GetTableRequest', full_name='google.bigtable.admin.table.v1.GetTableRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='google.bigtable.admin.table.v1.GetTableRequest.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, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=411, serialized_end=442, ) _DELETETABLEREQUEST = _descriptor.Descriptor( name='DeleteTableRequest', full_name='google.bigtable.admin.table.v1.DeleteTableRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='google.bigtable.admin.table.v1.DeleteTableRequest.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, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=444, serialized_end=478, ) _RENAMETABLEREQUEST = _descriptor.Descriptor( name='RenameTableRequest', full_name='google.bigtable.admin.table.v1.RenameTableRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='google.bigtable.admin.table.v1.RenameTableRequest.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, options=None), _descriptor.FieldDescriptor( name='new_id', full_name='google.bigtable.admin.table.v1.RenameTableRequest.new_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, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=480, serialized_end=530, ) _CREATECOLUMNFAMILYREQUEST = _descriptor.Descriptor( name='CreateColumnFamilyRequest', full_name='google.bigtable.admin.table.v1.CreateColumnFamilyRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='google.bigtable.admin.table.v1.CreateColumnFamilyRequest.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, options=None), _descriptor.FieldDescriptor( name='column_family_id', full_name='google.bigtable.admin.table.v1.CreateColumnFamilyRequest.column_family_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, options=None), _descriptor.FieldDescriptor( name='column_family', full_name='google.bigtable.admin.table.v1.CreateColumnFamilyRequest.column_family', 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, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=533, serialized_end=669, ) _DELETECOLUMNFAMILYREQUEST = _descriptor.Descriptor( name='DeleteColumnFamilyRequest', full_name='google.bigtable.admin.table.v1.DeleteColumnFamilyRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='google.bigtable.admin.table.v1.DeleteColumnFamilyRequest.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, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=671, serialized_end=712, ) _CREATETABLEREQUEST.fields_by_name['table'].message_type = google_dot_bigtable_dot_admin_dot_table_dot_v1_dot_bigtable__table__data__pb2._TABLE _LISTTABLESRESPONSE.fields_by_name['tables'].message_type = google_dot_bigtable_dot_admin_dot_table_dot_v1_dot_bigtable__table__data__pb2._TABLE _CREATECOLUMNFAMILYREQUEST.fields_by_name['column_family'].message_type = google_dot_bigtable_dot_admin_dot_table_dot_v1_dot_bigtable__table__data__pb2._COLUMNFAMILY DESCRIPTOR.message_types_by_name['CreateTableRequest'] = _CREATETABLEREQUEST DESCRIPTOR.message_types_by_name['ListTablesRequest'] = _LISTTABLESREQUEST DESCRIPTOR.message_types_by_name['ListTablesResponse'] = _LISTTABLESRESPONSE DESCRIPTOR.message_types_by_name['GetTableRequest'] = _GETTABLEREQUEST DESCRIPTOR.message_types_by_name['DeleteTableRequest'] = _DELETETABLEREQUEST DESCRIPTOR.message_types_by_name['RenameTableRequest'] = _RENAMETABLEREQUEST DESCRIPTOR.message_types_by_name['CreateColumnFamilyRequest'] = _CREATECOLUMNFAMILYREQUEST DESCRIPTOR.message_types_by_name['DeleteColumnFamilyRequest'] = _DELETECOLUMNFAMILYREQUEST CreateTableRequest = _reflection.GeneratedProtocolMessageType('CreateTableRequest', (_message.Message,), dict( DESCRIPTOR = _CREATETABLEREQUEST, __module__ = 'google.bigtable.admin.table.v1.bigtable_table_service_messages_pb2' # @@protoc_insertion_point(class_scope:google.bigtable.admin.table.v1.CreateTableRequest) )) _sym_db.RegisterMessage(CreateTableRequest) ListTablesRequest = _reflection.GeneratedProtocolMessageType('ListTablesRequest', (_message.Message,), dict( DESCRIPTOR = _LISTTABLESREQUEST, __module__ = 'google.bigtable.admin.table.v1.bigtable_table_service_messages_pb2' # @@protoc_insertion_point(class_scope:google.bigtable.admin.table.v1.ListTablesRequest) )) _sym_db.RegisterMessage(ListTablesRequest) ListTablesResponse = _reflection.GeneratedProtocolMessageType('ListTablesResponse', (_message.Message,), dict( DESCRIPTOR = _LISTTABLESRESPONSE, __module__ = 'google.bigtable.admin.table.v1.bigtable_table_service_messages_pb2' # @@protoc_insertion_point(class_scope:google.bigtable.admin.table.v1.ListTablesResponse) )) _sym_db.RegisterMessage(ListTablesResponse) GetTableRequest = _reflection.GeneratedProtocolMessageType('GetTableRequest', (_message.Message,), dict( DESCRIPTOR = _GETTABLEREQUEST, __module__ = 'google.bigtable.admin.table.v1.bigtable_table_service_messages_pb2' # @@protoc_insertion_point(class_scope:google.bigtable.admin.table.v1.GetTableRequest) )) _sym_db.RegisterMessage(GetTableRequest) DeleteTableRequest = _reflection.GeneratedProtocolMessageType('DeleteTableRequest', (_message.Message,), dict( DESCRIPTOR = _DELETETABLEREQUEST, __module__ = 'google.bigtable.admin.table.v1.bigtable_table_service_messages_pb2' # @@protoc_insertion_point(class_scope:google.bigtable.admin.table.v1.DeleteTableRequest) )) _sym_db.RegisterMessage(DeleteTableRequest) RenameTableRequest = _reflection.GeneratedProtocolMessageType('RenameTableRequest', (_message.Message,), dict( DESCRIPTOR = _RENAMETABLEREQUEST, __module__ = 'google.bigtable.admin.table.v1.bigtable_table_service_messages_pb2' # @@protoc_insertion_point(class_scope:google.bigtable.admin.table.v1.RenameTableRequest) )) _sym_db.RegisterMessage(RenameTableRequest) CreateColumnFamilyRequest = _reflection.GeneratedProtocolMessageType('CreateColumnFamilyRequest', (_message.Message,), dict( DESCRIPTOR = _CREATECOLUMNFAMILYREQUEST, __module__ = 'google.bigtable.admin.table.v1.bigtable_table_service_messages_pb2' # @@protoc_insertion_point(class_scope:google.bigtable.admin.table.v1.CreateColumnFamilyRequest) )) _sym_db.RegisterMessage(CreateColumnFamilyRequest) DeleteColumnFamilyRequest = _reflection.GeneratedProtocolMessageType('DeleteColumnFamilyRequest', (_message.Message,), dict( DESCRIPTOR = _DELETECOLUMNFAMILYREQUEST, __module__ = 'google.bigtable.admin.table.v1.bigtable_table_service_messages_pb2' # @@protoc_insertion_point(class_scope:google.bigtable.admin.table.v1.DeleteColumnFamilyRequest) )) _sym_db.RegisterMessage(DeleteColumnFamilyRequest) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), b'\n\"com.google.bigtable.admin.table.v1B!BigtableTableServiceMessagesProtoP\001') import abc from grpc.beta import implementations as beta_implementations from grpc.early_adopter import implementations as early_adopter_implementations from grpc.framework.alpha import utilities as alpha_utilities from grpc.framework.common import cardinality from grpc.framework.interfaces.face import utilities as face_utilities # @@protoc_insertion_point(module_scope)
[ 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 23645, 14, 14261, 11487, 14, 28482, 14, 11487, 14, 85, 16, 14, 14261, 11487, 62, 11487, 62, 15271, 62, 37348, 1095, 13, 1676, 1462, 198, ...
2.562778
6,061
#!flask/bin/python # Copyright 2021 Luis Blazquez Miambres (@luisblazquezm) # See LICENSE for details. from flask_restx import Api api = Api(version='1.0', title='Influencer Detection Project', description="**PORBI Influencer Detection project's Flask RESTX API**")
[ 2, 0, 2704, 2093, 14, 8800, 14, 29412, 198, 198, 2, 15069, 33448, 20894, 26176, 22281, 337, 1789, 65, 411, 4275, 2290, 271, 2436, 1031, 22281, 76, 8, 198, 2, 4091, 38559, 24290, 329, 3307, 13, 198, 198, 6738, 42903, 62, 2118, 87, ...
3.032967
91
''' Description: Author: Jiaqi Gu (jqgu@utexas.edu) Date: 2021-10-24 16:23:50 LastEditors: Jiaqi Gu (jqgu@utexas.edu) LastEditTime: 2021-10-24 16:23:50 ''' from collections import OrderedDict from typing import Callable, Dict, List, Optional, Tuple, Union import numpy as np import torch import torch.nn.functional as F from pyutils.general import logger from torch import Tensor, nn from torch.types import Device, _size from .layers.activation import ReLUN from .layers.custom_conv2d import MZIBlockConv2d from .layers.custom_linear import MZIBlockLinear from .sparse_bp_base import SparseBP_Base __all__ = ["SparseBP_MZI_CNN"]
[ 7061, 6, 198, 11828, 25, 198, 13838, 25, 449, 544, 40603, 1962, 357, 73, 80, 5162, 31, 315, 1069, 292, 13, 15532, 8, 198, 10430, 25, 33448, 12, 940, 12, 1731, 1467, 25, 1954, 25, 1120, 198, 5956, 18378, 669, 25, 449, 544, 40603, ...
2.826667
225
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Paddle-Lite full python api demo ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse from paddlelite.lite import * import numpy as np import platform # Command arguments parser = argparse.ArgumentParser() parser.add_argument( "--model_dir", default="", type=str, help="Non-combined Model dir path") parser.add_argument("--model_file", default="", type=str, help="Model file") parser.add_argument( "--param_file", default="", type=str, help="Combined model param file") parser.add_argument( "--input_shape", default=[1, 3, 224, 224], nargs='+', type=int, required=False, help="Model input shape, eg: 1 3 224 224. Defalut: 1 3 224 224") parser.add_argument( "--backend", default="", type=str, help="To use a particular backend for execution. Should be one of: arm|opencl|x86|x86_opencl|metal|nnadapter" ) parser.add_argument( "--image_path", default="", type=str, help="The path of test image file") parser.add_argument( "--label_path", default="", type=str, help="The path of label file") parser.add_argument( "--print_results", type=bool, default=False, help="Print results. Default: False") parser.add_argument( "--nnadapter_device_names", default="", type=str, help="Set nnadapter device names") parser.add_argument( "--nnadapter_context_properties", default="", type=str, help="Set nnadapter context properties") parser.add_argument( "--nnadapter_model_cache_dir", default="", type=str, help="Set nnadapter model cache dir") parser.add_argument( "--nnadapter_subgraph_partition_config_path", default="", type=str, help="Set nnadapter subgraph partition config path") parser.add_argument( "--nnadapter_mixed_precision_quantization_config_path", default="", type=str, help="Set nnadapter mixed precision quantization config path") if __name__ == '__main__': args = parser.parse_args() RunModel(args)
[ 2, 15069, 357, 66, 8, 13130, 350, 37382, 47, 37382, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845...
2.946785
902
from discord.ext.commands import BadArgument
[ 6738, 36446, 13, 2302, 13, 9503, 1746, 1330, 7772, 28100, 1713 ]
4
11
from selenium import webdriver navegador = webdriver.Chrome() navegador.get("https://webstatic-sea.mihoyo.com/ys/event/signin-sea/index.html?act_id=e202102251931481&lang=pt-pt")
[ 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 198, 77, 1015, 70, 7079, 796, 3992, 26230, 13, 1925, 5998, 3419, 198, 77, 1015, 70, 7079, 13, 1136, 7203, 5450, 1378, 12384, 12708, 12, 8583, 13, 76, 4449, 726, 78, 13, 785, 14, 893, ...
2.438356
73
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: envoy/config/filter/http/jwt_auth/v2alpha1/config.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 from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='envoy/config/filter/http/jwt_auth/v2alpha1/config.proto', package='istio.envoy.config.filter.http.jwt_auth.v2alpha1', syntax='proto3', serialized_pb=_b('\n7envoy/config/filter/http/jwt_auth/v2alpha1/config.proto\x12\x30istio.envoy.config.filter.http.jwt_auth.v2alpha1\x1a\x1egoogle/protobuf/duration.proto\"k\n\x07HttpUri\x12\x0b\n\x03uri\x18\x01 \x01(\t\x12\x11\n\x07\x63luster\x18\x02 \x01(\tH\x00\x12*\n\x07timeout\x18\x03 \x01(\x0b\x32\x19.google.protobuf.DurationB\x14\n\x12http_upstream_type\"^\n\nDataSource\x12\x12\n\x08\x66ilename\x18\x01 \x01(\tH\x00\x12\x16\n\x0cinline_bytes\x18\x02 \x01(\x0cH\x00\x12\x17\n\rinline_string\x18\x03 \x01(\tH\x00\x42\x0b\n\tspecifier\"\x87\x03\n\x07JwtRule\x12\x0e\n\x06issuer\x18\x01 \x01(\t\x12\x11\n\taudiences\x18\x02 \x03(\t\x12S\n\x0bremote_jwks\x18\x03 \x01(\x0b\x32<.istio.envoy.config.filter.http.jwt_auth.v2alpha1.RemoteJwksH\x00\x12R\n\nlocal_jwks\x18\x04 \x01(\x0b\x32<.istio.envoy.config.filter.http.jwt_auth.v2alpha1.DataSourceH\x00\x12\x0f\n\x07\x66orward\x18\x05 \x01(\x08\x12Q\n\x0c\x66rom_headers\x18\x06 \x03(\x0b\x32;.istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtHeader\x12\x13\n\x0b\x66rom_params\x18\x07 \x03(\t\x12\x1e\n\x16\x66orward_payload_header\x18\x08 \x01(\tB\x17\n\x15jwks_source_specifier\"\x8c\x01\n\nRemoteJwks\x12K\n\x08http_uri\x18\x01 \x01(\x0b\x32\x39.istio.envoy.config.filter.http.jwt_auth.v2alpha1.HttpUri\x12\x31\n\x0e\x63\x61\x63he_duration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration\"/\n\tJwtHeader\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cvalue_prefix\x18\x02 \x01(\t\"~\n\x11JwtAuthentication\x12H\n\x05rules\x18\x01 \x03(\x0b\x32\x39.istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule\x12\x1f\n\x17\x61llow_missing_or_failed\x18\x02 \x01(\x08\x42\x39Z7istio.io/api/envoy/config/filter/http/jwt_auth/v2alpha1b\x06proto3') , dependencies=[google_dot_protobuf_dot_duration__pb2.DESCRIPTOR,]) _HTTPURI = _descriptor.Descriptor( name='HttpUri', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.HttpUri', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='uri', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.HttpUri.uri', 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, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='cluster', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.HttpUri.cluster', 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, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='timeout', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.HttpUri.timeout', 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, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='http_upstream_type', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.HttpUri.http_upstream_type', index=0, containing_type=None, fields=[]), ], serialized_start=141, serialized_end=248, ) _DATASOURCE = _descriptor.Descriptor( name='DataSource', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.DataSource', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='filename', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.DataSource.filename', 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, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='inline_bytes', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.DataSource.inline_bytes', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='inline_string', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.DataSource.inline_string', 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, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='specifier', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.DataSource.specifier', index=0, containing_type=None, fields=[]), ], serialized_start=250, serialized_end=344, ) _JWTRULE = _descriptor.Descriptor( name='JwtRule', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='issuer', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule.issuer', 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, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='audiences', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule.audiences', index=1, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='remote_jwks', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule.remote_jwks', 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, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='local_jwks', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule.local_jwks', 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, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='forward', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule.forward', index=4, number=5, 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, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='from_headers', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule.from_headers', index=5, number=6, 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, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='from_params', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule.from_params', index=6, number=7, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='forward_payload_header', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule.forward_payload_header', index=7, number=8, 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, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='jwks_source_specifier', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule.jwks_source_specifier', index=0, containing_type=None, fields=[]), ], serialized_start=347, serialized_end=738, ) _REMOTEJWKS = _descriptor.Descriptor( name='RemoteJwks', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.RemoteJwks', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='http_uri', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.RemoteJwks.http_uri', 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, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='cache_duration', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.RemoteJwks.cache_duration', 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, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=741, serialized_end=881, ) _JWTHEADER = _descriptor.Descriptor( name='JwtHeader', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtHeader', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtHeader.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, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='value_prefix', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtHeader.value_prefix', 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, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=883, serialized_end=930, ) _JWTAUTHENTICATION = _descriptor.Descriptor( name='JwtAuthentication', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtAuthentication', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='rules', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtAuthentication.rules', 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, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='allow_missing_or_failed', full_name='istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtAuthentication.allow_missing_or_failed', index=1, number=2, 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, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=932, serialized_end=1058, ) _HTTPURI.fields_by_name['timeout'].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _HTTPURI.oneofs_by_name['http_upstream_type'].fields.append( _HTTPURI.fields_by_name['cluster']) _HTTPURI.fields_by_name['cluster'].containing_oneof = _HTTPURI.oneofs_by_name['http_upstream_type'] _DATASOURCE.oneofs_by_name['specifier'].fields.append( _DATASOURCE.fields_by_name['filename']) _DATASOURCE.fields_by_name['filename'].containing_oneof = _DATASOURCE.oneofs_by_name['specifier'] _DATASOURCE.oneofs_by_name['specifier'].fields.append( _DATASOURCE.fields_by_name['inline_bytes']) _DATASOURCE.fields_by_name['inline_bytes'].containing_oneof = _DATASOURCE.oneofs_by_name['specifier'] _DATASOURCE.oneofs_by_name['specifier'].fields.append( _DATASOURCE.fields_by_name['inline_string']) _DATASOURCE.fields_by_name['inline_string'].containing_oneof = _DATASOURCE.oneofs_by_name['specifier'] _JWTRULE.fields_by_name['remote_jwks'].message_type = _REMOTEJWKS _JWTRULE.fields_by_name['local_jwks'].message_type = _DATASOURCE _JWTRULE.fields_by_name['from_headers'].message_type = _JWTHEADER _JWTRULE.oneofs_by_name['jwks_source_specifier'].fields.append( _JWTRULE.fields_by_name['remote_jwks']) _JWTRULE.fields_by_name['remote_jwks'].containing_oneof = _JWTRULE.oneofs_by_name['jwks_source_specifier'] _JWTRULE.oneofs_by_name['jwks_source_specifier'].fields.append( _JWTRULE.fields_by_name['local_jwks']) _JWTRULE.fields_by_name['local_jwks'].containing_oneof = _JWTRULE.oneofs_by_name['jwks_source_specifier'] _REMOTEJWKS.fields_by_name['http_uri'].message_type = _HTTPURI _REMOTEJWKS.fields_by_name['cache_duration'].message_type = google_dot_protobuf_dot_duration__pb2._DURATION _JWTAUTHENTICATION.fields_by_name['rules'].message_type = _JWTRULE DESCRIPTOR.message_types_by_name['HttpUri'] = _HTTPURI DESCRIPTOR.message_types_by_name['DataSource'] = _DATASOURCE DESCRIPTOR.message_types_by_name['JwtRule'] = _JWTRULE DESCRIPTOR.message_types_by_name['RemoteJwks'] = _REMOTEJWKS DESCRIPTOR.message_types_by_name['JwtHeader'] = _JWTHEADER DESCRIPTOR.message_types_by_name['JwtAuthentication'] = _JWTAUTHENTICATION _sym_db.RegisterFileDescriptor(DESCRIPTOR) HttpUri = _reflection.GeneratedProtocolMessageType('HttpUri', (_message.Message,), dict( DESCRIPTOR = _HTTPURI, __module__ = 'envoy.config.filter.http.jwt_auth.v2alpha1.config_pb2' # @@protoc_insertion_point(class_scope:istio.envoy.config.filter.http.jwt_auth.v2alpha1.HttpUri) )) _sym_db.RegisterMessage(HttpUri) DataSource = _reflection.GeneratedProtocolMessageType('DataSource', (_message.Message,), dict( DESCRIPTOR = _DATASOURCE, __module__ = 'envoy.config.filter.http.jwt_auth.v2alpha1.config_pb2' # @@protoc_insertion_point(class_scope:istio.envoy.config.filter.http.jwt_auth.v2alpha1.DataSource) )) _sym_db.RegisterMessage(DataSource) JwtRule = _reflection.GeneratedProtocolMessageType('JwtRule', (_message.Message,), dict( DESCRIPTOR = _JWTRULE, __module__ = 'envoy.config.filter.http.jwt_auth.v2alpha1.config_pb2' # @@protoc_insertion_point(class_scope:istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtRule) )) _sym_db.RegisterMessage(JwtRule) RemoteJwks = _reflection.GeneratedProtocolMessageType('RemoteJwks', (_message.Message,), dict( DESCRIPTOR = _REMOTEJWKS, __module__ = 'envoy.config.filter.http.jwt_auth.v2alpha1.config_pb2' # @@protoc_insertion_point(class_scope:istio.envoy.config.filter.http.jwt_auth.v2alpha1.RemoteJwks) )) _sym_db.RegisterMessage(RemoteJwks) JwtHeader = _reflection.GeneratedProtocolMessageType('JwtHeader', (_message.Message,), dict( DESCRIPTOR = _JWTHEADER, __module__ = 'envoy.config.filter.http.jwt_auth.v2alpha1.config_pb2' # @@protoc_insertion_point(class_scope:istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtHeader) )) _sym_db.RegisterMessage(JwtHeader) JwtAuthentication = _reflection.GeneratedProtocolMessageType('JwtAuthentication', (_message.Message,), dict( DESCRIPTOR = _JWTAUTHENTICATION, __module__ = 'envoy.config.filter.http.jwt_auth.v2alpha1.config_pb2' # @@protoc_insertion_point(class_scope:istio.envoy.config.filter.http.jwt_auth.v2alpha1.JwtAuthentication) )) _sym_db.RegisterMessage(JwtAuthentication) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('Z7istio.io/api/envoy/config/filter/http/jwt_auth/v2alpha1')) # @@protoc_insertion_point(module_scope)
[ 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 39137, 14, 11250, 14, 24455, 14, 4023, 14, 73, 46569, 62, 18439, 14, 85, 17, 26591, 16, 14, 11250, 13, 1676, 1462, 198, 198, 11748, 25064...
2.338179
7,774
#!/usr/bin/python # -*- coding: gb2312 -*- import fileinput import os if __name__ == '__main__': fs = FileStream('1.txt', 1024) print fs.cuttimes() print fs.lastsize() while 1: fby = fs.getstream() if fby is not None: print '--------' print fby, len(fby) else: break
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 308, 65, 1954, 1065, 532, 9, 12, 198, 198, 11748, 2393, 15414, 198, 11748, 28686, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 2...
1.965909
176
import argparse from argparse import ArgumentError from libvirt_vm_optimizer.util.utils import Profile
[ 11748, 1822, 29572, 198, 6738, 1822, 29572, 1330, 45751, 12331, 198, 198, 6738, 9195, 48940, 62, 14761, 62, 40085, 7509, 13, 22602, 13, 26791, 1330, 13118, 628, 198 ]
3.785714
28
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module contains class MRT_File. The MRT_File class contains the functionality to load and parse mrt files. This is done through a series of steps, detailed in README. """ __authors__ = ["Justin Furuness", "Matt Jaccino"] __credits__ = ["Justin Furuness", "Matt Jaccino", "Cameron Morris"] __Lisence__ = "BSD" __maintainer__ = "Justin Furuness" __email__ = "jfuruness@gmail.com" __status__ = "Production" import os import logging from .tables import MRT_Announcements_Table from ....utils import utils from ....utils.base_classes import File
[ 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, 1212, 8265, 4909, 1398, 337, 14181, 62, 8979, 13, 198, 198, 464, 337, 14181, 62, 8979, 1398, 4909, 26...
3.035354
198
from rcaudio import * import time import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') demo2()
[ 6738, 48321, 24051, 1330, 1635, 198, 11748, 640, 198, 11748, 18931, 628, 198, 6404, 2667, 13, 35487, 16934, 7, 5715, 28, 6404, 2667, 13, 10778, 11, 198, 220, 220, 220, 220, 220, 220, 220, 5794, 11639, 4, 7, 292, 310, 524, 8, 82, 4...
2.410256
78
#!/usr/bin/python3 print("content-type: text/html") print() import subprocess as sp import cgi fs = cgi.FieldStorage() cmd = fs.getvalue("command") output = sp.getoutput("sudo "+cmd) print("<body style='padding: 40px;'>") print('<h1 style="color:#df405a;" >Output</h1>') print("<pre>{}</pre>".format(output)) print("</body>")
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 201, 198, 201, 198, 4798, 7203, 11299, 12, 4906, 25, 2420, 14, 6494, 4943, 201, 198, 4798, 3419, 201, 198, 201, 198, 11748, 850, 14681, 355, 599, 201, 198, 11748, 269, 12397, 201, 198, 201, ...
2.43662
142
from flask import Flask from flask_restful_swagger.swagger import SwaggerRegistry try: from unittest.mock import patch except ImportError: from mock import patch
[ 6738, 42903, 1330, 46947, 198, 198, 6738, 42903, 62, 2118, 913, 62, 2032, 7928, 13, 2032, 7928, 1330, 2451, 7928, 8081, 4592, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 16341, 17267, 1...
3.264151
53
import logging import webapp2 from googleapiclient.errors import HttpError from gcp_census.bigquery.bigquery_client import BigQuery from gcp_census.bigquery.bigquery_task import BigQueryTask
[ 11748, 18931, 198, 198, 11748, 3992, 1324, 17, 198, 6738, 23645, 499, 291, 75, 1153, 13, 48277, 1330, 367, 29281, 12331, 198, 198, 6738, 308, 13155, 62, 66, 7314, 13, 14261, 22766, 13, 14261, 22766, 62, 16366, 1330, 4403, 20746, 198, ...
3.193548
62
from os import popen
[ 6738, 28686, 1330, 1461, 268 ]
4
5
#!/usr/bin/env python3.6 import argparse import json import sys from typing import Sequence, MutableSequence from dresources import DAction, action from external_services import ExternalServices from gcp import GcpResource if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 13, 21, 198, 198, 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 25064, 198, 6738, 19720, 1330, 45835, 11, 13859, 540, 44015, 594, 198, 198, 6738, 288, 37540, 1330, 360, 12502, 11, ...
3.423077
78
#!/usr/bin/python3 import pytest import monitor.monitorshared as m import monitor.consumtodb as con def test_db_connection(tmpdir): "test postgres connection" conf = m.Configuration('configx.ini', "test") # in case the field is empty if conf.db_host == '': pytest.skip("no broker configured in config.ini") db_handle = con.connect_db(conf) # function will fail if cannot connect assert db_handle
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 12972, 9288, 628, 198, 11748, 5671, 13, 2144, 6742, 71, 1144, 355, 285, 198, 11748, 5671, 13, 5936, 388, 83, 375, 65, 355, 369, 628, 198, 4299, 1332, 62, 9945, 62, 38659, ...
2.826923
156
import argparse import torch import yaml
[ 11748, 1822, 29572, 198, 198, 11748, 28034, 198, 11748, 331, 43695, 628, 198 ]
3.384615
13
# This codes are referenced from the Github repo (https://github.com/parulnith/Building-a-Simple-Chatbot-in-Python-using-NLTK/blob/master/chatbot.py) # Loading the required packages import nltk import random import string import warnings from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from textblob import TextBlob # Setup warnings.filterwarnings('ignore') # Ignore warning messages f = open('corpus_linguistics.txt', 'r') # opening the corpus text = f.read() # reading the corpus # Convert all text from corpus to lower case text = text.lower() # Perform tokenization sent_tokens = nltk.sent_tokenize(text) word_tokens = nltk.word_tokenize(text) # Initialize set of greetings and responses user_greetings = ["hi", "hello", "good morning", "hey", "what's up"] bot_greetings = ["Hello, how may I be of assistance?"] user_gratitude = ["thank you", "thanks", "that was helpful"] bot_gratitude = ["You're welcome! Is there anything else you need?", "Happy to help! Are there other questions that I could help " "with?"] bot_exit_text = ["Thank you for using my services. Have a great day!", "Hope I was helpful. See you later :)", "Bye!"] languages = {"en": "English", "fr": "French", "es": "Spanish", "la": "Latin"} # Text Preprocessing lemmatizer = nltk.stem.WordNetLemmatizer() # Text Lemmatization # Function to perform lemmatization remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation) # Function to perform normalization # Generating response # Perform sentiment analysis # Language detection # Interact with chatbot framework based on input from user
[ 2, 770, 12416, 389, 20717, 422, 262, 38994, 29924, 357, 5450, 1378, 12567, 13, 785, 14, 1845, 377, 77, 342, 14, 25954, 12, 64, 12, 26437, 12, 30820, 13645, 12, 259, 12, 37906, 12, 3500, 12, 45, 27734, 42, 14, 2436, 672, 14, 9866, ...
3.010435
575
#!/usr/bin/env python # encoding: utf-8 import sys LEVEL = { 'NORMAL': 0, 'INFO': 1, 'DEBUG': 2, 'CRITICAl': 0, 'ERROR': 0, 'EXCEPTION': 0, } logger = Logger()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 11748, 25064, 198, 198, 2538, 18697, 796, 1391, 198, 220, 220, 220, 705, 35510, 42126, 10354, 657, 11, 198, 220, 220, 220, 705, 10778, 10354...
1.9375
96
import SocketServer import io import logging import struct import threading import PIL.Image import pika import config logging.basicConfig(level=logging.INFO) if __name__ == "__main__": print 'Connecting to queue server' queue_connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get('queue_server_host'), port=int(config.get('queue_server_port')))) socket_server_port = int(config.get('socket_server_port')) print 'Starting socket server on port ', socket_server_port socket_server = ThreadedTCPServer((config.get('socket_server_host'), socket_server_port), RequestHandler) try: socket_server.serve_forever() except KeyboardInterrupt: pass print 'Closing queue connection' queue_connection.close() print 'Stopping socket server' socket_server.shutdown() socket_server.server_close()
[ 11748, 47068, 10697, 198, 11748, 33245, 198, 11748, 18931, 198, 11748, 2878, 198, 11748, 4704, 278, 198, 198, 11748, 350, 4146, 13, 5159, 198, 11748, 279, 9232, 198, 198, 11748, 4566, 198, 198, 6404, 2667, 13, 35487, 16934, 7, 5715, 28,...
3.003356
298
from pygame import image
[ 6738, 12972, 6057, 1330, 2939 ]
4.8
5
import os import shutil import build_utils
[ 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 1382, 62, 26791, 628, 628, 628, 628, 198 ]
3.1875
16
from .explorer import Explorer __version__ = "1.0.2"
[ 6738, 764, 20676, 11934, 1330, 19142, 198, 198, 834, 9641, 834, 796, 366, 16, 13, 15, 13, 17, 1 ]
2.789474
19
import subprocess import os.path import json import time import urllib.parse from typing import Any, Tuple import config from requests_html import HTMLSession from markdownify import markdownify
[ 11748, 850, 14681, 198, 11748, 28686, 13, 6978, 198, 11748, 33918, 198, 11748, 640, 198, 11748, 2956, 297, 571, 13, 29572, 198, 6738, 19720, 1330, 4377, 11, 309, 29291, 198, 11748, 4566, 198, 6738, 7007, 62, 6494, 1330, 11532, 36044, 19...
3.92
50
import pysdot as ot import numpy as np import matplotlib.pyplot as plt numPts = 100 xbnds = [0.0,1.0] # minimum and maximum x values ybnds = [0.0,1.0] # minimum and maximum y values Ns = [50,50] bbox = ot.BoundingBox(xbnds[0],xbnds[1],ybnds[0],ybnds[1]) grid = ot.RegularGrid(bbox, Ns[0], Ns[1]) dens = np.ones(Ns) for i in range(Ns[0]): for j in range(Ns[1]): pt = grid.Center(i,j) dens[i,j] = np.exp(-30.0*( (pt[0]-0.5)**2 + (pt[1]-0.5)**2)) dist = ot.DiscretizedDistribution(grid,dens) # Construct the Centroidal Voronoi diagram. This function uses Lloyd's algorithm # with latin hypercube samples as initial points (https://en.wikipedia.org/wiki/Lloyd%27s_algorithm) # Arguments to BuildCentroidal are: # - The bounding box # - The number of seed points (same as number of cells) in the Voronoi diagram # - The maximum number of allowed iterations in Lloyd's algorithm # - A tolerance on the maximum distance between a cell centroid and seed point. diag = ot.LaguerreDiagram.BuildCentroidal(bbox,numPts,1000,0.001,dist) areas = diag.Areas(dist) # Plot the resulting centroidal Voronoi diagram fig, axs = plt.subplots(ncols=2,figsize=(14,6)) ot.PlotDiagram(diag, axs[0], distribution=dist, cell_colors=areas) axs[0].set_title('Weighted CVD') axs[1].imshow(dens.T,extent=[xbnds[0],xbnds[1],ybnds[0],ybnds[1]],origin='lower',alpha=0.8) axs[1].set_title('Density') plt.show()
[ 11748, 279, 893, 26518, 355, 30972, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 22510, 47, 912, 796, 1802, 198, 198, 30894, 358, 82, 796, 685, 15, 13, 15, 11, 16, 13, ...
2.417526
582
#Exercise: Try to make a function that accepts a function of only positional arguments and returns a function that takes the same number of positional arguments and, given they are all iterators, attempts every combination of one arguments from each iterator. #Skills: Partial application, Iteration papplycomboreverse = lambda fun, xiter : lambda *args : [fun(*args, x) for x in xiter]
[ 2, 3109, 23697, 25, 9993, 284, 787, 257, 2163, 326, 18178, 257, 2163, 286, 691, 45203, 7159, 290, 5860, 257, 2163, 326, 2753, 262, 976, 1271, 286, 45203, 7159, 290, 11, 1813, 484, 389, 477, 11629, 2024, 11, 6370, 790, 6087, 286, 530...
4.311111
90
import os import sys os.chdir(os.path.dirname(__file__)) sys.path.append(os.path.dirname(__file__)) sys.path.append(os.path.join(sys.path[0], '/var/www/haproxy-wi/app/')) from bottle import route, run, template, hook, response, request, post import sql import funct
[ 11748, 28686, 198, 11748, 25064, 198, 418, 13, 354, 15908, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 198, 17597, 13, 69...
2.3
130
# Copyright [2015] Hewlett-Packard Development Company, L.P. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import tempfile from oslo_log import log as logging from oslo_utils import netutils from six.moves import configparser from trove.common import cfg from trove.common.db import models from trove.common import exception from trove.common.i18n import _ from trove.common import instance as rd_instance from trove.common.stream_codecs import PropertiesCodec from trove.common import utils from trove.guestagent.common.configuration import ConfigurationManager from trove.guestagent.common.configuration import ImportOverrideStrategy from trove.guestagent.common import guestagent_utils from trove.guestagent.common import operating_system from trove.guestagent.common.operating_system import FileMode from trove.guestagent.datastore.experimental.vertica import system from trove.guestagent.datastore import service from trove.guestagent import pkg from trove.guestagent import volume LOG = logging.getLogger(__name__) CONF = cfg.CONF packager = pkg.Package() DB_NAME = 'db_srvr' MOUNT_POINT = CONF.vertica.mount_point # We will use a fake configuration file for the options managed through # configuration groups that we apply directly with ALTER DB ... SET ... FAKE_CFG = os.path.join(MOUNT_POINT, "vertica.cfg.fake")
[ 2, 15069, 685, 4626, 60, 30446, 15503, 12, 11869, 446, 7712, 5834, 11, 406, 13, 47, 13, 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,...
3.634578
509
""" Waymo dataset with votes. Author: Ahmed Bahnasy Date: 2020 """ import os import sys import numpy as np import pickle from torch.utils.data import Dataset import scipy.io as sio # to load .mat files for depth points BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, '..', 'utils')) from box_util import get_corners_from_labels_array import pc_util import waymo_utils from model_util_waymo import WaymoDatasetConfig DC = WaymoDatasetConfig() # dataset specific config MAX_NUM_OBJ = 128 # maximum number of objects allowed per scene # RAW_LABELS = {0: 'TYPE_UNKNOWN', 1: 'TYPE_VEHICLE' , 2: 'TYPE_PEDESTRIAN', 3: 'TYPE_SIGN', 4: 'TYPE_CYCLIST'} def viz_votes(pc, point_votes, point_votes_mask): """ Visualize point votes and point votes mask labels pc: (N,3 or 6), point_votes: (N,9), point_votes_mask: (N,) """ inds = (point_votes_mask==1) pc_obj = pc[inds,0:3] pc_obj_voted1 = pc_obj + point_votes[inds,0:3] pc_obj_voted2 = pc_obj + point_votes[inds,3:6] pc_obj_voted3 = pc_obj + point_votes[inds,6:9] pc_util.write_ply(pc_obj, 'pc_obj.ply') pc_util.write_ply(pc_obj_voted1, 'pc_obj_voted1.ply') pc_util.write_ply(pc_obj_voted2, 'pc_obj_voted2.ply') pc_util.write_ply(pc_obj_voted3, 'pc_obj_voted3.ply') def viz_obb(pc, label, mask, angle_classes, angle_residuals, size_classes, size_residuals): """ Visualize oriented bounding box ground truth pc: (N,3) label: (K,3) K == MAX_NUM_OBJ mask: (K,) angle_classes: (K,) angle_residuals: (K,) size_classes: (K,) size_residuals: (K,3) """ oriented_boxes = [] K = label.shape[0] for i in range(K): if mask[i] == 0: continue obb = np.zeros(7) obb[0:3] = label[i,0:3] heading_angle = DC.class2angle(angle_classes[i], angle_residuals[i]) box_size = DC.class2size(size_classes[i], size_residuals[i]) obb[3:6] = box_size obb[6] = -1 * heading_angle print(obb) oriented_boxes.append(obb) pc_util.write_oriented_bbox(oriented_boxes, 'gt_obbs.ply') pc_util.write_ply(label[mask==1,:], 'gt_centroids.ply') def get_sem_cls_statistics(): """ Compute number of objects for each semantic class """ d = WaymoDetectionVotesDataset(use_height=True, augment=False) sem_cls_cnt = {} for i in range(len(d)): if i%10==0: print(i) sample = d[i] pc = sample['point_clouds'] sem_cls = sample['sem_cls_label'] mask = sample['box_label_mask'] for j in sem_cls: if mask[j] == 0: continue if sem_cls[j] not in sem_cls_cnt: sem_cls_cnt[sem_cls[j]] = 0 sem_cls_cnt[sem_cls[j]] += 1 print(sem_cls_cnt) if __name__=='__main__': d = WaymoDetectionVotesDataset(use_height=True, augment=False) # for i in range(len(d)): sample = d[0] print(sample['vote_label'].shape, sample['vote_label_mask'].shape) pc_util.write_ply(sample['point_clouds'], 'pc.ply') viz_votes(sample['point_clouds'], sample['vote_label'], sample['vote_label_mask']) viz_obb(sample['point_clouds'], sample['center_label'], sample['box_label_mask'], sample['heading_class_label'], sample['heading_residual_label'], sample['size_class_label'], sample['size_residual_label'])
[ 37811, 6378, 5908, 27039, 351, 5690, 13, 198, 198, 13838, 25, 21157, 13081, 77, 4107, 198, 10430, 25, 12131, 198, 198, 37811, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2298, 293, 198, 6738, 28...
2.18874
1,563
import unittest import sin_testing as st import pexpect import os if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 7813, 62, 33407, 355, 336, 198, 11748, 613, 87, 806, 198, 11748, 28686, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.714286
42
from budgetportal.models import ( FinancialYear, Sphere, Government, Department, Programme, ) from django.core.management import call_command from django.test import TestCase from tempfile import NamedTemporaryFile from StringIO import StringIO import yaml
[ 6738, 4466, 634, 282, 13, 27530, 1330, 357, 198, 220, 220, 220, 11302, 17688, 11, 198, 220, 220, 220, 31798, 11, 198, 220, 220, 220, 5070, 11, 198, 220, 220, 220, 2732, 11, 198, 220, 220, 220, 35232, 11, 198, 8, 198, 6738, 42625, ...
3.321429
84
import json import logging import ssl import sys from oidcrp.exception import ResponseError logger = logging.getLogger(__name__)
[ 11748, 33918, 198, 11748, 18931, 198, 11748, 264, 6649, 198, 11748, 25064, 198, 198, 6738, 267, 312, 6098, 79, 13, 1069, 4516, 1330, 18261, 12331, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 628, 198...
3.166667
42
from __future__ import unicode_literals import requests import json import os import sys outputs = []
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 11748, 7007, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 22915, 82, 796, 17635, 628 ]
3.586207
29
#! /usr/bin/python3 # # @(!--#) @(#) swss.py, version 002, 27-july-2018 # # open a series of home pages and take a screen shot of each one # ################################################################################################ # # imports # import sys import os import argparse import glob import shutil import tempfile import time import datetime from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import * ################################################################################################ ######################################################################### ######################################################################### ######################################################################### ######################################################################### ######################################################################### ######################################################################### ################################################################################################ ########################################################################## progname = os.path.basename(sys.argv[0]) sys.exit(main()) # end of file
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 18, 198, 2, 198, 2, 2488, 7, 28112, 2, 8, 2488, 7, 2, 8, 1509, 824, 13, 9078, 11, 2196, 3571, 17, 11, 2681, 12, 73, 2062, 12, 7908, 198, 2, 198, 2, 1280, 257, 2168, 286, 1363, 5468, ...
5.549356
233
"""state consumed Revision ID: 0be658f07ac6 Revises: bd1e892d0609 Create Date: 2021-07-18 21:26:04.588007 """ from alembic import op import sqlalchemy as sa from sqlalchemy.sql import table, column from sqlalchemy import String # revision identifiers, used by Alembic. revision = '0be658f07ac6' down_revision = 'bd1e892d0609' branch_labels = None depends_on = None
[ 37811, 5219, 13529, 198, 198, 18009, 1166, 4522, 25, 657, 1350, 38431, 69, 2998, 330, 21, 198, 18009, 2696, 25, 275, 67, 16, 68, 4531, 17, 67, 15, 31751, 198, 16447, 7536, 25, 33448, 12, 2998, 12, 1507, 2310, 25, 2075, 25, 3023, 1...
2.65
140
from unittest import TestCase, mock from copy import deepcopy from pydantic.error_wrappers import ValidationError from basemodels.pydantic import Manifest from basemodels.pydantic.manifest.data.taskdata import TaskDataEntry SIMPLE = { "job_mode": "batch", "request_type": "image_label_multiple_choice", "requester_accuracy_target": 0.8, "requester_description": "pyhcaptcha internal_id: 69efdbe1-e586-42f8-bf05-a5745f75402a", "requester_max_repeats": 7, "requester_min_repeats": 3, "requester_question": {"en": "deploy to only certain sites"}, "requester_restricted_answer_set": {"one": {"en": "one"}}, "task_bid_price": -1, "unsafe_content": False, "oracle_stake": 0.05, "recording_oracle_addr": "0x6a0E68eA5F706339dd6bd354F53EfcB5B9e53E49", "reputation_oracle_addr": "0x6a0E68eA5F706339dd6bd354F53EfcB5B9e53E49", "reputation_agent_addr": "0x6a0E68eA5F706339dd6bd354F53EfcB5B9e53E49", "groundtruth_uri": "https://hmt-jovial-lamport.hcaptcha.com/pyhcaptcha-client/taskdata/sha1:bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f.json", "taskdata_uri": "https://hmt-jovial-lamport.hcaptcha.com/pyhcaptcha-client/taskdata/sha1:97d170e1550eee4afc0af065b78cda302a97674c.json", "job_total_tasks": 0, "job_api_key": "417714f0-7ce6-412b-b394-0d2ae58a8c6d", "restricted_audience": { "sitekey": [ {"dfe03e7c-f417-4726-8b14-ae033a3cc66e": {"score": 1}}, {"dfe03e7c-f417-4726-8b12-ae033a3cc66a": {"score": 1}}, ] }, } TASK = { "task_key": "407fdd93-687a-46bb-b578-89eb96b4109d", "datapoint_uri": "https://domain.com/file1.jpg", "datapoint_hash": "f4acbe8562907183a484498ba901bfe5c5503aaa", "metadata": { "key_1": "value_1", "key_2": "value_2", } }
[ 6738, 555, 715, 395, 1330, 6208, 20448, 11, 15290, 198, 6738, 4866, 1330, 2769, 30073, 198, 198, 6738, 279, 5173, 5109, 13, 18224, 62, 29988, 11799, 1330, 3254, 24765, 12331, 198, 6738, 1615, 368, 375, 1424, 13, 79, 5173, 5109, 1330, ...
2.032955
880
from os.path import exists def get_next_path(path_frmt: str, start: int = 1) -> str: """Return next available path based on path_frmt (1 positional-placeholder)""" return path_frmt.format(get_next_path_index(path_frmt, start=start)) def get_next_path_index(path_frmt: str, start: int = 1) -> int: """Get next index of given path format (1 positional-placeholder) Raises: ValueError: if path_frmt does not contain one and only one positional-placeholder such as '{}' or '{:03d}' """ try: # Try some random int to check path_frmt consistency assert "3823243077" in path_frmt.format(3823243077) except (IndexError, AssertionError): # IndexError means more than one placeholder, AssertionError means none raise ValueError("path_frmt must contain only one positional-placeholder") from None except KeyError: raise ValueError("path_frmt must contain no named-placeholder") from None i = start while exists(path_frmt.format(i)): i += 1 return i
[ 6738, 28686, 13, 6978, 1330, 7160, 628, 198, 4299, 651, 62, 19545, 62, 6978, 7, 6978, 62, 8310, 16762, 25, 965, 11, 923, 25, 493, 796, 352, 8, 4613, 965, 25, 198, 220, 220, 220, 37227, 13615, 1306, 1695, 3108, 1912, 319, 3108, 62,...
2.673367
398
from .core import where, old_where __version__ = "2016.02.28"
[ 6738, 764, 7295, 1330, 810, 11, 1468, 62, 3003, 198, 198, 834, 9641, 834, 796, 366, 5304, 13, 2999, 13, 2078, 1, 198 ]
2.73913
23
from setuptools import setup, find_packages setup( name="QtCompat", version="0.1", packages=find_packages(), scripts=[], # Project uses reStructuredText, so ensure that the docutils get # installed or upgraded on the target machine install_requires=[], package_data={ }, # metadata for upload to PyPI author="Jacob Schaer", author_email="", description="PyQt4, 5 and Pyside Compatibility Library", license="MIT", keywords="pyqt4 pyqt5 pyside compatibility", url="https://github.com/jacobschaer/qt_compat/", # project home page, if any # could also include long_description, download_url, classifiers, etc. )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 48, 83, 40073, 1600, 198, 220, 220, 220, 2196, 2625, 15, 13, 16, 1600, 198, 220, 220, 220, 10392, 28, 19796, 62, 43789, 22784, ...
2.935345
232
import os from unittest import TestCase from aibolit.patterns.joined_validation.joined_validation import JoinedValidation from pathlib import Path
[ 11748, 28686, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 257, 571, 6212, 13, 33279, 82, 13, 46416, 62, 12102, 341, 13, 46416, 62, 12102, 341, 1330, 16709, 7762, 24765, 198, 6738, 3108, 8019, 1330, 10644, 628 ]
3.794872
39
""" Global tuple to avoid make a new one each time a method is called """ my_tuple = ("London", 123, 18.2) if __name__ == '__main__': main_tuple = city_tuple_declaration() print(main_tuple) print(my_tuple) tuple_get_element(5) print(bool_to_string_translator(tuple_has_element("London"))) print(bool_to_string_translator(tuple_has_not_element("London")))
[ 37811, 198, 22289, 46545, 284, 3368, 787, 257, 649, 530, 1123, 640, 257, 2446, 318, 1444, 198, 37811, 198, 1820, 62, 83, 29291, 796, 5855, 23421, 1600, 17031, 11, 1248, 13, 17, 8, 628, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624...
2.539474
152
import django_filters from . models import NerSample
[ 11748, 42625, 14208, 62, 10379, 1010, 198, 198, 6738, 764, 4981, 1330, 21783, 36674, 628 ]
3.666667
15
# TODO Postcode: https://m3o.com/postcode/overview
[ 2, 16926, 46, 2947, 8189, 25, 3740, 1378, 76, 18, 78, 13, 785, 14, 7353, 8189, 14, 2502, 1177, 198 ]
2.55
20
import numpy as np
[ 11748, 299, 32152, 355, 45941 ]
3.6
5
# -*- coding: utf-8 -*- # Copyright 2020 The PsiZ 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. # ============================================================================ """Module of TensorFlow kernel layers. Classes: GroupAttention: A simple group-specific attention layer. Kernel: A kernel that allows the user to separately specify a distance and similarity function. AttentionKernel: A kernel that uses group-specific attention weights and allows the user to separately specify a distance and similarity function. GroupAttentionVariational: A variational group attention layer. """ import numpy as np import tensorflow as tf from tensorflow.python.keras import backend as K import psiz.keras.constraints as pk_constraints import psiz.keras.initializers as pk_initializers from psiz.keras.layers.variational import Variational from psiz.keras.layers.distances.minkowski import WeightedMinkowski from psiz.models.base import GroupLevel
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 12131, 383, 350, 13396, 57, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, ...
3.65625
416
# Generated by Django 2.1.7 on 2019-08-04 06:43 import datetime from django.db import migrations, models import uuid
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 22, 319, 13130, 12, 2919, 12, 3023, 9130, 25, 3559, 198, 198, 11748, 4818, 8079, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 334, 27112, 628 ]
2.975
40
import platform #check the platform for linux, macos, windows if platform.system() == "Linux": print("manylinux1_x86_64") elif platform.system() == "Windows": print("win-amd64") elif platform.system() == "Darwin": print("macosx_10_15_x86_64") else: print("Unknown")
[ 11748, 3859, 198, 2, 9122, 262, 3859, 329, 32639, 11, 8352, 418, 11, 9168, 198, 361, 3859, 13, 10057, 3419, 6624, 366, 19314, 1298, 198, 220, 220, 220, 3601, 7203, 805, 2645, 259, 2821, 16, 62, 87, 4521, 62, 2414, 4943, 198, 417, ...
2.660377
106
# https://leetcode.com/problems/mirror-reflection
[ 2, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 10793, 1472, 12, 5420, 1564, 628 ]
2.833333
18
# coding=utf-8 # *** WARNING: this file was generated by the Kulado Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import kulado import kulado.runtime from .. import utilities, tables
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 50024, 4533, 24118, 687, 10290, 357, 27110, 5235, 8, 16984, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760,...
3.710526
76
""" running converferce for finite differences and Taylor-Green vortex """ import os from math import pi import xml.etree.ElementTree as ET import platform_paths as pp import manipulator as ma # load parameter file ma.set_ids('../XML/parameterTGVTime.xml') TREE = ET.parse('../XML/parameterTGVTime.xml') ROOT = TREE.getroot() ma.set_parameter(ROOT, 'withoutput', 1) ma.set_parameter(ROOT, 'initial guess', 'zero') # ma.set_parameter( ROOT, 'refinement level', 1 ) # make executable ready EXE = 'peri_navier3DTime' os.chdir(pp.EXE_PATH) os.system('make '+EXE+' -j4') CASE_PATH = ['']*4 RUNS = range(1) RES = [10] STS = [0.1, 10., 1.] NFS = [72] ma.set_parameter(ROOT, 'nx', 65) ma.set_parameter(ROOT, 'ny', 65) ma.set_parameter(ROOT, 'nz', 5) CASE_PATH[0] = pp.DATA_PATH + '/FDTGV_conv2' pp.mkdir(CASE_PATH, 0) for re in RES: CASE_PATH[1] = '/re_'+str(re) pp.mkdir(CASE_PATH, 1) for st in STS: CASE_PATH[2] = '/a2_'+str(st) pp.mkdir(CASE_PATH, 2) for nf in NFS: CASE_PATH[3] = '/nt_'+str(nf) pp.mkdir(CASE_PATH, 3) # pp.chdir(CASE_PATH, 3) # ma.set_parameter(ROOT, 'Re', re) ma.set_parameter(ROOT, 'alpha2', 2.*pi*st*re) ma.set_parameter(ROOT, 'nf', nf) ma.set_parameter(ROOT, 'npx', 1) ma.set_parameter(ROOT, 'npy', 1) ma.set_parameter(ROOT, 'npz', 1) ma.set_parameter(ROOT, 'npf', 12) TREE.write('parameter3D.xml') # nptot = npx[i]*npy[i]*npf[i] nptot = 12 mem = int(max(1024, 60*1024/nptot)) for run in RUNS: print() print(CASE_PATH) exeString = \ pp.exe_pre(nptot, ' -N -R "rusage[mem=' + str(mem) + ']" -W 6:00', run) + \ pp.EXE_PATH+'/'+EXE print(exeString) os.system(exeString)
[ 37811, 2491, 6718, 2232, 344, 329, 27454, 5400, 290, 8121, 12, 13719, 42726, 37227, 198, 11748, 28686, 198, 6738, 10688, 1330, 31028, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 198, 11748, 3859, 62, 6978, 82, 355, 97...
1.78777
1,112
""" """ import logging import os import random import time import matplotlib import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from helper import loader, utility as util matplotlib.use("agg") INPUT_IMAGE_DIR = "input" INTERPOLATED_IMAGE_DIR = "interpolated" TRUE_IMAGE_DIR = "true"
[ 37811, 198, 198, 37811, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 640, 198, 198, 11748, 2603, 29487, 8019, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, ...
2.934579
107
from .context import main
[ 198, 6738, 764, 22866, 1330, 1388, 198 ]
3.857143
7
import os.path as osp import numpy as np import math from tqdm import tqdm import torch.nn as nn import torch.backends.cudnn as cudnn import torch.utils.data from torchvision import transforms, datasets from ofa.utils import AverageMeter, accuracy from ofa.model_zoo import ofa_specialized from ofa.imagenet_classification.elastic_nn.utils import set_running_statistics import copy import random net_id = ['pixel1_lat@143ms_top1@80.1_finetune@75', 'pixel1_lat@132ms_top1@79.8_finetune@75', 'pixel1_lat@79ms_top1@78.7_finetune@75', 'pixel1_lat@58ms_top1@76.9_finetune@75', 'pixel1_lat@40ms_top1@74.9_finetune@25', 'pixel1_lat@28ms_top1@73.3_finetune@25', 'pixel1_lat@20ms_top1@71.4_finetune@25', 'pixel2_lat@62ms_top1@75.8_finetune@25', 'pixel2_lat@50ms_top1@74.7_finetune@25', 'pixel2_lat@35ms_top1@73.4_finetune@25', 'pixel2_lat@25ms_top1@71.5_finetune@25', 'note10_lat@64ms_top1@80.2_finetune@75', 'note10_lat@50ms_top1@79.7_finetune@75', 'note10_lat@41ms_top1@79.3_finetune@75', 'note10_lat@16ms_top1@75.5_finetune@25', 'note10_lat@11ms_top1@73.6_finetune@25', 'note10_lat@8ms_top1@71.4_finetune@25', 'note8_lat@65ms_top1@76.1_finetune@25', 'note8_lat@49ms_top1@74.9_finetune@25', 'note8_lat@31ms_top1@72.8_finetune@25', 'note8_lat@22ms_top1@70.4_finetune@25', 's7edge_lat@88ms_top1@76.3_finetune@25', 's7edge_lat@58ms_top1@74.7_finetune@25', 's7edge_lat@41ms_top1@73.1_finetune@25', 's7edge_lat@29ms_top1@70.5_finetune@25', 'LG-G8_lat@24ms_top1@76.4_finetune@25', 'LG-G8_lat@16ms_top1@74.7_finetune@25', 'LG-G8_lat@11ms_top1@73.0_finetune@25', 'LG-G8_lat@8ms_top1@71.1_finetune@25', '1080ti_gpu64@27ms_top1@76.4_finetune@25', '1080ti_gpu64@22ms_top1@75.3_finetune@25', '1080ti_gpu64@15ms_top1@73.8_finetune@25', '1080ti_gpu64@12ms_top1@72.6_finetune@25', 'v100_gpu64@11ms_top1@76.1_finetune@25', 'v100_gpu64@9ms_top1@75.3_finetune@25', 'v100_gpu64@6ms_top1@73.0_finetune@25', 'v100_gpu64@5ms_top1@71.6_finetune@25', 'tx2_gpu16@96ms_top1@75.8_finetune@25', 'tx2_gpu16@80ms_top1@75.4_finetune@25', 'tx2_gpu16@47ms_top1@72.9_finetune@25', 'tx2_gpu16@35ms_top1@70.3_finetune@25', 'cpu_lat@17ms_top1@75.7_finetune@25', 'cpu_lat@15ms_top1@74.6_finetune@25', 'cpu_lat@11ms_top1@72.0_finetune@25', 'cpu_lat@10ms_top1@71.1_finetune@25', 'flops@595M_top1@80.0_finetune@75', 'flops@482M_top1@79.6_finetune@75', 'flops@389M_top1@79.1_finetune@75', ] sort_net_id=['tx2_gpu16@35ms_top1@70.3_finetune@25', 'note8_lat@22ms_top1@70.4_finetune@25', 's7edge_lat@29ms_top1@70.5_finetune@25', 'cpu_lat@10ms_top1@71.1_finetune@25', 'LG-G8_lat@8ms_top1@71.1_finetune@25', 'pixel1_lat@20ms_top1@71.4_finetune@25', 'note10_lat@8ms_top1@71.4_finetune@25', 'pixel2_lat@25ms_top1@71.5_finetune@25', 'v100_gpu64@5ms_top1@71.6_finetune@25', 'cpu_lat@11ms_top1@72. 0_finetune@25', '1080ti_gpu64@12ms_top1@72.6_finetune@25', 'note8_lat@31ms_top1@72.8_finetune@25', 'tx2_gpu16@47ms_top1@72.9_finetune@25', 'v100_gpu64@6ms_top1@73.0_finetune@25', 'LG-G8_lat@11ms_to p1@73.0_finetune@25', 's7edge_lat@41ms_top1@73.1_finetune@25', 'pixel1_lat@28ms_top1@73.3_finetune@25', 'pixel2_lat@35ms_top1@73.4_finetune@25', 'note10_lat@11ms_top1@73.6_finetune@25', '1080ti_gpu 64@15ms_top1@73.8_finetune@25', 'cpu_lat@15ms_top1@74.6_finetune@25', 's7edge_lat@58ms_top1@74.7_finetune@25', 'LG-G8_lat@16ms_top1@74.7_finetune@25', 'pixel2_lat@50ms_top1@74.7_finetune@25', 'note8_lat@49ms_top1@74.9_finetune@25', 'pixel1_lat@40ms_top1@74.9_finetune@25', '1080ti_gpu64@22ms_top1@75.3_finetune@25', 'v100_gpu64@9ms_top1@75.3_finetune@25', 'tx2_gpu16@80ms_top1@75.4_finetune@25', 'note10_lat@16ms_top1@75.5_finetune@25', 'cpu_lat@17ms_top1@75.7_finetune@25', 'tx2_gpu16@96ms_top1@75.8_finetune@25', 'pixel2_lat@62ms_top1@75.8_finetune@25', 'v100_gpu64@11ms_top1@76.1_finetune@25', 'note8_lat@65ms_top1@76.1_finetune@25', 's7edge_lat@88ms_top1@76.3_finetune@25', '1080ti_gpu64@27ms_top1@76.4_finetune@25', 'LG-G8_lat@24ms_top1@76.4_finetune@25', 'pixel1_lat@58ms_top1@76.9_finetune@75', 'pixel1_lat@79ms_top1@78.7_finetune@75', 'flops@389M_top1@79.1_finetune@75', 'note10_lat@41ms_top1@79.3_finetune@75', 'flops@482M_top1@79.6_finetune@75', 'note10_lat@50ms_top1@79.7_finetune@75', 'pixel1_lat@132ms_top1@79.8_finetune@75', 'flops@595M_top1@80.0_finetune@75', 'pixel1_lat@143ms_top1@80.1_finetune@75', 'note10_lat@64ms_top1@80.2_finetune@75']
[ 11748, 28686, 13, 6978, 355, 267, 2777, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 1891, 2412, 13, 66...
1.763307
2,649
# Script is deprecated, as of September 18, 2017. # zoneUnitCount now calculated with LoadData's _get_residential_units() # from pprint import pprint import os import sys import requests from collections import OrderedDict import csv import datetime PYTHON_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) sys.path.append(PYTHON_PATH) from housinginsights.sources.base import BaseApiConn from housinginsights.tools.logger import HILogger logger = HILogger(name=__file__, logfile="sources.log") if __name__ == '__main__': # Pushes everything from the logger to the command line output as well. my_api = CamaApiConn() csvfile = my_api.get_csv()
[ 2, 12327, 318, 39224, 11, 355, 286, 2693, 1248, 11, 2177, 13, 198, 2, 6516, 26453, 12332, 783, 10488, 351, 8778, 6601, 338, 4808, 1136, 62, 8154, 498, 62, 41667, 3419, 198, 2, 198, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 11748, ...
2.896266
241
""" The `~certbot_dns_cfproxy.dns_cfproxy` plugin automates the process of completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and subsequently removing, TXT records using the CFProxy API. Examples -------- .. code-block:: bash :caption: To acquire a certificate for ``example.com`` certbot certonly \\ -a certbot-dns-cfproxy:dns-cfproxy \\ -d example.com """
[ 37811, 198, 464, 4600, 93, 22583, 13645, 62, 67, 5907, 62, 12993, 36436, 13, 67, 5907, 62, 12993, 36436, 63, 13877, 3557, 689, 262, 1429, 286, 198, 785, 47130, 257, 7559, 67, 5907, 12, 486, 15506, 4427, 357, 63, 93, 330, 1326, 13, ...
2.811189
143
from flask import Flask, make_response, request from flask_cors import CORS import json from config import * from StudentCard import * from ApiError import * App = Flask(__name__) cors = CORS(App, resources={r'*': {'origins': ENV.ADDR_API_GATEWAY}}, headers='Content-Type: application/json') if __name__ == '__main__': App.run(host='0.0.0.0', port=ENV.PORT)
[ 6738, 42903, 1330, 46947, 11, 787, 62, 26209, 11, 2581, 198, 6738, 42903, 62, 66, 669, 1330, 327, 20673, 198, 11748, 33918, 198, 198, 6738, 4566, 1330, 1635, 198, 6738, 13613, 16962, 1330, 1635, 198, 6738, 5949, 72, 12331, 1330, 1635, ...
2.490446
157
import logging from smart_home.mqtt_client import MQTTClient from smart_home.utils_lambda import get_utc_timestamp, error_response, success_response, get_request_message_id, get_mqtt_topics_from_request, get_request_name, get_friendly_name_from_request
[ 11748, 18931, 198, 198, 6738, 4451, 62, 11195, 13, 76, 80, 926, 62, 16366, 1330, 337, 48, 15751, 11792, 198, 6738, 4451, 62, 11195, 13, 26791, 62, 50033, 1330, 651, 62, 315, 66, 62, 16514, 27823, 11, 4049, 62, 26209, 11, 1943, 62, ...
3.109756
82
from netCDF4 import Dataset import matplotlib import matplotlib.pyplot as plt from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection import matplotlib.cm as cm import numpy as np #------------------------------------------------------------- #------------------------------------------------------------- #------------------------------------------------------------------------------- if __name__ == "__main__": plot_testcase()
[ 6738, 2010, 34, 8068, 19, 1330, 16092, 292, 316, 198, 11748, 2603, 29487, 8019, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 13, 8071, 2052, 1330, 12280, 14520, 198, 6738, 2603, 29487, 8019...
4.777778
99
a, b = map(int, input().split()) if a+b >= 10: print("error") else: print(a+b)
[ 64, 11, 275, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 361, 257, 10, 65, 18189, 838, 25, 198, 220, 220, 220, 3601, 7203, 18224, 4943, 198, 17772, 25, 198, 220, 220, 220, 3601, 7, 64, 10, 65, 8, 198 ]
2.071429
42
#### import the simple module from the paraview from paraview.simple import * #### disable automatic camera reset on 'Show' paraview.simple._DisableFirstRenderCameraReset() network_number = 2 filename = 'test_network' directory = 'C:\\Users\\leal26\\Documents\\GitHub\\AeroPy\\aeropy\\CST\\' # get active view renderView = GetActiveViewOrCreate('RenderView') assembly = [] for i in range(1,network_number+1): # create a new 'XML Structured Grid Reader' test_network_vts = XMLStructuredGridReader(FileName=[directory + filename + str(i)+'.vts']) # show data in view test_network_vtsDisplay = Show(test_network_vts, renderView) # trace defaults for the display properties. test_network_vtsDisplay.Representation = 'Surface With Edges' test_network_vtsDisplay.ColorArrayName = [None, ''] test_network_vtsDisplay.OSPRayScaleFunction = 'PiecewiseFunction' test_network_vtsDisplay.SelectOrientationVectors = 'None' test_network_vtsDisplay.ScaleFactor = 0.1 test_network_vtsDisplay.SelectScaleArray = 'None' test_network_vtsDisplay.GlyphType = 'Arrow' test_network_vtsDisplay.GlyphTableIndexArray = 'None' test_network_vtsDisplay.DataAxesGrid = 'GridAxesRepresentation' test_network_vtsDisplay.PolarAxes = 'PolarAxesRepresentation' test_network_vtsDisplay.ScalarOpacityUnitDistance = 0.3272506722223079 # init the 'PiecewiseFunction' selected for 'OSPRayScaleFunction' test_network_vtsDisplay.OSPRayScaleFunction.Points = [2.326428429822192, 0.0, 0.5, 0.0, 37.626781425423815, 1.0, 0.5, 0.0] # reset view to fit data renderView.ResetCamera() # update the view to ensure updated data information renderView.Update() #### saving camera placements for all active views # current camera placement for renderView1 renderView.CameraPosition = [0.12476075744808501, 3.1845058646858693, 0.3710215545807592] renderView.CameraFocalPoint = [0.5, 0.5, 0.0037752263491506906] renderView.CameraViewUp = [-0.30729811760225784, -0.17101732138568032, 0.9361201539888863] renderView.CameraParallelScale = 0.7079657120931511 #### uncomment the following to render all views # RenderAllViews() # alternatively, if you want to write images, you can use SaveScreenshot(...).
[ 4242, 1330, 262, 2829, 8265, 422, 262, 1582, 615, 769, 201, 198, 6738, 1582, 615, 769, 13, 36439, 1330, 1635, 201, 198, 4242, 15560, 11353, 4676, 13259, 319, 705, 15307, 6, 201, 198, 1845, 615, 769, 13, 36439, 13557, 48893, 5962, 4581...
2.757869
826
import glob import json import os import subprocess import time import xml.etree.ElementTree as ET from xml.etree.ElementTree import ParseError import geopandas as gpd import rasterio import numpy as np from shapely.geometry import Polygon def listlike(arg): '''Checks whether an argument is list-like, returns boolean''' return not hasattr(arg, "strip") and (hasattr(arg, "__getitem__") or hasattr(arg, "__iter__")) def clean_dir(dir_to_clean, file_extensions): '''Deletes files with specified extension(s) from a directory. This function is intended to help cleanup outputs from command line tools that we do not want to keep. Files to be deleted will be identified using a wildcard with that file extension in dir_to_clean. Parameters ---------- dir_to_clean: string, path path to directory to delete files from file_extension: string or list-like of strings file extensions that will be used for identifying files to remove, such as ['.tfw', '.kml']. ''' if listlike(file_extensions): for ext in file_extensions: to_rem = glob.glob(os.path.join(dir_to_clean, '*{}'.format(ext))) for file in to_rem: os.remove(file) print("Removed {:,d} files with extension {}.".format( len(to_rem), ext)) elif type(file_extension) == str: to_rem = glob.glob(os.path.join(dir_to_clean, '*{}'.format(ext))) for file in to_rem: os.remove(file) print("Removed {:,d} files with extension {}.".format( len(to_rem), ext)) else: raise (TypeError, 'file_extensions needs to be a string or list-like of strings.') def clean_buffer_polys(poly_shp, tile_shp, odir, simp_tol=None, simp_topol=None): """Removes polygons within the buffer zone of a tile. This function removes polygons from a shapefile that fall in the buffered area of point cloud tile. When building footprints or tree crowns (for example) are delineated from a point cloud, a buffer around the tile is generally be used to avoid edge effects. This tool computes the centroid of each polygon and determines whether it falls within the bounds of the unbuffered tile. It outputs a new shapefile containing only those polygons whose centroids fall within the unbuffered tile. The polygons may be simplified using optional arguments simp_tol and simp_topol to reduce the number of points that define their boundaries. Parameters ---------- polygons_shp: string, path to shapefile (required) A shapefile containing the polygons delineated within a buffered tile. tile_shp: string, path to shapefile (required) A shapefile containing the bounds of the tile WITHOUT buffers odir: string, path to directory (required) Path to the output directory for the new shapefile simp_tol = numeric, Tolerance level for simplification. All points within a simplified geometry will be no more than simp_tol from the original. simp_topol = boolean (optional) Whether or not to preserve topology of polygons. If False, a quicker algorithm will be used, but may produce self-intersecting or otherwise invalid geometries. """ fname = os.path.basename(poly_shp) outfile = os.path.join(odir, fname) os.makedirs(odir, exist_ok=True) tile_boundary = gpd.read_file(tile_shp) polys = gpd.read_file(poly_shp) # boolean indicator of whether each polygon falls within tile boundary clean_polys_ix = polys.centroid.within(tile_boundary.loc[0].geometry) # retrieve the polygons within the boundary clean_polys = polys[clean_polys_ix] if simp_tol: clean_polys = clean_polys.simplify(simp_tol, simp_topol) if len(clean_polys) > 0: clean_polys.to_file(outfile) def clip_tile_from_shp(in_raster, in_shp, odir, buffer=0): '''Clips a raster image to the bounding box of a shapefile. The input raster will be clipped using a rasterio command line tool. The output raster will have the same name and file type as the input raster, and will be written to the output directory, odir. The process is executed using subprocess.run(). Parameters ---------- in_raster: string, path to file raster image to be clipped in_shp: string, path to file shapefile from which bounding box is calculated to clip the raster odir: string, path output directory where clipped raster will be stored buffer: numeric additional buffer to add to total bounding box of shapefile when clipping the raster Returns ------- proc_clip: CompletedProcess The result of executing subprocess.run using the rio clip command. ''' basename = os.path.basename(in_raster) # read the shapefile using geopandas and calculate its bounds gdf = gpd.read_file(in_shp) tile_bnds = ' '.join(str(x) for x in gdf.buffer(buffer).total_bounds) # create the output directory if it doesn't already exist os.makedirs(odir, exist_ok=True) outfile = os.path.join(odir, basename) # clip the raster proc_clip = subprocess.run( ['rio', 'clip', in_raster, outfile, '--bounds', tile_bnds], stderr=subprocess.PIPE, stdout=subprocess.PIPE) return proc_clip def convert_project(infile, outfile, crs): '''Converts a raster to another format and specifies its projection. Uses rasterio command line tool executed using subprocess. The file generated will have the same name and be in the same folder as the input file. Parameters ---------- infile: string, path to file input raster to be converted outfile: string, path to file output raster to be generated crs: string specification of coordinate reference system to use following rasterio command line tool (RIO) formatting (e.g., 'EPSG:3857') Returns ------- proc_convert: CompletedProcess result of executing subprocess.run using rio convert proc_project: CompletedProcess result of executing subprocess.run using rio edit-info ''' # convert the file to the new format proc_convert = subprocess.run(['rio', 'convert', infile, outfile], stderr=subprocess.PIPE, stdout=subprocess.PIPE) # add the projection info proc_project = subprocess.run(['rio', 'edit-info', '--crs', crs, outfile], stderr=subprocess.PIPE, stdout=subprocess.PIPE) return proc_convert, proc_project def validation_summary(xml_dir, verbose=False): ''' Generates a summary of validation results for a directory of lidar files Parameters ---------- xml_dir : string, path to directory directory containing xml files produced by LASvalidate verbose : boolean whether or not to include the messages describing why any files produced warning or failed validation. Returns ------- summary_report : a printed report ''' xmls = glob.glob(os.path.join(xml_dir, '*.xml')) passed = 0 warnings = 0 failed = 0 parse_errors = 0 warning_messages = [] failed_messages = [] for validation_report in xmls: try: tile_id = os.path.basename(validation_report).split('.')[0] tree = ET.parse(validation_report) root = tree.getroot() result = root.find('report').find('summary').text.strip() if result == 'pass': passed += 1 else: variable = root.find('report').find('details').find( result).find('variable').text note = root.find('report').find('details').find(result).find( 'note').text if result == 'fail': failed += 1 failed_messages.append('{} -> {} | {} : {}'.format( tile_id, result, variable, note)) elif result == 'warning': warnings += 1 warning_messages.append('{} -> {} | {} : {}'.format( tile_id, result, variable, note)) except ParseError: parse_errors += 1 summary = '''LASvalidate Summary ==================== Passed: {:,d} Failed: {:,d} Warnings: {:,d} ParseErrors: {:,d} '''.format(passed, failed, warnings, parse_errors) details = '''Details ======== {} {} '''.format('\n'.join(failed_messages), '\n'.join(warning_messages)) print(summary) if verbose: print(details) def move_invalid_tiles(xml_dir, dest_dir): '''Moves lidar data that fail validation checks into a new directory Parameters ---------- xml_dir : string, path to directory where the xml reports produced by LASvalidate can be found dest_dir : str, path to directory where you would like the point cloud and associated files to be moved Returns ------- A printed statement about how many tiles were moved. ''' xmls = glob.glob(os.path.join(xml_dir, '*.xml')) invalid_dir = dest_dir num_invalid = 0 for validation_report in xmls: tile_id = os.path.basename(validation_report).split('.')[0] tree = ET.parse(validation_report) root = tree.getroot() result = root.find('report').find('summary').text.strip() if result == 'fail': # move the lidar file to a different folder os.makedirs(invalid_dir, exist_ok=True) for invalid_file in glob.glob( os.path.join(xml_dir, tile_id + '*')): basename = os.path.basename(invalid_file) os.rename(invalid_file, os.path.join(invalid_dir, basename)) num_invalid += 1 print('Moved files for {} invalid tiles to {}'.format( num_invalid, invalid_dir)) def get_bbox_as_poly(infile, epsg=None): """Uses PDAL's info tool to extract the bounding box of a file as a shapely Polygon. If an EPSG code is provided, a GeoDataFrame is returned. Parameters ---------- infile : str, path to file path to input file that PDAL can read epsg : int EPSG code defining the coordinate reference system. Optional. Returns ------- bbox_poly : Polygon or GeoDataFrame By default (no EPSG is provided), a shapely Polygon with the bounding box as its coordinates is returned. If an EPSG code is specified, bbox_poly is returned as a GeoPandas GeoDataFrame. """ result = subprocess.run(['pdal', 'info', infile], stderr=subprocess.PIPE, stdout=subprocess.PIPE) json_result = json.loads(result.stdout.decode()) coords = json_result['stats']['bbox']['native']['boundary']['coordinates'] geometry = Polygon(*coords) if epsg: bbox_poly = gpd.GeoDataFrame( geometry=[geometry], crs={'init': 'epsg:{}'.format(epsg)}) else: bbox_poly = Polygon(*coords) return bbox_poly def fname(path): """returns the filename as basename split from extension. Parameters ----------- path : str, path to file filepath from which filename will be sliced Returns -------- filename : str name of file, split from extension """ filename = os.path.basename(path).split('.')[0] return filename def annulus(inner_radius, outer_radius, dtype=np.uint8): """Generates a flat, donut-shaped (annular) structuring element. A pixel is within the neighborhood if the euclidean distance between it and the origin falls between the inner and outer radii (inclusive). Parameters ---------- inner_radius : int The inner radius of the annular structuring element outer_radius : int The outer radius of the annular structuring element dtype : data-type The data type of the structuring element Returns ------- selem : ndarray The structuring element where elements of the neighborhood are 1 and 0 otherwise """ L = np.arange(-outer_radius, outer_radius + 1) X, Y = np.meshgrid(L, L) selem = np.array( ((X**2 + Y**2) <= outer_radius**2) * ( (X**2 + Y**2) >= inner_radius**2), dtype=dtype) return selem def inspect_failures(failed_dir): """Prints error messages reported for tiles that failed in the lidar processing pipeline. Parameters ---------- failed_dir : string, path to directory path to directory containing text files indicating any tiles which failed processing """ failed = glob.glob(os.path.join(failed_dir, '*.txt')) for filename in failed: with open(filename) as f: print([line for line in f.readlines() if line.rstrip() != '']) print('----------------------') def processing_summary(all_tiles, already_finished, processing_tiles, finished_dir, failed_dir, start_time): """Prints a summary indicating progress of a lidar processing pipeline. Parameters ---------- all_tiles : list-like all tiles within a lidar acquisition already_finished : list-like tiles which were successfully processed in a previous execution of the processing pipeline processing_tiles : list-like tiles which are being processed during the currently executing pipeline finished_dir : string, path to directory path to directory containing text files indicating any tiles which have finished processing failed_dir : string, path to directory path to directory containing text files indicating any tiles which failed processing start_time : float time the pipeline execution began, produced by time.time() """ failed = glob.glob(os.path.join(failed_dir, '*.txt')) finished = glob.glob(os.path.join(finished_dir, '*.txt')) summary = ''' Processing Summary ------------------- {:>5,d} tiles in acquisition {:>5,d} tiles previously finished in acquisition {:>5,d} tiles being processed in this run {:>5,d} tiles from this run finished {:>5,d} tiles failed '''.format( len(all_tiles), len(already_finished), len(processing_tiles), len(finished) - (len(all_tiles) - len(processing_tiles)), len(failed)) total_percent_unfinished = int(70 * (1 - len(finished) / len(all_tiles))) total_percent_finished = int(70 * len(finished) / len(all_tiles)) total_percent_failed = int(70 * len(failed) / len(all_tiles)) this_run_unfinished = int(70 - 70*(len(finished) - (len(all_tiles) - \ len(processing_tiles))) / len(processing_tiles)) this_run_finished = int(70*(len(finished) - (len(all_tiles) - \ len(processing_tiles))) / len(processing_tiles)) progress_bars = '|' + '=' * this_run_finished + ' '* this_run_unfinished +\ '!' * total_percent_failed + '| {:.1%} this run\n'.format((len(finished)\ - (len(all_tiles) - len(processing_tiles))) / len(processing_tiles)) + \ '|' + '=' * total_percent_finished + ' ' * total_percent_unfinished + '!' \ * total_percent_failed + '| {:.1%} total'.format(len(finished) / \ len(all_tiles)) print(summary) print(progress_bars) time_to_complete(start_time, len(processing_tiles), len(finished) - (len(all_tiles) - len(processing_tiles))) def print_dhms(s): """Prints number of days, hours, minutes, and seconds represented by number of seconds provided as input. Parameters ---------- s : numeric seconds """ days = s // (24 * 3600) s = s % (24 * 3600) hours = s // 3600 s %= 3600 minutes = s // 60 s %= 60 seconds = s if days > 0: print(f'{days:2.0f}d {hours:2.0f}h {minutes:2.0f}m {seconds:2.0f}s') elif hours > 0: print(f' {hours:2.0f}h {minutes:2.0f}m {seconds:2.0f}s') else: print(f' {minutes:2.0f}m {seconds:2.0f}s') def time_to_complete(start_time, num_jobs, jobs_completed): """Prints elapsed time and estimated time of completion. Parameters ---------- start_time : float time the pipeline execution began, produced by time.time() num_jobs : int total number of jobs to be completed jobs_completed : int number of jobs completed so far """ if jobs_completed == 0: print('\nNo jobs completed yet.') else: time_now = time.time() elapsed = time_now - start_time prop_complete = jobs_completed / num_jobs est_completion = elapsed / prop_complete time_left = est_completion - elapsed print('\nelapsed: ', end='\t') print_dhms(elapsed) print('remaining: ', end='\t') print_dhms(time_left) def make_buffered_fishnet(xmin, ymin, xmax, ymax, crs, spacing=1000, buffer=50): """Makes a GeoDataFrame with a fishnet grid that has overlapping edges. Converts an existing lidar tiling scheme into one that has overlapping tiles and which is aligned with a grid based on the spacing parameter. Parameters ---------- xmin, ymin, xmax, ymax : numeric Values indicating the extent of the existing lidar data. crs : Coordinate Reference System Must be readable by GeoPandas to create a GeoDataFrame. spacing : int Length and width of tiles in new tiling scheme prior to buffering buffer : int Amount of overlap between neighboring tiles. """ xmin, ymin = ( np.floor(np.array([xmin, ymin]) // spacing) * spacing).astype(int) xmax, ymax = ( np.ceil(np.array([xmax, ymax]) // spacing) * spacing).astype(int) + spacing xx, yy = np.meshgrid( np.arange(xmin, xmax + spacing, spacing), np.arange(ymin, ymax + spacing, spacing)) xx_leftbuff = xx[:, :-1] - buffer xx_rightbuff = xx[:, 1:] + buffer yy_downbuff = yy[:-1, :] - buffer yy_upbuff = yy[1:, :] + buffer ll = np.stack(( xx_leftbuff[1:, :].ravel(), # skip top row yy_downbuff[:, :-1].ravel())).T # skip right-most column ul = np.stack(( xx_leftbuff[:-1, :].ravel(), # skip bottom row yy_upbuff[:, :-1].ravel())).T # skip right-most column ur = np.stack(( xx_rightbuff[:-1, :].ravel(), # skip bottom row yy_upbuff[:, 1:].ravel())).T # skip left-most column lr = np.stack(( xx_rightbuff[1:, :].ravel(), # skip top row yy_downbuff[:, 1:].ravel())).T # skip left-most column buff_fishnet = np.stack([ll, ul, ur, lr]) polys = [ Polygon(buff_fishnet[:, i, :]) for i in range(buff_fishnet.shape[1]) ] ll_names = [x for x in (ll + buffer).astype(int).astype(str)] tile_ids = [ '_'.join(tile) + '_{}'.format(str(spacing)) for tile in ll_names ] buff_fishnet_gdf = gpd.GeoDataFrame(geometry=polys, crs=crs) buff_fishnet_gdf['tile_id'] = tile_ids return buff_fishnet_gdf.set_index('tile_id') def get_intersecting_tiles(src_tiles, new_tiles): """Identifies tiles from src that intersect tiles in new_tiles. This function is intended to identify the files which should be read for retiling a lidar acquisition into the new_tiles layout. src_tiles is expected to have a 'file_name' field. Parameters ---------- src_tiles : GeoDataFrame Original tiling scheme for lidar acquisition new_tiles : GeoDataFrame New tiling scheme for lidar acquisition, such as one created by the make_buffered_fishnet function Returns ------- joined_tiles : GeoDataFrame Each row shows a tile from new_tiles that intersected with one or more tiles from src_tiles. The list of tiles from src_tiles that intersect each tile in new_tiles are formatted as a space-delimited string. """ joined = gpd.sjoin(new_tiles, src_tiles) joined_tiles = joined.groupby(level=0)['file_name'].apply(list).apply( ' '.join).to_frame() joined_tiles.index.name = 'tile_id' joined_tiles = joined_tiles.rename({ 'file_name': 'intersecting_files' }, axis=1) return joined_tiles def parse_coords_from_tileid(tile_id): """Get the coordinates of the lower left corner of the tile, assuming the tile has been named in the pattern {XMIN}_{YMIN}_{LENGTH}. Parameters ---------- tile_id : string assumed tile_id follows the naming convention of {LLX}_{LLY}_{LENGTH} where: LLX = x-coordinate of lower-left corner of tile (in projected units) LLY = y-coordinate of lower-left corner of tile (in projected units) LENGTH = length of the raster (in projected units), assumed to be a square tile shape Returns ------- llx, lly, length : int x- and y- coordinates of lower-left corner and length of raster """ tile_parts = tile_id.split('_') if len(tile_parts) == 2: llx, lly = [int(coord) for coord in tile_parts] length = 1000 # assumed tile width if not explicit in tile_id elif len(tile_parts) == 3: llx, lly, length = [int(coord) for coord in tile_parts] return llx, lly, length
[ 11748, 15095, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 640, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 198, 6738, 35555, 13, 316, 631, 13, 20180, 27660, 1330, 2547, 325, 12331, 198, 1...
2.506525
8,659
#!/usr/bin/env python3 import unittest import sys sys.path.insert(0, '.') from random import choice from PIL import Image from stego.encoder import embed from stego.decoder import extract, _decompress, IncorrectPassword from stego.base import make_array, as_string, extract_metadata images = ['test/rgba.png', 'test/cmyk.tiff', 'test/greyscale.bmp'] image = choice(images) message = b'Pixels -> smallest unit(small colored square) that constitutes an images.' key = b'my_secret_key' if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 555, 715, 395, 198, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 705, 2637, 8, 198, 198, 6738, 4738, 1330, 3572, 198, 6738, 350, 4146, 1330, 7412, ...
2.912568
183
import pandas as pd from rpy2 import robjects from epysurv.simulation.utils import add_date_time_index_to_frame, r_list_to_frame
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 374, 9078, 17, 1330, 3857, 752, 82, 198, 198, 6738, 2462, 893, 333, 85, 13, 14323, 1741, 13, 26791, 1330, 751, 62, 4475, 62, 2435, 62, 9630, 62, 1462, 62, 14535, 11, 374, 62, 4868, 62, ...
2.693878
49
import cmake cmake.buildCmake( 'CodeBlockUnixMake', '../../', '../../assemble/' )
[ 11748, 12067, 539, 198, 198, 11215, 539, 13, 11249, 34, 15883, 7, 198, 220, 220, 220, 705, 10669, 12235, 47000, 12050, 3256, 198, 220, 220, 220, 705, 40720, 40720, 3256, 198, 220, 220, 220, 705, 40720, 40720, 292, 15140, 14, 6, 198, ...
2.159091
44
#!/usr/bin/env python3 # @file cow_pipeline.py # @author Ignacio Vizzo [ivizzo@uni-bonn.de] # # Copyright (c) 2021 Ignacio Vizzo, all rights reserved import argh from datasets import BunnyGeneratedDataset as Dataset from vdbfusion_pipeline import VDBFusionPipeline as Pipeline def main( data_source: str, config: str = "config/bunny.yaml", visualize: bool = False, ): """Help here!""" dataset = Dataset(data_source, apply_pose=True) pipeline = Pipeline(dataset, config, map_name="bunny") pipeline.run() pipeline.visualize() if visualize else None if __name__ == "__main__": argh.dispatch_command(main)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 2488, 7753, 220, 220, 220, 220, 220, 9875, 62, 79, 541, 4470, 13, 9078, 198, 2, 2488, 9800, 220, 220, 220, 16583, 48711, 569, 6457, 78, 220, 220, 220, 220, 685, 452, 6457, ...
2.599206
252
import os import pytest from dashboard_generator import DashboardGenerator
[ 11748, 28686, 198, 198, 11748, 12972, 9288, 198, 6738, 30415, 62, 8612, 1352, 1330, 16189, 3526, 8645, 1352, 628, 198 ]
3.9
20
""" Tests for opencadd.structure.superposition.engines.mda """ import pytest from opencadd.structure.core import Structure from opencadd.structure.superposition.engines.mda import MDAnalysisAligner
[ 37811, 198, 51, 3558, 329, 1280, 66, 2860, 13, 301, 5620, 13, 16668, 9150, 13, 1516, 1127, 13, 76, 6814, 198, 37811, 198, 198, 11748, 12972, 9288, 198, 6738, 1280, 66, 2860, 13, 301, 5620, 13, 7295, 1330, 32522, 198, 6738, 1280, 66,...
3.140625
64
import engine print("Python: Script 2") result = engine.query(Color) print("Python: Query colors from Script 2") for c in result: c.string() print("--------------------")
[ 11748, 3113, 198, 198, 4798, 7203, 37906, 25, 12327, 362, 4943, 198, 198, 20274, 796, 3113, 13, 22766, 7, 10258, 8, 198, 4798, 7203, 37906, 25, 43301, 7577, 422, 12327, 362, 4943, 198, 1640, 269, 287, 1255, 25, 198, 220, 220, 220, 2...
3.358491
53
# ##### BEGIN MIT LICENSE BLOCK ##### # # MIT License # # Copyright (c) 2022 Steven Garcia # # 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. # # ##### END MIT LICENSE BLOCK ##### import bpy from ..global_functions import tag_format from ..file_model import build_scene as build_scene_model from ..file_physics import build_scene as build_scene_physics from ..file_animation import build_scene as build_scene_animation from ..file_collision import build_scene as build_scene_collision from ..file_level import build_scene as build_scene_level from ..file_camera_track import build_scene as build_camera_track from ..file_model.process_file_mode_retail import process_file_mode_retail as process_mode from ..file_model.process_file_mod2_retail import process_file_mod2_retail as process_mod2 from ..file_collision.process_file_retail import process_file_retail as process_collision_retail from ..file_physics.process_file_retail import process_file_retail as process_physics_retail from ..file_animation.process_file_retail import process_file_retail as process_animation_retail from ..file_level.h1.process_file_retail import process_file_retail as process_level_retail from ..file_level.h2.process_file import process_file_retail as process_h2_level from ..file_camera_track.process_file_retail import process_file_retail as process_camera_track_retail if __name__ == '__main__': bpy.ops.import_scene.model()
[ 2, 46424, 347, 43312, 17168, 38559, 24290, 9878, 11290, 46424, 198, 2, 198, 2, 17168, 13789, 198, 2, 198, 2, 15069, 357, 66, 8, 33160, 8239, 18555, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1...
3.466476
701
import gzip, os, struct, zipfile, io
[ 198, 11748, 308, 13344, 11, 28686, 11, 2878, 11, 19974, 7753, 11, 33245, 628, 628 ]
2.733333
15
from __future__ import absolute_import from time import * import datetime import six def get_utctimestamp(mtime=None): # pragma: no cover """ Converts local mtime (timestamp) to integer UTC timestamp. If mtime is None, returns current UTC time. """ if mtime is None: if six.PY2: return int((datetime.datetime.now() - datetime.datetime(1970, 1, 1)).total_seconds()) return int(datetime.datetime.utcnow().timestamp()) return int(calendar.timegm(datetime.datetime.fromtimestamp(mtime).timetuple()))
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 640, 1330, 1635, 198, 11748, 4818, 8079, 198, 11748, 2237, 198, 198, 4299, 651, 62, 315, 310, 320, 27823, 7, 76, 2435, 28, 14202, 2599, 1303, 23864, 2611, 25, 645, 3002, 198, ...
2.947977
173
__version__ = [1, 0, 2] __versionstr__ = '.'.join([str(i) for i in __version__]) if __name__ == '__main__': print(__versionstr__)
[ 834, 9641, 834, 796, 685, 16, 11, 657, 11, 362, 60, 198, 198, 834, 9641, 2536, 834, 796, 705, 2637, 13, 22179, 26933, 2536, 7, 72, 8, 329, 1312, 287, 11593, 9641, 834, 12962, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417,...
2.368421
57
from pathlib import Path from typing import Dict from eodatasets3 import serialise from .common import assert_same, dump_roundtrip
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 360, 713, 198, 198, 6738, 304, 375, 265, 292, 1039, 18, 1330, 11389, 786, 198, 6738, 764, 11321, 1330, 6818, 62, 31642, 11, 10285, 62, 744, 39813, 628 ]
3.594595
37
import numpy as np import matplotlib.pyplot as plt #################### #################### comp_pJ = 22. * 1e-12 / 32. / 16. num_layers = 6 num_comparator = 8 results = np.load('results.npy', allow_pickle=True).item() y_mean = np.zeros(shape=(2, 2, 2, 2, num_layers)) y_std = np.zeros(shape=(2, 2, 2, 2, num_layers)) y_mac_per_cycle = np.zeros(shape=(2, 2, 2, 2, num_layers)) y_mac_per_pJ = np.zeros(shape=(2, 2, 2, 2, num_layers)) cycle = np.zeros(shape=(2, 2, 2, 2, num_layers)) nmac = np.zeros(shape=(2, 2, 2, 2, num_layers)) array = np.zeros(shape=(2, 2, 2, 2, num_layers)) y_ron = np.zeros(shape=(2, 2, 2, 2, num_layers)) y_roff = np.zeros(shape=(2, 2, 2, 2, num_layers)) y_adc = np.zeros(shape=(2, 2, 2, 2, num_layers, num_comparator)) y_energy = np.zeros(shape=(2, 2, 2, 2, num_layers)) array_util = np.zeros(shape=(2, 2, 2, 2, num_layers)) for key in sorted(results.keys()): (skip, cards, alloc, profile) = key alloc = 1 if alloc == 'block' else 0 layer_results = results[key] max_cycle = 0 for layer in range(num_layers): rdict = merge_dicts(layer_results[layer]) ############################ y_mean[skip][cards][alloc][profile][layer] = np.mean(rdict['mean']) y_std[skip][cards][alloc][profile][layer] = np.mean(rdict['std']) ############################ y_ron[skip][cards][alloc][profile][layer] = np.sum(rdict['ron']) y_roff[skip][cards][alloc][profile][layer] = np.sum(rdict['roff']) y_adc[skip][cards][alloc][profile][layer] = np.sum(rdict['adc'], axis=0) y_energy[skip][cards][alloc][profile][layer] += y_ron[skip][cards][alloc][profile][layer] * 2e-16 y_energy[skip][cards][alloc][profile][layer] += y_roff[skip][cards][alloc][profile][layer] * 2e-16 y_energy[skip][cards][alloc][profile][layer] += np.sum(y_adc[skip][cards][alloc][profile][layer] * np.array([1,2,3,4,5,6,7,8]) * comp_pJ) y_mac_per_cycle[skip][cards][alloc][profile][layer] = np.sum(rdict['nmac']) / np.sum(rdict['cycle']) y_mac_per_pJ[skip][cards][alloc][profile][layer] = np.sum(rdict['nmac']) / 1e12 / np.sum(y_energy[skip][cards][alloc][profile][layer]) ############################ cycle[skip][cards][alloc][profile][layer] = np.mean(rdict['cycle']) nmac[skip][cards][alloc][profile][layer] = np.mean(rdict['nmac']) array[skip][cards][alloc][profile][layer] = np.mean(rdict['array']) ############################ max_cycle = max(max_cycle, np.mean(rdict['cycle'])) ############################ for layer in range(num_layers): rdict = merge_dicts(layer_results[layer]) ############################ y_cycle = np.mean(rdict['cycle']) y_stall = np.mean(rdict['stall']) y_array = np.mean(rdict['array']) array_util[skip][cards][alloc][profile][layer] = (y_array * y_cycle - y_stall) / (y_array * max_cycle) ############################ #################### layers = np.array(range(1, 6+1)) skip_none = int(np.max(cycle[1, 0, 0, 0])) skip_layer = int(np.max(cycle[1, 0, 0, 1])) skip_block = int(np.max(cycle[1, 0, 1, 1])) cards_none = int(np.max(cycle[1, 1, 0, 0])) cards_layer = int(np.max(cycle[1, 1, 0, 1])) cards_block = int(np.max(cycle[1, 1, 1, 1])) height = [skip_none, skip_layer, skip_block, cards_none, cards_layer, cards_block] x = ['skip/none', 'skip/layer', 'skip/block', 'cards/none', 'cards/layer', 'cards/block'] #################### plt.rcParams.update({'font.size': 12}) #################### plt.cla() plt.clf() plt.close() plt.ylabel('# Cycles') # plt.xlabel('Method') plt.xticks(range(len(x)), x, rotation=45) width = 0.2 plt.bar(x=x, height=height, width=width) ax = plt.gca() for i, h in enumerate(height): # print (i, h) ax.text(i - width, h + np.min(height)*0.02, str(h), fontdict={'size': 12}) fig = plt.gcf() fig.set_size_inches(9, 5) plt.tight_layout() fig.savefig('cycles.png', dpi=300) ####################
[ 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 14468, 4242, 198, 198, 14468, 4242, 198, 198, 5589, 62, 79, 41, 796, 2534, 13, 1635, 352, 68, 12, 1065, 1220, 3933, 13, 1220...
2.231774
1,838
#!/usr/bin/env python # # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # # # # getversion.py - Parse version numbers from C header files. # import os import re import sys import traceback __all__ = ['Parser', 'Result'] def svn_extractor(parser, include_file): '''Pull values from svn.version.h''' p.search('SVN_VER_MAJOR', 'major') p.search('SVN_VER_MINOR', 'minor') p.search('SVN_VER_PATCH', 'patch') try: r = p.parse(include_file) except IOError: typ, val, tb = sys.exc_info() msg = ''.join(traceback.format_exception_only(typ, val)) usage_and_exit(msg) sys.stdout.write("%d.%d.%d" % (r.major, r.minor, r.patch)) def sqlite_extractor(parser, include_file): '''Pull values from sqlite3.h''' p.search('SQLITE_VERSION_NUMBER', 'version') try: r = p.parse(include_file) except IOError: typ, val, tb = sys.exc_info() msg = ''.join(traceback.format_exception_only(typ, val)) usage_and_exit(msg) major = r.version / 1000000 minor = (r.version - (major * 1000000)) / 1000 micro = (r.version - (major * 1000000) - (minor * 1000)) sys.stdout.write("%d.%d.%d" % (major, minor, micro)) extractors = { 'SVN' : svn_extractor, # 'SQLITE' : sqlite_extractor, # not used } if __name__ == '__main__': if len(sys.argv) == 3: extractor = extractors[sys.argv[1]] include_file = sys.argv[2] else: usage_and_exit("Incorrect number of arguments") # Extract and print the version number p = Parser() extractor(p, include_file)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, ...
2.828715
794
#!/usr/bin/python import httplib import random import argparse import sys #Get options parser = argparse.ArgumentParser( description='Testing vote app') parser.add_argument( '-port', type=int, help='port of server', default=8000) parser.add_argument( '-host', type=str, help='server name/ip', default="localhost") args = parser.parse_args() #Color table colorList = ["blue", "orange", "red", "green", "yellow" ] colorSize = len(colorList) - 1 #Connect with server conn = httplib.HTTPConnection(args.host, args.port) #initial request conn.request("GET", "/") r1 = conn.getresponse() #print(r1.status, r1.reason) print(r1.read()) #vote loop count = 0 while count < 100 : count = count + 1 nColor = random.randint(0, colorSize) conn.request("GET", "/v1/vote?color="+colorList[nColor]) r1 = conn.getresponse() #print(r1.read()) print # view current results conn.request("GET", "/v1/listVotes") r1 = conn.getresponse() print(r1.read()) conn.request("GET", "/v1/listWorkers") r1 = conn.getresponse() print(r1.read()) conn.close()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 11748, 1841, 489, 571, 198, 11748, 4738, 198, 11748, 1822, 29572, 198, 11748, 25064, 198, 198, 2, 3855, 3689, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 7, 198, 220, 220, 220, 220,...
2.485777
457
from uuid import UUID import django_rq import logging from datetime import datetime, timezone, timedelta from django.core.mail import mail_managers from django.db.models import Count from django.db.models.functions import TruncDay from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render from operator import itemgetter from researcher_workspace.utils import offset_month_and_year from vm_manager.models import Instance, Resize, Volume from vm_manager.utils.utils import get_nectar from vm_manager.vm_functions.resize_vm import downsize_expired_supersized_vms from vm_manager.utils.Check_ResearchDesktop_Availability import \ check_availability logger = logging.getLogger(__name__)
[ 6738, 334, 27112, 1330, 471, 27586, 198, 198, 11748, 42625, 14208, 62, 81, 80, 198, 11748, 18931, 198, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 640, 11340, 11, 28805, 12514, 198, 6738, 42625, 14208, 13, 7295, 13, 4529, 1330, 6920, ...
3.355856
222
# rename shading group name to material name but with SG ended import pymel.core as pm import re selSG = pm.ls(sl=True,fl=True) for SG in selSG: curMat = pm.listConnections(SG,d=1) for mat in curMat: if pm.nodeType(mat) == 'blinn' or pm.nodeType(mat) == 'lambert': sgNM = re.split("_mat",str(mat))[0]+"SG" pm.rename(SG,sgNM)
[ 2, 36265, 49065, 1448, 1438, 284, 2587, 1438, 475, 351, 26147, 4444, 198, 11748, 279, 4948, 417, 13, 7295, 355, 9114, 198, 11748, 302, 198, 741, 38475, 796, 9114, 13, 7278, 7, 6649, 28, 17821, 11, 2704, 28, 17821, 8, 198, 1640, 2614...
2.185629
167
import pytest from common.common import NETTING_ACCOUNT from fixture.application import Application
[ 11748, 12972, 9288, 198, 6738, 2219, 13, 11321, 1330, 30502, 48996, 62, 26861, 28270, 198, 6738, 29220, 13, 31438, 1330, 15678, 628, 628 ]
4.478261
23
"""CHAPPS Utilities Tests .. todo:: Write tests for :class:`~chapps.util.VenvDetector` """ import pytest from pprint import pprint as ppr from chapps.util import AttrDict, PostfixPolicyRequest pytestmark = pytest.mark.order(1)
[ 37811, 3398, 2969, 3705, 41086, 30307, 198, 198, 492, 284, 4598, 3712, 628, 220, 19430, 5254, 329, 1058, 4871, 25, 63, 93, 354, 18211, 13, 22602, 13, 53, 24330, 11242, 9250, 63, 198, 198, 37811, 198, 11748, 12972, 9288, 198, 6738, 279...
2.865854
82
from django.contrib import admin from .models import Map admin.site.register(Map)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 9347, 628, 198, 28482, 13, 15654, 13, 30238, 7, 13912, 8, 198 ]
3.36
25
from . import pwcnet from . import pwcnet_irr from . import pwcnet_occ_joint from . import pwcnet_irr_occ_joint from . import tr_flow from . import tr_features from . import IRR_PWC from . import IRR_PWC_occ_joint from . import STAR PWCNet = pwcnet.PWCNet PWCNet_irr = pwcnet_irr.PWCNet PWCNet_occ_joint = pwcnet_occ_joint.PWCNet PWCNet_irr_occ_joint = pwcnet_irr_occ_joint.PWCNet TRFlow = tr_flow.TRFlow TRFlow_occjoint = tr_flow.TRFlow_occjoint TRFlow_irr = tr_flow.TRFlow_irr TRFlow_irr_occjoint = tr_flow.TRFlow_irr_occjoint TRFeat = tr_features.TRFeat TRFeat_occjoint = tr_features.TRFeat_occjoint TRFeat_irr_occjoint = tr_features.TRFeat_irr_occjoint # -- With refinement --- IRR_PWC = IRR_PWC.PWCNet IRR_occ_joint = IRR_PWC_occ_joint.PWCNet StarFlow = STAR.StarFlow
[ 6738, 764, 1330, 279, 86, 66, 3262, 198, 6738, 764, 1330, 279, 86, 66, 3262, 62, 343, 81, 198, 198, 6738, 764, 1330, 279, 86, 66, 3262, 62, 13966, 62, 73, 1563, 198, 6738, 764, 1330, 279, 86, 66, 3262, 62, 343, 81, 62, 13966, ...
2.060606
396
import os import re #hack for python2 support try: from .blkdiscoveryutil import * except: from blkdiscoveryutil import * if __name__ == '__main__': import pprint pp = pprint.PrettyPrinter(indent=4) l = Blkid() devdata = l.call_blkid() pp.pprint(devdata) disks = l.find_disks(devdata) pp.pprint(disks) details = l.details() pp.pprint(details)
[ 11748, 28686, 198, 11748, 302, 198, 2, 31153, 329, 21015, 17, 1104, 198, 28311, 25, 198, 220, 220, 220, 422, 764, 2436, 74, 67, 40821, 22602, 1330, 1635, 198, 16341, 25, 198, 220, 220, 220, 422, 698, 74, 67, 40821, 22602, 1330, 1635...
2.351515
165
# Copyright 2018 Cristian Mattarei # # Licensed under the modified BSD (3-clause BSD) License. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from pysmt.shortcuts import And, Or, Solver, TRUE, FALSE, Not, EqualsOrIff, Implies, Iff, Symbol, BOOL from cosa.utils.logger import Logger from cosa.utils.formula_mngm import substitute, get_free_variables from cosa.representation import TS from cosa.encoders.ltl import LTLEncoder, verification_type from cosa.problem import VerificationStatus, VerificationType from cosa.analyzers.mcsolver import TraceSolver, BMCSolver, VerificationStrategy from cosa.analyzers.bmc_temporal import BMCTemporal from cosa.analyzers.bmc_safety import BMCSafety
[ 2, 15069, 2864, 24568, 666, 4705, 533, 72, 198, 2, 198, 2, 49962, 739, 262, 9518, 347, 10305, 357, 18, 12, 565, 682, 347, 10305, 8, 13789, 13, 198, 2, 198, 2, 17486, 2672, 416, 9723, 1099, 393, 4987, 284, 287, 3597, 11, 3788, 19...
3.42807
285
#!/usr/bin/python3 # # Copyright (c) 2012 Mikkel Schubert <MikkelSch@gmail.com> # # 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 typing import Any, Iterable, Optional, Type, Union import paleomix.common.versions as versions from paleomix.common.command import ( AtomicCmd, InputFile, OptionsType, OutputFile, ParallelCmds, TempOutputFile, ) from paleomix.node import CommandNode, Node, NodeError from paleomix.nodes.bwa import ( _get_max_threads, _get_node_description, _new_cleanup_command, ) BOWTIE2_VERSION = versions.Requirement( call=("bowtie2", "--version"), regexp=r"version (\d+\.\d+\.\d+)", specifiers=">=2.3.0", ) def _bowtie2_template( call: Any, reference: str, iotype: Union[Type[InputFile], Type[OutputFile]] = InputFile, **kwargs: Any ): return AtomicCmd( call, extra_files=[ iotype(reference + postfix) for postfix in ( ".1.bt2", ".2.bt2", ".3.bt2", ".4.bt2", ".rev.1.bt2", ".rev.2.bt2", ) ], requirements=[BOWTIE2_VERSION], **kwargs )
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 198, 2, 15069, 357, 66, 8, 2321, 17722, 7750, 3059, 84, 4835, 1279, 44, 1134, 7750, 14874, 31, 14816, 13, 785, 29, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 38...
2.623669
845
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # import tensorflow as tf #using matrix x_data = [[73., 80., 75.], [93., 88., 93.,], [89., 91., 90.], [96., 98., 100.], [73., 66., 70.]] y_data = [[152.], [185.], [180.], [196.], [142.]] X = tf.placeholder(tf.float32, shape=[None, 3]) #n . tensorflow none . Y = tf.placeholder(tf.float32, shape=[None, 1]) W = tf.Variable(tf.random_normal([3, 1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias') hypothesis = tf.matmul(X, W)+b cost = tf.reduce_mean(tf.square(hypothesis - Y)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5) train = optimizer.minimize(cost) sess = tf.Session() sess.run(tf.global_variables_initializer()) for step in range(2001): cost_val, hy_val, _ = sess.run([cost, hypothesis, train], feed_dict={X: x_data, Y: y_data}) if step % 10 == 0: print(step, "Cost:", cost_val, "\nPrediction:\n", hy_val)
[ 11748, 28686, 198, 418, 13, 268, 2268, 17816, 10234, 62, 8697, 47, 62, 23678, 62, 25294, 62, 2538, 18697, 20520, 796, 705, 17, 6, 1303, 220, 220, 220, 220, 220, 220, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 2, 3500,...
2.351759
398
# (c) Copyright 2014,2015 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import abc from oslo_serialization import jsonutils as json from freezer.storage import physical
[ 2, 357, 66, 8, 15069, 1946, 11, 4626, 30446, 15503, 12, 11869, 446, 7712, 5834, 11, 406, 13, 47, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779...
3.797872
188
from rubicon.repository.asynchronous import AsynchronousBaseRepository from rubicon.repository.utils import json
[ 6738, 6437, 4749, 13, 260, 1930, 37765, 13, 292, 31301, 1330, 1081, 31301, 14881, 6207, 13264, 198, 6738, 6437, 4749, 13, 260, 1930, 37765, 13, 26791, 1330, 33918, 628 ]
3.931034
29
""" ================================================== Example on how to plot multiple datasets at a time ================================================== This is an example of how to download and plot multiple datasets at a time. .. image:: ../../multi_ds_plot1.png """ import act import matplotlib.pyplot as plt # Place your username and token here username = '' token = '' act.discovery.download_data(username, token, 'sgpceilC1.b1', '2019-01-01', '2019-01-07') # Read in CEIL data and correct it ceil_ds = act.io.armfiles.read_netcdf('sgpceilC1.b1/sgpceilC1.b1.201901*.nc') ceil_ds = act.corrections.ceil.correct_ceil(ceil_ds, -9999.) # Read in the MET data met_ds = act.io.armfiles.read_netcdf( act.tests.sample_files.EXAMPLE_MET_WILDCARD) # You can use tuples if the datasets in the tuple contain a # datastream attribute. This is required in all ARM datasets. display = act.plotting.TimeSeriesDisplay( (ceil_ds, met_ds), subplot_shape=(2, ), figsize=(15, 10)) display.plot('backscatter', 'sgpceilC1.b1', subplot_index=(0, )) display.plot('temp_mean', 'sgpmetE13.b1', subplot_index=(1, )) display.day_night_background('sgpmetE13.b1', subplot_index=(1, )) plt.show() # You can also use a dictionary so that you can customize # your datastream names to something that may be more useful. display = act.plotting.TimeSeriesDisplay( {'ceiliometer': ceil_ds, 'met': met_ds}, subplot_shape=(2, ), figsize=(15, 10)) display.plot('backscatter', 'ceiliometer', subplot_index=(0, )) display.plot('temp_mean', 'met', subplot_index=(1, )) display.day_night_background('met', subplot_index=(1, )) plt.show() ceil_ds.close() met_ds.close()
[ 37811, 198, 10052, 4770, 855, 198, 16281, 319, 703, 284, 7110, 3294, 40522, 379, 257, 640, 198, 10052, 4770, 855, 198, 198, 1212, 318, 281, 1672, 286, 703, 284, 4321, 290, 198, 29487, 3294, 40522, 379, 257, 640, 13, 198, 198, 492, 2...
2.832765
586
flat_x = x.flatten() flat_y = y.flatten() flat_z = z.flatten() size = flat_x.shape[0] filename = 'landscapeData.h' open(filename, 'w').close() f = open(filename, 'a') f.write('#include "LinearMath/btScalar.h"\n#define Landscape01VtxCount 4\n#define Landscape01IdxCount 4\nbtScalar Landscape01Vtx[] = {\n') for i in range(size): f.write(str(flat_x[i])+'f,'+str(flat_y[i])+'f,'+str(flat_z[i])+'f,\n') f.write('};\n') f.write('btScalar Landscape01Nml[] = {\n') for i in range(size): f.write('1.0f,1.0f,1.0f,\n') f.write('};\n') f.write('btScalar Landscape01Tex[] = {\n') for i in range(size): f.write('1.0f,1.0f,1.0f,\n') f.write('};\n') f.write('unsigned short Landscape01Idx[] = {\n') for i in range(size): f.write(str(i)+','+str(i+1)+','+str(i+2)+',\n') f.write('};\n') f.close()
[ 38568, 62, 87, 796, 2124, 13, 2704, 41769, 3419, 198, 38568, 62, 88, 796, 331, 13, 2704, 41769, 3419, 198, 38568, 62, 89, 796, 1976, 13, 2704, 41769, 3419, 198, 7857, 796, 6228, 62, 87, 13, 43358, 58, 15, 60, 198, 198, 34345, 796,...
2.032828
396
#### # This script demonstrates how to use the Tableau Server Client # to create new projects, both at the root level and how to nest them using # parent_id. # # # To run the script, you must have installed Python 3.6 or later. #### import argparse import logging import sys import tableauserverclient as TSC if __name__ == '__main__': main()
[ 4242, 198, 2, 770, 4226, 15687, 703, 284, 779, 262, 8655, 559, 9652, 20985, 198, 2, 284, 2251, 649, 4493, 11, 1111, 379, 262, 6808, 1241, 290, 703, 284, 16343, 606, 1262, 198, 2, 2560, 62, 312, 13, 198, 2, 198, 2, 198, 2, 1675, ...
3.394231
104
from threading import Thread import time import unittest import rasterio as rio from rasterio.env import get_gdal_config def test_child_thread_inherits_env(): """A new thread inherit's the main thread's env""" t1 = Thread(target=func) with rio.Env(FROM_MAIN=True): t1.start() assert get_gdal_config('FROM_MAIN') is True assert get_gdal_config('lol') is None t1.join() def test_child_thread_isolation(): """Child threads have isolated environments""" t1 = Thread(target=func, args=('is_t1', True, 'is_t2')) t2 = Thread(target=func, args=('is_t2', True, 'is_t1')) t1.start() t2.start() t1.join() t2.join() if __name__ == '__main__': unittest.main()
[ 6738, 4704, 278, 1330, 14122, 198, 11748, 640, 198, 11748, 555, 715, 395, 198, 198, 11748, 374, 1603, 952, 355, 374, 952, 198, 6738, 374, 1603, 952, 13, 24330, 1330, 651, 62, 21287, 282, 62, 11250, 628, 198, 198, 4299, 1332, 62, 941...
2.355769
312
#!/usr/bin/python # # Copyright 2020 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests the open source construction environments.""" from absl import flags from absl.testing import absltest from absl.testing import parameterized import dm_construction import numpy as np FLAGS = flags.FLAGS flags.DEFINE_string("backend", "docker", "") def _make_random_action(action_spec, observation): """Makes a random action given an action spec and observation.""" # Sample the random action. action = {} for name, spec in action_spec.items(): if name == "Index": value = np.random.randint(observation["n_edge"]) elif spec.dtype in (np.int32, np.int64, int): value = np.random.randint(spec.minimum, spec.maximum + 1) else: value = np.random.uniform(spec.minimum, spec.maximum) action[name] = value return action def _random_unroll(env, seed=1234, num_steps=10, difficulty=5, random_choice_before_reset=False): """Take random actions in the given environment.""" np.random.seed(seed) action_spec = env.action_spec() if random_choice_before_reset: np.random.choice([8], p=[1.]) timestep = env.reset(difficulty=difficulty) trajectory = [timestep] actions = [None] for _ in range(num_steps): if timestep.last(): if random_choice_before_reset: np.random.choice([8], p=[1.]) timestep = env.reset(difficulty=difficulty) action = _make_random_action(action_spec, timestep.observation) timestep = env.step(action) trajectory.append(timestep) actions.append(action) return trajectory, actions if __name__ == "__main__": absltest.main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 198, 2, 15069, 12131, 10766, 28478, 21852, 15302, 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.962416
745
from tkinter import * ventana = Tk() ventana.geometry("500x500") ventana.title('PythonGuides') img = PhotoImage(file='./logo.png') img = img.subsample(3, 3) Label( ventana, image=img ).pack(fill="both") ventana.mainloop()
[ 6738, 256, 74, 3849, 1330, 1635, 198, 198, 1151, 2271, 796, 309, 74, 3419, 198, 1151, 2271, 13, 469, 15748, 7203, 4059, 87, 4059, 4943, 198, 1151, 2271, 13, 7839, 10786, 37906, 8205, 1460, 11537, 628, 198, 9600, 796, 5555, 5159, 7, ...
2.586207
87
#coding:utf8 #author: yqq #date: 2020/12/15 5:38 #descriptions: from decimal import Decimal, getcontext # getcontext() if __name__ == '__main__': assert htdf_to_satoshi(139623.71827296) == 13962371827296 assert htdf_to_satoshi('139623.71827296') == 13962371827296 assert htdf_to_satoshi(13962371827296) == 13962371827296 * 10 ** 8 pass
[ 2, 66, 7656, 25, 40477, 23, 198, 2, 9800, 25, 331, 38227, 198, 2, 4475, 25, 12131, 14, 1065, 14, 1314, 642, 25, 2548, 198, 2, 20147, 1968, 507, 25, 198, 198, 6738, 32465, 1330, 4280, 4402, 11, 651, 22866, 198, 198, 2, 651, 22866...
2.316129
155
from dataclasses import asdict from hanzi_font_deconstructor.common.generate_training_data import ( STROKE_VIEW_BOX, get_training_input_svg_and_masks, ) from os import path, makedirs from pathlib import Path import shutil import argparse PROJECT_ROOT = Path(__file__).parents[2] DEST_FOLDER = PROJECT_ROOT / "data" parser = argparse.ArgumentParser( description="Generate training data for a model to deconstruct hanzi into strokes" ) parser.add_argument("--max-strokes-per-img", default=5, type=int) parser.add_argument("--total-images", default=50, type=int) args = parser.parse_args() if __name__ == "__main__": # create and empty the dest folder if path.exists(DEST_FOLDER): shutil.rmtree(DEST_FOLDER) makedirs(DEST_FOLDER) makedirs(DEST_FOLDER / "sample_svgs") # create the data data = { "viewbox": STROKE_VIEW_BOX, "imgs": [], } for i in range(args.total_images): (img_svg, stroke_masks) = get_training_input_svg_and_masks(256) label = f"{i}-{len(stroke_masks)}" with open(DEST_FOLDER / "sample_svgs" / f"{label}.svg", "w") as img_file: img_file.write(img_svg) print(".") print("Done!")
[ 6738, 4818, 330, 28958, 1330, 355, 11600, 198, 6738, 289, 272, 17027, 62, 10331, 62, 12501, 261, 7249, 273, 13, 11321, 13, 8612, 378, 62, 34409, 62, 7890, 1330, 357, 198, 220, 220, 220, 3563, 13252, 7336, 62, 28206, 62, 39758, 11, 1...
2.323755
522
from generic_dataset.data_pipeline import DataPipeline from generic_dataset.generic_sample import synchronize_on_fields from generic_dataset.sample_generator import SampleGenerator import numpy as np import generic_dataset.utilities.save_load_methods as slm pipeline_rgb_to_gbr = DataPipeline().add_operation(lambda data, engine: (data[:, :, [2, 1, 0]], engine)) # To model a regression problem, label_set parameter must be empty GeneratedSampleRegression = SampleGenerator(name='GeneratedSampleRegression', label_set=set()).add_dataset_field(field_name='rgb_image', field_type=np.ndarray, save_function=slm.save_compressed_numpy_array, load_function=slm.load_compressed_numpy_array) \ .add_dataset_field(field_name='bgr_image', field_type=np.ndarray, save_function=slm.save_cv2_image_bgr, load_function=slm.load_cv2_image_bgr) \ .add_field(field_name='field_3', field_type=int) \ .add_custom_pipeline(method_name='create_pipeline_convert_rgb_to_bgr', elaborated_field='rgb_image', final_field='bgr_image', pipeline=pipeline_rgb_to_gbr) \ .add_custom_method(method_name='field_3_is_positive', function=field_3_is_positive) \ .generate_sample_class()
[ 6738, 14276, 62, 19608, 292, 316, 13, 7890, 62, 79, 541, 4470, 1330, 6060, 47, 541, 4470, 198, 6738, 14276, 62, 19608, 292, 316, 13, 41357, 62, 39873, 1330, 18305, 1096, 62, 261, 62, 25747, 198, 6738, 14276, 62, 19608, 292, 316, 13,...
2.740654
428