content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
""" Setup. python setup.py build_ext --inplace """ from distutils.core import setup from Cython.Build import cythonize setup(ext_modules=cythonize('splay_tree.pyx'))
[ 37811, 198, 40786, 13, 198, 198, 29412, 9058, 13, 9078, 1382, 62, 2302, 1377, 259, 5372, 198, 37811, 198, 198, 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 198, 6738, 327, 7535, 13, 15580, 1330, 3075, 400, 261, 1096, 628, 198, 40406,...
2.758065
62
from WebApp.mainapp import app import dash_html_components as html import flask from REST_API.rest_api import API from WebApp.Layout import Layout app.layout = Layout() app.server.register_blueprint(API) server = app.server if __name__ == '__main__': # app.run_server(debug=False, host='0.0.0.0', port=90) app.run_server(debug=True)
[ 6738, 5313, 4677, 13, 12417, 1324, 1330, 598, 198, 11748, 14470, 62, 6494, 62, 5589, 3906, 355, 27711, 198, 11748, 42903, 198, 6738, 30617, 62, 17614, 13, 2118, 62, 15042, 1330, 7824, 198, 6738, 5313, 4677, 13, 32517, 1330, 47639, 198, ...
2.811475
122
''' Leia 2 valores inteiros (A e B). Aps, o programa deve mostrar uma mensagem "Sao Multiplos" ou "Nao sao Multiplos", indicando se os valores lidos so mltiplos entre si. ''' data = str(input()) values = data.split(' ') first_value = int(values[0]) second_value = int(values[1]) if(second_value > first_value): resul = second_value / first_value if(first_value * resul == second_value and second_value % first_value == 0): print('Sao Multiplos') else: print('Nao sao Multiplos') else: result = first_value / second_value if(second_value * result == first_value and first_value % second_value == 0): print('Sao Multiplos') else: print('Nao sao Multiplos')
[ 7061, 6, 198, 3123, 544, 362, 1188, 2850, 493, 20295, 4951, 357, 32, 304, 347, 737, 317, 862, 11, 267, 1430, 64, 390, 303, 749, 20040, 334, 2611, 285, 641, 363, 368, 366, 50, 5488, 15237, 489, 418, 1, 267, 84, 198, 1, 45, 5488, ...
2.494774
287
import re from slack_bolt import App from app.onboarding import ( message_multi_users_select, message_multi_users_select_lazy, ) from app.tutorials import ( tutorial_page_transition, tutorial_page_transition_lazy, app_home_opened, app_home_opened_lazy, page1_home_tab_button_click, page1_home_tab_button_click_lazy, page1_home_tab_users_select_lazy, page1_home_tab_users_select, page2_modal, page2_modal_lazy, page2_modal_submission, page4_create_channel, page4_create_channel_lazy, page4_create_channel_submission, page4_create_channel_submission_lazy, page4_create_channel_setup, page4_create_channel_setup_lazy, global_shortcut_handler, global_shortcut_view_submission, global_shortcut_view_submission_lazy, message_shortcut_handler, message_shortcut_handler_lazy, external_data_source_handler, )
[ 11748, 302, 198, 198, 6738, 30740, 62, 25593, 1330, 2034, 198, 198, 6738, 598, 13, 261, 27794, 1330, 357, 198, 220, 220, 220, 3275, 62, 41684, 62, 18417, 62, 19738, 11, 198, 220, 220, 220, 3275, 62, 41684, 62, 18417, 62, 19738, 62, ...
2.414439
374
import nltk import re from nltk.corpus import wordnet # This method reads the file and redacts names in it and writes redacted data to file with extension python3.redacted
[ 11748, 299, 2528, 74, 198, 11748, 302, 198, 6738, 299, 2528, 74, 13, 10215, 79, 385, 1330, 1573, 3262, 198, 198, 2, 770, 2446, 9743, 262, 2393, 290, 2266, 8656, 3891, 287, 340, 290, 6797, 44740, 1366, 284, 2393, 351, 7552, 21015, 18...
3.702128
47
# Space : O(n) # Time : O(m*n)
[ 2, 4687, 220, 220, 220, 220, 1058, 440, 7, 77, 8, 198, 2, 3862, 220, 220, 220, 220, 220, 1058, 440, 7, 76, 9, 77, 8, 198 ]
1.481481
27
import os from datetime import datetime import time import pandas as pd from datasets.linear import LinearProblem from regresion.linear.feature import PolFeatures from regresion.linear.linear import LinearRegression # lr = LinearRegression() # p = ParkingProblem(lr) # p.fit_solving()
[ 11748, 28686, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 640, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 40522, 13, 29127, 1330, 44800, 40781, 198, 6738, 842, 411, 295, 13, 29127, 13, 30053, 1330, 2165, 23595, ...
3.452381
84
from output.models.nist_data.atomic.name.schema_instance.nistschema_sv_iv_atomic_name_max_length_1_xsd.nistschema_sv_iv_atomic_name_max_length_1 import NistschemaSvIvAtomicNameMaxLength1 __all__ = [ "NistschemaSvIvAtomicNameMaxLength1", ]
[ 6738, 5072, 13, 27530, 13, 77, 396, 62, 7890, 13, 47116, 13, 3672, 13, 15952, 2611, 62, 39098, 13, 77, 1023, 2395, 2611, 62, 21370, 62, 452, 62, 47116, 62, 3672, 62, 9806, 62, 13664, 62, 16, 62, 87, 21282, 13, 77, 1023, 2395, 26...
2.392157
102
""" 1. Normalizing the entire dataset with mean and variance, shuffle, compression=9 runs for more than 8 hours on ocelote and results in a file of more than 150GB. 2. Try normalizing with only variance and without shuffle. """ import os.path import sys import time import h5py import numpy as np def calculate_mean_variance(dsets): """ Given a list of datasets calculate the mean and variance for all rows in all datasets. Arguments: dsets: sequence of datasets with matching column counts Returns: (mean, variance): tuple of mean vector and variance vector """ print('calculating mean and variance for "{}"'.format([dset.name for dset in dsets])) t0 = time.time() mean = np.zeros((1, dsets[0].shape[1])) M2 = np.zeros((1, dsets[0].shape[1])) count = 0 for dset in dsets: # find the right subset size to load without running out of memory # if dset has more than 10,000 rows use 10,000 # if dset has fewer than 10,000 rows load the whole dset dsubset = np.zeros((min(10000, dset.shape[0]), dset.shape[1])) print(' working on "{}"'.format(dset.name)) for n in range(0, dset.shape[0], dsubset.shape[0]): m = min(n + dsubset.shape[0], dset.shape[0]) dset.read_direct(dsubset, source_sel=np.s_[n:m, :]) t00 = time.time() for i in range(0, dsubset.shape[0]): count = count + 1 delta = dsubset[i, :] - mean mean += delta / count delta2 = dsubset[i, :] - mean M2 += delta * delta2 print(' processed slice [{}:{}] {:5.2f}s'.format(n, m, time.time()-t00)) print(' finished mean and variance in {:5.2f}s'.format(time.time()-t0)) # return mean, variance return (mean, M2/(count - 1)) if __name__ == '__main__': main()
[ 37811, 198, 16, 13, 14435, 2890, 262, 2104, 27039, 351, 1612, 290, 24198, 11, 36273, 11, 19794, 28, 24, 4539, 329, 517, 621, 807, 2250, 319, 198, 220, 220, 267, 5276, 1258, 290, 2482, 287, 257, 2393, 286, 517, 621, 6640, 4579, 13, ...
2.315217
828
from flask_restful import fields from .custom import Num, EdgeUrl, PaginateUrl getCommentField = { "id": fields.Integer, "time": fields.DateTime(attribute="timestamp"), "author_name": fields.String(attribute="username"), "article_id": fields.Integer(attribute="postid"), "body": fields.String, "urls": { "arthor": fields.Url("api.user", absolute=True), "post": fields.Url("api.post", absolute=True), }, } getPostCommentsField = { "prev": EdgeUrl("api.post_comments", 0), "next": EdgeUrl("api.post_comments", 1), "all_comments": fields.Integer(attribute="total"), "all_pages": fields.Integer(attribute="pages"), "urls": fields.List( PaginateUrl("api.comment", "commentid", "id"), attribute="items" ), }
[ 6738, 42903, 62, 2118, 913, 1330, 7032, 198, 6738, 764, 23144, 1330, 31835, 11, 13113, 28165, 11, 31525, 4559, 28165, 198, 198, 1136, 21357, 15878, 796, 1391, 198, 220, 220, 220, 366, 312, 1298, 7032, 13, 46541, 11, 198, 220, 220, 220...
2.698962
289
from django import template from faq.forms import FaqInstanceForm, FaqAnswerForm from faq.models import FaqInstance, FaqAnswer register = template.Library()
[ 6738, 42625, 14208, 1330, 11055, 198, 198, 6738, 24685, 80, 13, 23914, 1330, 18350, 80, 33384, 8479, 11, 18350, 80, 33706, 8479, 198, 6738, 24685, 80, 13, 27530, 1330, 18350, 80, 33384, 11, 18350, 80, 33706, 628, 198, 30238, 796, 11055,...
3.521739
46
# flake8: noqa """ MarkFlow MarkDown Section Detection Library This library provide this functions MarkFlow uses to split a document into it's individual text types. """ from .atx_heading import * from .blank_line import * from .block_quote import * from .fenced_code_block import * from .indented_code_block import * from .link_reference_definition import * from .list import * from .paragraph import * from .setext_heading import * from .table import * from .thematic_break import *
[ 2, 781, 539, 23, 25, 645, 20402, 198, 37811, 198, 9704, 37535, 2940, 8048, 7275, 46254, 10074, 198, 198, 1212, 5888, 2148, 428, 5499, 2940, 37535, 3544, 284, 6626, 257, 3188, 656, 340, 338, 198, 43129, 2420, 3858, 13, 198, 37811, 198,...
3.6
135
from django import forms from apps.forms import FormMixin from django.core import validators from .models import User from django.core.cache import cache
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 6725, 13, 23914, 1330, 5178, 35608, 259, 198, 6738, 42625, 14208, 13, 7295, 1330, 4938, 2024, 198, 6738, 764, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 7295, 13, 23870, 1330, 12940, 628, ...
3.829268
41
import pytest from receives.receiver import Receiver
[ 198, 11748, 12972, 9288, 198, 6738, 11583, 13, 260, 39729, 1330, 39106, 628 ]
4.230769
13
import json import logging from django.core.exceptions import ValidationError from django.db import transaction from django.forms import DateField, CharField import requests import requests.exceptions from . import models from contracts.crawler_forms import EntityForm, ContractForm, \ TenderForm, clean_place, PriceField logger = logging.getLogger(__name__)
[ 11748, 33918, 198, 11748, 18931, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 3254, 24765, 12331, 198, 6738, 42625, 14208, 13, 9945, 1330, 8611, 198, 6738, 42625, 14208, 13, 23914, 1330, 7536, 15878, 11, 3178, 15878, 198...
3.596154
104
""" Precisely APIs Enhance & enrich your data, applications, business processes, and workflows with rich location, information, and identify APIs. # noqa: E501 The version of the OpenAPI document: 11.9.3 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from com.precisely.apis.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, OpenApiModel ) from com.precisely.apis.exceptions import ApiAttributeError
[ 37811, 198, 220, 220, 220, 28737, 786, 306, 23113, 628, 220, 220, 220, 32999, 1222, 22465, 534, 1366, 11, 5479, 11, 1597, 7767, 11, 290, 670, 44041, 351, 5527, 4067, 11, 1321, 11, 290, 5911, 23113, 13, 220, 1303, 645, 20402, 25, 412...
2.661654
266
from .api_handler import DefaultFourHundredResponse from .api_keys import ApiKeys from .xray import XRay
[ 6738, 764, 15042, 62, 30281, 1330, 15161, 15137, 39, 3229, 31077, 198, 6738, 764, 15042, 62, 13083, 1330, 5949, 72, 40729, 198, 6738, 764, 87, 2433, 1330, 1395, 19591, 198 ]
3.5
30
import copy import json import os from unittest.mock import MagicMock, call from bravado.client import SwaggerClient import bravado.exception from bravado_falcon import FalconHttpClient import falcon import pytest import pytest_falcon.plugin import responses import yaml from data_acquisition.acquisition_request import AcquisitionRequest, RequestNotFoundError from data_acquisition.consts import (ACQUISITION_PATH, DOWNLOAD_CALLBACK_PATH, METADATA_PARSER_CALLBACK_PATH, GET_REQUEST_PATH) from data_acquisition.resources import (get_download_callback_url, get_metadata_callback_url, AcquisitionResource) import tests from tests.consts import (TEST_DOWNLOAD_REQUEST, TEST_DOWNLOAD_CALLBACK, TEST_ACQUISITION_REQ, TEST_ACQUISITION_REQ_JSON) FAKE_TIME = 234.25 FAKE_TIMESTAMP = 234 def test_get_download_callback_url(): callback_url = get_download_callback_url('https://some-test-das-url', 'some-test-id') assert callback_url == 'https://some-test-das-url/v1/das/callback/downloader/some-test-id' def test_get_metadata_callback_url(): callback_url = get_metadata_callback_url('https://some-test-das-url', 'some-test-id') assert callback_url == 'https://some-test-das-url/v1/das/callback/metadata/some-test-id'
[ 11748, 4866, 198, 11748, 33918, 198, 11748, 28686, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 6139, 44, 735, 11, 869, 198, 198, 6738, 49025, 4533, 13, 16366, 1330, 2451, 7928, 11792, 198, 11748, 49025, 4533, 13, 1069, 4516, 198, 673...
2.576336
524
import sys import platform from neo4j import ServiceUnavailable from GraphOfDocs.neo4j_wrapper import Neo4jDatabase from GraphOfDocs.utils import generate_words, read_dataset, clear_screen from GraphOfDocs.parse_args import parser from GraphOfDocs.create import * if __name__ == '__main__': # If only one argument is specified, # Then it's the script name. # Print help for using the script and exit. if len(sys.argv) == 1: parser.print_help() parser.exit() # Parse all arguments from terminal. args = parser.parse_args() # If create flag is set but no dirpath is specified, print error. if args.create and args.dirpath is None: parser.error('Please set the dirpath flag and specify a valid filepath!') # Else if create flag is specified along with a valid dirpath. elif args.create: print(args) # Run the graphofdocs function with create and initialize set to True. # The first argument (0th index) after the dirpath flag is the actual directory path. graphofdocs(True, True, args.dirpath[0], args.window_size[0], args.extend_window, args.insert_stopwords, args.lemmatize, args.stem) # Else if reinitialize flag is specified, unset the create flag. elif args.reinitialize: print(args) # Run the graphofdocs function with create set to False and initialize set to True. # We also set the directory path to None, since its not needed. graphofdocs(False, True, None, args.window_size[0], args.extend_window, args.insert_stopwords, args.lemmatize, args.stem)
[ 11748, 25064, 201, 198, 11748, 3859, 201, 198, 6738, 19102, 19, 73, 1330, 4809, 3118, 15182, 201, 198, 6738, 29681, 5189, 23579, 82, 13, 710, 78, 19, 73, 62, 48553, 1330, 21227, 19, 73, 38105, 201, 198, 6738, 29681, 5189, 23579, 82, ...
2.682183
623
# # Autogenerated by Frugal Compiler (3.4.3) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # from threading import Lock from frugal.middleware import Method from frugal.exceptions import TApplicationExceptionType from frugal.exceptions import TTransportExceptionType from frugal.processor import FBaseProcessor from frugal.processor import FProcessorFunction from frugal.util.deprecate import deprecated from frugal.util import make_hashable from thrift.Thrift import TApplicationException from thrift.Thrift import TMessageType from thrift.transport.TTransport import TTransportException from .ttypes import * def _write_application_exception(ctx, oprot, method, ex_code=None, message=None, exception=None): if exception is not None: x = exception else: x = TApplicationException(type=ex_code, message=message) oprot.write_response_headers(ctx) oprot.writeMessageBegin(method, TMessageType.EXCEPTION, 0) x.write(oprot) oprot.writeMessageEnd() oprot.get_transport().flush() return x
[ 2, 198, 2, 5231, 519, 877, 515, 416, 376, 2143, 282, 3082, 5329, 357, 18, 13, 19, 13, 18, 8, 198, 2, 198, 2, 8410, 5626, 48483, 4725, 48481, 7013, 15986, 311, 11335, 14603, 7013, 35876, 25003, 7013, 15986, 8410, 2751, 198, 2, 628,...
3.039886
351
# 279. Perfect Squares # Runtime: 60 ms, faster than 96.81% of Python3 online submissions for Perfect Squares. # Memory Usage: 14.7 MB, less than 42.95% of Python3 online submissions for Perfect Squares.
[ 2, 39466, 13, 16374, 5056, 3565, 198, 198, 2, 43160, 25, 3126, 13845, 11, 5443, 621, 9907, 13, 6659, 4, 286, 11361, 18, 2691, 22129, 329, 16374, 5056, 3565, 13, 198, 198, 2, 14059, 29566, 25, 1478, 13, 22, 10771, 11, 1342, 621, 54...
3.551724
58
""" Definitions for Card, Suit, Pip, etc. WARN: DO NOT CHANGE THE ENUMS IN THIS FILE! Changing the values might affect the ordering of the state/action space of agents, and will break compatibility with previously saved model checkpoints. """ from enum import IntEnum pip_scores = { Pip.sieben: 0, Pip.acht: 0, Pip.neun: 0, Pip.unter: 2, Pip.ober: 3, Pip.koenig: 4, Pip.zehn: 10, Pip.sau: 11} def new_deck(): """ Returns an ordered deck. """ return [Card(suit, pip) for suit in Suit for pip in Pip]
[ 37811, 198, 7469, 50101, 329, 5172, 11, 28871, 11, 25149, 11, 3503, 13, 198, 198, 37771, 25, 8410, 5626, 5870, 27746, 3336, 12964, 52, 5653, 3268, 12680, 45811, 0, 198, 48333, 262, 3815, 1244, 2689, 262, 16216, 286, 262, 1181, 14, 267...
2.660194
206
MAX_COPIES = 2 RECV_SIZE = 1024 SEND_SIZE = 1024 SERVER_IP = "172.24.1.107" SERVER_PORT = 10000 # Error Codes CODE_SUCCESS = 300 CODE_FAILURE = 400
[ 198, 22921, 62, 34, 3185, 11015, 796, 362, 198, 2200, 33538, 62, 33489, 796, 28119, 198, 50, 10619, 62, 33489, 796, 28119, 198, 35009, 5959, 62, 4061, 796, 366, 23628, 13, 1731, 13, 16, 13, 15982, 1, 198, 35009, 5959, 62, 15490, 796...
2.217391
69
if __name__ == '__main__': key = "train" base_path = "./data/Twitter/" src_path = base_path + key + "_post.txt" conv_path = base_path + key + "_conv.txt" tag_path = base_path + key + "_tag.txt" srcs = read_file(src_path) convs = read_file(conv_path) tags = read_file(tag_path) new_data = repeat(srcs, convs, tags) write_to_file(base_path + key + "new_post.txt", new_data[0]) write_to_file(base_path + key + "new_conv.txt", new_data[1]) write_to_file(base_path + key + "new_tag.txt", new_data[2])
[ 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1994, 796, 366, 27432, 1, 198, 220, 220, 220, 2779, 62, 6978, 796, 366, 19571, 7890, 14, 14254, 30487, 198, 220, 220, 220, 12351, 62, 6978,...
2.254098
244
import mock
[ 11748, 15290, 628, 628, 198 ]
3.2
5
"""Script that establishes a session in a wireless network managed by Cisco Web Authentication. This script requests for re-establishing a session in a wireless network managed by Cisco Web Authentication. Copyright 2013 Dario B. darizotas at gmail dot com This software is licensed under a new BSD License. Unported License. http://opensource.org/licenses/BSD-3-Clause """ from wlanapi.wlanapiwrapper import * from wlanapi.wlanconninfo import * from webauth.CiscoWebAuth import * import sys import argparse import ssl # Main def login(args): """Wrapper function to use through argparse to login to the wireless network""" manager = CiscoWebAuthManager() if manager.isConnected(args.ssid): if not manager.login(args.host, args.user, args.pwd): sys.exit(1) else: print "Not associated to %s. There is nothing to do." % args.ssid def logout(args): """Wrapper function to use through argparse to logout to the wireless network""" manager = CiscoWebAuthManager() if manager.isConnected(args.ssid): if not manager.logout(args.host): sys.exit(1) else: print "Not associated to %s. There is nothing to do." % args.ssid # Top-level argument parser parser = argparse.ArgumentParser(description='Establishes a session in a wireless network managed ' \ 'by Cisco Web Authentication.') # SSID wireless network param parser.add_argument('ssid', help='SSID name of the wireless network') parser.add_argument('host', help='Cisco Web Authentication hostname or IP') subparser = parser.add_subparsers(title='sub-commands', help='Available sub-commands') # Login sub-command parserCmdLogin = subparser.add_parser('login', help='Login request') parserCmdLogin.add_argument('-u', '--user', required=True, help='User name') parserCmdLogin.add_argument('-p', '--pwd', required=True, help='Password') parserCmdLogin.set_defaults(func=login) # Logout sub-command parserCmdLogout = subparser.add_parser('logout', help='Logout request') parserCmdLogout.set_defaults(func=logout) args = parser.parse_args() args.func(args) sys.exit(0)
[ 37811, 7391, 326, 30742, 257, 6246, 287, 257, 12521, 3127, 5257, 416, 28289, 5313, 48191, 13, 198, 198, 1212, 4226, 7007, 329, 302, 12, 40037, 278, 257, 6246, 287, 257, 12521, 3127, 5257, 416, 28289, 5313, 220, 198, 47649, 3299, 13, 1...
3.038571
700
from django.urls import path from qr_code import views app_name = 'qr_code' urlpatterns = [ path('images/serve-qr-code-image/', views.serve_qr_code_image, name='serve_qr_code_image') ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 198, 6738, 10662, 81, 62, 8189, 1330, 5009, 628, 198, 1324, 62, 3672, 796, 705, 80, 81, 62, 8189, 6, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 17566, 14, 26...
2.37037
81
""" Stable Marriage Problem solution using Gale-Shapley. Copyright 2020. Siwei Wang. """ # pylint: disable=no-value-for-parameter from typing import Optional from click import command, option, Path from read_validate import get_smp from marriage import compute_smp from write import print_results if __name__ == '__main__': main()
[ 37811, 198, 1273, 540, 24509, 20647, 4610, 1262, 36483, 12, 2484, 499, 1636, 13, 198, 198, 15269, 12131, 13, 15638, 42990, 15233, 13, 198, 37811, 198, 2, 279, 2645, 600, 25, 15560, 28, 3919, 12, 8367, 12, 1640, 12, 17143, 2357, 198, ...
3.356436
101
import pysam import json import bisect import subprocess Main(InputFileSAM = "/Data/NGS_Data/20211228_NGS_MinjaF_Pool/Results/Human_HiC/K1/splits/8_S73_L003.fastq.gz.filtered.sam", OutputFileTXT = "test_mergednodups.txt.gz", InterPairsTXT = "test_interpairs.txt.gz", MappingQualityFailedSAM = "/dev/null", ChimericAmbiguousFileSAM = "/dev/null", UnmappedSAM = "/dev/null", StatsTXT = "test.stats.txt", RestrictionSiteFile = None, MinMAPQ = 30)
[ 11748, 279, 893, 321, 198, 11748, 33918, 198, 11748, 47457, 478, 198, 11748, 850, 14681, 198, 198, 13383, 7, 20560, 8979, 49302, 796, 12813, 6601, 14, 10503, 50, 62, 6601, 14, 1238, 2481, 1065, 2078, 62, 10503, 50, 62, 9452, 6592, 37,...
2.602339
171
# https://open.kattis.com/problems/carrots import sys print sys.stdin.read().split()[1]
[ 2, 3740, 1378, 9654, 13, 74, 1078, 271, 13, 785, 14, 1676, 22143, 14, 7718, 24744, 201, 198, 201, 198, 11748, 25064, 201, 198, 201, 198, 4798, 25064, 13, 19282, 259, 13, 961, 22446, 35312, 3419, 58, 16, 60, 201, 198 ]
2.317073
41
from abc import ABC, abstractmethod from typing import Any, List, Optional import pandas as pd from yacht.config import Config ####################################################################################################################### transforms_registry = { 'RelativeClosePriceScaling': RelativeClosePriceScaling, 'AverageValueDiff': AverageValueDiff }
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 19720, 1330, 4377, 11, 7343, 11, 32233, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 43207, 13, 11250, 1330, 17056, 628, 628, 198, 198, 29113, 29113, 29113, 14468, ...
4.517647
85
import csv import logging import os import discord from discord.ext import commands, tasks from discord.utils import get # logging config logging.basicConfig( filename=".log/reg.log", format="%(asctime)s - %(message)s", level=logging.INFO, datefmt="%d-%b-%y %H:%M:%S", ) # set up channel ids and enviroment variables reg_channel_id = int(os.environ["REG_CHANNEL_ID"]) try: log_channel_id = int(os.environ["LOG_CHANNEL_ID"]) except: log_channel_id = None try: only_respond_reg = int(os.environ["ONLY_RESPOND_REG"]) except: only_respond_reg = False # TODO: seperate customization in conf file event_name = "EuroPython" instruction = f"Welcome to {event_name}! Please use `!register <Full Name>, <Ticket Number>` to register.\nE.g. `!register James Brown, 99999`\nNOTE: please ONLY register for YOURSELF." bot = commands.Bot( command_prefix="!", description=f"Registration Desk for {event_name}", help_command=None, ) bot.run(os.environ["REG_BOT_SECRET"])
[ 11748, 269, 21370, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 11, 8861, 198, 6738, 36446, 13, 26791, 1330, 651, 198, 198, 2, 18931, 4566, 198, 6404, 2667, 13, 35487, 16934, 7, 198, ...
2.608247
388
#!/usr/bin/env python # skeleton from http://kmkeen.com/socketserver/2009-04-03-13-45-57-003.html import socketserver, subprocess, sys from threading import Thread from pprint import pprint import json my_unix_command = ['bc'] HOST = 'localhost' PORT = 12321 with open('storage.json') as data_file: JSONdata = json.load(data_file)['commands'] def __init__(self, server_address, RequestHandlerClass): socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass) if __name__ == "__main__": server = SimpleServer((HOST, PORT), SingleTCPHandler) try: server.serve_forever() except KeyboardInterrupt: sys.exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 18328, 422, 2638, 1378, 13276, 365, 268, 13, 785, 14, 82, 11603, 18497, 14, 10531, 12, 3023, 12, 3070, 12, 1485, 12, 2231, 12, 3553, 12, 11245, 13, 6494, 198, 198, 11748, 3...
2.395349
301
from keycloakclient.aio.mixins import WellKnownMixin from keycloakclient.openid_connect import ( KeycloakOpenidConnect as SyncKeycloakOpenidConnect, PATH_WELL_KNOWN, ) __all__ = ( 'KeycloakOpenidConnect', )
[ 6738, 1994, 565, 15877, 16366, 13, 64, 952, 13, 19816, 1040, 1330, 3894, 29870, 35608, 259, 198, 6738, 1994, 565, 15877, 16366, 13, 9654, 312, 62, 8443, 1330, 357, 198, 220, 220, 220, 7383, 565, 15877, 11505, 312, 13313, 355, 35908, 9...
2.662651
83
""" Handles operator precedence. """ from jedi._compatibility import unicode from jedi.parser import representation as pr from jedi import debug from jedi.common import PushBackIterator from jedi.evaluate.compiled import CompiledObject, create, builtin from jedi.evaluate import analysis def create_precedence(expression_list): iterator = PushBackIterator(iter(expression_list)) return _check_operator(iterator) def _syntax_error(element, msg='SyntaxError in precedence'): debug.warning('%s: %s, %s' % (msg, element, element.start_pos)) def _get_number(iterator, priority=PythonGrammar.LOWEST_PRIORITY): el = next(iterator) if isinstance(el, pr.Operator): if el in PythonGrammar.FACTOR: right = _get_number(iterator, PythonGrammar.FACTOR_PRIORITY) elif el in PythonGrammar.NOT_TEST \ and priority >= PythonGrammar.NOT_TEST_PRIORITY: right = _get_number(iterator, PythonGrammar.NOT_TEST_PRIORITY) elif el in PythonGrammar.SLICE \ and priority >= PythonGrammar.SLICE_PRIORITY: iterator.push_back(el) return None else: _syntax_error(el) return _get_number(iterator, priority) return Precedence(None, el, right) elif isinstance(el, pr.tokenize.Token): return _get_number(iterator, priority) else: return el
[ 37811, 198, 12885, 829, 10088, 38177, 13, 198, 37811, 198, 198, 6738, 474, 13740, 13557, 5589, 25901, 1330, 28000, 1098, 198, 6738, 474, 13740, 13, 48610, 1330, 10552, 355, 778, 198, 6738, 474, 13740, 1330, 14257, 198, 6738, 474, 13740, ...
2.468531
572
#!/usr/bin/env python __author__ = 'Will Kamp' __copyright__ = 'Copyright 2013, Matrix Mariner Inc.' __license__ = 'BSD' __email__ = 'will@mxmariner.com' __status__ = 'Development' # 'Prototype', 'Development', or 'Production' import os # def __walker(self, args, p_dir, p_file): # map_extensions, include_only = args # if include_only is not None: # include_only = set(include_only) # for f in p_file: # if f.upper().endswith(map_extensions) and (include_only is None or f in include_only) and not f.startswith( # "."): # self.file_paths.append(os.path.join(p_dir, f)) if __name__ == '__main__': print("foo")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 834, 9800, 834, 796, 705, 8743, 45327, 6, 198, 834, 22163, 4766, 834, 796, 705, 15269, 2211, 11, 24936, 1526, 7274, 3457, 2637, 198, 834, 43085, 834, 796, 705, 21800, 6, 198, 83...
2.268608
309
"""Command line interface for fsh-validator.""" import os import sys import argparse from pathlib import Path import yaml from .fsh_validator import ( print_box, run_sushi, validate_all_fsh, validate_fsh, download_validator, bcolors, VALIDATOR_BASENAME, store_log, assert_sushi_installed, get_fsh_base_path, get_fhir_version_from_sushi_config, ) from .fshpath import FshPath def get_config(base_path: Path): """ Get the config file from the base path. :param base_path: The base path to the .fsh-validator.yml File. :return: Configuration """ config_file = base_path / ".fsh-validator.yml" if not config_file.exists(): return dict() return yaml.safe_load(open(config_file)) def main(): """ fsh-validator command line interface main. :return: None """ parser = argparse.ArgumentParser( description="Validate a fsh file", formatter_class=argparse.RawTextHelpFormatter, ) arg_fname = parser.add_argument( "filename", help="fsh file names (basename only - no path)", nargs="*" ) parser.add_argument( "--all", dest="all", action="store_true", help="if set, all detected profiles will be validated", required=False, default=False, ) parser.add_argument( "--subdir", dest="subdir", type=str, help="Specifies the subdirectory (relative to input/fsh/) in which to search for profiles if --all is set", required=False, default="", ) parser.add_argument( "--validator-path", dest="path_validator", type=str, help="path to validator", required=False, default=None, ) parser.add_argument( "--verbose", dest="verbose", action="store_true", help="Be verbose", required=False, default=False, ) parser.add_argument( "--no-sushi", dest="no_sushi", action="store_true", help="Do not run sushi before validating", required=False, default=False, ) parser.add_argument( "--log-path", dest="log_path", type=str, help="log file path - if supplied, log files will be written", required=False, default=None, ) args = parser.parse_args() if not args.all and len(args.filename) == 0: raise argparse.ArgumentError( arg_fname, "filename must be set if --all is not specified" ) elif args.all and len(args.filename) == 0: # Use current working dir as input path filenames = [FshPath(os.getcwd())] else: filenames = [FshPath(filename) for filename in args.filename] base_paths = set(filename.fsh_base_path() for filename in filenames) if len(base_paths) > 1: raise ValueError( "Found multiple base paths for fsh project, expecting exactly one" ) base_path = base_paths.pop() validator_path = ( args.path_validator if args.path_validator is not None else base_path ) fname_validator = Path(validator_path) / VALIDATOR_BASENAME if not fname_validator.exists(): print_box("Downloading java validator") download_validator(fname_validator.resolve()) if not args.no_sushi: print_box("Running SUSHI") run_sushi(base_path) fhir_version = get_fhir_version_from_sushi_config(base_path) config = get_config(base_path) if "exclude_code_systems" in config: exclude_code_systems = set(config["exclude_code_systems"]) else: exclude_code_systems = set() if "exclude_resource_type" in config: exclude_resource_types = set(config["exclude_resource_type"]) else: exclude_resource_types = set() if args.all: print_box("Validating all FSH files") results = validate_all_fsh( base_path, args.subdir, str(fname_validator), exclude_code_systems=exclude_code_systems, exclude_resource_types=exclude_resource_types, fhir_version=fhir_version, verbose=args.verbose, ) else: print_box("Validating FSH files") results = validate_fsh( filenames, str(fname_validator), fhir_version=fhir_version, exclude_code_systems=exclude_code_systems, exclude_resource_types=exclude_resource_types, verbose=args.verbose, ) if args.log_path is not None: log_path = Path(args.log_path) if not log_path.exists(): log_path.mkdir() store_log(results, log_path) if any([r.failed() for r in results]): print_box("Errors during profile validation", col=bcolors.FAIL) sys.exit(1) else: print_box("All profiles successfully validated", col=bcolors.OKGREEN) sys.exit(0) if __name__ == "__main__": main()
[ 37811, 21575, 1627, 7071, 329, 277, 1477, 12, 12102, 1352, 526, 15931, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 1822, 29572, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 331, 43695, 198, 6738, 764, 69, 1477, 62, 12102, 1352, ...
2.220705
2,270
import os from enum import Enum def getPackageDirectory(package: AppPackage, version: str = None): "Gets the directory where the specified package is installed." varName = f'AZ_BATCH_APP_PACKAGE_{package.value}' if version != None: varName = f'{varName}#{version}' return os.environ[varName]
[ 11748, 28686, 198, 198, 6738, 33829, 1330, 2039, 388, 628, 198, 198, 4299, 651, 27813, 43055, 7, 26495, 25, 2034, 27813, 11, 2196, 25, 965, 796, 6045, 2599, 198, 220, 220, 220, 366, 38, 1039, 262, 8619, 810, 262, 7368, 5301, 318, 65...
2.824561
114
""" This file should be imported at the bottom of configure.py TODO: All of this may be moved into a single function in the future so people can choose a reactor in configure.py """ from twisted.internet import reactor from twisted.internet.task import LoopingCall from threading import currentThread, Thread # Check to see if main thread is alive mainthread = currentThread() # Every second, make sure that the interface thread is alive. LoopingCall(checkExit).start(1) # start the network loop in a new thread Thread(target=lambda : reactor.run(installSignalHandlers=0)).start()
[ 37811, 201, 198, 1212, 2393, 815, 307, 17392, 379, 262, 4220, 286, 17425, 13, 9078, 201, 198, 201, 198, 51, 3727, 46, 25, 201, 198, 3237, 286, 428, 743, 307, 3888, 656, 257, 2060, 2163, 287, 262, 2003, 201, 198, 568, 661, 460, 385...
3.532164
171
import random import time import requests
[ 198, 11748, 4738, 198, 11748, 640, 198, 11748, 7007, 628 ]
4.4
10
from django.shortcuts import render from django.views import View # Create your views here.
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 33571, 1330, 3582, 198, 198, 2, 13610, 534, 5009, 994, 13 ]
3.833333
24
#!/usr/bin/python # -*- coding: utf-8 -*- """hashvis by Peter Hosey Reads from standard input or files, and prints what it reads, along with colorized versions of any hashes or signatures found in each line. The goal here is visual comparability. You should be able to tell whether two hashes are the same at a glance, rather than having to closely compare digits (or, more probably, not bother and just assume the hashes match!). The more obvious of the two methods used is shaping the output: Each hash will be represented as a rectangle of an aspect ratio determined by the hash. You may thus end up with one that's tall and one that's wide, or one that's square (if the hash length is a square number) and one that isn't. If two hashes are the same shape (or if you passed --oneline), another difference is that each byte is represented by a different pair of foreground and background colors. You should thus be able to compare the color-patterns rather than having to look at individual digits. """ # #mark - Imports and utilities import sys import os import re import base64 import binascii import cmath as math range = xrange # #mark - Parsing MD5_exp = re.compile(r'^MD5 \(.*\) = ([0-9a-fA-F]+)') fingerprint_exp = re.compile(r'^(?:R|ECD)SA key fingerprint is (?:(?:MD5:)?(?P<hex>[:0-9a-fA-F]+)|SHA256:(?P<base64>[+/0-9a-zA-Z]+))\.') commit_exp = re.compile(r'^commit ([0-9a-fA-F]+)') more_base64_padding_than_anybody_should_ever_need = '=' * 64 def extract_hash_from_line(input_line): "Returns a tuple of the extracted hash as hex, and whether it was originally hex (vs, say, base64). The hash may be None if none was found in the input." if input_line[:1] == 'M': match = MD5_exp.match(input_line) if match: return match.group(1), True else: return '', False elif input_line[:1] in 'RE': match = fingerprint_exp.match(input_line) if match: hex = match.group('hex') if hex: return hex, True b64str = match.group('base64') if b64str: # Pacify the base64 module, which wants *some* padding (at least sometimes) but doesn't care how much. b64str += more_base64_padding_than_anybody_should_ever_need # Re-encode to hex for processing downstream. Arguably a refactoring opportunity return binascii.b2a_hex(base64.b64decode(b64str)), False return '', False elif input_line[:7] == 'commit ': match = commit_exp.match(input_line) if match: return match.group(1), True if input_line: try: hash, not_the_hash = input_line.split(None, 1) except ValueError: # Insufficient fields. This line doesn't contain any whitespace. Use the entire line. hash = input_line hash = hash.strip().replace('-', '') try: int(hash, 16) except ValueError: # Not a hex number. return None, False else: return hash, True # #mark - Representation def fgcolor(idx, deep_color=False): if deep_color: return '\x1b[38;5;{0}m'.format(idx) idx = ((idx >> 4) & 0xf) # 90 is bright foreground; 30 is dull foreground. if idx < 0x8: base = 30 else: base = 90 idx = idx - 0x8 return '\x1b[{0}m'.format(base + idx) def bgcolor(idx, deep_color=False): if deep_color: idx = ((idx & 0xf) << 4) | ((idx & 0xf0) >> 4) # This add 128 and mod 256 is important, because it ensures double-digits such as 00 remain different colors. return '\x1b[48;5;{0}m'.format((idx + 128) % 256) else: idx = (idx & 0xf) # 100 is bright background; 40 is dull background. if idx < 0x8: base = 40 else: base = 100 idx = idx - 0x8 return '\x1b[{0}m'.format(base + idx) BOLD = '\x1b[1m' RESET = '\x1b[0m' if __name__ == '__main__': # #mark - Self-tests run_tests = False if run_tests: # A square number. Should contain a diagonal pair (in this case, (16,16)). factors_of_256 = set(factors(256)) assert factors_of_256 == set([(256, 1), (16, 16), (8, 32), (2, 128), (64, 4), (1, 256), (32, 8), (128, 2), (4, 64)]) # A rectangular number: not square, but still composite. No diagonal pair here. factors_of_12 = set(factors(12)) assert factors_of_12 == set([(2, 6), (12, 1), (1, 12), (6, 2), (4, 3), (3, 4)]) assert (1, 256) in factors_of_256 assert (256, 1) in factors_of_256 assert (1, 256) not in except_one(factors_of_256) assert (256, 1) not in except_one(factors_of_256) # A prime number. Should have exactly one pair of factors. factors_of_5 = set(factors(5)) assert factors_of_5 == set([(1, 5), (5, 1)]) assert list(parse_hex('ab15e')) == [0xab, 0x15, 0x0e] assert list(parse_hex(':::ab:15:e')) == [0xab, 0x15, 0x0e] assert extract_hash_from_line('RSA key fingerprint is b8:79:03:7d:00:44:98:6e:67:a0:59:1a:01:21:36:38.\n') == ('b8:79:03:7d:00:44:98:6e:67:a0:59:1a:01:21:36:38', True) assert extract_hash_from_line('RSA key fingerprint is b8:79:03:7d:00:44:98:6e:67:a0:59:1a:01:21:36:38.') == ('b8:79:03:7d:00:44:98:6e:67:a0:59:1a:01:21:36:38', True) #Alternate output example from https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Authentication_Keys : assert extract_hash_from_line('RSA key fingerprint is MD5:10:4a:ec:d2:f1:38:f7:ea:0a:a0:0f:17:57:ea:a6:16.') == ('10:4a:ec:d2:f1:38:f7:ea:0a:a0:0f:17:57:ea:a6:16', True) # Also from https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Authentication_Keys : assert extract_hash_from_line('ECDSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.\n') == ('2cf162318aeb098415b1550fce3387bfe663cb10879556093015457ab5423fb9', False), extract_hash_from_line('ECDSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.\n') assert extract_hash_from_line('ECDSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.') == ('2cf162318aeb098415b1550fce3387bfe663cb10879556093015457ab5423fb9', False), extract_hash_from_line('ECDSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.') # Mix and match RSA and ECDSA with MD5 and SHA256: assert extract_hash_from_line('ECDSA key fingerprint is MD5:10:4a:ec:d2:f1:38:f7:ea:0a:a0:0f:17:57:ea:a6:16.') == ('10:4a:ec:d2:f1:38:f7:ea:0a:a0:0f:17:57:ea:a6:16', True) assert extract_hash_from_line('RSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.\n') == ('2cf162318aeb098415b1550fce3387bfe663cb10879556093015457ab5423fb9', False), extract_hash_from_line('RSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.\n') #UUID assert extract_hash_from_line('E6CD379E-12CD-4E00-A83A-B06E74CF03B8') == ('E6CD379E12CD4E00A83AB06E74CF03B8', True), extract_hash_from_line('E6CD379E-12CD-4E00-A83A-B06E74CF03B8') assert extract_hash_from_line('e6cd379e-12cd-4e00-a83a-b06e74cf03b8') == ('e6cd379e12cd4e00a83ab06e74cf03b8', True), extract_hash_from_line('e6cd379e-12cd-4e00-a83a-b06e74cf03b8') assert extract_hash_from_line('MD5 (hashvis.py) = e21c7b846f76826d52a0ade79ef9cb49\n') == ('e21c7b846f76826d52a0ade79ef9cb49', True) assert extract_hash_from_line('MD5 (hashvis.py) = e21c7b846f76826d52a0ade79ef9cb49') == ('e21c7b846f76826d52a0ade79ef9cb49', True) assert extract_hash_from_line('8b948e9c85fdf68f872017d7064e839c hashvis.py\n') == ('8b948e9c85fdf68f872017d7064e839c', True) assert extract_hash_from_line('8b948e9c85fdf68f872017d7064e839c hashvis.py') == ('8b948e9c85fdf68f872017d7064e839c', True) assert extract_hash_from_line('2c9997ce32cb35823b2772912e221b350717fcb2d782c667b8f808be44ae77ba1a7b94b4111e386c64a2e87d15c64a2fc2177cd826b9a0fba6b348b4352ed924 hashvis.py\n') == ('2c9997ce32cb35823b2772912e221b350717fcb2d782c667b8f808be44ae77ba1a7b94b4111e386c64a2e87d15c64a2fc2177cd826b9a0fba6b348b4352ed924', True) assert extract_hash_from_line('2c9997ce32cb35823b2772912e221b350717fcb2d782c667b8f808be44ae77ba1a7b94b4111e386c64a2e87d15c64a2fc2177cd826b9a0fba6b348b4352ed924 hashvis.py') == ('2c9997ce32cb35823b2772912e221b350717fcb2d782c667b8f808be44ae77ba1a7b94b4111e386c64a2e87d15c64a2fc2177cd826b9a0fba6b348b4352ed924', True) assert extract_hash_from_line('#!/usr/bin/python\n')[0] is None # Protip: Use vis -co to generate these. (line,) = hash_to_pic('78', represent_as_hex=True, deep_color=False) assert line == '\033[1m\033[37m\033[100m78\033[0m', repr(line) (line,) = hash_to_pic('7f', represent_as_hex=True, deep_color=False) assert line == '\033[1m\033[37m\033[107m7f\033[0m', repr(line) assert list(hash_to_pic('aebece', deep_color=False)) != list(hash_to_pic('deeefe', deep_color=False)), (list(hash_to_pic('aebece', deep_color=False)), list(hash_to_pic('deeefe', deep_color=False))) assert list(hash_to_pic('eaebec', deep_color=False)) != list(hash_to_pic('edeeef', deep_color=False)), (list(hash_to_pic('eaebec', deep_color=False)), list(hash_to_pic('edeeef', deep_color=False))) sys.exit(0) # #mark - Main use_256color = os.getenv('TERM') == 'xterm-256color' import argparse parser = argparse.ArgumentParser(description="Visualize hexadecimal input (hashes, UUIDs, etc.) as an arrangement of color blocks.") parser.add_argument('--one-line', '--oneline', action='store_true', help="Unconditionally produce a rectangle 1 character tall. The default is to choose a pair of width and height based upon one of the bytes of the input.") parser.add_argument('--color-test', '--colortest', action='store_true', help="Print the 16-color, 256-color foreground, and 256-color background color palettes, then exit.") options, args = parser.parse_known_args() if options.color_test: for x in range(16): print fgcolor(x, deep_color=False), print bgcolor(x, deep_color=False), else: print for x in range(256): sys.stdout.write(fgcolor(x, deep_color=True) + bgcolor(x, deep_color=True) + '%02x' % (x,)) else: print RESET import sys sys.exit(0) import fileinput for input_line in fileinput.input(args): print input_line.rstrip('\n') hash, is_hex = extract_hash_from_line(input_line) if hash: for output_line in hash_to_pic(hash, only_ever_one_line=options.one_line, represent_as_hex=is_hex, deep_color=use_256color): print output_line
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 17831, 4703, 416, 5613, 367, 577, 88, 198, 198, 5569, 82, 422, 3210, 5128, 393, 3696, 11, 290, 20842, 644, 340, ...
2.339118
4,264
# https://projecteuler.net/problem=7 import math print(sum(sieve(2000000)))
[ 2, 3740, 1378, 16302, 68, 18173, 13, 3262, 14, 45573, 28, 22, 201, 198, 201, 198, 11748, 10688, 201, 198, 201, 198, 4798, 7, 16345, 7, 82, 12311, 7, 2167, 2388, 22305, 201, 198 ]
2.441176
34
"""Add new types Revision ID: 32053847c4db Revises: 05a62958a9cc Create Date: 2019-06-11 10:36:14.456629 """ from alembic import context from sqlalchemy.orm import sessionmaker # revision identifiers, used by Alembic. revision = '32053847c4db' down_revision = '05a62958a9cc' branch_labels = None depends_on = None all_commands = [ (""" ALTER TABLE data_source CHANGE `format` `format` ENUM( 'CSV','CUSTOM','GEO_JSON','HAR_IMAGE_FOLDER','HDF5','DATA_FOLDER', 'IMAGE_FOLDER', 'JDBC','JSON','NETCDF4','PARQUET','PICKLE','SHAPEFILE', 'TAR_IMAGE_FOLDER','TEXT', 'VIDEO_FOLDER', 'UNKNOWN','XML_FILE') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL;""", """ ALTER TABLE data_source CHANGE `format` `format` ENUM( 'CSV','CUSTOM','GEO_JSON','HDF5','JDBC','JSON', 'NETCDF4','PARQUET','PICKLE','SHAPEFILE','TEXT', 'UNKNOWN','XML_FILE') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL;""" ), (""" ALTER TABLE `storage` CHANGE `type` `type` ENUM( 'HDFS','OPHIDIA','ELASTIC_SEARCH','MONGODB','POSTGIS','HBASE', 'CASSANDRA','JDBC','LOCAL') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL;""", """ ALTER TABLE `storage` CHANGE `type` `type` ENUM( 'HDFS','OPHIDIA','ELASTIC_SEARCH','MONGODB','POSTGIS','HBASE', 'CASSANDRA','JDBC') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL;""", ), ( """ALTER TABLE `model` CHANGE `type` `type` ENUM( 'KERAS','SPARK_ML_REGRESSION','SPARK_MLLIB_CLASSIFICATION', 'SPARK_ML_CLASSIFICATION','UNSPECIFIED') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL; """, """ALTER TABLE `model` CHANGE `type` `type` ENUM( 'KERAS','SPARK_ML_REGRESSION','SPARK_MLLIB_CLASSIFICATION', 'SPARK_ML_CLASSIFICATION','UNSPECIFIED') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL; """ ) ]
[ 37811, 4550, 649, 3858, 198, 198, 18009, 1166, 4522, 25, 20959, 49561, 2857, 66, 19, 9945, 198, 18009, 2696, 25, 8870, 64, 48602, 3365, 64, 24, 535, 198, 16447, 7536, 25, 13130, 12, 3312, 12, 1157, 838, 25, 2623, 25, 1415, 13, 2231,...
2.084052
928
from advanced_tools.IO_path_utils import * from advanced_tools.algorithm_utils import *
[ 6738, 6190, 62, 31391, 13, 9399, 62, 6978, 62, 26791, 1330, 1635, 198, 6738, 6190, 62, 31391, 13, 282, 42289, 62, 26791, 1330, 1635, 198 ]
3.52
25
import os import pickle import functools import errno import shutil from urllib.request import urlopen #import definitions def disk_cache(basename, directory, method=False): """ Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.pickle'. """ directory = os.path.expanduser(directory) ensure_directory(directory) return wrapper def download(url, directory, filename=None): """ Download a file and return its filename on the local file system. If the file is already there, it will not be downloaded again. The filename is derived from the url if not provided. Return the filepath. """ if not filename: _, filename = os.path.split(url) directory = os.path.expanduser(directory) ensure_directory(directory) filepath = os.path.join(directory, filename) if os.path.isfile(filepath): return filepath print('Download', filepath) with urlopen(url) as response, open(filepath, 'wb') as file_: shutil.copyfileobj(response, file_) return filepath def ensure_directory(directory): """ Create the directories along the provided directory path that do not exist. """ directory = os.path.expanduser(directory) try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise e
[ 11748, 28686, 201, 198, 11748, 2298, 293, 201, 198, 11748, 1257, 310, 10141, 201, 198, 11748, 11454, 3919, 201, 198, 11748, 4423, 346, 201, 198, 6738, 2956, 297, 571, 13, 25927, 1330, 19016, 9654, 201, 198, 2, 11748, 17336, 201, 198, ...
2.773124
573
import cv2 import time import numpy as np import imutils camera= 0 cam = cv2.VideoCapture(camera) fgbg = cv2.createBackgroundSubtractorMOG2(history=1000,varThreshold=0,detectShadows=False) width=600 height=480 fps_time = 0 while True: ret_val,image = cam.read() image = cv2.resize(image,(width,height)) image = cv2.GaussianBlur(image, (5, 5), 0) fgmask = fgbg.apply(image) # image = fgbg.apply(image,learningRate=0.001) # image = imutils.resize(image, width=500) # gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cnts = cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] # loop over the contours x_left = -1 y_left = -1 x_right = -1 y_right = -1 for c in cnts: # if the contour is too small, ignore it # if cv2.contourArea(c) > 500: # continue # compute the bounding box for the contour, draw it on the frame, # and update the text (x, y, w, h) = cv2.boundingRect(c) if x_left ==-1 : x_left = x y_left = y if x < x_left: x_left = x if y < y_left: y_left = y if x+w > x_right: x_right = x+w if y+h > y_right: y_right = y+h # cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2) if (x_left==0 and y_left==0 and x_right==width and y_right==height)==False: cv2.rectangle(image, (x_left, y_left), (x_right, y_right), (0, 255, 0), 2) # cv2.putText(image, # "FPS: %f [press 'q'to quit]" % (1.0 / (time.time() - fps_time)), # (10, 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, # (0, 255, 0), 2) cv2.imshow('tf-pose-estimation result',fgmask) cv2.imshow('tf-pose-estimation result2',image) fps_time = time.time() if cv2.waitKey(1)==ord('q'): cam.release() cv2.destroyAllWindows() break
[ 11748, 269, 85, 17, 198, 11748, 640, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 545, 26791, 198, 25695, 28, 657, 198, 20991, 796, 269, 85, 17, 13, 10798, 49630, 7, 25695, 8, 198, 69, 22296, 70, 796, 269, 85, 17, 13, 17953, 21...
1.916908
1,035
#Given a positive integer num, write a function which returns True if num is a perfect square else False.
[ 2, 15056, 257, 3967, 18253, 997, 11, 3551, 257, 2163, 543, 5860, 6407, 611, 997, 318, 257, 2818, 6616, 2073, 10352, 13, 198 ]
4.608696
23
from minescrubber_core import abstract from . import mainwindow def run(): controller = Controller() controller.run(ui_class=UI)
[ 6738, 949, 3798, 25089, 527, 62, 7295, 1330, 12531, 628, 198, 6738, 764, 1330, 1388, 17497, 628, 628, 198, 4299, 1057, 33529, 198, 220, 220, 220, 10444, 796, 22741, 3419, 198, 220, 220, 220, 10444, 13, 5143, 7, 9019, 62, 4871, 28, 1...
3.177778
45
from .power_group import PowerGroup
[ 6738, 764, 6477, 62, 8094, 1330, 4333, 13247, 198 ]
4
9
""" .. module:: elementtype.py :platform: Linux .. moduleauthor:: Michael Schilonka <michael@schilonka.de> """ import logging
[ 37811, 198, 492, 8265, 3712, 5002, 4906, 13, 9078, 198, 220, 220, 1058, 24254, 25, 7020, 198, 198, 492, 8265, 9800, 3712, 3899, 3059, 33576, 4914, 1279, 76, 40302, 31, 20601, 33576, 4914, 13, 2934, 29, 628, 198, 37811, 198, 198, 11748...
2.836735
49
# coding=utf-8 from OTLMOW.OTLModel.Classes.Put import Put from OTLMOW.OTLModel.Classes.PutRelatie import PutRelatie from OTLMOW.GeometrieArtefact.VlakGeometrie import VlakGeometrie # Generated with OTLClassCreator. To modify: extend, do not edit
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 440, 14990, 44, 3913, 13, 2394, 43, 17633, 13, 9487, 274, 13, 11588, 1330, 5930, 198, 6738, 440, 14990, 44, 3913, 13, 2394, 43, 17633, 13, 9487, 274, 13, 11588, 6892, 265, 494, 1330, 5930, 6...
2.648936
94
# get the training data D, sample the Generator with random z to produce r N = X_train z = np.random.uniform(-1, 1, (1, z_dim)) r = G.predict_on_batch(z) # define our distance measure S to be L1 S = lambda n, r: np.sum(np.abs(n - r)) # compute the distances between the reference and the samples in N using the measure D distances = [D(n, r) for n in N] # find the indices of the most similar samples and select them from N nearest_neighbors_index = np.argpartition(distances, k) nearest_neighbors_images = N[nearest_neighbors_index] # generate fake images from the discriminator n_fake_images = 5000 z = np.random.uniform(-1, 1, (n_fake_images, z_dim)) x = G.predict_on_batch(z) # marginal probability of y q_y = np.mean(p_y_given_x, axis=0) inception_scores = p_y_given_x * (np.log(p_y_given_x) - np.log(q_y) inception_score = np.exp(np.mean(inception_scores)) return inception_score def get_mean_and_covariance(data): mean = np.mean(data, axis=0) covariance = np.cov(data, rowvar=False) # rowvar? return mean, covariance def compute_frechet_inception_distance(mean_r, mean_f, cov_r, cov_f): l2_mean = np.sum((mean_r - mean_f)**2) cov_mean, _ = np.trace(scipy.linalg.sqrtm(np.dot(cov_r, cov_f))) return l2_mu + np.trace(cov_r) + np.trace(cov_f) - 2 * np.trace(cov_mean)
[ 2, 651, 262, 3047, 1366, 360, 11, 6291, 262, 35986, 351, 4738, 1976, 284, 4439, 374, 201, 198, 45, 796, 1395, 62, 27432, 201, 198, 89, 796, 45941, 13, 25120, 13, 403, 6933, 32590, 16, 11, 352, 11, 357, 16, 11, 1976, 62, 27740, 4...
2.358261
575
import os import boto3 # import subprocess from subprocess import Popen, PIPE from time import sleep import json import ast from datetime import datetime, time, timedelta, date import logging import logging.handlers import sys, getopt import glob import shutil logger = logging.getLogger() logger.setLevel(logging.INFO) #### #### function defs #### if __name__=='__main__': main() # main(sys.argv[1:])
[ 11748, 28686, 198, 11748, 275, 2069, 18, 198, 2, 1330, 850, 14681, 198, 6738, 850, 14681, 1330, 8099, 268, 11, 350, 4061, 36, 198, 6738, 640, 1330, 3993, 198, 11748, 33918, 198, 11748, 6468, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11...
3.021898
137
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-10-21 # @Author : Emily Wenger (ewenger@uchicago.edu) import time import numpy as np import tensorflow as tf import tensorflow_addons as tfa from keras.utils import Progbar
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 10430, 220, 220, 220, 1058, 12131, 12, 940, 12, 2481, 198, 2, 2488, 13838, 220, 1058, 17608, 31415, 357, 413...
2.648352
91
from abc import ABCMeta, abstractmethod import database from . import w_l
[ 6738, 450, 66, 1330, 9738, 48526, 11, 12531, 24396, 198, 11748, 6831, 198, 198, 6738, 764, 1330, 266, 62, 75, 198 ]
3.571429
21
from typing import Callable
[ 6738, 19720, 1330, 4889, 540, 628, 628, 198 ]
4
8
import setuptools setuptools.setup( name= 'ramCOH', version= '0.1', description= '...', author= 'Thomas van Gerve', packages= setuptools.find_packages( exclude= ['examples'] ), # package_dir= {'' : 'petroPy'}, package_data= {'ramCOH': ['static/*']}, install_requires= [ 'pandas', 'matplotlib', 'numpy', 'scipy', 'csaps' ] )
[ 11748, 900, 37623, 10141, 198, 198, 2617, 37623, 10141, 13, 40406, 7, 198, 220, 220, 220, 1438, 28, 705, 859, 8220, 39, 3256, 198, 220, 220, 220, 2196, 28, 705, 15, 13, 16, 3256, 198, 220, 220, 220, 6764, 28, 705, 986, 3256, 198, ...
2.082474
194
from chess_game._board import make_board from chess_game.chess_game import ChessGame from chess_game.play_game import get_user_input, game_event_loop if __name__ == "__main__": game_board = make_board() # pawn = Pawn('x', 'y', None, None, None) # pawn.move() print('Chess') print(' : Rules') print(' : input - piece''s position x,y, second x,y = destination') print(" : x = row number 1 though 8") print(" : y = column number 1 though 8") player1_name = get_user_input(' : Enter player one name', is_move=False) player2_name = get_user_input(' : Enter player two name', is_move=False) print('------------------------------------------------') chess_game = ChessGame(game_board, player1_name, player2_name) game_event_loop(chess_game)
[ 6738, 19780, 62, 6057, 13557, 3526, 1330, 787, 62, 3526, 198, 6738, 19780, 62, 6057, 13, 2395, 824, 62, 6057, 1330, 25774, 8777, 198, 6738, 19780, 62, 6057, 13, 1759, 62, 6057, 1330, 651, 62, 7220, 62, 15414, 11, 983, 62, 15596, 62,...
2.860215
279
""" Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3. """ import Math
[ 37811, 198, 15056, 257, 13934, 5509, 11, 1064, 663, 5415, 6795, 13, 198, 198, 464, 5415, 6795, 318, 262, 1271, 286, 13760, 1863, 262, 14069, 3108, 422, 262, 6808, 10139, 866, 284, 262, 15189, 3634, 12835, 10139, 13, 198, 198, 6425, 25...
2.784
125
# time 15 mins # used time 15 mins # time 15 mins # used time 15 mins # this is actually a correct solution # the code i submitted a day ago, which passed lintcode, is actually wrong after i looked KMP up # the previous version does not take care of the situations where the target contains repeatitive elements
[ 2, 640, 1315, 23550, 198, 2, 973, 640, 1315, 23550, 198, 198, 2, 640, 1315, 23550, 198, 2, 973, 640, 1315, 23550, 198, 198, 2, 428, 318, 1682, 257, 3376, 4610, 198, 2, 262, 2438, 1312, 8948, 257, 1110, 2084, 11, 543, 3804, 300, ...
4.131579
76
# -*- coding: cp1252 -*- # -*- coding: utf-8 -*- """ Algoritmos y Estructuras de Datos Proyecto Final Antonio Reyes #17273 Esteban Cabrera #17781 Miguel #17102 """ import random import xlrd file_location = "C:/Users/Antonio/Desktop/Recommendation-System-python-neo4J-master/Database.xlsx" workbook = xlrd.open_workbook(file_location) sheet = workbook.sheet_by_index(0) from neo4jrestclient.client import GraphDatabase db = GraphDatabase("http://localhost:7474",username="neo4j", password="1111") dataB = db.labels.create("Database") gen = db.labels.create("Genero") #se crea un diccionario (como vimos en hashmaps) database = {} #donde se guardan los generos de las series que ya se vieron historial = [] #en el for se puede poner sheet.nrows para imprimir todo #se utiliza el cdigo mostrado en este link para mostrar los generos que se repiten ms veces #https://stackoverflow.com/questions/3594514/how-to-find-most-common-elements-of-a-list #mtodo para mostrar todas las series y peliculas de un genero #****************************************************************************************************** #******************************************************************************************************* menu() opcion = input("Option: ") print ("**********************************") print ("**********************************") while(opcion != 9): if(opcion == 0): add_Excel() print ("**********************************") print ("**********************************") print ("Values added to Database") menu() opcion = input("Option: ") elif(opcion == 1): add_database() print ("**********************************") print ("**********************************") menu() opcion = input("Option: ") elif(opcion == 2): watch() print ("**********************************") print ("**********************************") menu() opcion = input("Option: ") elif(opcion == 3): show_genre() print ("**********************************") print ("**********************************") menu() opcion = input("Option: ") else: print("This option is not valid") print ("**********************************") print ("**********************************") menu() opcion = input("Option: ") print ("Thanks for using the program")
[ 2, 532, 9, 12, 19617, 25, 31396, 1065, 4309, 532, 9, 12, 201, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 2348, 7053, 270, 16785, 331, 412, 7249, 17786, 390, 16092, 418, 201, 198, 29...
2.733119
933
from flask import Flask import time from _thread import get_ident app=Flask(__name__) if __name__=="__main__": app.run(port=6003)
[ 198, 6738, 42903, 1330, 46947, 198, 11748, 640, 198, 6738, 220, 4808, 16663, 1330, 651, 62, 738, 198, 198, 1324, 28, 7414, 2093, 7, 834, 3672, 834, 8, 198, 198, 361, 11593, 3672, 834, 855, 1, 834, 12417, 834, 1298, 198, 220, 220, ...
2.584906
53
import unittest import util.strings as strings if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 11748, 7736, 13, 37336, 355, 13042, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.722222
36
# Data sources database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [('C3', False)], seedMechanisms = ['GRI-Mech3.0'], kineticsDepositories = ['training'], kineticsFamilies = 'default', kineticsEstimator = 'rate rules', ) # List of species species( label='ethane', reactive=True, structure=SMILES("CC"), ) species( label='N2', reactive=False, structure=adjacencyList(""" 1 N u0 p1 c0 {2,T} 2 N u0 p1 c0 {1,T} """), ) # Reaction systems simpleReactor( temperature=(1350,'K'), pressure=(1.0,'bar'), initialMoleFractions={ "ethane": 0.1, "N2": 0.9 }, terminationConversion={ 'ethane': 0.9, }, terminationTime=(1e6,'s'), ) simulator( atol=1e-16, rtol=1e-8, ) model( toleranceKeepInEdge=0.0, toleranceMoveToCore=0.1, toleranceInterruptSimulation=0.1, maximumEdgeSpecies=100000, ) options( units='si', saveRestartPeriod=None, generateOutputHTML=True, generatePlots=False, saveEdgeSpecies=True, saveSimulationProfiles=True, verboseComments=True, ) pressureDependence( method='modified strong collision', maximumGrainSize=(0.5,'kcal/mol'), minimumNumberOfGrains=250, temperatures=(300,2200,'K',2), pressures=(0.01,100,'bar',3), interpolation=('Chebyshev', 6, 4), maximumAtoms=15, )
[ 2, 6060, 4237, 198, 48806, 7, 198, 220, 220, 220, 10811, 5908, 43, 11127, 796, 37250, 39754, 35048, 5908, 23377, 6, 4357, 198, 220, 220, 220, 6317, 43, 11127, 796, 685, 10786, 34, 18, 3256, 10352, 8, 4357, 198, 220, 220, 220, 9403, ...
2.279412
612
# Copyright (c) 2019-2021 by University of Kassel, Tu Dortmund, RWTH Aachen University and Fraunhofer # Institute for Energy Economics and Energy System Technology (IEE) Kassel and individual # contributors (see AUTHORS file for details). All rights reserved. __version__ = "1.3.0" __author__ = "smeinecke" import os sb_dir = os.path.dirname(os.path.realpath(__file__)) from simbench.converter import * from simbench.networks import *
[ 2, 15069, 357, 66, 8, 13130, 12, 1238, 2481, 416, 2059, 286, 15035, 741, 11, 16749, 36888, 11, 33212, 4221, 317, 330, 831, 2059, 290, 39313, 403, 71, 30288, 198, 2, 5136, 329, 6682, 18963, 290, 6682, 4482, 8987, 357, 40, 6500, 8, ...
3.244444
135
import assistantResume from speak_module import speak from database import speak_is_on
[ 11748, 8796, 4965, 2454, 198, 6738, 2740, 62, 21412, 1330, 2740, 198, 6738, 6831, 1330, 2740, 62, 271, 62, 261 ]
4.3
20
import vk_api from vk_api.utils import get_random_id from vk_bot.core.sql.vksql import *
[ 11748, 410, 74, 62, 15042, 198, 6738, 410, 74, 62, 15042, 13, 26791, 1330, 651, 62, 25120, 62, 312, 198, 6738, 410, 74, 62, 13645, 13, 7295, 13, 25410, 13, 85, 591, 13976, 1330, 1635 ]
2.514286
35
"""Wallpaper Downloader Main Module.""" import argparse import asyncio import logging import sys from datetime import datetime from wallpaperdownloader.downloader import download, LOGGER_NAME def abort(*args): """Print message to the stderr and exit the program.""" print(*args, file=sys.stderr) sys.exit(1) def check_args(args): """Check if arguments are valid.""" month, year = (args.month, args.year) if month < 1 or month > 12: abort("Invalid month number %d", month) date_string = f"{year:04}{month:02}" if date_string < "201205": abort("There are no wallpapers older than May 2012") if date_string > datetime.now().strftime("%Y%M"): abort("Too early... come a bit later") def configure_logger(level): """Configure console log output.""" logger = logging.getLogger(LOGGER_NAME) handler = logging.StreamHandler() logger.setLevel(level) handler.setLevel(level) logger.addHandler(handler) def main(): """Run WD main routine.""" parser = argparse.ArgumentParser( description="Download wallpapers from www.smashingmagazine.com" ) parser.add_argument("month", type=int, help="Month number") parser.add_argument("year", type=int, help="Year") parser.add_argument("resolution", type=str, help="Image resolution") parser.add_argument( "-v", "--verbose", action="store_true", help="Enable verbose output" ) args = parser.parse_args() check_args(args) configure_logger(logging.DEBUG if args.verbose else logging.INFO) year, month, res = (args.year, args.month, args.resolution) asyncio.get_event_loop().run_until_complete(download(year, month, res)) if __name__ == "__main__": main()
[ 37811, 22401, 20189, 10472, 263, 8774, 19937, 526, 15931, 198, 198, 11748, 1822, 29572, 198, 11748, 30351, 952, 198, 11748, 18931, 198, 11748, 25064, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 39328, 15002, 263, 13, 15002, 2...
2.816129
620
""" Functions shared across the main window, the welcome window and the system tray. """ import os import qcrash.api as qcrash from PyQt5 import QtWidgets from hackedit.app import templates, settings from hackedit.app.dialogs.dlg_about import DlgAbout from hackedit.app.dialogs.dlg_template_answers import DlgTemplateVars from hackedit.app.dialogs.preferences import DlgPreferences from hackedit.app.wizards.new import WizardNew def show_about(window): """ Shows the about dialog on the parent window :param window: parent window. """ DlgAbout.show_about(window) def check_for_update(*args, **kwargs): """ Checks for update. :param window: parent window :param show_up_to_date_msg: True to show a message box when the app is up to date. """ # todo: improve this: make an update wizard that update both hackedit # and its packages (to ensure compatiblity) # if pip_tools.check_for_update('hackedit', __version__): # answer = QtWidgets.QMessageBox.question( # window, 'Check for update', # 'A new version of HackEdit is available...\n' # 'Would you like to install it now?') # if answer == QtWidgets.QMessageBox.Yes: # try: # status = pip_tools.graphical_install_package( # 'hackedit', autoclose_dlg=True) # except RuntimeError as e: # QtWidgets.qApp.processEvents() # QtWidgets.QMessageBox.warning( # window, 'Update failed', # 'Failed to update hackedit: %r' % e) # else: # QtWidgets.qApp.processEvents() # if status: # QtWidgets.QMessageBox.information( # window, 'Check for update', # 'Update completed with sucess, the application ' # 'will now restart...') # window.app.restart() # else: # QtWidgets.QMessageBox.warning( # window, 'Update failed', # 'Failed to update hackedit') # else: # _logger().debug('HackEdit up to date') # if show_up_to_date_msg: # QtWidgets.QMessageBox.information( # window, 'Check for update', 'HackEdit is up to date.') pass
[ 37811, 198, 24629, 2733, 4888, 1973, 262, 1388, 4324, 11, 262, 7062, 4324, 290, 262, 1080, 198, 2213, 323, 13, 198, 198, 37811, 198, 11748, 28686, 198, 198, 11748, 10662, 6098, 1077, 13, 15042, 355, 10662, 6098, 1077, 198, 6738, 9485, ...
2.159641
1,115
""" pygame-menu https://github.com/ppizarror/pygame-menu LOCALS Local constants. License: ------------------------------------------------------------------------------- The MIT License (MIT) Copyright 2017-2021 Pablo Pizarro R. @ppizarror 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. ------------------------------------------------------------------------------- """ __all__ = [ # Alignment 'ALIGN_CENTER', 'ALIGN_LEFT', 'ALIGN_RIGHT', # Data types 'INPUT_FLOAT', 'INPUT_INT', 'INPUT_TEXT', # Positioning 'POSITION_CENTER', 'POSITION_EAST', 'POSITION_NORTH', 'POSITION_NORTHEAST', 'POSITION_SOUTHWEST', 'POSITION_SOUTH', 'POSITION_SOUTHEAST', 'POSITION_NORTHWEST', 'POSITION_WEST', # Orientation 'ORIENTATION_HORIZONTAL', 'ORIENTATION_VERTICAL', # Scrollarea 'SCROLLAREA_POSITION_BOTH_HORIZONTAL', 'SCROLLAREA_POSITION_BOTH_VERTICAL', 'SCROLLAREA_POSITION_FULL', # Cursors 'CURSOR_ARROW', 'CURSOR_CROSSHAIR', 'CURSOR_HAND', 'CURSOR_IBEAM', 'CURSOR_NO', 'CURSOR_SIZEALL', 'CURSOR_SIZENESW', 'CURSOR_SIZENS', 'CURSOR_SIZENWSE', 'CURSOR_SIZEWE', 'CURSOR_WAIT', 'CURSOR_WAITARROW', # Event compatibility 'FINGERDOWN', 'FINGERMOTION', 'FINGERUP' ] import pygame as __pygame # Alignment ALIGN_CENTER = 'align-center' ALIGN_LEFT = 'align-left' ALIGN_RIGHT = 'align-right' # Input data type INPUT_FLOAT = 'input-float' INPUT_INT = 'input-int' INPUT_TEXT = 'input-text' # Position POSITION_CENTER = 'position-center' POSITION_EAST = 'position-east' POSITION_NORTH = 'position-north' POSITION_NORTHEAST = 'position-northeast' POSITION_NORTHWEST = 'position-northwest' POSITION_SOUTH = 'position-south' POSITION_SOUTHEAST = 'position-southeast' POSITION_SOUTHWEST = 'position-southwest' POSITION_WEST = 'position-west' # Menu ScrollArea position SCROLLAREA_POSITION_BOTH_HORIZONTAL = 'scrollarea-position-both-horizontal' SCROLLAREA_POSITION_BOTH_VERTICAL = 'scrollarea_position-both-vertical' SCROLLAREA_POSITION_FULL = 'scrollarea-position-full' # Orientation ORIENTATION_HORIZONTAL = 'orientation-horizontal' ORIENTATION_VERTICAL = 'orientation-vertical' # Cursors CURSOR_ARROW = None if not hasattr(__pygame, 'SYSTEM_CURSOR_ARROW') else __pygame.SYSTEM_CURSOR_ARROW CURSOR_CROSSHAIR = None if not hasattr(__pygame, 'SYSTEM_CURSOR_CROSSHAIR') else __pygame.SYSTEM_CURSOR_CROSSHAIR CURSOR_HAND = None if not hasattr(__pygame, 'SYSTEM_CURSOR_HAND') else __pygame.SYSTEM_CURSOR_HAND CURSOR_IBEAM = None if not hasattr(__pygame, 'SYSTEM_CURSOR_IBEAM') else __pygame.SYSTEM_CURSOR_IBEAM CURSOR_NO = None if not hasattr(__pygame, 'SYSTEM_CURSOR_NO') else __pygame.SYSTEM_CURSOR_NO CURSOR_SIZEALL = None if not hasattr(__pygame, 'SYSTEM_CURSOR_SIZEALL') else __pygame.SYSTEM_CURSOR_SIZEALL CURSOR_SIZENESW = None if not hasattr(__pygame, 'SYSTEM_CURSOR_SIZENESW') else __pygame.SYSTEM_CURSOR_SIZENESW CURSOR_SIZENS = None if not hasattr(__pygame, 'SYSTEM_CURSOR_SIZENS') else __pygame.SYSTEM_CURSOR_SIZENS CURSOR_SIZENWSE = None if not hasattr(__pygame, 'SYSTEM_CURSOR_SIZENWSE') else __pygame.SYSTEM_CURSOR_SIZENWSE CURSOR_SIZEWE = None if not hasattr(__pygame, 'SYSTEM_CURSOR_SIZEWE') else __pygame.SYSTEM_CURSOR_SIZEWE CURSOR_WAIT = None if not hasattr(__pygame, 'SYSTEM_CURSOR_WAIT') else __pygame.SYSTEM_CURSOR_WAIT CURSOR_WAITARROW = None if not hasattr(__pygame, 'SYSTEM_CURSOR_WAITARROW') else __pygame.SYSTEM_CURSOR_WAITARROW # Events compatibility with lower pygame versions FINGERDOWN = -1 if not hasattr(__pygame, 'FINGERDOWN') else __pygame.FINGERDOWN FINGERMOTION = -1 if not hasattr(__pygame, 'FINGERMOTION') else __pygame.FINGERMOTION FINGERUP = -1 if not hasattr(__pygame, 'FINGERUP') else __pygame.FINGERUP
[ 37811, 198, 9078, 6057, 12, 26272, 198, 5450, 1378, 12567, 13, 785, 14, 381, 528, 283, 1472, 14, 9078, 6057, 12, 26272, 198, 198, 29701, 23333, 198, 14565, 38491, 13, 198, 198, 34156, 25, 198, 10097, 24305, 198, 464, 17168, 13789, 357...
2.52537
1,892
import os import sys from enum import Enum from enum import unique from typing import List # Set system constants based on the current platform if sys.platform.startswith("win32"): DEFAULT_SYSTEM_CONFIG_PATH = os.path.join(os.environ["APPDATA"], "config") elif sys.platform.startswith("linux"): DEFAULT_SYSTEM_CONFIG_PATH = os.path.join(os.environ["HOME"], ".config") elif sys.platform.startswith("darwin"): DEFAULT_SYSTEM_CONFIG_PATH = os.path.join( os.environ["HOME"], "Library", "Application Support" ) else: DEFAULT_SYSTEM_CONFIG_PATH = os.path.join(os.environ["HOME"], "config") # System configuration PACKAGE_BASE_CONFIG_FOLDER = "ventress-functions" PACKAGE_CONFIG_DIR_PATH = os.path.join( DEFAULT_SYSTEM_CONFIG_PATH, PACKAGE_BASE_CONFIG_FOLDER ) DEFAULT_LOG_FILENAME = "functions.log" DEFAULT_LOG_FILEPATH = os.path.join(PACKAGE_CONFIG_DIR_PATH, DEFAULT_LOG_FILENAME) # Project constants PROJECT_VENDOR = "ventress" PROJECT_MARK = "ventress-functions"
[ 11748, 28686, 198, 11748, 25064, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 33829, 1330, 3748, 198, 6738, 19720, 1330, 7343, 198, 198, 2, 5345, 1080, 38491, 1912, 319, 262, 1459, 3859, 198, 361, 25064, 13, 24254, 13, 9688, 2032, 342,...
2.625654
382
#- Copyright 2014 GOTO 10. #- Licensed under the Apache License, Version 2.0 (see LICENSE). ## Utilities used for creating build extensions. from abc import ABCMeta, abstractmethod # Abstract superclass of the tool sets loaded implicitly into each context. # There can be many of these, one for each context. # Controller for this kind of extension. There is only one of these for each # kind of extension.
[ 2, 12, 15069, 1946, 402, 26631, 838, 13, 198, 2, 12, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 3826, 38559, 24290, 737, 198, 198, 2235, 41086, 973, 329, 4441, 1382, 18366, 13, 198, 198, 6738, 450, 66, 1330, 9738, ...
4.039216
102
# -*- coding: utf-8 -*- ''' REFERENCES: [1] Y. Bar-Shalom, X. R. Li, and T. Kirubarajan, "Estimation with Applications to Tracking and Navigation," New York: John Wiley and Sons, Inc, 2001. [2] R. A. Singer, "Estimating Optimal Tracking Filter Performance for Manned Maneuvering Targets," in IEEE Transactions on Aerospace and Electronic Systems, vol. AES-6, no. 4, pp. 473-483, July 1970. [3] X. Rong Li and V. P. Jilkov, "Survey of maneuvering target tracking. Part I. Dynamic models," in IEEE Transactions on Aerospace and Electronic Systems, vol. 39, no. 4, pp. 1333-1364, Oct. 2003. [4] W. Koch, "Tracking and Sensor Data Fusion: Methodological Framework and Selected Applications," Heidelberg, Germany: Springer, 2014. [5] Mo Longbin, Song Xiaoquan, Zhou Yiyu, Sun Zhong Kang and Y. Bar-Shalom, "Unbiased converted measurements for tracking," in IEEE Transactions on Aerospace and Electronic Systems, vol. 34, no. 3, pp. 1023-1027, July 1998 ''' from __future__ import division, absolute_import, print_function __all__ = [ 'F_poly', 'F_singer', 'F_van_keuk', 'Q_poly_dc', 'Q_poly_dd', 'Q_singer', 'Q_van_keuk', 'H_pos_only', 'R_pos_only', 'F_cv', 'f_cv', 'f_cv_jac', 'Q_cv_dc', 'Q_cv_dd', 'H_cv', 'h_cv', 'h_cv_jac', 'R_cv', 'F_ca', 'f_ca', 'f_ca_jac', 'Q_ca_dc', 'Q_ca_dd', 'H_ca', 'h_ca', 'h_ca_jac', 'R_ca', 'F_ct', 'f_ct', 'f_ct_jac', 'Q_ct', 'h_ct', 'h_ct_jac', 'R_ct', 'convert_meas', 'model_switch', 'trajectory_cv', 'trajectory_ca', 'trajectory_ct', 'trajectory_generator', 'trajectory_with_pd', 'trajectory_to_meas' ] import numbers import numpy as np import scipy.linalg as lg import scipy.stats as st import scipy.special as sl from tracklib.utils import sph2cart, pol2cart def F_poly(order, axis, T): ''' This polynomial transition matrix is used with discretized continuous-time models as well as direct discrete-time models. see section 6.2 and 6.3 in [1]. Parameters ---------- order : int The order of the filter. If order=2, then it is constant velocity, 3 means constant acceleration, 4 means constant jerk, etc. axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. Returns ------- F : ndarray The state transition matrix under a linear dynamic model of the given order and axis. ''' assert (order >= 1) assert (axis >= 1) F_base = np.zeros((order, order)) tmp = np.arange(order) F_base[0, :] = T**tmp / sl.factorial(tmp) for row in range(1, order): F_base[row, row:] = F_base[0, :order - row] F = np.kron(np.eye(axis), F_base) return F def F_singer(axis, T, tau=20): ''' Get the singer model transition matrix, see section 8.2 in [1]. Parameters ---------- axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. tau : float The time constant of the target acceleration autocorrelation, that is, the decorrelation time is approximately 2*tau. A reasonable range of tau for Singer's model is between 5 and 20 seconds. Typical values of tau for aircraft are 20s for slow turn and 5s for an evasive maneuver. If this parameter is omitted, the default value of 20 is used.The time constant is assumed the same for all dimensions of motion, so this parameter is scalar. Returns ------- F : ndarray The state transition matrix under a Gauss-Markov dynamic model of the given axis. ''' assert (axis >= 1) alpha = 1 / tau F_base = np.zeros((3, 3)) aT = alpha * T eaT = np.exp(-aT) F_base[0, 0] = 1 F_base[0, 1] = T F_base[0, 2] = (aT - 1 + eaT) * tau**2 F_base[1, 1] = 1 F_base[1, 2] = (1 - eaT) * tau F_base[2, 2] = eaT F = np.kron(np.eye(axis), F_base) return F def F_van_keuk(axis, T, tau=20): ''' Get the state transition matrix for the van Keuk dynamic model. This is a direct discrete-time model such that the acceleration advances in each dimension over time as a[k+1]=exp(-T/tau)a[k]+std*sqrt(1-exp(-2*T/tau))*v[k], see section 2.2.1 in [4] Parameters ---------- axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. tau : float The time constant of the target acceleration autocorrelation, that is, the decorrelation time is approximately 2*tau. A reasonable range of tau for Singer's model is between 5 and 20 seconds. Typical values of tau for aircraft are 20s for slow turn and 5s for an evasive maneuver. If this parameter is omitted, the default value of 20 is used.The time constant is assumed the same for all dimensions of motion, so this parameter is scalar. Returns ------- F : ndarray The state transition matrix under a Gauss-Markov dynamic model of the given axis. ''' assert (axis >= 1) F_base = F_poly(3, 1, T) F_base[-1, -1] = np.exp(-T / tau) F = np.kron(np.eye(axis), F_base) return F def Q_poly_dc(order, axis, T, std): ''' Process noise covariance matrix used with discretized continuous-time models. see section 6.2 in [1]. Parameters ---------- order : int The order of the filter. If order=2, then it is constant velocity, 3 means constant acceleration, 4 means constant jerk, etc. axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. std : number, list The standard deviation (square root of intensity) of continuous-time porcess noise Returns ------- Q : ndarray Process noise convariance ''' assert (order >= 1) assert (axis >= 1) if isinstance(std, numbers.Number): std = [std] * axis sel = np.arange(order - 1, -1, -1) col, row = np.meshgrid(sel, sel) Q_base = T**(col + row + 1) / (sl.factorial(col) * sl.factorial(row) * (col + row + 1)) Q = np.kron(np.diag(std)**2, Q_base) return Q def Q_poly_dd(order, axis, T, std, ht=0): ''' Process noise covariance matrix used with direct discrete-time models. see section 6.3 in [1]. Parameters ---------- order : int The order of the filter. If order=2, then it is constant velocity, 3 means constant acceleration, 4 means constant jerk, etc. axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. std : number, list The standard deviation of discrete-time porcess noise ht : int ht means that the order of the noise is `ht` greater than the highest order of the state, e.g., if the highest order of state is acceleration, then ht=0 means that the noise is of the same order as the highest order of state, that is, the noise is acceleration and the model is DWPA, see section 6.3.3 in [1]. If the highest order is velocity, the ht=1 means the noise is acceleration and the model is DWNA, see section 6.3.2 in [1]. Returns ------- Q : ndarray Process noise convariance Notes ----- For the model to which the alpha filter applies, we have order=0, ht=2. Likewise, for the alpha-beta filter, order=1, ht=1 and for the alpha- beta-gamma filter, order=2, ht=0 ''' assert (order >= 1) assert (axis >= 1) if isinstance(std, numbers.Number): std = [std] * axis sel = np.arange(ht + order - 1, ht - 1, -1) L = T**sel / sl.factorial(sel) Q_base = np.outer(L, L) Q = np.kron(np.diag(std)**2, Q_base) return Q def Q_singer(axis, T, std, tau=20): ''' Process noise covariance matrix used with Singer models. see section 8.2 in [1] Parameters ---------- axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. std : number, list std is the instantaneous standard deviation of the acceleration knowm as Ornstein-Uhlenbeck process, which can be obtained by assuming it to be 1. Equal to a maxmum acceleration a_M with probability p_M and -a_M with the same probability 2. Equal to zero with probability p_0 3. Uniformly distributed in [-a_M, a_M] with the remaining probability mass All parameters mentioned above are chosen by the designer. So the expected std^2 is (a_M^2 / 3)*(1 + 4*p_M - p_0) tau : float The time constant of the target acceleration autocorrelation, that is, the decorrelation time is approximately 2*tau. A reasonable range of tau for Singer's model is between 5 and 20 seconds. Typical values of tau for aircraft are 20s for slow turn and 5s for an evasive maneuver. If this parameter is omitted, the default value of 20 is used.The time constant is assumed the same for all dimensions of motion, so this parameter is scalar. Returns ------- Q : ndarray Process noise convariance ''' assert (axis >= 1) if isinstance(std, numbers.Number): std = [std] * axis alpha = 1 / tau aT = alpha * T eaT = np.exp(-aT) e2aT = np.exp(-2 * aT) q11 = tau**4 * (1 - e2aT + 2 * aT + 2 * aT**3 / 3 - 2 * aT**2 - 4 * aT * eaT) q12 = tau**3 * (e2aT + 1 - 2 * eaT + 2 * aT * eaT - 2 * aT + aT**2) q13 = tau**2 * (1 - e2aT - 2 * aT * eaT) q22 = tau**2 * (4 * eaT - 3 - e2aT + 2 * aT) q23 = tau * (e2aT + 1 - 2 * eaT) q33 = 1 - e2aT Q_base = np.array([[q11, q12, q13], [q12, q22, q23], [q13, q23, q33]], dtype=float) Q = np.kron(np.diag(std)**2, Q_base) return Q def Q_van_keuk(axis, T, std, tau=20): ''' Process noise covariance matrix for a Van Keuk dynamic model, see section 2.2.1 in [4] Parameters ---------- axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. std : number, list std is the instantaneous standard deviation of the acceleration knowm as Ornstein-Uhlenbeck process, which can be obtained by assuming it to be 1. Equal to a maxmum acceleration a_M with probability p_M and -a_M with the same probability 2. Equal to zero with probability p_0 3. Uniformly distributed in [-a_M, a_M] with the remaining probability mass All parameters mentioned above are chosen by the designer. So the expected std^2 is (a_M^2 / 3)*(1 + 4*p_M - p_0) tau : float The time constant of the target acceleration autocorrelation, that is, the decorrelation time is approximately 2*tau. A reasonable range of tau for Singer's model is between 5 and 20 seconds. Typical values of tau for aircraft are 20s for slow turn and 5s for an evasive maneuver. If this parameter is omitted, the default value of 20 is used. The time constant is assumed the same for all dimensions of motion, so this parameter is scalar. Returns ------- Q : ndarray Process noise convariance ''' assert (axis >= 1) if isinstance(std, numbers.Number): std = [std] * axis Q_base = np.diag([0., 0., 1.]) Q_base = (1 - np.exp(-2 * T / tau)) * Q_base Q = np.kron(np.diag(std)**2, Q_base) return Q def H_pos_only(order, axis): ''' Position-only measurement matrix is used with discretized continuous-time models as well as direct discrete-time models. see section 6.5 in [1]. Parameters ---------- order : int The order of the filter. If order=2, then it is constant velocity, 3 means constant acceleration, 4 means constant jerk, etc. axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. Returns ------- H : ndarray the measurement or obervation matrix ''' assert (order >= 1) assert (axis >= 1) H = np.eye(order * axis) H = H[::order] return H def R_pos_only(axis, std): ''' Position-only measurement noise covariance matrix and the noise of each axis is assumed to be uncorrelated. Parameters ---------- axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. Returns ------- R : ndarray the measurement noise covariance matrix ''' assert (axis >= 1) if isinstance(std, numbers.Number): std = [std] * axis R = np.diag(std)**2 return R def trajectory_generator(record): ''' record = { 'interval': [1, 1], 'start': [ [0, 0, 0], [0, 5, 0] ], 'pattern': [ [ {'model': 'cv', 'length': 100, 'velocity': [250, 250, 0]}, {'model': 'ct', 'length': 25, 'turnrate': 30} ], [ {'model': 'cv', 'length': 100, 'velocity': [250, 250, 0]}, {'model': 'ct', 'length': 30, 'turnrate': 30, 'velocity': 30} ] ], 'noise': [ 10 * np.eye(3), 10 * np.eye(3) ], 'pd': [ 0.9, 0.9 ], 'entries': 2 } ''' dim, order, axis = 9, 3, 3 ca_sel = range(dim) acc_sel = range(2, dim, order) cv_sel = np.setdiff1d(ca_sel, acc_sel) ct_sel = np.setdiff1d(ca_sel, acc_sel) insert_sel = [2, 4, 6] interval = record['interval'] start = record['start'] pattern = record['pattern'] noise = record['noise'] entries = record['entries'] trajs_state = [] for i in range(entries): head = np.kron(start[i], [1., 0., 0.]) state = np.kron(start[i], [1., 0., 0.]).reshape(1, -1) for pat in pattern[i]: if pat['model'] == 'cv': ret, head_cv = trajectory_cv(head[cv_sel], interval[i], pat['length'], pat['velocity']) ret = np.insert(ret, insert_sel, 0, axis=1) head = ret[-1, ca_sel] state[-1, acc_sel] = 0 # set the acceleration of previous state to zero state[-1, cv_sel] = head_cv # change the velocity of previous state state = np.vstack((state, ret)) elif pat['model'] == 'ca': ret, head_ca = trajectory_ca(head, interval[i], pat['length'], pat['acceleration']) head = ret[-1, ca_sel] state[-1, ca_sel] = head_ca # change the acceleartion of previous state state = np.vstack((state, ret)) elif pat['model'] == 'ct': if 'velocity' in pat: ret, head_ct = trajectory_ct(head[ct_sel], interval[i], pat['length'], pat['turnrate'], pat['velocity']) else: ret, head_ct = trajectory_ct(head[ct_sel], interval[i], pat['length'], pat['turnrate']) ret = np.insert(ret, insert_sel, 0, axis=1) head = ret[-1, ca_sel] state[-1, acc_sel] = 0 state[-1, ct_sel] = head_ct state = np.vstack((state, ret)) else: raise ValueError('invalid model') trajs_state.append(state) # add noise trajs_meas = [] for i in range(entries): H = H_ca(axis) traj_len = trajs_state[i].shape[0] noi = st.multivariate_normal.rvs(cov=noise[i], size=traj_len) trajs_meas.append(np.dot(trajs_state[i], H.T) + noi) return trajs_state, trajs_meas
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 7061, 6, 198, 2200, 24302, 24181, 1546, 25, 198, 58, 16, 60, 575, 13, 2409, 12, 2484, 282, 296, 11, 1395, 13, 371, 13, 7455, 11, 290, 309, 13, 7385, 549, 283, 1228...
2.367861
6,951
# Generated by Django 3.2.4 on 2021-06-19 08:48 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 19, 319, 33448, 12, 3312, 12, 1129, 8487, 25, 2780, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
""" Orchestrate experiment execution. """ import typing as tp import attr from benchbuild.experiment import Experiment from benchbuild.project import Project from benchbuild.utils import actions, tasks ExperimentCls = tp.Type[Experiment] Experiments = tp.List[ExperimentCls] ProjectCls = tp.Type[Project] Projects = tp.List[ProjectCls] ExperimentProject = tp.Tuple[ExperimentCls, ProjectCls] Actions = tp.Sequence[actions.Step] StepResults = tp.List[actions.StepResult]
[ 37811, 198, 5574, 2395, 23104, 6306, 9706, 13, 198, 37811, 198, 11748, 19720, 355, 256, 79, 198, 198, 11748, 708, 81, 198, 198, 6738, 7624, 11249, 13, 23100, 3681, 1330, 29544, 198, 6738, 7624, 11249, 13, 16302, 1330, 4935, 198, 6738, ...
3.118421
152
""" Mask R-CNN Dataset functions and classes. Copyright (c) 2017 Matterport, Inc. Licensed under the MIT License (see LICENSE for details) Written by Waleed Abdulla """ import numpy as np import tensorflow as tf import keras.backend as KB import keras.layers as KL import keras.initializers as KI import keras.engine as KE import mrcnn.utils as utils from mrcnn.loss import smooth_l1_loss import pprint pp = pprint.PrettyPrinter(indent=2, width=100) ##----------------------------------------------------------------------- ## FCN loss ##----------------------------------------------------------------------- def fcn_loss_graph(target_masks, pred_masks): # def fcn_loss_graph(input): # target_masks, pred_masks = input """Mask binary cross-entropy loss for the masks head. target_masks: [batch, height, width, num_classes]. pred_masks: [batch, height, width, num_classes] float32 tensor """ # Reshape for simplicity. Merge first two dimensions into one. print('\n fcn_loss_graph ' ) print(' target_masks shape :', target_masks.get_shape()) print(' pred_masks shape :', pred_masks.get_shape()) mask_shape = tf.shape(target_masks) print(' mask_shape shape :', mask_shape.shape) target_masks = KB.reshape(target_masks, (-1, mask_shape[1], mask_shape[2])) print(' target_masks shape :', target_masks.shape) pred_shape = tf.shape(pred_masks) print(' pred_shape shape :', pred_shape.shape) pred_masks = KB.reshape(pred_masks, (-1, pred_shape[1], pred_shape[2])) print(' pred_masks shape :', pred_masks.get_shape()) # Compute binary cross entropy. If no positive ROIs, then return 0. # shape: [batch, roi, num_classes] # Smooth-L1 Loss loss = KB.switch(tf.size(target_masks) > 0, smooth_l1_loss(y_true=target_masks, y_pred=pred_masks), tf.constant(0.0)) loss = KB.mean(loss) loss = KB.reshape(loss, [1, 1]) print(' loss type is :', type(loss)) return loss ##----------------------------------------------------------------------- ## FCN loss for L2 Normalized graph ##----------------------------------------------------------------------- def fcn_norm_loss_graph(target_masks, pred_masks): ''' Mask binary cross-entropy loss for the masks head. target_masks: [batch, height, width, num_classes]. pred_masks: [batch, height, width, num_classes] float32 tensor ''' print(type(target_masks)) pp.pprint(dir(target_masks)) # Reshape for simplicity. Merge first two dimensions into one. print('\n fcn_norm_loss_graph ' ) print(' target_masks shape :', target_masks.shape) print(' pred_masks shape :', pred_masks.shape) print('\n L2 normalization ------------------------------------------------------') output_shape=KB.int_shape(pred_masks) print(' output shape is :' , output_shape, ' ', pred_masks.get_shape(), pred_masks.shape, tf.shape(pred_masks)) output_flatten = KB.reshape(pred_masks, (pred_masks.shape[0], -1, pred_masks.shape[-1]) ) output_norm1 = KB.l2_normalize(output_flatten, axis = 1) output_norm = KB.reshape(output_norm1, KB.shape(pred_masks) ) print(' output_flatten : ', KB.int_shape(output_flatten) , ' Keras tensor ', KB.is_keras_tensor(output_flatten) ) print(' output_norm1 : ', KB.int_shape(output_norm1) , ' Keras tensor ', KB.is_keras_tensor(output_norm1) ) print(' output_norm final : ', KB.int_shape(output_norm) , ' Keras tensor ', KB.is_keras_tensor(output_norm) ) pred_masks1 = output_norm print('\n L2 normalization ------------------------------------------------------') gauss_flatten = KB.reshape(target_masks, (target_masks.shape[0], -1, target_masks.shape[-1]) ) gauss_norm1 = KB.l2_normalize(gauss_flatten, axis = 1) gauss_norm = KB.reshape(gauss_norm1, KB.shape(target_masks)) print(' guass_flatten : ', KB.int_shape(gauss_flatten), 'Keras tensor ', KB.is_keras_tensor(gauss_flatten) ) print(' gauss_norm shape : ', KB.int_shape(gauss_norm1) , 'Keras tensor ', KB.is_keras_tensor(gauss_norm1) ) print(' gauss_norm final shape: ', KB.int_shape(gauss_norm) , 'Keras tensor ', KB.is_keras_tensor(gauss_norm) ) print(' complete') target_masks1 = gauss_norm mask_shape = tf.shape(target_masks1) print(' mask_shape shape :', mask_shape.shape) target_masks1 = KB.reshape(target_masks1, (-1, mask_shape[1], mask_shape[2])) print(' target_masks shape :', target_masks1.shape) pred_shape = tf.shape(pred_masks1) print(' pred_shape shape :', pred_shape.shape) pred_masks1 = KB.reshape(pred_masks1, (-1, pred_shape[1], pred_shape[2])) print(' pred_masks shape :', pred_masks1.get_shape()) # Compute binary cross entropy. If no positive ROIs, then return 0. # shape: [batch, roi, num_classes] # Smooth-L1 Loss loss = KB.switch(tf.size(target_masks1) > 0, smooth_l1_loss(y_true=target_masks1, y_pred=pred_masks1), tf.constant(0.0)) loss = KB.mean(loss) loss = KB.reshape(loss, [1, 1]) print(' loss type is :', type(loss)) return loss
[ 37811, 198, 45195, 371, 12, 18474, 198, 27354, 292, 316, 5499, 290, 6097, 13, 198, 198, 15269, 357, 66, 8, 2177, 16900, 634, 11, 3457, 13, 198, 26656, 15385, 739, 262, 17168, 13789, 357, 3826, 38559, 24290, 329, 3307, 8, 198, 25354, ...
2.28989
2,463
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def plot_well_map(df_logs, fig_size=(10, 10)): """ Simple map of locations of nearby wells """ f, ax = plt.subplots(figsize=fig_size) df = df_logs.drop_duplicates(subset=['HACKANAME', 'X', 'Y']) plt.scatter(df['X'], df['Y']) plt.axis('scaled') for label, x, y in zip(df['HACKANAME'], df['X'], df['Y']): plt.annotate(label, xy=(x, y), xytext=(-10, 10), textcoords='offset points') return f, ax def make_log_plot(df_logs, well_name, cols=['GR', 'DT', 'CALI'], ztop=None, zbot=None, fig_size=(8, 12)): """ Single well log plot, both GR and Resistivity """ logs = df_logs[df_logs['HACKANAME'] == well_name] logs = logs.sort_values(by='TVDSS') if not ztop: ztop = logs.TVDSS.min() if not zbot: zbot = logs.TVDSS.max() f, ax = plt.subplots(nrows=1, ncols=len(cols), figsize=fig_size) for i in range(len(ax)): log_name = cols[i] ax[i].scatter(logs[log_name], logs['TVDSS'], marker='+') ax[i].set_xlabel(log_name) ax[i].set_ylim(ztop, zbot) ax[i].invert_yaxis() ax[i].grid() ax[i].locator_params(axis='x', nbins=3) if i > 0: ax[i].set_yticklabels([]) # ax[0].set_xlabel("GR") # ax[0].set_xlim(0, 150) # ax[1].set_xlabel("RESD") # ax[1].set_xscale('log') # ax[1].set_xlim(0.2, 2000) # ax[1].set_yticklabels([]) f.suptitle('Well: {}'.format(well_name), fontsize=14, y=0.94) return f, ax def add_predictions(ax, predictions): """ Add predicted bands onto plt axes""" # Scatter plot ax.scatter(predictions['value'], predictions['TVDSS'], marker='+') # Shaded bands tvds = predictions[predictions.model_name == 'high']['TVDSS'] x_hi = predictions[predictions.model_name == 'high']['value'] x_lo = predictions[predictions.model_name == 'low']['value'] ax.fill(np.concatenate([x_lo, x_hi[::-1]]), np.concatenate([tvds, tvds[::-1]]), alpha=0.5)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 384, 397, 1211, 355, 3013, 82, 628, 198, 4299, 7110, 62, 4053, 62, 8899, 7, 7568, 62, 640...
2.024482
1,062
#!/usr/bin/env python """ cc_plugin_eustace.eustace_global_attrs Compliance Test Suite: Check core global attributes in EUSTACE files """ import os from netCDF4 import Dataset # Import base objects from compliance checker from compliance_checker.base import Result, BaseNCCheck, GenericFile # Restrict which vocabs will load (for efficiency) os.environ["ESSV_VOCABS_ACTIVE"] = "eustace-team" # Import checklib import checklib.register.nc_file_checks_register as check_package
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 535, 62, 33803, 62, 68, 436, 558, 13, 68, 436, 558, 62, 20541, 62, 1078, 3808, 198, 198, 38143, 3610, 6208, 26264, 25, 6822, 4755, 3298, 12608, 287, 4576, 2257, 11598, 36...
3.121795
156
import unittest import translator if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 33417, 198, 220, 220, 220, 220, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419 ]
2.575758
33
s1 = Student("Harry", 12) # access instance variables print('Student:', s1.name, s1.age) # access class variable print('School name:', Student.school_name) # Modify instance variables s1.name = 'Jessa' s1.age = 14 print('Student:', s1.name, s1.age) # Modify class variables Student.school_name = 'XYZ School' print('School name:', Student.school_name)
[ 198, 198, 82, 16, 796, 13613, 7203, 18308, 1600, 1105, 8, 198, 2, 1895, 4554, 9633, 198, 4798, 10786, 38778, 25, 3256, 264, 16, 13, 3672, 11, 264, 16, 13, 496, 8, 198, 198, 2, 1895, 1398, 7885, 198, 4798, 10786, 26130, 1438, 25, ...
2.879032
124
# -*- coding: utf-8 -*- from . import base from .audit_log import * from .channel import * from .emoji import * from .gateway import * from .guild import * from .invite import * from .oauth import * from .user import * from .voice import * from .webhook import *
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 764, 1330, 2779, 198, 6738, 764, 3885, 270, 62, 6404, 1330, 1635, 198, 6738, 764, 17620, 1330, 1635, 198, 6738, 764, 368, 31370, 1330, 1635, 198, 6738, 764, ...
2.966292
89
#!/usr/bin/python # -*- coding: utf-8 -*- import os import datetime import hamster.client import reports import argparse import pdfkit import gettext gettext.install('brainz', '../datas/translations/') # custom settings: reportTitle = "My Activities Report" activityFilter = "unfiled" # find dates: today = datetime.date.today() first = today.replace(day=1) previousLast = first - datetime.timedelta(days=1) previousFirst = previousLast.replace(day=1) # assign arguments: parser = argparse.ArgumentParser(description="export the hamster database to pdf") parser.add_argument("--thismonth", action="store_true", help="export this month's records") parser.add_argument("--lastmonth", action="store_true", help="export last month's records") parser.add_argument("-s", dest="startDate", default=today, help="start date (default: today)", type=valid_date) parser.add_argument("-e", dest="endDate", default=today, help="end date (default: today)", type=valid_date) parser.add_argument("-o", dest="reportFile", default="report.pdf", help="output file (default: report.pdf)") # parse arguments: args = parser.parse_args() if args.thismonth: args.startDate = first args.endDate = today if args.lastmonth: args.startDate = previousFirst args.endDate = previousLast # prepare filenames: htmlFilename = os.path.splitext(args.reportFile)[0]+".html" pdfFilename = os.path.splitext(args.reportFile)[0]+".pdf" storage = hamster.client.Storage() facts = storage.get_facts(args.startDate, args.endDate) # generate report reports.simple(facts, args.startDate, args.endDate, htmlFilename) # convert .html to .pdf file: pdfkit.from_file(htmlFilename, pdfFilename)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 4818, 8079, 198, 11748, 8891, 1706, 13, 16366, 198, 11748, 3136, 198, 11748, 1822, 29572, 198, ...
3.100559
537
from functools import wraps # created by PL # git hello world if __name__ == '__main__': s = SingleTon(1) t = SingleTon(2) print (s is t) print (s.a, t.a) print (s.val, t.val) print ('test') print ("git test")
[ 6738, 1257, 310, 10141, 1330, 27521, 201, 198, 2, 2727, 416, 9297, 201, 198, 2, 17606, 23748, 995, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 220, 220, 220, 264, 796, 14206, 354...
2.127119
118
# Custo da viagem distancia = float(input('Qual a distncia da sua viagem? ')) valor1 = distancia * 0.5 valor2 = distancia * 0.45 print('Voc est prestes a comear uma viagem de {}Km/h.'.format(distancia)) if distancia <= 200: print('O preo de sua passagem ser de R${:.2f}.'.format(valor1)) else: print('O preo de sua passagem ser de R${:.2f}.'.format(valor2))
[ 2, 40619, 78, 12379, 25357, 363, 368, 198, 17080, 1192, 544, 796, 12178, 7, 15414, 10786, 46181, 257, 1233, 10782, 544, 12379, 424, 64, 25357, 363, 368, 30, 705, 4008, 198, 2100, 273, 16, 796, 1233, 1192, 544, 1635, 657, 13, 20, 198...
2.2875
160
"""Difference classes.""" __all__ = [ 'BaseDifference', 'Missing', 'Extra', 'Invalid', 'Deviation', ] from cmath import isnan from datetime import timedelta from ._compatibility.builtins import * from ._compatibility import abc from ._compatibility.contextlib import suppress from ._utils import _make_token from ._utils import pretty_timedelta_repr NOVALUE = _make_token( 'NoValueType', '<no value>', 'Token to mark when a value does not exist.', truthy=False, ) NANTOKEN = _make_token( 'NanTokenType', '<nan token>', 'Token for comparing differences that contain not-a-number values.', ) def _nan_to_token(value): """Return NANTOKEN if *value* is NaN else return value unchanged.""" if isinstance(value, tuple): return tuple(func(x) for x in value) return func(value) def _safe_isnan(x): """Wrapper for isnan() so it won't fail on non-numeric values.""" try: return isnan(x) except TypeError: return False def _slice_datetime_repr_prefix(obj_repr): """Takes a default "datetime", "date", or "timedelta" repr and returns it with the module prefix sliced-off:: >>> _slice_datetime_repr_prefix('datetime.date(2020, 12, 25)') 'date(2020, 12, 25)' """ # The following implementation (using "startswith" and "[9:]") # may look clumsy but it can run up to 10 times faster than a # more concise "re.compile()" and "regex.sub()" approach. In # some situations, this function can get called many, many # times. DON'T GET CLEVER--KEEP THIS FUNCTION FAST. if obj_repr.startswith('datetime.datetime(') \ or obj_repr.startswith('datetime.date(') \ or obj_repr.startswith('datetime.timedelta('): return obj_repr[9:] return obj_repr class Deviation(BaseDifference): """Created when a quantative value deviates from its expected value. In the following example, the dictionary item ``'C': 33`` does not satisfy the required item ``'C': 30``:: data = {'A': 10, 'B': 20, 'C': 33} requirement = {'A': 10, 'B': 20, 'C': 30} datatest.validate(data, requirement) Running this example raises the following error: .. code-block:: none :emphasize-lines: 2 ValidationError: does not satisfy mapping requirement (1 difference): { 'C': Deviation(+3, 30), } """ __slots__ = ('_deviation', '_expected') def __repr__(self): cls_name = self.__class__.__name__ deviation = self._deviation if _safe_isnan(deviation): deviation_repr = "float('nan')" elif isinstance(deviation, timedelta): deviation_repr = pretty_timedelta_repr(deviation) else: try: deviation_repr = '{0:+}'.format(deviation) # Apply +/- sign except (TypeError, ValueError): deviation_repr = repr(deviation) expected = self._expected if _safe_isnan(expected): expected_repr = "float('nan')" else: expected_repr = repr(expected) if expected_repr.startswith('datetime.'): expected_repr = _slice_datetime_repr_prefix(expected_repr) return '{0}({1}, {2})'.format(cls_name, deviation_repr, expected_repr) def _make_difference(actual, expected, show_expected=True): """Returns an appropriate difference for *actual* and *expected* values that are known to be unequal. Setting *show_expected* to False, signals that the *expected* argument should be omitted when creating an Invalid difference (this is useful for reducing duplication when validating data against a single function or object). """ if actual is NOVALUE: return Missing(expected) if expected is NOVALUE: return Extra(actual) if isinstance(expected, bool) or isinstance(actual, bool): if show_expected: return Invalid(actual, expected) return Invalid(actual) try: deviation = actual - expected return Deviation(deviation, expected) except (TypeError, ValueError): if show_expected: return Invalid(actual, expected) return Invalid(actual)
[ 37811, 28813, 1945, 6097, 526, 15931, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 705, 14881, 28813, 1945, 3256, 198, 220, 220, 220, 705, 43730, 3256, 198, 220, 220, 220, 705, 27726, 3256, 198, 220, 220, 220, 705, 44651, ...
2.526844
1,695
from django.conf.urls import include, url, re_path from rest_framework import routers from . import views urlpatterns = [ re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/versiontime", views.get_last_processed_time), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/players", views.get_player_list), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/sessions", views.get_player_to_session_map), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/puzzles", views.get_puzzles), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/puzzlekeys", views.get_puzzle_keys), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/snapshotsperpuzzle", views.get_snapshot_metrics), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/attempted", views.get_attempted_puzzles), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/completed", views.get_completed_puzzles), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/timeperpuzzle", views.get_time_per_puzzle), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/funnelperpuzzle", views.get_funnel_per_puzzle), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/shapesperpuzzle", views.get_shapes_per_puzzle), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/modesperpuzzle", views.get_modes_per_puzzle), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/levelsofactivity", views.get_levels_of_activity), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/sequencebetweenpuzzles", views.get_sequence_between_puzzles), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/mloutliers", views.get_machine_learning_outliers), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/persistence", views.get_persistence_by_attempt_data), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/puzzlepersistence", views.get_persistence_by_puzzle_data), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/insights", views.get_insights), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/difficulty", views.get_puzzle_difficulty_mapping), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/misconceptions", views.get_misconceptions_data), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/competency", views.get_competency_data), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/report/(?P<start>[0-9]+)/(?P<end>[0-9]+)", views.get_report_summary), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/report", views.get_report_summary), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/(?P<player>[a-zA-Z0-9-_.]+)/(?P<level>[a-zA-Z0-9-_.]+)/replayurls", views.get_replay_urls), re_path(r"^(?P<slug>[a-zA-Z0-9-_]+)/dashboard/", views.dashboard), re_path(r"^(?P<slug>[a-zA-Z0-9-_]+)/thesisdashboard/", views.thesis_dashboard) ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 2291, 11, 19016, 11, 302, 62, 6978, 198, 6738, 1334, 62, 30604, 1330, 41144, 198, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 302, 62, 6978,...
1.980449
1,381
from typing import Any, Dict, List, Sequence import numpy as np import torch from detectron2.engine import DefaultPredictor
[ 6738, 19720, 1330, 4377, 11, 360, 713, 11, 7343, 11, 45835, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 4886, 1313, 17, 13, 18392, 1330, 15161, 47, 17407, 273, 628 ]
3.705882
34
from user_agent2.base import ( generate_user_agent, generate_navigator, generate_navigator_js, )
[ 6738, 2836, 62, 25781, 17, 13, 8692, 1330, 357, 198, 220, 220, 220, 7716, 62, 7220, 62, 25781, 11, 198, 220, 220, 220, 7716, 62, 28341, 23823, 11, 198, 220, 220, 220, 7716, 62, 28341, 23823, 62, 8457, 11, 198, 8, 198 ]
2.595238
42
import glob import random import uuid import numpy as np from multiprocessing import Pool from sklearn.metrics import ( recall_score, precision_score, accuracy_score, f1_score, mean_squared_error) from mutagene.io.profile import read_profile_file, write_profile, read_signatures from mutagene.signatures.identify import NegLogLik from mutagene.benchmark.deconstructsigs import deconstruct_sigs_custom from mutagene.benchmark.generate_benchmark import * # from mutagene.identify import decompose_mutational_profile_counts
[ 11748, 15095, 198, 11748, 4738, 198, 11748, 334, 27112, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 18540, 305, 919, 278, 1330, 19850, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 357, 198, 220, 220, 220, 10014, 62, 26675, 11,...
3.263804
163
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-01 13:47 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 13, 20, 319, 2177, 12, 2999, 12, 486, 1511, 25, 2857, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 1...
2.73913
69
import argparse import os import sys from ckl.values import ( ValueList, ValueString, NULL ) from ckl.errors import ( CklSyntaxError, CklRuntimeError ) from ckl.interpreter import Interpreter if __name__ == "__main__": main()
[ 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 6738, 269, 41582, 13, 27160, 1330, 357, 198, 220, 220, 220, 11052, 8053, 11, 198, 220, 220, 220, 11052, 10100, 11, 198, 220, 220, 220, 15697, 198, 8, 198, 6738, 269, ...
2.565657
99
import datetime import fnmatch import hashlib import json import time import arrow import os from botocore.exceptions import ClientError from boto.s3.key import Key from security_monkey.alerters import custom_alerter from security_monkey.common.sts_connect import connect from security_monkey import app, db from security_monkey.datastore import Account from security_monkey.task_scheduler.alert_scheduler import schedule_krampus_alerts
[ 11748, 4818, 8079, 198, 11748, 24714, 15699, 198, 11748, 12234, 8019, 198, 11748, 33918, 198, 11748, 640, 198, 11748, 15452, 198, 11748, 28686, 198, 198, 6738, 10214, 420, 382, 13, 1069, 11755, 1330, 20985, 12331, 198, 6738, 275, 2069, 13...
3.675
120
# noinspection PyPackageRequirements from telegram import InlineKeyboardMarkup, InlineKeyboardButton
[ 2, 645, 1040, 14978, 9485, 27813, 42249, 198, 6738, 573, 30536, 1330, 554, 1370, 9218, 3526, 9704, 929, 11, 554, 1370, 9218, 3526, 21864, 628 ]
4.08
25
import urllib2 import json FAKE_PACKAGES = ( 'south', 'django-debug-toolbar', 'django-extensions', 'django-social-auth', ) fetcher = GuitarWebAPI('http://localhost:8000/api/v1/')
[ 11748, 2956, 297, 571, 17, 198, 11748, 33918, 198, 198, 7708, 7336, 62, 47, 8120, 25552, 796, 357, 198, 220, 220, 220, 705, 35782, 3256, 198, 220, 220, 220, 705, 28241, 14208, 12, 24442, 12, 25981, 5657, 3256, 198, 220, 220, 220, 70...
2.313953
86
import zipfile from getpass import getpass import os import stat import tempfile from os import path from .crypto import encrypt
[ 11748, 19974, 7753, 198, 6738, 651, 6603, 1330, 651, 6603, 198, 198, 11748, 28686, 198, 11748, 1185, 198, 11748, 20218, 7753, 198, 6738, 28686, 1330, 3108, 198, 198, 6738, 764, 29609, 78, 1330, 34117, 628 ]
3.771429
35
from typing import List #
[ 6738, 19720, 1330, 7343, 628, 198, 2, 220, 198, 220, 220, 220, 220, 220, 220, 220, 220 ]
2.176471
17
""" File: pages/page.py Author: Luke Mason Description: Main part of the application, the actual graph page. """ # Application imports from message import log, error, success from settings import APP_NAME, COLOR, FONT, FONT_SIZE, SCREEN_WIDTH, SCREEN_HEIGHT, WIDTH, HEIGHT, PAD, _QUIT from sprites.vertex import Vertex from sprites.edge import Edge from pages.page import Page from graph import Graph as G # Pygame imports from pygame import draw, sprite, event, mouse, display, init, key, MOUSEBUTTONUP, MOUSEBUTTONDOWN, MOUSEMOTION, QUIT, \ KEYDOWN, K_BACKSPACE, K_DELETE, KMOD_SHIFT # Python imports from math import atan2, degrees, cos, sin
[ 37811, 198, 8979, 25, 5468, 14, 7700, 13, 9078, 198, 13838, 25, 11336, 14737, 198, 198, 11828, 25, 8774, 636, 286, 262, 3586, 11, 262, 4036, 4823, 2443, 13, 198, 37811, 198, 2, 15678, 17944, 198, 6738, 3275, 1330, 2604, 11, 4049, 11...
3.080569
211
import brownie
[ 11748, 7586, 494, 628 ]
4
4
# Filenames : <tahm1d> # Python bytecode : 2.7 # Time decompiled : Thu Sep 10 23:29:38 2020 # Selector <module> in line 4 file <tahm1d> # Timestamp in code: 2020-09-02 17:33:14 import os, sys, time from os import system from time import sleep if __name__ == '__main__': menu()
[ 2, 7066, 268, 1047, 1058, 1279, 83, 993, 76, 16, 67, 29, 198, 2, 11361, 18022, 8189, 1058, 362, 13, 22, 198, 2, 3862, 38237, 3902, 1058, 26223, 8621, 838, 2242, 25, 1959, 25, 2548, 12131, 198, 2, 9683, 273, 1279, 21412, 29, 287, ...
2.623853
109