content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import time from fabric.api import run, env, task, put, cd, local, sudo env.use_ssh_config = True env.hosts = ['iota_node']
[ 11748, 640, 198, 6738, 9664, 13, 15042, 1330, 1057, 11, 17365, 11, 4876, 11, 1234, 11, 22927, 11, 1957, 11, 21061, 198, 198, 24330, 13, 1904, 62, 45824, 62, 11250, 796, 6407, 198, 24330, 13, 4774, 82, 796, 37250, 72, 4265, 62, 17440...
2.714286
49
import sqlite3 from random import randint, choice import numpy as np conn = sqlite3.connect('ej.db') c = conn.cursor() #OBTENIENDO TAMAnOS MAXIMOS MINIMOS Y PROMEDIO# c.execute('SELECT MAX(alto) FROM features') resultado = c.fetchone() if resultado: altoMax = resultado[0] c.execute('SELECT MIN(alto) FROM features') resultado = c.fetchone() if resultado: altoMin = resultado[0] altoProm = abs((altoMax + altoMin) / 2) #print altoMax , altoProm , altoMin arrAlto = [altoMax , altoProm , altoMin] c.execute('SELECT MAX(ancho) FROM features') resultado = c.fetchone() if resultado: anchoMax = resultado[0] c.execute('SELECT MIN(ancho) FROM features') resultado = c.fetchone() if resultado: anchoMin = resultado[0] anchoProm = abs((anchoMax + anchoMin) / 2) anchoMaxProm = abs((anchoMax + anchoProm) / 2) anchoMinProm = abs((anchoMin + anchoProm) / 2) arrAncho = [anchoMax, anchoMaxProm, anchoProm, anchoMinProm, anchoMin] #### CREANDO CLASES NEGATIVAS for i in range(0,3): for j in range(0,5): for _ in range(10): negAncho = arrAncho[j] negAlto = arrAlto[i] rand_alto_max = int(negAlto * 1.5) rand_alto_min = int(negAlto * 0.5) r3 = rand_alto_max * 2 rand_ancho_max = int(negAncho*1.5) rand_ancho_min = int(negAncho*0.5) r33 = rand_ancho_max * 2 f1 = choice([np.random.randint(1, rand_alto_min), np.random.randint(rand_alto_max, r3)]) f2 = choice([np.random.randint(1, rand_ancho_min), np.random.randint(rand_ancho_max, r33)]) c.execute("insert into features (ancho, alto, area, clase) values (?, ?, ?, ?)", (f2, f1, f2*f1, 0)) conn.commit() conn.close()
[ 11748, 44161, 578, 18, 198, 6738, 4738, 1330, 43720, 600, 11, 3572, 198, 11748, 299, 32152, 355, 45941, 628, 198, 37043, 796, 44161, 578, 18, 13, 8443, 10786, 68, 73, 13, 9945, 11537, 198, 198, 66, 796, 48260, 13, 66, 21471, 3419, 1...
2.12154
831
from pylab import * import cython import time, timeit from brian2.codegen.runtime.cython_rt.modified_inline import modified_cython_inline import numpy from scipy import weave import numexpr import theano from theano import tensor as tt tau = 20 * 0.001 N = 1000000 b = 1.2 # constant current mean, the modulation varies freq = 10.0 t = 0.0 dt = 0.0001 _array_neurongroup_a = a = linspace(.05, 0.75, N) _array_neurongroup_v = v = rand(N) ns = {'_array_neurongroup_a': a, '_array_neurongroup_v': v, '_N': N, 'dt': dt, 't': t, 'tau': tau, 'b': b, 'freq': freq,# 'sin': numpy.sin, 'pi': pi, } code = ''' cdef int _idx cdef int _vectorisation_idx cdef int N = <int>_N cdef double a, v, _v #cdef double [:] _cy_array_neurongroup_a = _array_neurongroup_a #cdef double [:] _cy_array_neurongroup_v = _array_neurongroup_v cdef double* _cy_array_neurongroup_a = &(_array_neurongroup_a[0]) cdef double* _cy_array_neurongroup_v = &(_array_neurongroup_v[0]) for _idx in range(N): _vectorisation_idx = _idx a = _cy_array_neurongroup_a[_idx] v = _cy_array_neurongroup_v[_idx] _v = a*sin(2.0*freq*pi*t) + b + v*exp(-dt/tau) + (-a*sin(2.0*freq*pi*t) - b)*exp(-dt/tau) #_v = a*b+0.0001*sin(v) #_v = a*b+0.0001*v v = _v _cy_array_neurongroup_v[_idx] = v ''' f_mod, f_arg_list = modified_cython_inline(code, locals=ns, globals={}) # return theano.function([a, v], # a*tt.sin(2.0*freq*pi*t) + b + v*tt.exp(-dt/tau) + (-a*tt.sin(2.0*freq*pi*t) - b)*tt.exp(-dt/tau)) theano.config.gcc.cxxflags = '-O3 -ffast-math' theano_func = get_theano_func() #print theano.pp(theano_func.maker.fgraph.outputs[0]) #print #theano.printing.debugprint(theano_func.maker.fgraph.outputs[0]) #theano.printing.pydotprint(theano_func, 'func.png') #exit() if __name__=='__main__': funcs = [#timefunc_cython_inline, timefunc_cython_modified_inline, timefunc_numpy, timefunc_numpy_smart, timefunc_numpy_blocked, timefunc_numexpr, timefunc_numexpr_smart, timefunc_weave_slow, timefunc_weave_fast, timefunc_theano, ] if 1: print 'Values' print '======' for f in funcs: check_values(f) print if 1: print 'Times' print '=====' for f in funcs: dotimeit(f)
[ 6738, 279, 2645, 397, 1330, 1635, 201, 198, 11748, 3075, 400, 261, 201, 198, 11748, 640, 11, 640, 270, 201, 198, 6738, 275, 4484, 17, 13, 8189, 5235, 13, 43282, 13, 948, 400, 261, 62, 17034, 13, 41771, 62, 45145, 1330, 9518, 62, 9...
1.897239
1,304
from .banks import callback_view, go_to_bank_gateway from .samples import sample_payment_view, sample_result_view
[ 6738, 764, 43558, 1330, 23838, 62, 1177, 11, 467, 62, 1462, 62, 17796, 62, 10494, 1014, 198, 6738, 764, 82, 12629, 1330, 6291, 62, 37301, 62, 1177, 11, 6291, 62, 20274, 62, 1177, 198 ]
3.352941
34
#!/usr/bin/env python # encoding: utf-8 """ update.py Created by Thomas Mangin on 2009-09-06. Copyright (c) 2009-2013 Exa Networks. All rights reserved. """ import unittest from exabgp.configuration.environment import environment env = environment.setup('') from exabgp.bgp.message.update.update import * from exabgp.bgp.message.update.attribute.community import to_Community from exabgp.bgp.message.update.attribute.community import Community, Communities # def test_2_ipv4_broken (self): # header = ''.join([chr(c) for c in h]) # message = ''.join([chr(c) for c in m]) # message = ''.join([chr(c) for c in [0x0, 0x0, 0x0, 0xf, 0x40, 0x1, 0x1, 0x0, 0x40, 0x2, 0x4, 0x2, 0x1, 0xfd, 0xe8, 0x0, 0x0, 0x0, 0x0, 0x18, 0xa, 0x0, 0x1]]) # update = new_Update(message) if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 37811, 198, 19119, 13, 9078, 198, 198, 41972, 416, 5658, 27609, 259, 319, 3717, 12, 2931, 12, 3312, 13, 198, 15269, 357, 66, 8, 3717, 12, 6390,...
2.405882
340
# nuScenes dev-kit. # Code written by Holger Caesar & Oscar Beijbom, 2018. # Licensed under the Creative Commons [see licence.txt] import argparse import json import os import random import time from typing import Tuple, Dict, Any import numpy as np from nuscenes import NuScenes from nuscenes.eval.detection.algo import accumulate, calc_ap, calc_tp from nuscenes.eval.detection.config import config_factory from nuscenes.eval.detection.constants import TP_METRICS from nuscenes.eval.detection.data_classes import DetectionConfig, MetricDataList, DetectionMetrics, EvalBoxes from nuscenes.eval.detection.loaders import load_prediction, load_gt, add_center_dist, filter_eval_boxes from nuscenes.eval.detection.render import summary_plot, class_pr_curve, class_tp_curve, dist_pr_curve, visualize_sample if __name__ == "__main__": # Settings. parser = argparse.ArgumentParser(description='Evaluate nuScenes result submission.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('result_path', type=str, help='The submission as a JSON file.') parser.add_argument('--output_dir', type=str, default='~/nuscenes-metrics', help='Folder to store result metrics, graphs and example visualizations.') parser.add_argument('--eval_set', type=str, default='val', help='Which dataset split to evaluate on, train, val or test.') parser.add_argument('--dataroot', type=str, default='/data/sets/nuscenes', help='Default nuScenes data directory.') parser.add_argument('--version', type=str, default='v1.0-trainval', help='Which version of the nuScenes dataset to evaluate on, e.g. v1.0-trainval.') parser.add_argument('--config_name', type=str, default='cvpr_2019', help='Name of the configuration to use for evaluation, e.g. cvpr_2019.') parser.add_argument('--plot_examples', type=int, default=10, help='How many example visualizations to write to disk.') parser.add_argument('--render_curves', type=int, default=1, help='Whether to render PR and TP curves to disk.') parser.add_argument('--verbose', type=int, default=1, help='Whether to print to stdout.') args = parser.parse_args() result_path_ = os.path.expanduser(args.result_path) output_dir_ = os.path.expanduser(args.output_dir) eval_set_ = args.eval_set dataroot_ = args.dataroot version_ = args.version config_name_ = args.config_name plot_examples_ = args.plot_examples render_curves_ = bool(args.render_curves) verbose_ = bool(args.verbose) cfg_ = config_factory(config_name_) nusc_ = NuScenes(version=version_, verbose=verbose_, dataroot=dataroot_) nusc_eval = NuScenesEval(nusc_, config=cfg_, result_path=result_path_, eval_set=eval_set_, output_dir=output_dir_, verbose=verbose_) nusc_eval.main(plot_examples=plot_examples_, render_curves=render_curves_)
[ 2, 14364, 3351, 18719, 1614, 12, 15813, 13, 198, 2, 6127, 3194, 416, 6479, 1362, 24088, 1222, 15694, 1355, 2926, 65, 296, 11, 2864, 13, 198, 2, 49962, 739, 262, 17404, 13815, 685, 3826, 17098, 13, 14116, 60, 198, 198, 11748, 1822, 2...
2.519121
1,229
import unittest from onlinejudge_api.main import main
[ 11748, 555, 715, 395, 198, 198, 6738, 2691, 10456, 469, 62, 15042, 13, 12417, 1330, 1388, 628 ]
3.294118
17
#!/usr/bin/env python3 # This file is part of ODM and distributed under the terms of the # MIT license. See COPYING. import json import sys import odm.cli if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 770, 2393, 318, 636, 286, 440, 23127, 290, 9387, 739, 262, 2846, 286, 262, 198, 2, 17168, 5964, 13, 4091, 27975, 45761, 13, 198, 198, 11748, 33918, 198, 11748, 25064, 198...
2.884058
69
# Copyright (c) 2014 Ahmed H. Ismail # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from unittest import TestCase import spdx from spdx.parsers.tagvalue import Parser from spdx.parsers.lexers.tagvalue import Lexer from spdx.parsers.tagvaluebuilders import Builder from spdx.parsers.loggers import StandardLogger from spdx.version import Version
[ 2, 15069, 357, 66, 8, 1946, 21157, 367, 13, 1148, 4529, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198...
3.645299
234
# Standard library imports from subprocess import call as subprocess_call from utility import fileexists from time import sleep as time_sleep from datetime import datetime mount_try = 1 not_yet = True done = False start_time = datetime.now() if fileexists("/home/rpi4-sftp/usb/drive_present.txt"): when_usba = 0 else: when_usba = -1 if fileexists("/home/duck-sftp/usb/drive_present.txt"): when_usbb = 0 else: when_usbb = -1 if fileexists("/home/pi/mycloud/drive_present.txt"): when_mycloud = 0 else: when_mycloud = -1 while (mount_try < 30) and not_yet: try: usba_mounted = fileexists("/home/rpi4-sftp/usb/drive_present.txt") usbb_mounted = fileexists("/home/duck-sftp/usb/drive_present.txt") mycloud_mounted = fileexists("/home/pi/mycloud/drive_present.txt") if not(usba_mounted and usbb_mounted and mycloud_mounted): print("Something Needs mounting this is try number: ", mount_try) subprocess_call(["sudo", "mount", "-a"]) mount_try += 1 usba_mounted_after = fileexists("/home/rpi4-sftp/usb/drive_present.txt") usbb_mounted_after = fileexists("/home/duck-sftp/usb/drive_present.txt") mycloud_mounted_after = fileexists("/home/pi/mycloud/drive_present.txt") if not(usba_mounted) and usba_mounted_after: when_usba = round((datetime.now() - start_time).total_seconds(),2) if not(usbb_mounted) and usbb_mounted_after: when_usbb = round((datetime.now() - start_time).total_seconds(),2) if not(mycloud_mounted) and mycloud_mounted_after: when_mycloud = round((datetime.now() - start_time).total_seconds(),2) if usba_mounted_after and usbb_mounted_after and mycloud_mounted_after: print("Success at :",when_usba,when_usbb,when_mycloud, " secs from start") not_yet = False done = True except: print("Count: ", count," error") time_sleep(1) if done: print("Great!") else: print("Failed to do all or drive_present.txt file not present; Times :",when_usba,when_usbb,when_mycloud) while True: time_sleep(20000)
[ 2, 8997, 5888, 17944, 201, 198, 6738, 850, 14681, 1330, 869, 355, 850, 14681, 62, 13345, 201, 198, 6738, 10361, 1330, 2393, 1069, 1023, 201, 198, 6738, 640, 1330, 3993, 355, 640, 62, 42832, 201, 198, 6738, 4818, 8079, 1330, 4818, 8079...
2.468293
820
from django.http.response import HttpResponse from django.shortcuts import render from django.shortcuts import redirect, render from cryptography.fernet import Fernet from .models import Book, UserDetails from .models import Contact from .models import Book from .models import Report from .models import Diagnostic from datetime import datetime # Create your views here. # def index(request): # context={ 'alpha': 'This is sent'} # if request.method=='POST': # pass # else: return render(request, 'index.html',context) #HttpResponse('This is homepage') # def appointment(request,email,name): # if request.method == "POST": # problem = request.POST.get('problem') # book = Appoint(problem=problem, email=email, name=name) # book.save() # return render(request,"index.html")
[ 6738, 42625, 14208, 13, 4023, 13, 26209, 1330, 367, 29281, 31077, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 18941, 11, 8543, 198, 6738, 45898, 13, 69, 1142, 316, 1330, 38982, ...
2.971831
284
from __future__ import with_statement import os import sys from mock import Mock from django.template import Template, Context, TemplateSyntaxError from django.test import TestCase from compressor.conf import settings from compressor.signals import post_compress from compressor.tests.base import css_tag, test_dir def render(template_string, context_dict=None): """ A shortcut for testing template output. """ if context_dict is None: context_dict = {} c = Context(context_dict) t = Template(template_string) return t.render(c).strip() def script(content="", src="", scripttype="text/javascript"): """ returns a unicode text html script element. >>> script('#this is a comment', scripttype="text/applescript") '<script type="text/applescript">#this is a comment</script>' """ out_script = u'<script ' if scripttype: out_script += u'type="%s" ' % scripttype if src: out_script += u'src="%s" ' % src return out_script[:-1] + u'>%s</script>' % content
[ 6738, 11593, 37443, 834, 1330, 351, 62, 26090, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 6738, 15290, 1330, 44123, 198, 198, 6738, 42625, 14208, 13, 28243, 1330, 37350, 11, 30532, 11, 37350, 13940, 41641, 12331, 198, 6738, 4262...
2.879121
364
from ...address_translator import AT from ...errors import CLEOperationError from . import Relocation import struct import logging l = logging.getLogger('cle.relocations.generic')
[ 6738, 2644, 21975, 62, 7645, 41880, 1330, 5161, 198, 6738, 2644, 48277, 1330, 30301, 32180, 12331, 198, 6738, 764, 1330, 4718, 5040, 198, 11748, 2878, 198, 198, 11748, 18931, 198, 75, 796, 18931, 13, 1136, 11187, 1362, 10786, 2375, 13, ...
3.934783
46
# Copyright (c) 2010-2014 openpyxl import pytest from openpyxl.styles.borders import Border, Side from openpyxl.styles.fills import GradientFill from openpyxl.styles.colors import Color from openpyxl.writer.styles import StyleWriter from openpyxl.tests.helper import get_xml, compare_xml
[ 2, 15069, 357, 66, 8, 3050, 12, 4967, 1280, 9078, 87, 75, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 1280, 9078, 87, 75, 13, 47720, 13, 65, 6361, 1330, 15443, 11, 12075, 198, 6738, 1280, 9078, 87, 75, 13, 47720, 13, 69, 2171, ...
3.084211
95
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, 15720, 602, 628 ]
2.891892
37
from unittest import TestCase from io import StringIO import json
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 33245, 1330, 10903, 9399, 198, 198, 11748, 33918, 198 ]
3.722222
18
import sys
[ 11748, 25064, 628 ]
4
3
# -*- coding: utf-8 -*- # # Tencent is pleased to support the open source community by making QT4C available. # Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. # QT4C is licensed under the BSD 3-Clause License, except for the third-party components listed below. # A copy of the BSD 3-Clause License is included in this file. # ''' ''' import unittest import os import sys test_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.dirname(test_dir)) if __name__ == '__main__': main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 9368, 1087, 318, 10607, 284, 1104, 262, 1280, 2723, 2055, 416, 1642, 1195, 51, 19, 34, 1695, 13, 220, 220, 198, 2, 15069, 357, 34, 8, 12131, 2320, 43, 3...
2.839378
193
from cffi import FFI ffibuilder = FFI() ffibuilder.cdef(""" int test(int t); """) ffibuilder.set_source("_pi_cffi", """ #include "brute.h" """, sources=['brute.c']) if __name__ == "__main__": ffibuilder.compile(verbose = True)
[ 6738, 269, 487, 72, 1330, 376, 11674, 198, 198, 487, 571, 3547, 263, 796, 376, 11674, 3419, 198, 198, 487, 571, 3547, 263, 13, 66, 4299, 7203, 15931, 198, 600, 1332, 7, 600, 256, 1776, 198, 15931, 4943, 198, 198, 487, 571, 3547, 2...
1.664948
194
"""Board Module""" import copy from typing import Tuple, List from src.coordinate import Coordinate from src.snake import Snake def get_other_snakes(self, exclude_id) -> List[Snake]: """Get the List of Snakes whose IDs don't match the given ID.""" return [snake for snake in self.snakes if snake.id != exclude_id] def advance_snake_along_path(self, snake_id: str, path: List[Coordinate]): """Return a new board with our snake advanced along given path.""" new_board = copy.deepcopy(self) return new_board.__help_advance_snake_along_path(snake_id, path) def __help_advance_snake_along_path(self, snake_id: str, path: List[Coordinate]): """Do the actual advancement of the snake along the path.""" me = next((snake for snake in self.snakes if snake.id == snake_id), None) if not me: raise ValueError("No snake for given id!") me.coordinates += path me.coordinates = me.coordinates[len(path):] me.coordinates.reverse() me.coordinates.append(me.coordinates[-1]) print("new coords:") for coord in me.coordinates: print(coord) return self
[ 37811, 29828, 19937, 37811, 198, 11748, 4866, 198, 6738, 19720, 1330, 309, 29291, 11, 7343, 198, 6738, 12351, 13, 37652, 4559, 1330, 22819, 4559, 198, 6738, 12351, 13, 16184, 539, 1330, 16705, 628, 220, 220, 220, 825, 651, 62, 847, 62, ...
2.556745
467
import os import zipfile from typing import List import pandas as pd import urllib from personalized_nlp.settings import STORAGE_DIR from personalized_nlp.utils.data_splitting import split_texts from personalized_nlp.datasets.datamodule_base import BaseDataModule
[ 11748, 28686, 198, 11748, 19974, 7753, 198, 6738, 19720, 1330, 7343, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2956, 297, 571, 198, 198, 6738, 28949, 62, 21283, 79, 13, 33692, 1330, 46366, 11879, 62, 34720, 198, 6738, 28949...
3.410256
78
# Generated by Django 4.0 on 2022-03-03 02:15 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 604, 13, 15, 319, 33160, 12, 3070, 12, 3070, 7816, 25, 1314, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.966667
30
import os import warnings from django.conf import settings CAPTCHA_FONT_PATH = getattr(settings, 'CAPTCHA_FONT_PATH', os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'fonts/Vera.ttf'))) CAPTCHA_FONT_SIZE = getattr(settings, 'CAPTCHA_FONT_SIZE', 22) CAPTCHA_LETTER_ROTATION = getattr(settings, 'CAPTCHA_LETTER_ROTATION', (-35, 35)) CAPTCHA_BACKGROUND_COLOR = getattr(settings, 'CAPTCHA_BACKGROUND_COLOR', '#ffffff') CAPTCHA_FOREGROUND_COLOR = getattr(settings, 'CAPTCHA_FOREGROUND_COLOR', '#001100') CAPTCHA_CHALLENGE_FUNCT = getattr(settings, 'CAPTCHA_CHALLENGE_FUNCT', 'captcha.helpers.random_char_challenge') CAPTCHA_NOISE_FUNCTIONS = getattr(settings, 'CAPTCHA_NOISE_FUNCTIONS', ('captcha.helpers.noise_arcs', 'captcha.helpers.noise_dots',)) CAPTCHA_FILTER_FUNCTIONS = getattr(settings, 'CAPTCHA_FILTER_FUNCTIONS', ('captcha.helpers.post_smooth',)) CAPTCHA_WORDS_DICTIONARY = getattr(settings, 'CAPTCHA_WORDS_DICTIONARY', '/usr/share/dict/words') CAPTCHA_PUNCTUATION = getattr(settings, 'CAPTCHA_PUNCTUATION', '''_"',.;:-''') CAPTCHA_FLITE_PATH = getattr(settings, 'CAPTCHA_FLITE_PATH', None) CAPTCHA_SOX_PATH = getattr(settings, 'CAPTCHA_SOX_PATH', None) CAPTCHA_TIMEOUT = getattr(settings, 'CAPTCHA_TIMEOUT', 5) # Minutes CAPTCHA_LENGTH = int(getattr(settings, 'CAPTCHA_LENGTH', 4)) # Chars # CAPTCHA_IMAGE_BEFORE_FIELD = getattr(settings, 'CAPTCHA_IMAGE_BEFORE_FIELD', True) CAPTCHA_DICTIONARY_MIN_LENGTH = getattr(settings, 'CAPTCHA_DICTIONARY_MIN_LENGTH', 0) CAPTCHA_DICTIONARY_MAX_LENGTH = getattr(settings, 'CAPTCHA_DICTIONARY_MAX_LENGTH', 99) CAPTCHA_IMAGE_SIZE = getattr(settings, 'CAPTCHA_IMAGE_SIZE', None) CAPTCHA_IMAGE_TEMPLATE = getattr(settings, 'CAPTCHA_IMAGE_TEMPLATE', 'captcha/image.html') CAPTCHA_HIDDEN_FIELD_TEMPLATE = getattr(settings, 'CAPTCHA_HIDDEN_FIELD_TEMPLATE', 'captcha/hidden_field.html') CAPTCHA_TEXT_FIELD_TEMPLATE = getattr(settings, 'CAPTCHA_TEXT_FIELD_TEMPLATE', 'captcha/text_field.html') if getattr(settings, 'CAPTCHA_FIELD_TEMPLATE', None): msg = ("CAPTCHA_FIELD_TEMPLATE setting is deprecated in favor of widget's template_name.") warnings.warn(msg, DeprecationWarning) CAPTCHA_FIELD_TEMPLATE = getattr(settings, 'CAPTCHA_FIELD_TEMPLATE', None) if getattr(settings, 'CAPTCHA_OUTPUT_FORMAT', None): msg = ("CAPTCHA_OUTPUT_FORMAT setting is deprecated in favor of widget's template_name.") warnings.warn(msg, DeprecationWarning) CAPTCHA_OUTPUT_FORMAT = getattr(settings, 'CAPTCHA_OUTPUT_FORMAT', None) CAPTCHA_MATH_CHALLENGE_OPERATOR = getattr(settings, 'CAPTCHA_MATH_CHALLENGE_OPERATOR', '*') CAPTCHA_GET_FROM_POOL = getattr(settings, 'CAPTCHA_GET_FROM_POOL', False) CAPTCHA_GET_FROM_POOL_TIMEOUT = getattr(settings, 'CAPTCHA_GET_FROM_POOL_TIMEOUT', 5) CAPTCHA_TEST_MODE = getattr(settings, 'CAPTCHA_TEST_MODE', False) # Failsafe if CAPTCHA_DICTIONARY_MIN_LENGTH > CAPTCHA_DICTIONARY_MAX_LENGTH: CAPTCHA_DICTIONARY_MIN_LENGTH, CAPTCHA_DICTIONARY_MAX_LENGTH = CAPTCHA_DICTIONARY_MAX_LENGTH, CAPTCHA_DICTIONARY_MIN_LENGTH
[ 11748, 28686, 198, 11748, 14601, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 198, 33177, 51, 49285, 62, 37, 35830, 62, 34219, 796, 651, 35226, 7, 33692, 11, 705, 33177, 51, 49285, 62, 37, 35830, 62, 34219, 3256, 28686, 1...
2.461161
1,223
from __future__ import absolute_import, division, print_function, \ with_statement import logging import os.path import time import tornado.escape import tornado.gen import tornado.ioloop from tornado.test.util import unittest from tornado.testing import AsyncHTTPTestCase, gen_test import tornado.web from pilbox.app import PilboxApplication from pilbox.errors import SignatureError, ClientError, HostError, \ BackgroundError, DimensionsError, FilterError, FormatError, ModeError, \ PositionError, QualityError, UrlError, ImageFormatError, FetchError from pilbox.signature import sign from pilbox.test import image_test try: from urllib import urlencode except ImportError: from urllib.parse import urlencode try: import cv except ImportError: cv = None logger = logging.getLogger("tornado.application")
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 3467, 198, 220, 220, 220, 351, 62, 26090, 198, 198, 11748, 18931, 198, 11748, 28686, 13, 6978, 198, 11748, 640, 198, 198, 11748, 33718, 13, 41915, 198, ...
3.384
250
#!/usr/bin/env python from scipy import * from pylab import * #from pylab import imshow #! #! Some graphical explorations of the Julia sets with python and pyreport #!######################################################################### #$ #$ We start by defining a function J: #$ \[ J_c : z \rightarrow z^2 + c \] #$ [x,y] = ogrid[ -1:1:0.002, -1:1:0.002 ] z = x + y *1j #! If we study the divergence of function J under repeated iteration #! depending on its inital conditions we get a very pretty graph threshTime = zeros_like(z) for i in range(40): z = J(0.285)(z) threshTime += z*conj(z) > 4 figure(0) axes([0,0,1,1]) axis('off') imshow(threshTime) bone() show() #! We can also do that systematicaly for other values of c: axes([0,0,1,1]) axis('off') rcParams.update({'figure.figsize': [10.5,5]}) c_values = (0.285 + 0.013j, 0.45 - 0.1428j, -0.70176 -0.3842j, -0.835-0.2321j, -0.939 +0.167j, -0.986+0.87j) for i,c in enumerate(c_values): threshTime = zeros_like(z) z = x + y *1j for n in range(40): z = J(c)(z) threshTime += z*conj(z) > 4 subplot(2,3,i+1) imshow(threshTime) axis('off') show()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 629, 541, 88, 1330, 1635, 198, 6738, 279, 2645, 397, 1330, 1635, 198, 2, 6738, 279, 2645, 397, 1330, 545, 12860, 198, 2, 0, 198, 2, 0, 2773, 27831, 39180, 602, 286, 262, 2230...
2.303571
504
# Generated by Django 2.2.21 on 2021-06-23 12:43 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 2481, 319, 33448, 12, 3312, 12, 1954, 1105, 25, 3559, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295,...
2.840909
44
import logging from lora_multihop import serial_connection, variables
[ 11748, 18931, 198, 198, 6738, 300, 5799, 62, 16680, 4449, 404, 1330, 11389, 62, 38659, 11, 9633, 628, 628 ]
3.894737
19
#!/usr/bin/env python # Copyright (c) 2013-2014, Rethink Robotics # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the Rethink Robotics nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ copied from Baxter RSDK Joint Position Example: file playback """ from __future__ import print_function import sys import rospy import baxter_interface from baxter_interface import CHECK_VERSION import glob from std_srvs.srv import Empty def clean_line(line, names): """ Cleans a single line of recorded joint positions @param line: the line described in a list to process @param names: joint name keys """ #convert the line of strings to a float or None line = [try_float(x) for x in line.rstrip().split(',')] #zip the values with the joint names combined = zip(names[1:], line[1:]) #take out any tuples that have a none value cleaned = [x for x in combined if x[1] is not None] #convert it to a dictionary with only valid commands command = dict(cleaned) left_command = dict((key, command[key]) for key in command.keys() if key[:-2] == 'left_') right_command = dict((key, command[key]) for key in command.keys() if key[:-2] == 'right_') return (command, left_command, right_command, line) def map_file(filename, loops=1): """ Loops through csv file @param filename: the file to play @param loops: number of times to loop values < 0 mean 'infinite' Does not loop indefinitely, but only until the file is read and processed. Reads each line, split up in columns and formats each line into a controller command in the form of name/value pairs. Names come from the column headers first column is the time stamp """ left = baxter_interface.Limb('left') right = baxter_interface.Limb('right') grip_left = baxter_interface.Gripper('left', CHECK_VERSION) grip_right = baxter_interface.Gripper('right', CHECK_VERSION) rate = rospy.Rate(1000) if grip_left.error(): grip_left.reset() if grip_right.error(): grip_right.reset() if (not grip_left.calibrated() and grip_left.type() != 'custom'): grip_left.calibrate() if (not grip_right.calibrated() and grip_right.type() != 'custom'): grip_right.calibrate() print("Playing back: %s" % (filename,)) with open(filename, 'r') as f: lines = f.readlines() keys = lines[0].rstrip().split(',') l = 0 # If specified, repeat the file playback 'loops' number of times while loops < 1 or l < loops: i = 0 l += 1 print("Moving to start position...") _cmd, lcmd_start, rcmd_start, _raw = clean_line(lines[1], keys) left.move_to_joint_positions(lcmd_start) right.move_to_joint_positions(rcmd_start) start_time = rospy.get_time() for values in lines[1:]: i += 1 loopstr = str(loops) if loops > 0 else "forever" sys.stdout.write("\r Record %d of %d, loop %d of %s" % (i, len(lines) - 1, l, loopstr)) sys.stdout.flush() cmd, lcmd, rcmd, values = clean_line(values, keys) #command this set of commands until the next frame while (rospy.get_time() - start_time) < values[0]: if rospy.is_shutdown(): print("\n Aborting - ROS shutdown") return False if len(lcmd): left.set_joint_positions(lcmd) if len(rcmd): right.set_joint_positions(rcmd) if ('left_gripper' in cmd and grip_left.type() != 'custom'): grip_left.command_position(cmd['left_gripper']) if ('right_gripper' in cmd and grip_right.type() != 'custom'): grip_right.command_position(cmd['right_gripper']) rate.sleep() print return True ### if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 628, 198, 2, 15069, 357, 66, 8, 2211, 12, 4967, 11, 371, 2788, 676, 47061, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2297, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 3...
2.518552
2,183
import abc from typing import Dict, Callable import tensorflow as tf from flink_ml_framework.context import Context from flink_ml_framework.java_file import * from ..runner import tf_helper, io_helper from ..runner.output_writer import DirectOutputWriter try: from flink_ml_tensorflow.tensorflow_context import TFContext except: from flink_ml_tensorflow2.tensorflow_context import TFContext # noinspection PyUnresolvedReferences from tensorflow_io.core.python.ops import core_ops __all__ = ['TF1_TYPE', 'TF2_TYPE'] TF1_TYPE = 'tf1' TF2_TYPE = 'tf2'
[ 11748, 450, 66, 198, 6738, 19720, 1330, 360, 713, 11, 4889, 540, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 781, 676, 62, 4029, 62, 30604, 13, 22866, 1330, 30532, 198, 6738, 781, 676, 62, 4029, 62, 30604, 13, 12355, ...
2.92228
193
import pytest ENCODING = 'utf-8'
[ 11748, 12972, 9288, 198, 198, 24181, 3727, 2751, 796, 705, 40477, 12, 23, 6, 628, 198 ]
2.25
16
import json import os from utilities.SaveLoadJson import SaveLoadJson as SLJ from utilities.LineCount import LineCount as LC import subprocess from geolite2 import geolite2
[ 11748, 33918, 198, 11748, 28686, 198, 6738, 20081, 13, 16928, 8912, 41, 1559, 1330, 12793, 8912, 41, 1559, 355, 12419, 41, 198, 6738, 20081, 13, 13949, 12332, 1330, 6910, 12332, 355, 22228, 198, 198, 11748, 850, 14681, 198, 198, 6738, 4...
3.5
50
from nemo.collections.nlp.losses.sgd_loss import SGDDialogueStateLoss
[ 6738, 36945, 78, 13, 4033, 26448, 13, 21283, 79, 13, 22462, 274, 13, 82, 21287, 62, 22462, 1330, 26147, 16458, 498, 5119, 9012, 43, 793, 198 ]
2.692308
26
# -*- coding: utf-8 -*- from .settings import * DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['LOCAL_DB_NAME'], 'USER': os.environ['LOCAL_DB_USER'], 'PASSWORD': os.environ['LOCAL_DB_PASSWORD'], 'HOST': '127.0.0.1', 'PORT': '5432', } }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 764, 33692, 1330, 1635, 198, 198, 30531, 796, 6407, 198, 198, 51, 3620, 6489, 6158, 62, 30531, 796, 16959, 198, 198, 35, 1404, 6242, 1921, 1546, 796, 1391, ...
1.900498
201
print('Controle de terrenos') print('-' * 20) l = float(input('qual a largura do terreno: ')) c = float(input('qual o comprimento do terreno: ')) area(l , c)
[ 198, 4798, 10786, 4264, 18090, 390, 1059, 918, 418, 11537, 198, 4798, 10786, 19355, 1635, 1160, 8, 198, 75, 796, 12178, 7, 15414, 10786, 13255, 257, 2552, 5330, 466, 1059, 918, 78, 25, 705, 4008, 198, 66, 796, 12178, 7, 15414, 10786, ...
2.590164
61
import datetime ano = (datetime.datetime.now()).year nasc = int(input("Digite o seu ano de nascimento: ")) categoria = 0 if (ano - nasc) <= 9: categoria = str("MIRIM") elif 9 < (ano - nasc) <= 14: categoria = str("INFANTIL") elif 14 < (ano - nasc) <= 19 : categoria = str("JUNIOR") elif 19 < (ano - nasc) <= 25: categoria = str("SNIOR") else: categoria = str("MASTER") print(f"A categoria do atleta {str(categoria)}.")
[ 11748, 4818, 8079, 198, 5733, 796, 357, 19608, 8079, 13, 19608, 8079, 13, 2197, 3419, 737, 1941, 198, 77, 3372, 796, 493, 7, 15414, 7203, 19511, 578, 267, 384, 84, 281, 78, 390, 299, 3372, 3681, 78, 25, 366, 4008, 198, 66, 2397, 7...
2.345745
188
import torch def ndcg_binary_at_k_batch_torch(X_pred, heldout_batch, k=100, device='cpu'): """ Normalized Discounted Cumulative Gain@k for for predictions [B, I] and ground-truth [B, I], with binary relevance. ASSUMPTIONS: all the 0's in heldout_batch indicate 0 relevance. """ batch_users = X_pred.shape[0] # batch_size _, idx_topk = torch.topk(X_pred, k, dim=1, sorted=True) tp = 1. / torch.log2(torch.arange(2, k + 2, device=device).float()) heldout_batch_nonzero = (heldout_batch > 0).float() DCG = (heldout_batch_nonzero[torch.arange(batch_users, device=device).unsqueeze(1), idx_topk] * tp).sum(dim=1) heldout_nonzero = (heldout_batch > 0).sum(dim=1) # num. of non-zero items per batch. [B] IDCG = torch.tensor([(tp[:min(n, k)]).sum() for n in heldout_nonzero]).to(device) return DCG / IDCG def recall_at_k_batch_torch(X_pred, heldout_batch, k=100): """ Recall@k for predictions [B, I] and ground-truth [B, I]. """ batch_users = X_pred.shape[0] _, topk_indices = torch.topk(X_pred, k, dim=1, sorted=False) # [B, K] X_pred_binary = torch.zeros_like(X_pred) if torch.cuda.is_available(): X_pred_binary = X_pred_binary.cuda() X_pred_binary[torch.arange(batch_users).unsqueeze(1), topk_indices] = 1 X_true_binary = (heldout_batch > 0).float() # .toarray() # [B, I] k_tensor = torch.tensor([k], dtype=torch.float32) if torch.cuda.is_available(): X_true_binary = X_true_binary.cuda() k_tensor = k_tensor.cuda() tmp = (X_true_binary * X_pred_binary).sum(dim=1).float() recall = tmp / torch.min(k_tensor, X_true_binary.sum(dim=1).float()) return recall
[ 11748, 28034, 628, 198, 4299, 299, 17896, 70, 62, 39491, 62, 265, 62, 74, 62, 43501, 62, 13165, 354, 7, 55, 62, 28764, 11, 2714, 448, 62, 43501, 11, 479, 28, 3064, 11, 3335, 11639, 36166, 6, 2599, 198, 220, 220, 220, 37227, 198, ...
2.285521
739
# All credit to https://stackoverflow.com/questions/46571448/tkinter-and-a-html-file - thanks DELICA - https://stackoverflow.com/users/7027346/delica from cefpython3 import cefpython as cef import ctypes try: import tkinter as tk from tkinter import messagebox except ImportError: import Tkinter as tk import sys import platform import logging as _logging # Fix for PyCharm hints warnings WindowUtils = cef.WindowUtils() # Platforms WINDOWS = (platform.system() == "Windows") LINUX = (platform.system() == "Linux") MAC = (platform.system() == "Darwin") # Globals logger = _logging.getLogger("tkinter_.py") url = "localhost:8050/" # if __name__ == '__main__': logger.setLevel(_logging.INFO) stream_handler = _logging.StreamHandler() formatter = _logging.Formatter("[%(filename)s] %(message)s") stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) logger.info("CEF Python {ver}".format(ver=cef.__version__)) logger.info("Python {ver} {arch}".format( ver=platform.python_version(), arch=platform.architecture()[0])) logger.info("Tk {ver}".format(ver=tk.Tcl().eval('info patchlevel'))) assert cef.__version__ >= "55.3", "CEF Python v55.3+ required to run this" sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error root = tk.Tk() app = MainFrame(root) root.protocol("WM_DELETE_WINDOW", on_closing) # Tk must be initialized before CEF otherwise fatal error (Issue #306) cef.Initialize() root.mainloop() # app.mainloop() cef.Shutdown()
[ 2, 1439, 3884, 284, 3740, 1378, 25558, 2502, 11125, 13, 785, 14, 6138, 507, 14, 19, 37680, 1415, 2780, 14, 30488, 3849, 12, 392, 12, 64, 12, 6494, 12, 7753, 532, 5176, 28163, 25241, 532, 3740, 1378, 25558, 2502, 11125, 13, 785, 14, ...
2.784787
539
import re from glob import glob import os.path as osp infiles = glob(osp.join(osp.dirname(__file__),"*.xml.in")) for fname in infiles: with open(fname,"r") as fh: in_lines = fh.readlines() out_lines = do_substitution(in_lines) outfname = fname[:-3] with open(outfname,"w") as fh: fh.writelines(out_lines)
[ 11748, 302, 628, 628, 198, 198, 6738, 15095, 1330, 15095, 198, 11748, 28686, 13, 6978, 355, 267, 2777, 198, 10745, 2915, 796, 15095, 7, 2117, 13, 22179, 7, 2117, 13, 15908, 3672, 7, 834, 7753, 834, 27267, 24620, 19875, 13, 259, 48774,...
2.217949
156
# Generated by Django 3.2.12 on 2022-03-28 11:57 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 1065, 319, 33160, 12, 3070, 12, 2078, 1367, 25, 3553, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.8
30
#!/usr/bin/env python3 # encoding: utf-8 import sys import urllib.parse import selenium.webdriver driver = selenium.webdriver.Firefox() # for some reason, detectportal.firefox.com and connectivitycheck.gstatic.com are not blocked # therefore, they cannot be used to detect connectivity # we instead visit another site that is known not to ever have TLS driver.get('http://neverssl.com') if 'neverssl.com' in urllib.parse.urlparse(driver.current_url).netloc: exit() driver.find_element_by_css_selector('label[for="promo_button"]').click() driver.find_element_by_css_selector('input[alt="Next"]').click() driver.find_element_by_css_selector('#PromotionCode').send_keys('lobby18') driver.find_element_by_css_selector('input[alt="Connect"]').click() exit()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 11748, 25064, 198, 11748, 2956, 297, 571, 13, 29572, 198, 198, 11748, 384, 11925, 1505, 13, 12384, 26230, 198, 198, 26230, 796, 384, 119...
3.01992
251
#!/usr/bin/env python import os from collections import OrderedDict import cPickle as pickle import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib.cm import get_cmap from matplotlib import style from scipy import stats from scipy import integrate if __name__ == "__main__": FILEPATH = "~/Savanna/Data/HowardSprings_IAV/pickled/agg/mean_monthly_leaf.pkl" PKLPATH = os.path.expanduser(FILEPATH) main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 11748, 269, 31686, 293, 355, 2298, 293, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, ...
2.837209
172
#!/usr/local/bin/python2.7 from flask import Flask import sys from flask_frozen import Freezer from upload_s3 import set_metadata from config import AWS_DIRECTORY app = Flask(__name__) app.config.from_object('config') from views import * # Serving from s3 leads to some complications in how static files are served if len(sys.argv) > 1: if sys.argv[1] == 'build': PROJECT_ROOT = '/' + AWS_DIRECTORY elif sys.argv[1] == 'test': PROJECT_ROOT = '/www.vpr.net/' + AWS_DIRECTORY else: PROJECT_ROOT = '/' app.wsgi_app = WebFactionMiddleware(app.wsgi_app) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'build': app.debug = True freezer = Freezer(app) freezer.freeze() set_metadata() else: app.run(debug=True)
[ 2, 48443, 14629, 14, 12001, 14, 8800, 14, 29412, 17, 13, 22, 198, 198, 6738, 42903, 1330, 46947, 198, 11748, 25064, 198, 6738, 42903, 62, 69, 42005, 1330, 3232, 9107, 198, 6738, 9516, 62, 82, 18, 1330, 900, 62, 38993, 198, 6738, 456...
2.370588
340
#!/usr/bin/python from setup import * payload = open(sys.argv[1], "rb").read() dtb = open(sys.argv[2], "rb").read() if len(sys.argv) > 3: initramfs = open(sys.argv[3], "rb").read() initramfs_size = len(initramfs) else: initramfs = None initramfs_size = 0 compressed_size = len(payload) compressed_addr = u.malloc(compressed_size) dtb_addr = u.malloc(len(dtb)) print("Loading %d bytes to 0x%x..0x%x..." % (compressed_size, compressed_addr, compressed_addr + compressed_size)) iface.writemem(compressed_addr, payload, True) print("Loading DTB to 0x%x..." % dtb_addr) iface.writemem(dtb_addr, dtb) kernel_size = 32 * 1024 * 1024 kernel_base = u.memalign(2 * 1024 * 1024, kernel_size) print("Kernel_base: 0x%x" % kernel_base) assert not (kernel_base & 0xffff) if initramfs is not None: initramfs_base = u.memalign(65536, initramfs_size) print("Loading %d initramfs bytes to 0x%x..." % (initramfs_size, initramfs_base)) iface.writemem(initramfs_base, initramfs, True) p.kboot_set_initrd(initramfs_base, initramfs_size) if p.kboot_prepare_dt(dtb_addr): print("DT prepare failed") sys.exit(1) #kernel_size = p.xzdec(compressed_addr, compressed_size) #if kernel_size < 0: #raise Exception("Decompression header check error!",) #print("Uncompressed kernel size: %d bytes" % kernel_size) print("Uncompressing...") iface.dev.timeout = 40 kernel_size = p.gzdec(compressed_addr, compressed_size, kernel_base, kernel_size) print(kernel_size) if kernel_size < 0: raise Exception("Decompression error!") print("Decompress OK...") p.dc_cvau(kernel_base, kernel_size) p.ic_ivau(kernel_base, kernel_size) print("Ready to boot") daif = u.mrs(DAIF) daif |= 0x3c0 u.msr(DAIF, daif) print("DAIF: %x" % daif) p.kboot_boot(kernel_base) iface.ttymode()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 6738, 9058, 1330, 1635, 198, 198, 15577, 2220, 796, 1280, 7, 17597, 13, 853, 85, 58, 16, 4357, 366, 26145, 11074, 961, 3419, 198, 28664, 65, 796, 1280, 7, 17597, 13, 853, 85, 58, 17,...
2.424528
742
import json import os import multiprocessing import struct import importlib from socketserver import TCPServer, StreamRequestHandler
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 18540, 305, 919, 278, 198, 11748, 2878, 198, 11748, 1330, 8019, 198, 6738, 37037, 18497, 1330, 17283, 3705, 18497, 11, 13860, 18453, 25060, 628, 628 ]
4.25
32
from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from . import helpers # Create your views here.
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 17594, 62, 35827, 198, 6738, 42625, 14208, 13, 4023, 1330, 449, 1559, 31077, 198, 6738, 42625, 14208, 13, 3...
3.426471
68
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ .. module: security_monkey.watchers.vpc.vpn :platform: Unix .. version:: $$VERSION$$ .. moduleauthor:: Alex Cline <alex.cline@gmail.com> @alex.cline """ from cloudaux.aws.ec2 import describe_vpn_connections from security_monkey.cloudaux_watcher import CloudAuxWatcher from security_monkey.watcher import ChangeItem DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
[ 2, 220, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 220, 220, 220, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 220, 220, 220, ...
3.009524
315
from itertools import count import numpy as np
[ 6738, 340, 861, 10141, 1330, 954, 198, 11748, 299, 32152, 355, 45941, 628 ]
3.692308
13
from flask_wtf import FlaskForm from wtforms import StringField,TextAreaField,SubmitField from wtforms.validators import Required
[ 6738, 42903, 62, 86, 27110, 1330, 46947, 8479, 198, 6738, 266, 83, 23914, 1330, 10903, 15878, 11, 8206, 30547, 15878, 11, 45135, 15878, 198, 6738, 266, 83, 23914, 13, 12102, 2024, 1330, 20906, 198 ]
3.823529
34
import re import astrodata from astrodata import (astro_data_tag, TagSet, astro_data_descriptor, returns_list) from astrodata.fits import FitsLoader, FitsProvider from ..soar import AstroDataSOAR
[ 11748, 302, 198, 11748, 6468, 305, 7890, 198, 198, 6738, 6468, 305, 7890, 1330, 357, 459, 305, 62, 7890, 62, 12985, 11, 17467, 7248, 11, 6468, 305, 62, 7890, 62, 20147, 1968, 273, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 2...
2.528736
87
# -*- coding: utf-8 -*- #
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 198 ]
1.588235
17
import os, sys import numpy as np import cv2 import random import torch from configs import Config from kernelGAN import KernelGAN from data import DataGenerator from learner import Learner import tqdm DATA_LOC = "/mnt/data/NTIRE2020/realSR/track2" # "/mnt/data/NTIRE2020/realSR/track1" DATA_X = "DPEDiphone-tr-x" # "Corrupted-tr-x" DATA_Y = "DPEDiphone-tr-y" # "Corrupted-tr-y" DATA_VAL = "DPEDiphone-va" # "Corrupted-va-x" if __name__ == "__main__": seed_num = 0 torch.manual_seed(seed_num) torch.cuda.manual_seed(seed_num) torch.cuda.manual_seed_all(seed_num) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False np.random.seed(seed_num) random.seed(seed_num) # exit(0) data = {"X":[os.path.join(DATA_LOC, DATA_X, f) for f in os.listdir(os.path.join(DATA_LOC, DATA_X)) if f[-4:] == ".png"], "Y":[os.path.join(DATA_LOC, DATA_Y, f) for f in os.listdir(os.path.join(DATA_LOC, DATA_Y)) if f[-4:] == ".png"], "val":[os.path.join(DATA_LOC, DATA_VAL, f) for f in os.listdir(os.path.join(DATA_LOC, DATA_VAL)) if f[-4:] == ".png"]} Kernels = [] Noises = [] for f in data["X"]: estimate_kernel(f) print("fin.")
[ 11748, 28686, 11, 25064, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 4738, 198, 11748, 28034, 198, 198, 6738, 4566, 82, 1330, 17056, 198, 6738, 9720, 45028, 1330, 32169, 45028, 198, 6738, 1366, 1330, 60...
2.257353
544
from unittest import TestCase from pyRdfa import pyRdfa
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 12972, 49, 7568, 64, 1330, 12972, 49, 7568, 64, 628 ]
2.9
20
from setuptools import setup, find_packages from os.path import join, dirname setup( name='pyoai', version='2.4.6.b', author='Infrae', author_email='rob.cermak@gmail.com', url='https://github.com/jr3cermak/robs-kitchensink/tree/master/python/pyoai', classifiers=["Development Status :: 4 - Beta", "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Topic :: Software Development :: Libraries :: Python Modules", "Environment :: Web Environment"], description="""\ The oaipmh module is a Python implementation of an "Open Archives Initiative Protocol for Metadata Harvesting" (version 2) client and server. The protocol is described here: http://www.openarchives.org/OAI/openarchivesprotocol.html """, long_description=(open(join(dirname(__file__), 'README.rst')).read()+ '\n\n'+ open(join(dirname(__file__), 'HISTORY.txt')).read()), packages=find_packages('src'), package_dir = {'': 'src'}, zip_safe=False, license='BSD', keywords='OAI-PMH xml archive', install_requires=['lxml'], )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 6738, 28686, 13, 6978, 1330, 4654, 11, 26672, 3672, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 79, 8226, 1872, 3256, 198, 220, 220, 220, 2196, 11639, 17, 13, 1...
2.527473
455
import torch from torch import nn import math #0 left hip #1 left knee #2 left foot #3 right hip #4 right knee #5 right foot #6 middle hip #7 neck #8 nose #9 head #10 left shoulder #11 left elbow #12 left wrist #13 right shoulder #14 right elbow #15 right wrist ''' def temporal_loss(J, K, J_R, K_R): # J is J3d at time t and K is J3d at time t+k. J_R means the reversed rotation of J return torch.norm(J - K - J_R + K_R, dim=1)**2 ''' ''' def random_rotation(J3d): # J = torch.transpose(J3d, 1, 2) J = J3d root = torch.zeros(J.shape[0:2]) for i in range(J.shape[0]): theta = torch.rand(1).cuda() * 2*torch.tensor(math.pi).cuda() # random theta root[i] = J[i,:,8] # joint 8 = nose is root temp = rotation(J[i,:,:], theta, root[i].unsqueeze(1), False) # print(temp.shape) J[i,:,:] = temp return J, theta, root # need these values in the code def rotation(J, theta, root, is_reversed): # rotation over y axis by theta D = root[2] # absolute depth of the root joint v_t = torch.tensor([[0], [0], [D]]).cuda() # translation vector if is_reversed: root, v_t = v_t, root # swap theta = -theta # R = torch.tensor([[torch.cos(theta), -torch.sin(theta), 0], [torch.sin(theta), torch.cos(theta), 0], [0, 0, 1]]) # rotation matrix over z by theta degrees R = torch.tensor([[torch.cos(theta), 0, torch.sin(theta)], [0, 1, 0], [-torch.sin(theta), 0, torch.cos(theta)]]).cuda() # rotation matrix over y by theta degrees # R = torch.tensor([[1, 0, 0], [0, torch.cos(theta), -torch.sin(theta)], [0, torch.sin(theta), torch.cos(theta)]]) # rotation matrix over x by theta degrees J_R = torch.matmul(R, J.cuda() - root.cuda()) + v_t # rotation return J_R def reverse_rotation(J3d_R, theta, root): # J = torch.transpose(J3d_R, 1, 2) J = J3d_R for i in range(J.shape[0]): J[i,:,:] = rotation(J[i,:,:].cuda(), theta.cuda(), root[i].unsqueeze(1).cuda(), True) return J '''
[ 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 198, 11748, 10688, 198, 198, 2, 15, 1364, 10359, 198, 2, 16, 1364, 10329, 198, 2, 17, 1364, 2366, 198, 2, 18, 826, 10359, 198, 2, 19, 826, 10329, 198, 2, 20, 826, 2366, 198, 2, 21, ...
2.337379
824
from des109 import moeda preco = float(input('Digite o preo pretendido: ')) print(f'''A metade do preo {(moeda.metade(preco))} O dobro do preo {(moeda.dobra(preco))} Aumentando o preo 10% temos {(moeda.aumentar(preco, 10))} Diminuindo o preo 13% temos {(moeda.aumentar(preco, 13))}''')
[ 6738, 748, 14454, 1330, 6941, 18082, 198, 198, 3866, 1073, 796, 12178, 7, 15414, 10786, 19511, 578, 267, 662, 78, 16614, 17305, 25, 705, 4008, 198, 4798, 7, 69, 7061, 6, 32, 1138, 671, 466, 662, 78, 220, 1391, 7, 5908, 18082, 13, ...
2.201493
134
#!/usr/bin/env python2 import xmlrpclib db = 'odoo9' user = 'admin' password = 'admin' uid = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/2/common')\ .authenticate(db, user, password, {}) odoo = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/2/object') installed_modules = odoo.execute_kw( db, uid, password, 'ir.module.module', 'search_read', [[('state', '=', 'installed')], ['name']], {}) for module in installed_modules: print module['name']
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 11748, 35555, 81, 79, 565, 571, 198, 198, 9945, 796, 705, 375, 2238, 24, 6, 198, 7220, 796, 705, 28482, 6, 198, 28712, 796, 705, 28482, 6, 198, 27112, 796, 35555, 81, 79, 565, ...
2.590164
183
from abc import * import numpy as np ########################################################### ########################################################### ###########################################################
[ 6738, 450, 66, 1330, 1635, 198, 11748, 299, 32152, 355, 45941, 628, 198, 29113, 14468, 7804, 21017, 628, 198, 29113, 14468, 7804, 21017, 628, 198, 29113, 14468, 7804, 21017, 198 ]
7.433333
30
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 628 ]
3.75
8
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._enums import * __all__ = ['PartnerRegistrationArgs', 'PartnerRegistration'] def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, authorized_azure_subscription_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, customer_service_uri: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, logo_uri: Optional[pulumi.Input[str]] = None, long_description: Optional[pulumi.Input[str]] = None, partner_customer_service_extension: Optional[pulumi.Input[str]] = None, partner_customer_service_number: Optional[pulumi.Input[str]] = None, partner_name: Optional[pulumi.Input[str]] = None, partner_registration_name: Optional[pulumi.Input[str]] = None, partner_resource_type_description: Optional[pulumi.Input[str]] = None, partner_resource_type_display_name: Optional[pulumi.Input[str]] = None, partner_resource_type_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, setup_uri: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, visibility_state: Optional[pulumi.Input[Union[str, 'PartnerRegistrationVisibilityState']]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = PartnerRegistrationArgs.__new__(PartnerRegistrationArgs) __props__.__dict__["authorized_azure_subscription_ids"] = authorized_azure_subscription_ids __props__.__dict__["customer_service_uri"] = customer_service_uri __props__.__dict__["location"] = location __props__.__dict__["logo_uri"] = logo_uri __props__.__dict__["long_description"] = long_description __props__.__dict__["partner_customer_service_extension"] = partner_customer_service_extension __props__.__dict__["partner_customer_service_number"] = partner_customer_service_number __props__.__dict__["partner_name"] = partner_name __props__.__dict__["partner_registration_name"] = partner_registration_name __props__.__dict__["partner_resource_type_description"] = partner_resource_type_description __props__.__dict__["partner_resource_type_display_name"] = partner_resource_type_display_name __props__.__dict__["partner_resource_type_name"] = partner_resource_type_name if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["setup_uri"] = setup_uri __props__.__dict__["tags"] = tags __props__.__dict__["visibility_state"] = visibility_state __props__.__dict__["name"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["system_data"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:eventgrid:PartnerRegistration"), pulumi.Alias(type_="azure-native:eventgrid/v20200401preview:PartnerRegistration"), pulumi.Alias(type_="azure-nextgen:eventgrid/v20200401preview:PartnerRegistration"), pulumi.Alias(type_="azure-native:eventgrid/v20201015preview:PartnerRegistration"), pulumi.Alias(type_="azure-nextgen:eventgrid/v20201015preview:PartnerRegistration")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(PartnerRegistration, __self__).__init__( 'azure-native:eventgrid:PartnerRegistration', resource_name, __props__, opts)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
2.355283
2,035
import os import glob import cv2 import numpy as np import torch from torchvision.transforms import transforms from natsort import natsorted from models import resmasking_dropout1 from utils.datasets.fer2013dataset import EMOTION_DICT from barez import show transform = transforms.Compose( [ transforms.ToPILImage(), transforms.ToTensor(), ] ) model = resmasking_dropout1(3, 7) # state = torch.load('./saved/checkpoints/resmasking_dropout1_rot30_2019Nov17_14.33') state = torch.load("./saved/checkpoints/Z_resmasking_dropout1_rot30_2019Nov30_13.32") model.load_state_dict(state["net"]) model.cuda() model.eval() for image_path in natsorted( glob.glob("/home/z/research/bkemo/images/**/*.png", recursive=True) ): image_name = os.path.basename(image_path) print(image_name) # image_path = '/home/z/research/bkemo/images/disgust/0.0_dc10a3_1976_0.png' image = cv2.imread(image_path) image = cv2.resize(image, (224, 224)) tensor = transform(image) tensor = torch.unsqueeze(tensor, 0) tensor = tensor.cuda() # output = model(tensor) x = model.conv1(tensor) # 112 x = model.bn1(x) x = model.relu(x) x = model.maxpool(x) # 56 x = model.layer1(x) # 56 m = model.mask1(x) x = x * (1 + m) x = model.layer2(x) # 28 m = model.mask2(x) x = x * (1 + m) x = model.layer3(x) # 14 heat_1 = activations_mask(x) m = model.mask3(x) x = x * (1 + m) # heat_2 = activations_mask(m) x = model.layer4(x) # 7 m = model.mask4(x) x = x * (1 + m) x = model.avgpool(x) x = torch.flatten(x, 1) output = model.fc(x) # print(np.sum(heat_1 - heat_2)) # show(np.concatenate((image, heat_1, heat_2), axis=1)) cv2.imwrite( "./masking_provements/{}".format(image_name), np.concatenate((image, heat_1), axis=1), ) # np.concatenate((image, heat_1, heat_2), axis=1)) # output = output.cpu().numpy() # print(EMOTION_DICT[torch.argmax(output, 1).item()])
[ 11748, 28686, 198, 11748, 15095, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 10178, 13, 7645, 23914, 1330, 31408, 198, 6738, 299, 1381, 419, 1330, 299, 1381, 9741, 198, 6738, 4981, 1...
2.192641
924
import time import colorama while True: consulta = gerenciador_de_pagamento() consulta = str(input('Quer consultar novamente? ')) if consulta in ['sim', 'Sim', 'SIM']: pass elif consulta in ['no', 'nao','No', 'Nao', 'NAO','NO']: break else: break
[ 11748, 640, 198, 11748, 3124, 1689, 198, 4514, 6407, 25, 198, 220, 220, 220, 5725, 64, 796, 308, 14226, 979, 7079, 62, 2934, 62, 79, 363, 3263, 78, 3419, 198, 220, 220, 220, 5725, 64, 796, 965, 7, 15414, 10786, 4507, 263, 5725, 28...
2.203008
133
""" Created on 2 Apr 2017 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) """ from collections import OrderedDict from scs_core.data.json import JSONable # --------------------------------------------------------------------------------------------------------------------
[ 37811, 198, 41972, 319, 362, 2758, 2177, 198, 198, 31, 9800, 25, 31045, 3944, 2364, 357, 1671, 36909, 13, 6667, 2364, 31, 35782, 1073, 5773, 4234, 13, 785, 8, 198, 37811, 198, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, ...
4.737705
61
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs __all__ = [ 'GetNamespaceResult', 'AwaitableGetNamespaceResult', 'get_namespace', ] warnings.warn("""The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-native:notificationhubs:getNamespace'.""", DeprecationWarning) def get_namespace(namespace_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetNamespaceResult: """ Description of a Namespace resource. Latest API Version: 2017-04-01. :param str namespace_name: The namespace name. :param str resource_group_name: The name of the resource group. """ pulumi.log.warn("""get_namespace is deprecated: The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-native:notificationhubs:getNamespace'.""") __args__ = dict() __args__['namespaceName'] = namespace_name __args__['resourceGroupName'] = resource_group_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:notificationhubs/latest:getNamespace', __args__, opts=opts, typ=GetNamespaceResult).value return AwaitableGetNamespaceResult( created_at=__ret__.created_at, critical=__ret__.critical, data_center=__ret__.data_center, enabled=__ret__.enabled, id=__ret__.id, location=__ret__.location, metric_id=__ret__.metric_id, name=__ret__.name, namespace_type=__ret__.namespace_type, provisioning_state=__ret__.provisioning_state, region=__ret__.region, scale_unit=__ret__.scale_unit, service_bus_endpoint=__ret__.service_bus_endpoint, sku=__ret__.sku, status=__ret__.status, subscription_id=__ret__.subscription_id, tags=__ret__.tags, type=__ret__.type, updated_at=__ret__.updated_at)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
2.577465
923
import json from pygments import highlight from pygments.lexers import JsonLexer from pygments.formatters import TerminalFormatter
[ 11748, 33918, 198, 6738, 12972, 11726, 1330, 7238, 198, 6738, 12972, 11726, 13, 2588, 364, 1330, 449, 1559, 45117, 263, 198, 6738, 12972, 11726, 13, 18982, 1010, 1330, 24523, 8479, 1436, 628, 198 ]
4.030303
33
#!/usr/bin/env python3 import os from opendbc.can.parser import CANParser from cereal import car from selfdrive.car.interfaces import RadarInterfaceBase RADAR_MSGS_C = list(range(0x2c2, 0x2d4+2, 2)) # c_ messages 706,...,724 RADAR_MSGS_D = list(range(0x2a2, 0x2b4+2, 2)) # d_ messages LAST_MSG = max(RADAR_MSGS_C + RADAR_MSGS_D) NUMBER_MSGS = len(RADAR_MSGS_C) + len(RADAR_MSGS_D)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 28686, 198, 6738, 1034, 437, 15630, 13, 5171, 13, 48610, 1330, 15628, 46677, 198, 6738, 33158, 1330, 1097, 198, 6738, 2116, 19472, 13, 7718, 13, 3849, 32186, 1330, 38426, 3931...
2.181818
176
""" wrapper for ccmake command line tool """ import subprocess name = 'ccmake' platforms = ['linux', 'osx'] optional = True not_found = "required for 'fips config' functionality" #------------------------------------------------------------------------------- def check_exists(fips_dir) : """test if ccmake is in the path :returns: True if ccmake is in the path """ try: out = subprocess.check_output(['ccmake', '--version']) return True except (OSError, subprocess.CalledProcessError): return False #------------------------------------------------------------------------------- def run(build_dir) : """run ccmake to configure cmake project :param build_dir: directory where ccmake should run :returns: True if ccmake returns successful """ res = subprocess.call('ccmake .', cwd=build_dir, shell=True) return res == 0
[ 37811, 198, 48553, 329, 269, 11215, 539, 3141, 1627, 2891, 198, 37811, 198, 11748, 850, 14681, 198, 198, 3672, 796, 705, 535, 15883, 6, 198, 24254, 82, 796, 37250, 23289, 3256, 705, 418, 87, 20520, 198, 25968, 796, 6407, 198, 1662, 62...
3.088136
295
import os import numpy as np import tensorflow as tf from image_quality.utils import utils
[ 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 2939, 62, 13237, 13, 26791, 1330, 3384, 4487, 628, 198 ]
3.357143
28
from Test import Test, Test as test ''' Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out. Example: Given an input string of: apples, pears # and bananas grapes bananas !apples The output expected would be: apples, pears grapes bananas The code would be called like so: result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) # result should == "apples, pears\ngrapes\nbananas" ''' # Split by rows, then find earliest marker and extract string before it # Top solution, split list by \n, edit in place # Top solution expanded Test.assert_equals(solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]), "apples, pears\ngrapes\nbananas") Test.assert_equals(solution("a #b\nc\nd $e f g", ["#", "$"]), "a\nc\nd") Test.assert_equals(solution('= - avocados oranges pears cherries\nlemons apples\n- watermelons strawberries', ['#', '?', '=', ',', '.', '-', '!']), '\nlemons apples\n')
[ 6738, 6208, 1330, 6208, 11, 6208, 355, 1332, 198, 198, 7061, 6, 198, 20988, 262, 4610, 523, 326, 340, 22670, 477, 2420, 326, 5679, 597, 286, 257, 900, 286, 2912, 19736, 3804, 287, 13, 4377, 13216, 10223, 379, 262, 886, 286, 262, 162...
2.980337
356
# -*- coding: utf-8 -*- """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from qiskit.quantum_info.operators.channel import Choi, PTM, Kraus, Chi, SuperOp import numpy as np from qat.comm.quops.ttypes import QuantumChannel, RepresentationType from qat.comm.datamodel.ttypes import Matrix, ComplexNumber def array_to_matrix(array): """ Transform a two dimmentional numpy array to a myqlm Matrix. Args: array: (ndarray) a two dimmentional numpy array Returns: (Matrix): a myqlm Matrix """ assert len(array.shape) == 2, "The array must be two dimmentional" data = [] for arr in array: for elem in arr: data.append(ComplexNumber(np.real(elem), np.imag(elem))) matri = Matrix(array.shape[0], array.shape[1], data) return matri def qiskit_to_qchannel(representation): """ Create a myqlm representation of quantum channel from a qiskit representation of a quantum channel. Args: representation: (Kraus|Choi|Chi|SuperOp|PTM) qiskit representation of a quantum channel. Returns: (QuantumChannel): myqlm representation of a quantum channel. """ qchannel = None qiskit_data = representation.data # Find what representation it is. # Then create the corresponding matrix (kraus_ops|basis|matrix)from the data # of the representation. # Finally, create the QuantumChannel with the RepresentationType, the arity # (got from the qiskit representation) and the matrix. if isinstance(representation, Kraus): kraus_ops = [] for arr in qiskit_data: kraus_ops.append(array_to_matrix(arr)) qchannel = QuantumChannel( representation=RepresentationType.KRAUS, arity=representation.num_qubits, kraus_ops=kraus_ops) elif isinstance(representation, Chi): basis = [] basis.append(array_to_matrix(qiskit_data)) qchannel = QuantumChannel( representation=RepresentationType.CHI, arity=representation.num_qubits, basis=basis) elif isinstance(representation, SuperOp): basis = [] basis.append(array_to_matrix(qiskit_data)) qchannel = QuantumChannel( representation=RepresentationType.SUPEROP, arity=representation.num_qubits, basis=basis) elif isinstance(representation, PTM): matri = array_to_matrix(qiskit_data) qchannel = QuantumChannel( representation=RepresentationType.PTM, arity=representation.num_qubits, matrix=matri) elif isinstance(representation, Choi): matri = array_to_matrix(qiskit_data) qchannel = QuantumChannel( representation=RepresentationType.CHOI, arity=representation.num_qubits, matrix=matri) return qchannel def qchannel_to_qiskit(representation): """ Create a qiskit representation of quantum channel from a myqlm representation of a quantum channel. Args: representation: (QuantumChannel) myqlm representation of a quantum channel. Returns: (Kraus|Choi|Chi|SuperOp|PTM): qiskit representation of a quantum channel. """ rep = representation.representation # Find what representation it is. # Then create the corresponding matrix and shape it like qiskit is expecting it. # Finally, create the qiskit representation from that matrix. if rep in (RepresentationType.PTM, RepresentationType.CHOI): matri = representation.matrix data_re = [] data_im = [] for i in range(matri.nRows): for j in range(matri.nCols): data_re.append(matri.data[i * matri.nRows + j].re + 0.j) data_im.append(matri.data[i * matri.nRows + j].im) data = np.array(data_re) data.imag = np.array(data_im) data = data.reshape((matri.nRows, matri.nCols)) return PTM(data) if (rep == RepresentationType.PTM) else Choi(data) if rep in (RepresentationType.CHI, RepresentationType.SUPEROP): final_data = [] for matri in representation.basis: data_re = [] data_im = [] for i in range(matri.nRows): for j in range(matri.nCols): data_re.append(matri.data[i * matri.nRows + j].re + 0.j) data_im.append(matri.data[i * matri.nRows + j].im) data = np.array(data_re) data.imag = np.array(data_im) data = data.reshape((matri.nRows, matri.nCols)) final_data.append(data) if rep == RepresentationType.CHI: return Chi(final_data) if len(final_data) > 1 else Chi(final_data[0]) return SuperOp(final_data) if len(final_data) > 1 else SuperOp(final_data[0]) if rep == RepresentationType.KRAUS: final_data = [] for matri in representation.kraus_ops: data_re = [] data_im = [] for i in range(matri.nRows): for j in range(matri.nCols): data_re.append(matri.data[i * matri.nRows + j].re + 0.j) data_im.append(matri.data[i * matri.nRows + j].im) data = np.array(data_re) data.imag = np.array(data_im) data = data.reshape((matri.nRows, matri.nCols)) final_data.append(data) return Kraus(final_data) return None
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 220, 220, 220, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 220, 220, 220, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, ...
2.365399
2,630
# Authors: Robert Luke <mail@robertluke.net> # # License: BSD (3-clause) import numpy as np from mne import Annotations, create_info from mne.io import RawArray def simulate_nirs_raw(sfreq=3., amplitude=1., sig_dur=300., stim_dur=5., isi_min=15., isi_max=45.): """ Create simulated data. .. warning:: Work in progress: I am trying to think on the best API. Parameters ---------- sfreq : Number The sample rate. amplitude : Number The amplitude of the signal to simulate in uM. sig_dur : Number The length of the signal to generate in seconds. stim_dur : Number The length of the stimulus to generate in seconds. isi_min : Number The minimum duration of the inter stimulus interval in seconds. isi_max : Number The maximum duration of the inter stimulus interval in seconds. Returns ------- raw : instance of Raw The generated raw instance. """ from nilearn.stats.first_level_model import make_first_level_design_matrix from pandas import DataFrame frame_times = np.arange(sig_dur * sfreq) / sfreq onset = 0. onsets = [] conditions = [] durations = [] while onset < sig_dur - 60: onset += np.random.uniform(isi_min, isi_max) + stim_dur onsets.append(onset) conditions.append("A") durations.append(stim_dur) events = DataFrame({'trial_type': conditions, 'onset': onsets, 'duration': durations}) dm = make_first_level_design_matrix(frame_times, events, drift_model='polynomial', drift_order=0) annotations = Annotations(onsets, durations, conditions) info = create_info(ch_names=['Simulated'], sfreq=sfreq, ch_types=['hbo']) raw = RawArray(dm[["A"]].to_numpy().T * amplitude * 1.e-6, info, verbose=False) raw.set_annotations(annotations) return raw
[ 2, 46665, 25, 5199, 11336, 1279, 4529, 31, 305, 4835, 2290, 365, 13, 3262, 29, 198, 2, 198, 2, 13789, 25, 347, 10305, 357, 18, 12, 565, 682, 8, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 285, 710, 1330, 47939, 11, 2251, ...
2.279867
904
from cryptomodel.cryptostore import user_notification, user_channel, user_transaction, operation_type from mongoengine import Q from cryptodataaccess import helpers from cryptodataaccess.helpers import if_none_raise, if_none_raise_with_id
[ 6738, 8194, 296, 375, 417, 13, 29609, 455, 382, 1330, 2836, 62, 1662, 2649, 11, 2836, 62, 17620, 11, 2836, 62, 7645, 2673, 11, 4905, 62, 4906, 198, 6738, 285, 25162, 18392, 1330, 1195, 198, 198, 6738, 8194, 375, 1045, 15526, 1330, 4...
3.492754
69
""" util.auth2: Authentication tools This module is based off of util.auth, except with the action paradigm removed. """ from flask import session from app.models import Account from app.util import course as course_util # Session keys SESSION_EMAIL = 'email' def create_account(email: str, password: str, first_name: str, last_name: str, fsuid: str, course_list: list = []): """ Creates an account for a single user. :email: Required, the email address of the user. :password: Required, user's chosen password. :first_name: Required, user's first name. :last_name: Required, user's last name. :fsuid: Optional, user's FSUID. :course_list: Optional, courses being taken by user :return: Account object. """ account = Account( email=email, first_name=first_name, last_name=last_name, fsuid=fsuid, is_admin=False ) # Set user's extra credit courses course_util.set_courses(account, course_list) account.set_password(password) account.save() return account def get_account(email: str=None): """ Retrieves account via email (defaults to using session), otherwise redirects to login page. :email: Optional email string, if not provided will use session['email'] :return: Account if email is present in session, None otherwise. """ try: email = email or session['email'] return Account.objects.get_or_404(email=email) except: return None
[ 37811, 7736, 13, 18439, 17, 25, 48191, 4899, 628, 220, 220, 220, 770, 8265, 318, 1912, 572, 286, 7736, 13, 18439, 11, 2845, 351, 262, 2223, 198, 220, 220, 220, 23457, 4615, 13, 198, 37811, 198, 198, 6738, 42903, 1330, 6246, 198, 198...
2.76259
556
from PyQt5.QtWidgets import * from matplotlib.backends.backend_qt5agg import FigureCanvas from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
[ 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1635, 201, 198, 6738, 2603, 29487, 8019, 13, 1891, 2412, 13, 1891, 437, 62, 39568, 20, 9460, 1330, 11291, 6090, 11017, 201, 198, 6738, 2603, 29487, 8019, 13, 26875, 1330, 112...
3.084507
71
import numpy as np from pymoo.core.algorithm import Algorithm from pymoo.core.population import Population from pymoo.util.termination.no_termination import NoTermination from pyallocation.allocation import FastAllocation from pyallocation.problem import AllocationProblem
[ 11748, 299, 32152, 355, 45941, 198, 6738, 279, 4948, 2238, 13, 7295, 13, 282, 42289, 1330, 978, 42289, 198, 6738, 279, 4948, 2238, 13, 7295, 13, 39748, 1330, 20133, 198, 6738, 279, 4948, 2238, 13, 22602, 13, 41382, 13, 3919, 62, 41382...
3.808219
73
import os
[ 11748, 28686, 628, 628 ]
3.25
4
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools from heat.api.openstack.v1 import util from heat.api.openstack.v1.views import views_common from heat.rpc import api as rpc_api _collection_name = 'stacks' basic_keys = ( rpc_api.STACK_ID, rpc_api.STACK_NAME, rpc_api.STACK_DESCRIPTION, rpc_api.STACK_STATUS, rpc_api.STACK_STATUS_DATA, rpc_api.STACK_CREATION_TIME, rpc_api.STACK_DELETION_TIME, rpc_api.STACK_UPDATED_TIME, rpc_api.STACK_OWNER, rpc_api.STACK_PARENT, rpc_api.STACK_USER_PROJECT_ID, rpc_api.STACK_TAGS, )
[ 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, ...
2.574074
432
import itertools import numpy as np import pandas as pd def find_intersections(formula_lists,group_labels,exclusive = True): """ Docstring for function pyKrev.find_intersections ==================== This function compares n lists of molecular formula and outputs a dictionary containing the intersections between each list. Use ---- find_intersections([list_1,..,list_n],['group_1',...,'group_n']) Returns a dictionary in which each key corresponds to a combination of group labels and the corresponding value is a set containing the intersections between the groups in that combination. Parameters ---------- formula_lists: a list containing n lists of molecular formula. Each item in the sub list should be a formula string. group_labels: a list containing n strings of corresponding group labels. exclusive: True or False, depending on whether you want the intersections to contain only unique values. """ if len(formula_lists) != len(group_labels): raise InputError('formula_lists and group_labels must be of equal length') combinations = [seq for i in range(0,len(group_labels)+1) for seq in itertools.combinations(group_labels,i) if len(seq) > 0] combinations = sorted(combinations,key = lambda c : len(c),reverse = True) # sort combinations by length if exclusive == True: assigned_formula = set() #create a set that will hold all the formula already assigned to a group amb = pd.DataFrame(data = formula_lists).T amb.columns = group_labels intersections = dict() for combo in combinations: queries = [] for c in combo: formula = list(filter(None,amb[c])) #Remove None entries introduced by dataframe queries.append(set(formula)) if len(queries) == 1: #if there is only one query find the unique elements in it q_set = frozenset(queries[0]) #qset is a frozen set, so it will not be mutated by changes to queries[0] for f_list in formula_lists: #cycle all formula in formula_lists set_f = frozenset(f_list) #convert f_list to sets, must be frozen so type matches q_set if set_f == q_set: # ignore the set that corresponds to the query pass else: queries[0] = queries[0] - set_f #delete any repeated elements in fset intersections[combo] = queries[0] elif len(queries) > 1: if exclusive == True: q_intersect = intersect(queries) intersections[combo] = q_intersect - assigned_formula #remove any elements from q_intersect that have already been assigned assigned_formula.update(q_intersect) #update the assigned_set with q_intersect else: intersections[combo] = intersect(queries) return intersections def intersect(samples,counter=0): """ This command uses recursion to find the intersections between a variable number of sets given in samples. Where samples = [set_1,set_2,...,set_n] """ if len(samples) == 1: return samples[0] a = samples[counter] b = samples[counter+1::] if len(b) == 1: #check to see whether the recursion has reached the final element return a & b[0] else: counter += 1 return a & intersect(samples,counter)
[ 11748, 340, 861, 10141, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 4299, 1064, 62, 3849, 23946, 7, 687, 4712, 62, 20713, 11, 8094, 62, 23912, 1424, 11, 41195, 796, 6407, 2599, 198, 220, 220, ...
2.521893
1,416
import os import glob import shutil from tinytag import TinyTag """ root = 'C:/' copy_to = '/copy to/folder' tag = TinyTag.get('C:/Users/jchap/OneDrive/Pictures/(VERYRAREBOYZ) (feat. $ki Mask The Slump God and Drugz).mp3') print(tag.artist) print('song duration: '+str(tag.duration)) """ f = [] f=glob.glob('C:/Users/jchap/OneDrive/*.mp3') print(f) musicDirectory=[] musicFiles =[] # tag = TinyTag.get(f[0]) # print(tag.artist) # for root, dirs, files in os.walk("C:/Users/jchap/OneDrive/"): for root, dirs, files in os.walk("C:/"): for file in files: if file.endswith(".mp3"): musicFiles.append(file) musicDirectory.append(os.path.join(root, file)) #print(os.path.join(root, file)) print('files'+str(musicFiles)) tag = TinyTag.get(musicDirectory[0]) print('Artist',tag.artist) print('Album Artist',tag.albumartist) print('Title',tag.title) print('Biterate',tag.bitrate) print('music directory'+str(musicDirectory)) print(len(musicDirectory)) currentDirectory =os.path.dirname(__file__) with open(currentDirectory+'/The_Krabby_Patty Formula_.m3u', "r") as f: content_list = [word.strip() for word in f] """ my_file = open(currentDirectory+'/The_Krabby_Patty Formula_.m3u', "r") content_list = my_file. readlines() """ # print('playlist contents') # print(content_list) musicDirectory musicWithoutDuplicates = [] duplicatesList = [] count =0 # check for tags equal to none #musicDirectory =[x for x in musicDirectory j = TinyTag.get(x) if x != 'wdg'] #remove tracks without albumn artist or title for track in reversed(range(len(musicDirectory))): try: trackTag = TinyTag.get(musicDirectory[track]) if str(trackTag.albumartist)== 'None' or str(trackTag.title)=='None': print('albumArtist = none',musicDirectory[track]) print('removing track and adding to log file') musicDirectory.remove(musicDirectory[track]) except IndexError: break #check for duplicates for j in range(len(musicDirectory)): musicDtag = TinyTag.get(musicDirectory[j]) duplicateL=[] duplicateLBiterate=[] for duplicate in range(len(musicDirectory)): duplicateTag = TinyTag.get(musicDirectory[duplicate]) musicWithoutDuplicates.append(musicDirectory[j]) if duplicateTag.albumartist == musicDtag.albumartist or duplicateTag.albumartist in musicDtag.albumartist: if duplicateTag.title == musicDtag.title or duplicateTag.title in musicDtag.title : #check if last iteration if duplicate>=len(musicDirectory)-1: print("found a duplicate!",musicDirectory[duplicate],duplicateTag.albumartist,duplicateTag.title) if len(duplicateLBiterate)==1:## did something here may need to change the conditional statement or add another print('biterate') #[x for x in duplicateL if TinyTag.get(musicDirectory[x]).bitrate > musicDirectory[x]] print("Current duplicate Bite rate", duplicateLBiterate) for x in range(len(duplicateL)): if TinyTag.get(duplicateL[x]).bitrate == max(duplicateLBiterate): #REMOVE ONE WITH THE BEST BITERATE duplicateL.remove(duplicateL[x]) print('duplicate list',duplicateL) #Add duplicatesList = duplicatesList + duplicateL else: print("found a duplicate!",musicDirectory[duplicate],duplicateTag.albumartist,duplicateTag.title) duplicateL.append(musicDirectory[duplicate]) duplicateLBiterate.append(duplicateTag.bitrate) print('dup ',duplicatesList) #remove duplicates from list for u in range(len(duplicatesList)): for i in range(len(musicDirectory)): if duplicatesList[u]==musicDirectory[i]: musicDirectory.remove(musicDirectory[i]) print('music ',musicDirectory) #create playlist newPlaylist = open("Test.m3u", "w") #add file path to the respective track in the new playlist for content in enumerate(content_list): # split strings into artist and title trackNumber=content[0] trackArray =str(content[1]).split('-') albumArtist= trackArray[0].strip() title=trackArray[1].strip() print('title:',title) print('albumArtist:',albumArtist) for trackDirectory in range(len(musicDirectory)): trackTag = TinyTag.get(musicDirectory[trackDirectory]) if trackTag.albumartist == albumArtist or trackTag.albumartist in albumArtist: if trackTag.title == title or trackTag.title in title: newPlaylist.write(trackDirectory + " " + content) newPlaylist.close() try: while True: content.next() except StopIteration: pass break else: print() else: print()
[ 11748, 28686, 201, 198, 11748, 15095, 201, 198, 11748, 4423, 346, 201, 198, 6738, 7009, 12985, 1330, 20443, 24835, 201, 198, 201, 198, 37811, 6808, 796, 705, 34, 14079, 6, 201, 198, 30073, 62, 1462, 796, 31051, 30073, 284, 14, 43551, ...
2.180567
2,470
#import modules import os import csv #input csvpath = os.path.join('Resources', 'budget_data.csv') #output outfile = os.path.join('Analysis', 'pybankstatements.txt') #declare variables months = []; total_m = 1; net_total = 0; total_change = 0; monthly_changes = []; greatest_inc = ['', 0]; greatest_dec = ['', 0] #open & read csv with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') header = next(csvreader) first_row = next(csvreader) previous_row = int(first_row[1]) net_total = int(first_row[1]) #loop for row in csvreader: net_total += int(row[1]) total_m = total_m+1 current_value = int(row[1]) change_value = int(current_value-previous_row) monthly_changes.append(change_value) months.append(row[0]) previous_row = int(row[1]) total_change = total_change + change_value if change_value > greatest_inc[1]: greatest_inc[0] = str(row[0]) greatest_inc[1] = change_value if change_value < greatest_dec[1]: greatest_dec[0] = str(row[0]) greatest_dec[1] = change_value avg_change = total_change/len(months) output = ( f"\n Financial Analysis \n" f"------------------------------\n" f"Total Months: {total_m}\n" f"Total: ${net_total}\n" f"Average Change: ${avg_change:.2f}\n" f"Greatest Increase in Profits: {greatest_inc[0]} (${greatest_inc[1]})\n" f"Greatest Decrease in Profits: {greatest_dec[0]} (${greatest_dec[1]})\n") with open(outfile, "w") as txt_file: txt_file.write(output) outfile
[ 2, 11748, 13103, 198, 11748, 28686, 198, 11748, 269, 21370, 198, 2, 15414, 198, 40664, 6978, 796, 28686, 13, 6978, 13, 22179, 10786, 33236, 3256, 705, 37315, 62, 7890, 13, 40664, 11537, 198, 2, 22915, 198, 448, 7753, 796, 28686, 13, 6...
2.291317
714
from enum import Enum from constants.globals import HEALTH_EMOJIS NETWORK_ERROR = ' There was an error while getting data \nAn API endpoint is down!' HEALTH_LEGEND = f'\n*Node health*:\n{HEALTH_EMOJIS[True]} - *healthy*\n{HEALTH_EMOJIS[False]} - *unhealthy*\n' \ f'{HEALTH_EMOJIS[None]} - *unknown*\n' NETWORK_HEALTHY_AGAIN = "The network is safe and efficient again! "
[ 6738, 33829, 1330, 2039, 388, 198, 198, 6738, 38491, 13, 4743, 672, 874, 1330, 11179, 40818, 62, 3620, 46, 41, 1797, 198, 198, 12884, 33249, 62, 24908, 796, 705, 1318, 373, 281, 4049, 981, 1972, 1366, 3467, 77, 2025, 7824, 36123, 318,...
2.459627
161
import random import fire import json import os import numpy as np import tensorflow as tf import pytumblr import mysql.connector import datetime from random import seed import model, sample, encoder if __name__ == '__main__': fire.Fire(interact_model())
[ 11748, 4738, 198, 11748, 2046, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 12972, 45364, 198, 11748, 48761, 13, 8443, 273, 198, 11748, 4818, 8079, 198, 6...
3.371795
78
from sys import version_info if version_info[0] <= 2 and version_info[1] <= 4: else: all = all
[ 6738, 25064, 1330, 2196, 62, 10951, 198, 198, 361, 2196, 62, 10951, 58, 15, 60, 19841, 362, 290, 2196, 62, 10951, 58, 16, 60, 19841, 604, 25, 198, 17772, 25, 198, 220, 220, 220, 477, 796, 477, 198 ]
2.631579
38
from rest_framework import serializers from cms.api.serializers import UniCMSContentTypeClass, UniCMSCreateUpdateSerializer from cms.medias.serializers import MediaSerializer from . models import Carousel, CarouselItem, CarouselItemLink, CarouselItemLinkLocalization, CarouselItemLocalization
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 198, 6738, 269, 907, 13, 15042, 13, 46911, 11341, 1330, 43376, 34, 5653, 19746, 6030, 9487, 11, 43376, 34, 5653, 16447, 10260, 32634, 7509, 198, 198, 6738, 269, 907, 13, 2379, 292, 13, 4...
3.719512
82
#!/usr/bin/env python3 """ Copyright (c) 2018-2021 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from openvino.runtime import Core, get_version import cv2 as cv import numpy as np import logging as log from time import perf_counter import sys from argparse import ArgumentParser, SUPPRESS from pathlib import Path sys.path.append(str(Path(__file__).resolve().parents[2] / 'common/python')) sys.path.append(str(Path(__file__).resolve().parents[2] / 'common/python/openvino/model_zoo')) import monitors from images_capture import open_images_capture from model_api.performance_metrics import PerformanceMetrics log.basicConfig(format='[ %(levelname)s ] %(message)s', level=log.DEBUG, stream=sys.stdout) if __name__ == "__main__": args = build_arg().parse_args() sys.exit(main(args) or 0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 15069, 357, 66, 8, 2864, 12, 1238, 2481, 8180, 10501, 628, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 345, 743, 407, 77...
3.381443
388
# coding: utf-8 """ [AHOI cookbook](/ahoi/docs/cookbook/index.html) [Data Privacy](/sandboxmanager/#/privacy) [Terms of Service](/sandboxmanager/#/terms) [Imprint](https://sparkassen-hub.com/impressum/) &copy; 2016&dash;2017 Starfinanz - Ein Unternehmen der Finanz Informatik # noqa: E501 OpenAPI spec version: 2.1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from swagger_client.models.amount import Amount # noqa: F401,E501 def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, Transfer): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 220, 628, 220, 220, 220, 685, 18429, 46, 40, 4255, 2070, 16151, 14, 17108, 72, 14, 31628, 14, 27916, 2070, 14, 9630, 13, 6494, 8, 220, 685, 6601, 16777, 16151, ...
2.5
432
# Copyright 2015-2017 ARM Limited, Google and contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import unicode_literals from __future__ import division from __future__ import print_function from builtins import chr import os import json import shutil import sys import unittest import utils_tests import trappy from trappy.ftrace import GenericFTrace from trappy.systrace import SysTrace
[ 2, 220, 220, 220, 15069, 1853, 12, 5539, 20359, 15302, 11, 3012, 290, 20420, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11...
3.720648
247
from enum import Enum
[ 6738, 33829, 1330, 2039, 388, 628 ]
3.833333
6
from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.shortcuts import render from django.urls import reverse from django.http import HttpResponseRedirect, HttpResponse from django.utils import timezone from olaf.models import * from olaf.forms import * from olaf.utility import usertools from olaf.chess.controller import proccess_move form_operation_dict = { 'login' : ( usertools.login_user, LoginForm, 'olaf/login.html', {}, 'index', { 'message' : "You're logged in. :)"} ), 'register' : ( usertools.register_user, RegisterForm, 'olaf/register.html', {}, 'index', { 'message' : "An activation email has been sent to you" } ), 'password_reset_request' : ( usertools.init_pass_reset_token, ForgotPasswordUsernameOrEmailForm, 'olaf/password_reset_request.html', {}, 'index', { 'message' : "An email containing the password reset link will be sent to your email"} ), 'reset_password' : ( usertools.reset_password_action, PasswordChangeForm, 'olaf/reset_password.html', {}, 'olaf:login', { 'message' : "Password successfully changed, you can login now" } ), 'resend_activation_email' : ( usertools.resend_activation_email, ResendActivationUsernameOrEmailForm, 'olaf/resend_activation_email.html', {}, 'index', { 'message' : "Activation email successfully sent to your email" } ), } #view functions
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 17594, 62, 35827, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 426...
2.746641
521
from __future__ import print_function import argparse import torch import torch.utils.data import matplotlib.pyplot as plt from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from torch.utils.tensorboard import SummaryWriter from ce_vae_test.networks.min_vae import MinVae from ce_vae_test.trainer.ce_trainer import CeVaeTrainer from ce_vae_test.sampler.dataset_sampler import SamplerDatasetWithReplacement parser = argparse.ArgumentParser(description='VAE MNIST Example') parser.add_argument('--batch-size', type=int, default=128, metavar='N', help='input batch size for training (default: 128)') parser.add_argument('--epochs', type=int, default=10, metavar='N', help='number of epochs to train (default: 10)') parser.add_argument('--no-cuda', action='store_true', default=False, help='enables CUDA training') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') parser.add_argument('--log-interval', type=int, default=10, metavar='N', help='how many batches to wait before logging training status') args = parser.parse_args() args.cuda = not args.no_cuda and torch.cuda.is_available() torch.manual_seed(args.seed) device = torch.device("cuda" if args.cuda else "cpu") writer = SummaryWriter() kwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {} train_sampler = SamplerDatasetWithReplacement( dataset=datasets.MNIST('../data', train=True, download=True, transform=transforms.ToTensor()), batch_size=args.batch_size ) test_sampler = SamplerDatasetWithReplacement( dataset=datasets.MNIST('../data', train=False, transform=transforms.ToTensor()), batch_size=args.batch_size * 10 ) cevae = MinVae( input_size=28 * 28, output_size=10, latent_dim=2, hidden_sizes_dec=[5], device=device ).to(device) trainer = CeVaeTrainer( vae=cevae, num_epochs=300, train_loader=train_sampler, test_loader=test_sampler, writer=writer, device=device, alpha=0.90, lamda=0.22 ) trainer.run()
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 1822, 29572, 198, 11748, 28034, 198, 11748, 28034, 13, 26791, 13, 7890, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 28034, 1330, 299, 77, 11, 6436, ...
2.388379
981
from __future__ import absolute_import, division, print_function from appr.auth import ApprAuth from appr.commands.command_base import CommandBase, PackageSplit
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 198, 6738, 598, 81, 13, 18439, 1330, 2034, 81, 30515, 198, 6738, 598, 81, 13, 9503, 1746, 13, 21812, 62, 8692, 1330, 9455, 14881, 11, 15717, 41205, 6...
3.790698
43
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
#!/usr/bin/env python '''tzwhere.py - time zone computation from latitude/longitude. Ordinarily this is loaded as a module and instances of the tzwhere class are instantiated and queried directly ''' import collections try: import ujson as json # loads 2 seconds faster than normal json except: try: import json except ImportError: import simplejson as json import math import gzip import os import shapely.geometry as geometry import shapely.prepared as prepared # We can save about 222MB of RAM by turning our polygon lists into # numpy arrays rather than tuples, if numpy is installed. try: import numpy WRAP = numpy.asarray COLLECTION_TYPE = numpy.ndarray except ImportError: WRAP = tuple COLLECTION_TYPE = tuple # for navigation and pulling values/files this_dir, this_filename = os.path.split(__file__) BASE_DIR = os.path.dirname(this_dir) def read_tzworld(path): reader = read_json return reader(path) def read_json(path): with gzip.open(path, "rb") as f: featureCollection = json.loads(f.read().decode("utf-8")) return featureCollection def feature_collection_polygons(featureCollection): """Turn a feature collection into an iterator over polygons. Given a featureCollection of the kind loaded from the json input, unpack it to an iterator which produces a series of (tzname, polygon) pairs, one for every polygon in the featureCollection. Here tzname is a string and polygon is a list of floats. """ for feature in featureCollection['features']: tzname = feature['properties']['TZID'] if feature['geometry']['type'] == 'Polygon': exterior = feature['geometry']['coordinates'][0] interior = feature['geometry']['coordinates'][1:] yield (tzname, (exterior, interior)) if __name__ == "__main__": prepareMap()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 7061, 6, 22877, 3003, 13, 9078, 532, 640, 6516, 29964, 422, 32477, 14, 6511, 3984, 13, 198, 198, 35422, 21565, 428, 318, 9639, 355, 257, 8265, 290, 10245, 286, 262, 256, 89, 300...
2.912442
651
from mindmeld.models.helpers import register_query_feature
[ 6738, 2000, 1326, 335, 13, 27530, 13, 16794, 364, 1330, 7881, 62, 22766, 62, 30053, 628 ]
3.75
16
#!/usr/bin/python # -*- coding: utf-8 -*-
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198 ]
1.909091
22
#!/usr/bin/python # -*- coding: utf-8 -*- # [Import start] from flask import Blueprint, jsonify # [Import end] app = Blueprint( 'hoge', __name__, url_prefix='/hoge' )
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 685, 20939, 923, 60, 198, 6738, 42903, 1330, 39932, 11, 33918, 1958, 198, 2, 685, 20939, 886, 60, 198, 198, 1324, ...
2.303797
79
#!/usr/bin/env python3 import apt_pkg import sys from apt_pkg import CURSTATE_INSTALLED, version_compare from operator import lt, le, eq, ge, gt # Function mappings for relationship operators. relation_operators = {"<<": lt, "<=": le, "=": eq, ">=": ge, ">>": gt} # Set up APT cache. apt_pkg.init() cache = apt_pkg.Cache(None) missing_packages = [] for i in sys.argv[1:]: # Build the package relationship string for use by 'apt-get satisfy'. relationship_operator = None for j in ["<=", ">=", "<", ">", "="]: if j in i: relationship_operator = j break if relationship_operator is not None: if relationship_operator in ["<", ">"]: relationship_operator_formatted = j + j else: relationship_operator_formatted = j package = i.split(relationship_operator) pkgname = package[0] pkgver = package[1] package_string = f"{pkgname} ({relationship_operator_formatted} {pkgver})" else: pkgname = i pkgver = None package_string = pkgname # Check if the package is in the cache. try: pkg = cache[pkgname] except KeyError: missing_packages += [package_string] continue # Get the list of installed and provided packages that are currently installed. installed_pkg_versions = [] if pkg.current_state == CURSTATE_INSTALLED: installed_pkg_versions += [pkg] for i in pkg.provides_list: parent_pkg = i[2].parent_pkg if parent_pkg.current_state == CURSTATE_INSTALLED: installed_pkg_versions += [parent_pkg] # If an installed package was found and no relationship operators were used, the dependency has been satisfied. if (len(installed_pkg_versions) != 0) and (relationship_operator is None): continue # Otherwise, check all matching installed packages and see if any of them fit the specified relationship operator. matched_pkg = False for i in installed_pkg_versions: installed_version = i.current_ver.ver_str version_result = version_compare(installed_version, pkgver) if relation_operators[relationship_operator_formatted](version_result, 0): matched_pkg = True if not matched_pkg: missing_packages += [package_string] for i in missing_packages: print(i) exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 15409, 62, 35339, 198, 11748, 25064, 198, 198, 6738, 15409, 62, 35339, 1330, 327, 4261, 44724, 62, 38604, 7036, 1961, 11, 2196, 62, 5589, 533, 198, 6738, 10088, 1330, 300, 8...
2.607221
914
# Generated by Django 3.0.7 on 2020-08-24 06:17 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 22, 319, 12131, 12, 2919, 12, 1731, 9130, 25, 1558, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
print "Hello World!" print "Trying my hand at Git!" print "Something else" for i in range(10): print i
[ 4798, 366, 15496, 2159, 2474, 198, 4798, 366, 51, 14992, 616, 1021, 379, 15151, 2474, 198, 4798, 366, 22210, 2073, 1, 198, 1640, 1312, 287, 2837, 7, 940, 2599, 198, 220, 220, 220, 3601, 1312, 198 ]
2.972222
36
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic import DetailView, ListView from projects.models import Project from status.models import Status from .models import Task from .forms import TaskForm, FilterForm
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 19816, 1040, 1330, 23093, 37374, 35608, 259, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 13, 19312, 1330, 13610, 7680, 11, 10133, 7680, 11, 23520, 7680, 198, 6738, 42625, 14208, 13, 3...
3.926829
82
import os import math import time import geohash import geojson from geojson import MultiLineString from shapely import geometry import shapefile import numpy import datetime as dt import pandas as pd import logging logger = logging.getLogger(__name__) source_shape_file_path = "C:/temp/2018/" threshold = 60*60 cols = ['start', 'end','start_epoch_round','end_epoch_round','start_epoch_round_dt','end_epoch_round_dt'] times = [] for root,dirs,files in os.walk(source_shape_file_path): for file in files: with open(os.path.join(root,file),"r") as auto: if file.endswith(".shp"): try: filename = file.replace(".shp","") shape=shapefile.Reader(source_shape_file_path+filename+"/"+file) for r in shape.iterRecords(): start_time = dt.datetime.strptime(r[1], '%Y%j %H%M') end_time = dt.datetime.strptime(r[2], '%Y%j %H%M') epoch_s = dt.datetime.timestamp(dt.datetime.strptime(r[1], '%Y%j %H%M')) epoch_e = dt.datetime.timestamp(dt.datetime.strptime(r[2], '%Y%j %H%M')) # sometimes start is later than end time, we'll assume the earlier time is start epoch_end_round = round(max(epoch_s,epoch_e) / threshold) * threshold epoch_start_round = round(min(epoch_s,epoch_e) / threshold) * threshold epoch_end_round_dt = dt.datetime.utcfromtimestamp(3600 * ((max(epoch_s,epoch_e) + 1800) // 3600)) epoch_start_round_dt = dt.datetime.utcfromtimestamp(3600 * ((min(epoch_s,epoch_e) + 1800) // 3600)) times.append([start_time,end_time,epoch_start_round,epoch_end_round,epoch_start_round_dt,epoch_end_round_dt]) break except: logger.error('failed to parse file:'+source_shape_file_path+filename+"/") continue df = pd.DataFrame(times, columns=cols) df.to_csv('noaa_times.csv')
[ 11748, 28686, 198, 11748, 10688, 198, 11748, 640, 198, 11748, 4903, 1219, 1077, 198, 11748, 4903, 13210, 1559, 198, 6738, 4903, 13210, 1559, 1330, 15237, 13949, 10100, 198, 6738, 5485, 306, 1330, 22939, 198, 11748, 5485, 7753, 198, 11748, ...
1.98381
1,050