content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
''' Faa um programa que leia um nmero inteiro e mostre na tela o seu sucessor e seu antecessor. ''' n = int(input('Entre com um valor: ')) antecessor = n - 1 sucessor = n + 1 msg = 'o antecessor do nmero {} {} e seu sucessor {}'.format(n, antecessor, sucessor) print(msg)
[ 7061, 6, 198, 37, 7252, 23781, 1430, 64, 8358, 443, 544, 23781, 299, 647, 78, 493, 68, 7058, 304, 749, 260, 12385, 256, 10304, 267, 384, 84, 424, 919, 273, 304, 384, 84, 29692, 919, 273, 13, 198, 198, 7061, 6, 198, 198, 77, 796,...
2.367521
117
import pytest from mitzasql.sql_parser.parser import parse from mitzasql.utils import dfs
[ 11748, 12972, 9288, 198, 6738, 285, 4224, 292, 13976, 13, 25410, 62, 48610, 13, 48610, 1330, 21136, 198, 6738, 285, 4224, 292, 13976, 13, 26791, 1330, 288, 9501, 198 ]
3.103448
29
version = '2.0.1048'
[ 9641, 796, 705, 17, 13, 15, 13, 940, 2780, 6, 198 ]
1.909091
11
# Importing standard libraires import sys ''' Main Function for the program. Logic is as follows Make two frequency tables for two strings Take overlap of both and add up the non overlapping regions (absolute values) ''' if __name__ == "__main__": # Parsing in the input s1 = list(sys.stdin.readline().rstrip()) s2 = list(sys.stdin.readline().rstrip()) # Initialize the character array as a hashtable charFreqs1 = [0]*26 charFreqs2 = [0]*26 anagram = [0]*26 # Record frequencies of characters in s1 and s2 for i in s1: charFreqs1[ord(i) - ord('a')] += 1 for i in s2: charFreqs2[ord(i) - ord('a')] += 1 for i in range(26): anagram[i] = abs(charFreqs1[i] - charFreqs2[i]) print sum(anagram)
[ 2, 17267, 278, 3210, 9195, 430, 2387, 198, 11748, 25064, 198, 198, 7061, 6, 198, 220, 220, 220, 8774, 15553, 329, 262, 1430, 13, 30146, 318, 355, 5679, 198, 220, 220, 220, 6889, 734, 8373, 8893, 329, 734, 13042, 198, 220, 220, 220, ...
2.460317
315
from .utilities import Response SCHEDULE_RESPONSE = b""" {"error":{"code":200,"message":"Success"},"data":{"classes":[{ "id":113209,"sector":"F","class_type_id":48,"start_date":"2020-06-07", "end_date":"2020-06-07","start_time":"09:00:00","end_time":"09:45:00", "duration":"2700000","teacher_id":782,"location_id":10,"level_id":9, "pillar_id":6,"button_status":0,"booking_id":0, "start_datetime":"2020-06-07T09:00:00+08:00","is_free":false, "color_code":"","is_filmed":false,"is_online":0,"is_cycling":false, "free_class_type":0,"special_flag":null,"duration_min":45, "class_type":{"id":48,"name":"TRX Blast", "description":"","is_fuze":false,"pillar":{"name":"Strength", "color":"#ed1c24","code":"strength_and_conditioning"},"level":"All Levels"}, "teacher":{"id":782,"name":"","full_name":"","image_link":"", "type":"teacher"}}]}} """
[ 6738, 764, 315, 2410, 1330, 18261, 198, 198, 50, 3398, 1961, 24212, 62, 19535, 47, 1340, 5188, 796, 275, 37811, 198, 4895, 18224, 8351, 8189, 1298, 2167, 553, 20500, 2404, 33244, 13018, 7890, 8351, 37724, 20598, 90, 198, 1, 312, 1298, ...
2.689103
312
''' Ta-libMACD ''' import pandas as pd import numpy as np import talib as ta import tushare as ts from matplotlib import rc import matplotlib.pyplot as plt import seaborn as sns rc('mathtext', default='regular') sns.set_style('white') # %matplotlib plt.rcParams["figure.figsize"] = (20, 10) dw = ts.get_k_data("600600") close = dw.close.values dw['macd'], dw['macdsignal'], dw['macdhist'] = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) dw[['close','macd','macdsignal','macdhist']].plot() plt.show()
[ 7061, 6, 198, 38586, 12, 8019, 44721, 35, 198, 7061, 6, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 3305, 571, 355, 20486, 198, 11748, 256, 1530, 533, 355, 40379, 198, 6738, 2603, 29487, 8019,...
2.504854
206
import logging from regression_model.config import config from regression_model.config import logging_config VERSION_PATH = config.PACKAGE_ROOT / 'VERSION' with open(VERSION_PATH, 'r') as version_file: __version__ = version_file.read().strip()
[ 11748, 18931, 198, 198, 6738, 20683, 62, 19849, 13, 11250, 1330, 4566, 198, 6738, 20683, 62, 19849, 13, 11250, 1330, 18931, 62, 11250, 628, 198, 43717, 62, 34219, 796, 4566, 13, 47, 8120, 11879, 62, 13252, 2394, 1220, 705, 43717, 6, 1...
3.36
75
from datetime import date year_current_date = date.today().year get_info("Cleberton", 28, 1.69, 75) # Funo recebe algumas informaoes por parametro, e retorna ano de nascimento, imc # com algumas frases customizadas
[ 6738, 4818, 8079, 1330, 3128, 198, 198, 1941, 62, 14421, 62, 4475, 796, 3128, 13, 40838, 22446, 1941, 628, 198, 198, 1136, 62, 10951, 7203, 34349, 527, 1122, 1600, 2579, 11, 352, 13, 3388, 11, 5441, 8, 198, 198, 2, 11138, 78, 1407, ...
2.650602
83
import json from sys import stdout # START data = '''{ "name": "bugs", "age": 76 }''' obj = json.loads(data) json.dump(obj, stdout) # END print(obj)
[ 11748, 33918, 198, 6738, 25064, 1330, 14367, 448, 198, 198, 2, 33303, 198, 7890, 796, 705, 7061, 90, 198, 220, 220, 220, 366, 3672, 1298, 366, 32965, 1600, 198, 220, 220, 220, 366, 496, 1298, 8684, 198, 92, 7061, 6, 198, 26801, 796,...
2.285714
70
"""Tests for SpeedTest integration.""" from unittest.mock import patch import speedtest from openpeerpower import config_entries from openpeerpower.components import speedtestdotnet from openpeerpower.setup import async_setup_component from tests.common import MockConfigEntry
[ 37811, 51, 3558, 329, 8729, 14402, 11812, 526, 15931, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 198, 11748, 2866, 9288, 198, 198, 6738, 1280, 33350, 6477, 1330, 4566, 62, 298, 1678, 198, 6738, 1280, 33350, 6477, 13, 5589...
3.837838
74
# Kertaus, kerta 3 # Muuttujat ja sytteen lukeminen kyttjlt nimi = input("Anna nimesi: ") kengnnumero = input("Mik on kengnnumerosi: ") print("Moi vaan, " + nimi + "! Kengnnumerosi on " + kengnnumero + ".") # F-merkkijono print(f"Moi vaan, {nimi}! Kengnnumerosi on {kengnnumero}.") # Numerot # Iklaskuri syntymvuosi = input("Mik on syntymvuotesi? ") syntymvuosi = int(syntymvuosi) # Muunnetaan merkkijono kokonaisluvuksi, jotta voimme laskea sill ik = 2021 - syntymvuosi print(f"Iksi vuoden 2021 lopussa on {ik}") # Laskin, joka osaa kertoa lukuja luku1 = int(input("Anna luku: ")) luku2 = int(input("Anna toinen luku: ")) tulos = luku1 * luku2 print(f"{luku1} * {luku2} = {tulos}") # Laskin, joka laskee kolmen luvun summan summa = 0 luku = int(input("Ensimminen luku: ")) summa = summa + luku luku = int(input("Toinen luku: ")) summa = summa + luku luku = int(input("kolmas luku: ")) summa = summa + luku print(f"Lukujen summa: {summa}") # Minklaisia laskuja voi laskea print(5+2) print(5-2) print(5*2) print(5/2) print(5//2) print(5%2) print(2 + 2 * 3) print((2 + 2) * 3) # Liukuluvut = desimaaliluvut luku1 = 4.0 luku2 = 1.5 tulos = luku1 - luku2 print(f"Tulos on {tulos}") print(f"{luku1} - {luku2} = {tulos}")
[ 2, 509, 861, 8717, 11, 479, 861, 64, 513, 198, 198, 2, 8252, 15318, 23577, 265, 45091, 827, 83, 7821, 300, 4649, 1084, 268, 479, 88, 926, 73, 2528, 198, 77, 25236, 796, 5128, 7203, 31160, 299, 999, 72, 25, 366, 8, 198, 74, 1516,...
2.041391
604
import requests from lxml import etree if __name__ == '__main__': headers = {"User-Agent":'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'} url = 'https://www.apache.org/dist/ant/' sourceHTML = requests.get(url, headers = headers) selector = etree.HTML(sourceHTML.text) folder_list = selector.xpath('//pre[position()=1]/a[@href]') for elmt in folder_list: # href_TT = elmt.get('href') print('href_TT ', href_TT) if href_TT[len(href_TT)-1] == '/': print('folder_list', elmt.attrib)
[ 11748, 7007, 198, 6738, 300, 19875, 1330, 2123, 631, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 24697, 796, 19779, 12982, 12, 36772, 1298, 6, 44, 8590, 5049, 14, 20, 13, 15, 357, 11209, 2...
2.264706
272
from h1d_wrapper.h1d_wrapper import Element, Mesh, Linearizer
[ 6738, 289, 16, 67, 62, 48553, 13, 71, 16, 67, 62, 48553, 1330, 11703, 11, 47529, 11, 44800, 7509, 198 ]
3.1
20
import pytest from jelm import Jelm, Node, Edge from jelm.tests.network_case_set_class import NetwokCaseTemplate
[ 11748, 12972, 9288, 198, 198, 6738, 474, 417, 76, 1330, 449, 417, 76, 11, 19081, 11, 13113, 198, 198, 6738, 474, 417, 76, 13, 41989, 13, 27349, 62, 7442, 62, 2617, 62, 4871, 1330, 3433, 86, 482, 20448, 30800, 628, 628, 628, 628, 6...
2.777778
45
''' Evaluation code for trajectory prediction. We record the objects in the last frame of every sequence in test dataset as considered objects, which is stored in considered_objects.txt. We compare the error between your predicted locations in the next 3s(six positions) and the ground truth for these considered objects. To run this script, make sure that your results are in required format. ''' import os import argparse import numpy as np if __name__ == '__main__': main()
[ 7061, 6, 198, 36, 2100, 2288, 2438, 329, 22942, 17724, 13, 198, 198, 1135, 1700, 262, 5563, 287, 262, 938, 5739, 286, 790, 8379, 287, 1332, 27039, 355, 3177, 5563, 11, 543, 318, 8574, 287, 3177, 62, 48205, 13, 14116, 13, 198, 1135, ...
3.96
125
# !/usr/bin/python # -*- coding: utf-8 -*- import click import os try: # Python 2.x version from urllib2 import HTTPError, URLError except: # Python 3.x version from urllib.error import HTTPError, URLError from shellfoundry.exceptions import FatalError from shellfoundry.utilities.config_reader import Configuration, CloudShellConfigReader from shellfoundry.utilities.installer import ShellInstaller from shellfoundry.utilities.shell_config_reader import ShellConfigReader from shellfoundry.utilities.shell_package import ShellPackage from shellfoundry.utilities.shell_package_installer import ShellPackageInstaller
[ 2, 5145, 14, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 3904, 198, 11748, 28686, 198, 28311, 25, 198, 220, 220, 220, 1303, 11361, 362, 13, 87, 2196, 198, 220, 220, ...
3.342105
190
#!/usr/bin/python import rospy from rospy import ROSException from std_msgs.msg import Header, Bool from std_srvs.srv import SetBool from geometry_msgs.msg import PoseWithCovarianceStamped, Point, Quaternion from sensor_msgs.msg import NavSatFix, NavSatStatus from sam_msgs.msg import GetGPSFixAction, GetGPSFixFeedback, GetGPSFixResult from sam_msgs.msg import PercentStamped import actionlib import tf_conversions import tf from tf.transformations import quaternion_from_euler, quaternion_multiply from geodesy import utm import math import numpy as np if __name__ == "__main__": rospy.init_node('gps_fix_server', anonymous=False) #True) check_server = GPSFixServer(rospy.get_name()) rospy.spin()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 686, 2777, 88, 198, 6738, 686, 2777, 88, 1330, 48263, 16922, 198, 6738, 14367, 62, 907, 14542, 13, 19662, 1330, 48900, 11, 347, 970, 198, 6738, 14367, 62, 27891, 14259, 13, 27891,...
2.891129
248
# -*- coding: utf-8 -*- from puremvc.patterns.proxy import Proxy from .. import ApplicationFacade
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 5899, 76, 28435, 13, 33279, 82, 13, 36436, 1330, 38027, 198, 198, 6738, 11485, 1330, 15678, 47522, 671, 628 ]
2.885714
35
import pygame import os
[ 11748, 12972, 6057, 198, 11748, 28686, 628 ]
3.571429
7
# This Python file uses the following encoding: utf-8 from app.package.views.Calibrate_view import CalibrateView from app.package.controllers.Calibrate_controller import CalibrateController from app.package.models.Calibrate_model import CalibrateModel import sys import matplotlib from PySide2.QtWidgets import QApplication from PySide2 import QtCore from .package.models.NewProjectModel import NewProjectModel from .package.models.DataAcquisitionModel import DataAcquisitionModel from .package.models.DisplayResultsModel import DisplayResultsModel from .package.controllers.Navigator import Navigator from .package.controllers.NewProjectController import NewProjectController from .package.controllers.DataAcquisitionController import ( DataAcquisitionController) from .package.controllers.DisplayResultsController import ( DisplayResultsController) from .package.views.MainWindow import MainWindow from .package.views.NewProjectView import NewProjectView from .package.views.DataAcquisitionView import DataAcquisitionView from .package.views.DisplayResultsView import DisplayResultsView sys._excepthook = sys.excepthook sys.excepthook = exception_hook matplotlib.use('tkagg') if __name__ == "__main__": main() # if __name__ == "__main__": # import cProfile # cProfile.run('main()', 'output.dat') # import pstats # from pstats import SortKey # with open("output_time.dat", "w") as f: # p = pstats.Stats("output.dat", stream=f) # p.sort_stats("time").print_stats() # with open("output_calls.dat", "w") as f: # p = pstats.Stats("output.dat", stream=f) # p.sort_stats("calls").print_stats()
[ 2, 770, 11361, 2393, 3544, 262, 1708, 21004, 25, 3384, 69, 12, 23, 198, 6738, 598, 13, 26495, 13, 33571, 13, 9771, 2889, 378, 62, 1177, 1330, 2199, 2889, 378, 7680, 198, 6738, 598, 13, 26495, 13, 3642, 36667, 13, 9771, 2889, 378, ...
3.063985
547
import datetime import decimal from playhouse.sqlite_ext import * # Peewee assumes that the `pysqlite2` module was compiled against the # BerkeleyDB SQLite libraries. from pysqlite2 import dbapi2 as berkeleydb berkeleydb.register_adapter(decimal.Decimal, str) berkeleydb.register_adapter(datetime.date, str) berkeleydb.register_adapter(datetime.time, str)
[ 11748, 4818, 8079, 198, 11748, 32465, 198, 198, 6738, 711, 4803, 13, 25410, 578, 62, 2302, 1330, 1635, 198, 198, 2, 2631, 413, 1453, 18533, 326, 262, 4600, 79, 893, 13976, 578, 17, 63, 8265, 373, 14102, 1028, 262, 198, 2, 14727, 110...
3.103448
116
from numpy.random import standard_normal from numbers import Number def simulation_analysis(project, sim_dict, iterations=250, valuator=None): """ Purpose: Analyses the effects of uncertainty of a system by performing a Monte Carlo simulation. Args: project: An instance of Project to perform the simulation on sim_dict: A dict where the key is the name of the cashflow to simulate and the value is either a number defining the standard deviation for the cashflow as a percentage, or a function defining some way to modify the cashflow by an amount """ # Make every sim_fun value a callable, converting numbers to stdev functions for key in sim_dict: if isinstance(sim_dict[key], Number): stdev = sim_dict[key] sim_dict[key] = std_dist valuator = valuator or project.npw if not callable(valuator): return TypeError("Valuator must be a callable construct!") # Perform the simulation valuations = [] for _ in range(iterations): with project as p: for key in sim_dict: sim_fun = sim_dict[key] n_cashflows = len(p[key]) for n in range(n_cashflows): cf = p[key][n] cf.amount += sim_fun(cf.amount) valuations.append(valuator()) return valuations
[ 6738, 299, 32152, 13, 25120, 1330, 3210, 62, 11265, 198, 6738, 3146, 1330, 7913, 628, 198, 4299, 18640, 62, 20930, 7, 16302, 11, 985, 62, 11600, 11, 34820, 28, 9031, 11, 1188, 84, 1352, 28, 14202, 2599, 198, 220, 220, 220, 37227, 19...
2.441781
584
import logging from telegram.ext import CommandHandler logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 198, 6738, 573, 30536, 13, 2302, 1330, 9455, 25060, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 628, 628, 628 ]
3.3
30
# -*- coding: utf-8 -*- """ @file @brief Fonctions retournant des jeux de donnes. """ import os def get_data_folder(): """ Retourne le rpertoire de donnes inclus dans ce module. """ this = os.path.dirname(__file__) data = os.path.join(this, "data") return os.path.abspath(data)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 31, 7753, 198, 31, 65, 3796, 376, 261, 2733, 1005, 1798, 415, 748, 11223, 2821, 390, 836, 2516, 13, 198, 37811, 198, 11748, 28686, 628, 198, 4299, 651, 62,...
2.320611
131
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 628 ]
3.75
8
import os from os.path import join import traceback from bs4 import BeautifulSoup from nose.plugins import Plugin
[ 11748, 28686, 198, 6738, 28686, 13, 6978, 1330, 4654, 198, 11748, 12854, 1891, 198, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 9686, 13, 37390, 1330, 42636, 628 ]
3.741935
31
""" aiohttp-ultrajson ----------------- Integrates UltraJSON with your aiohttp application. """ from setuptools import setup setup( name='aiohttp-ultrajson', version='0.1.0', url='https://github.com/sunghyunzz/aiohttp-ultrajson', license='MIT', author='sunghyunzz', author_email='me@sunghyunzz.com', description='Integrates UltraJSON with your aiohttp application.', long_description=__doc__, py_modules=['aiohttp_ultrajson'], zip_safe=False, platforms='any', install_requires=[ 'aiohttp>2', 'ujson>=1.34' ], classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP', 'Framework :: AsyncIO' ] )
[ 37811, 198, 64, 952, 4023, 12, 586, 430, 17752, 198, 1783, 12, 198, 198, 34500, 9700, 14563, 40386, 351, 534, 257, 952, 4023, 3586, 13, 198, 37811, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 7, 198, 220, 220, 220, 14...
2.442543
409
n, m = map(int, input().split()) scores = list(map(int, input().split())) answers = list(map(int, input().split())) for i in range(n): actuals = list(map(int, input().split())) result = 0 for i, score in enumerate(scores): if actuals[i] == answers[i]: result += score print(result)
[ 77, 11, 285, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 198, 1416, 2850, 796, 1351, 7, 8899, 7, 600, 11, 5128, 22446, 35312, 3419, 4008, 198, 198, 504, 86, 364, 796, 1351, 7, 8899, 7, 600, 11, 5128, 22446, 35312, 3419,...
2.350365
137
""" Tools for network communication. """ import abc import io import json import socket import struct import sys import time import zlib import dh.ejson import dh.utils # NumPy is only needed for some parts and is optional try: import numpy as np except ImportError as e: _NUMPY_ERROR = e else: _NUMPY_ERROR = None ### #%% socket message types ### ### #%% extended socket with support for multiple message types ### ### #%% socket servers/clients ###
[ 37811, 198, 33637, 329, 3127, 6946, 13, 198, 37811, 198, 198, 11748, 450, 66, 198, 11748, 33245, 198, 11748, 33918, 198, 11748, 17802, 198, 11748, 2878, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 1976, 8019, 198, 198, 11748, 34590, ...
3.102564
156
from setuptools import setup setup( name = 'apache-replay', version = '0.0.3', url = 'https://github.com/danizen/apache-replay.git', author = 'Daniel Davis', author_email = 'dan@danizen.net', description = 'Facilitates replaying of Apache files in Common Log and Combined Log format', long_description = get_readme(), long_description_content_type='text/markdown; charset=UTF-8; variant=CommonMark', packages = ['apache_replay'], entry_points={ 'console_scripts': [ 'apache-replay=apache_replay.script:main', ] }, install_requires = ['attrs', 'requests'], tests_require = ['attrs', 'requests', 'pytest', 'pytest-pythonpath', 'pytest-cov', 'tox'], classifiers = [ 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Topic :: Software Development :: Testing :: Traffic Generation', ] )
[ 6738, 900, 37623, 10141, 1330, 9058, 628, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 796, 705, 43073, 12, 260, 1759, 3256, 198, 220, 220, 220, 2196, 796, 705, 15, 13, 15, 13, 18, 3256, 198, 220, 220, 220, 19016, 796, 705, 5450,...
2.659722
432
from distutils.core import setup setup( name='do_more', packages=['do_more'], version='0.1.0', description='A library enhancing pydoit features.', author='Duy Tin Truong', author_email='', url='https://github.com/duytintruong/do_more', download_url='https://github.com/duytintruong/do_more/archive/0.1.0.tar.gz', keywords=['pipeline', 'data', 'doit'], classifiers=[], install_requires=[ 'doit>=0.31.1', ], )
[ 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 4598, 62, 3549, 3256, 198, 220, 220, 220, 10392, 28, 17816, 4598, 62, 3549, 6, 4357, 198, 220, 220, 220, 2196, 11639, 15, 13, 16, 13, 15, 325...
2.32
200
import pandas as pd import numpy as np import elist.elist as elel import edict.edict as eded import tlist.tlist as tltl import copy __all__ = [ '_append_col', '_append_cols', '_append_row', '_append_rows', '_cn2clocs', '_col', '_cols', '_columns_map', '_crop', '_get_clocs', '_get_rlocs', '_getitem', '_index_map', '_insert_col', '_insert_cols', '_insert_row', '_insert_rows', '_ltd_index_first', '_ltd_index_last', '_name2ilocs', '_prepend_col', '_prepend_cols', '_prepend_row', '_prepend_rows', '_reindex_cols', '_reindex_rows', '_rename_cols', '_rename_rows', '_repl_col', '_repl_cols', '_repl_row', '_repl_rows', '_rmcol', '_rmcols', '_rmrow', '_rmrows', '_rn2rlocs', '_row', '_rows', '_setitem', '_subtb', '_swapcol', '_swaprow', '_transpose', '_fliplr', '_flipud' ] #all operations will generate a new Qtable(copy.deepcopy), and will not change the original Qtable #columns col-names-list no-duplicate-names-permitted #index rowname-names-list no-duplicate-names-permitted #df pd.DataFrame # index_map = _index_map(df) # columns_map = _columns_map(df) # _getitem(df,rowname,colname,rloc=0,cloc=0) # rloc relative-row-position # cloc relative-col-position #rn ---------------------rowname #cn ---------------------colname
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1288, 396, 13, 46331, 355, 9766, 75, 198, 11748, 1225, 713, 13, 276, 713, 355, 1225, 276, 198, 11748, 256, 4868, 13, 83, 4868, 355, 256, 2528, 75, 198,...
2.245315
587
from typing import List, Tuple import sentencepiece as spm import tensorflow as tf import tensorflow.keras as keras from npgru.predictor.category_predictor import CategoryPredictor from npgru.preprocessor.model_file import get_model_dir
[ 6738, 19720, 1330, 7343, 11, 309, 29291, 198, 198, 11748, 6827, 12239, 355, 599, 76, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 11192, 273, 11125, 13, 6122, 292, 355, 41927, 292, 198, 198, 6738, 299, 6024, 622, 13, 79, 174...
3.287671
73
# Generated by Django 3.1.6 on 2021-04-25 19:46 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 21, 319, 33448, 12, 3023, 12, 1495, 678, 25, 3510, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
import math line = raw_input().strip().split() N = int(line[0]) cap = float(line[1]) items = [] for _ in xrange(N): items.append(map(float, raw_input().split())) items = sorted(items, cmp=custcmp) answer = 0.0 index = 0 while cap > 0 and index < N: cur = items[index] to_add = min(cur[1], cap) answer += to_add*(cur[0]/cur[1]) cap -= to_add index+=1 print answer
[ 11748, 10688, 198, 198, 1370, 796, 8246, 62, 15414, 22446, 36311, 22446, 35312, 3419, 198, 198, 45, 796, 493, 7, 1370, 58, 15, 12962, 198, 11128, 796, 12178, 7, 1370, 58, 16, 12962, 198, 198, 23814, 796, 17635, 198, 198, 1640, 4808, ...
2.388535
157
from random import randint from time import sleep opcao = 123 cont = 0 while opcao != 0: print('-=-' * 20) print('Vou pensar em um nmero entre 0 e 10, quer tentar adivinhar?') print('-=-' * 20) print('\n[ 1 ] Sim [ 0 ] No') opcao = int(input('Escolha uma das opes acima\n>')) if opcao == 1: computador = randint(0, 10) # O computador sorteia um nmero de 0 a 10 usuario = int(input('\nEscolha um nmero entre 0 e 10: ').strip()) cont += 1 while usuario != computador: if usuario < computador: print('Mais... Tente novamente') else: print('Menos... Tente novamente') usuario = int(input('Insira outro nmero: ')) cont += 1 if usuario == computador: print('\nPARABNS. Voc ACERTOU!!!') print('Calculando a quantide de tentivas necessrias...') sleep(1) print('-=-' * 15) print(f'Voc precisou de {cont} tentativa(s) para acertar.') print('-=-'* 15) elif opcao == 0: print('Voc saiu do jogo.')
[ 6738, 4738, 1330, 43720, 600, 198, 6738, 640, 1330, 3993, 198, 198, 404, 66, 5488, 796, 17031, 198, 3642, 796, 657, 198, 4514, 1034, 66, 5488, 14512, 657, 25, 198, 220, 220, 220, 3601, 10786, 12, 10779, 6, 1635, 1160, 8, 198, 220, ...
1.97007
568
# -*- coding: utf-8 -*- """Demo153_RareCategories.ipynb ## Rare Categories - Labels - The number of labels in the dataset are different - __high cardinality__ refers to uniqueness of data values - The lower the cardinality, the more duplicated elements in a column - A column with the lowest possible cardinality would have the same value for every row - Highly cardinal variables dominate tree based algorithms - Labels may only be present in the training data set, but not in the test data set - Labels may appear in the test set that were not present in the training set __Tree methods are biased towards variables with many labels__ """ import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from google.colab import drive drive.mount('/content/gdrive') data = pd.read_csv("gdrive/My Drive/Colab Notebooks/FeatureEngineering/train.csv") cat_cols = ['Name', 'Sex', 'Ticket', 'Cabin', 'Embarked'] for i in cat_cols: print('Number of categories in the variable {}: {}'.format(i,len(data[i].unique()))) print('Total rows: {}'.format(len(data))) data['Sex'].value_counts() data['Cabin_processed'] = data['Cabin'].astype(str).str[0] data['Cabin_processed_X'] = data['Cabin'].astype(str).str[1] cat_cols = [ 'Sex', 'Embarked', 'Cabin_processed'] for i in cat_cols: sns.catplot(x=i, kind='count', data=data) data['Cabin_processed'].value_counts() / len(data) for i in cat_cols: sns.catplot(x=i,data=data, hue='Survived', kind='count', palette="ch:.25") """### Transform Rare Labels""" _temp = pd.Series(data['Cabin_processed'].value_counts() / len(data)) _temp.sort_values(ascending=False) _temp _temp = pd.Series(data['Cabin_processed'].value_counts() / len(data)) _temp for i in _labels: data['Cabin_processed'].replace(i, 'rare', inplace=True) _temp = pd.Series(data['Cabin_processed'].value_counts() / len(data)) _temp
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 11522, 78, 21395, 62, 26737, 34, 26129, 13, 541, 2047, 65, 198, 198, 2235, 14423, 45486, 198, 198, 12, 3498, 1424, 220, 198, 198, 12, 383, 1271, 286, 14722, 287...
2.872727
660
#!/usr/bin/env python import sys import os import argparse import adios import skel_settings import skel_bpls # Command line parsing is chained together. This is stage two. The first stage happens in ../bin/skel # TODO: Get rid of this in favor of chained version, above. if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 1822, 29572, 198, 198, 11748, 512, 4267, 198, 11748, 6146, 75, 62, 33692, 198, 11748, 6146, 75, 62, 65, 489, 82, 198, 198, 2, 9455, 1627, ...
2.929204
113
# Copyright 2021 LINE Corporation # # LINE Corporation 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: # # https://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.
[ 2, 220, 15069, 33448, 48920, 10501, 198, 2, 198, 2, 220, 48920, 10501, 16625, 428, 2393, 284, 345, 739, 262, 24843, 13789, 11, 198, 2, 220, 2196, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 407, 779, 428, 2393, 2845, 287, ...
3.834356
163
"""Provides a Preprocessed action for the Microsoft Visual Studio compilers. """ import os import SCons.Action import SCons.Util import preprocessed_builder # XXX These are internal to SCons and may change in the future...but it's unlikely from SCons.Tool.msvc import CSuffixes, CXXSuffixes, msvc_batch_key # TODO Contribute this back to SCons # XXX Adapted from SCons' msvc_output_flag def msvc_pp_output_flag(target, source, env, for_signature): """ Returns the correct /Fi flag for batching. If batching is disabled or there's only one source file, then we return an /Fi string that specifies the target explicitly. Otherwise, we return an /Fi string that just specifies the first target's directory (where the Visual C/C++ compiler will put the .i files). """ # TODO /Fi is not supported on Visual Studio 9.00 (2008) and earlier # https://msdn.microsoft.com/en-us/library/8z9z0bx6(v=vs.90).aspx # Fixing MSVC_BATCH mode. Previous if did not work when MSVC_BATCH # was set to False. This new version should work better. Removed # len(source)==1 as batch mode can compile only one file # (and it also fixed problem with compiling only one changed file # with batch mode enabled) if not 'MSVC_BATCH' in env or env.subst('$MSVC_BATCH') in ('0', 'False', '', None): return '/Fi$TARGET' else: # The Visual C/C++ compiler requires a \ at the end of the /Fi # option to indicate an output directory. We use os.sep here so # that the test(s) for this can be run on non-Windows systems # without having a hard-coded backslash mess up command-line # argument parsing. return '/Fi${TARGET.dir}' + os.sep CPreprocessedAction = SCons.Action.Action("$PPCCCOM", "$PPCCCOMSTR", batch_key=msvc_batch_key, targets='$CHANGED_TARGETS') CXXPreprocessedAction = SCons.Action.Action("$PPCXXCOM", "$PPCXXCOMSTR", batch_key=msvc_batch_key, targets='$CHANGED_TARGETS')
[ 37811, 15946, 1460, 257, 3771, 14681, 276, 2223, 329, 262, 5413, 15612, 11733, 552, 34393, 13, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 6374, 684, 13, 12502, 198, 11748, 6374, 684, 13, 18274, 346, 198, 11748, 662, 14681, 276, 62,...
2.514586
857
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 11748, 4818, 8079, 198, 6738, 5366, 13, 9945, 1330, 20613, 198, 6738, 5366, 13, 85, 17, 1330, 10011, 2611, 44, 4254, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198 ]
3.263158
38
import requests import json from os import environ from .models import Order, Piece from .BLConsul import BLConsul GATEWAY_PORT = environ.get("HAPROXY_PORT") GATEWAY_ADDRESS = environ.get("HAPROXY_IP") MACHINE_SERVICE = "machine" PAYMENT_SERVICE = "payment" DELIVERY_SERVICE = "delivery" AUTH_SERVICE = "auth" CA_CERT = environ.get("RABBITMQ_CA_CERT") consul = BLConsul.get_instance()
[ 11748, 7007, 198, 11748, 33918, 198, 6738, 28686, 1330, 551, 2268, 198, 6738, 764, 27530, 1330, 8284, 11, 27053, 198, 6738, 764, 33, 5639, 684, 377, 1330, 347, 5639, 684, 377, 198, 198, 38, 6158, 27285, 62, 15490, 796, 551, 2268, 13, ...
2.519481
154
# Generated by Django 3.1.7 on 2021-02-26 21:54 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 22, 319, 33448, 12, 2999, 12, 2075, 2310, 25, 4051, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
#################################################################################################### # # congruence_closure_module.py # # Authors: # Jeremy Avigad # Rob Lewis # # This module maintains a union-find structure for terms in Blackboard, which is currently only used # for congruence closure. It should perhaps be integrated differently into Blackboard. # # Contains a set for each equality class (up to constant multiples) of terms, and tracks which terms # appear as arguments to which function terms. # #################################################################################################### import polya.main.terms as terms import polya.main.messages as messages import polya.util.timer as timer import fractions import itertools
[ 29113, 29113, 29113, 4242, 198, 2, 198, 2, 369, 48929, 594, 62, 17966, 62, 21412, 13, 9078, 198, 2, 198, 2, 46665, 25, 198, 2, 11753, 5184, 328, 324, 198, 2, 3851, 10174, 198, 2, 198, 2, 770, 8265, 16047, 257, 6441, 12, 19796, 4...
4.828025
157
import pandas as pd import numpy as np import csv
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 21370, 198 ]
2.941176
17
import http.server import os import socketserver Handler = http.server.SimpleHTTPRequestHandler httpd = socketserver.TCPServer(("127.0.0.1", 8080), Handler) print("server:\thttp://127.0.0.1:8080\n\nlog:") httpd.serve_forever()
[ 11748, 2638, 13, 15388, 198, 11748, 28686, 198, 11748, 37037, 18497, 198, 198, 25060, 796, 2638, 13, 15388, 13, 26437, 40717, 18453, 25060, 198, 198, 4023, 67, 796, 37037, 18497, 13, 4825, 3705, 18497, 7, 7203, 16799, 13, 15, 13, 15, ...
2.655172
87
#!/usr/bin/env python3 import locale import sys from datetime import datetime as dt import pywikibot as pwb if __name__ == '__main__': main(sys.argv) # vim: set ts=4 sts=4 sw=4 tw=100 et:
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 36693, 198, 11748, 25064, 198, 198, 6738, 4818, 8079, 1330, 4818, 8079, 355, 288, 83, 198, 198, 11748, 12972, 20763, 571, 313, 355, 279, 39346, 628, 198, 198, 361, 1159...
2.426829
82
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> # pip install imapclient // pip install pyzmail >>> import imapclient >>> conn= imapclient.IMAPClient('imap.gmail.com', ssl=True) #True to use SSL encryption >>> conn.login('example2@mail.com','whatever') >>> conn.select_folter('INBOX',readonly= True) >>> UIDs = conn.search(['SINCE 20-Aug-2015']) #return a list of unique IDs for mails >>> rawMessage=conn.fetch(['mail int UID number to fetch'],['BODY[]','FLAGS']) >>> import pyzmail >>> pyzmail.PyzMessage.factory(rawMessage['same UID Number passed to rawMessage'][b'BODY']) >>> message=pyzmail.PyzMessage.factory(rawMessage['same UID Number passed to rawMessage'][b'BODY']) T >>> message.get_subject() #mail's subject >>> message.get_addresses('from') >>> message.get_addresses('to') >>> message.get_addresses('bcc') >>> message.text_part # return len and type >>> message.text_part #None if doesn't have html >>> message.html_part == None # True >>> message.text_part.get_payload().decode('UTF-8') >>> message.text_part.charset >>> conn.list_folders() >>> conn.select_folder('INBOX',readonly=False) #to modify the inbox >>> UIDS= conn.search(['ON 24-Aug-2015']) >>> conn.delete_messages(['UIDs to delete']) >>> ''' Full documentation ar: https://imapclient.readthedocs.org http://www.magiksys.net/pyzmail '''
[ 37906, 513, 13, 23, 13, 18, 357, 31499, 14, 85, 18, 13, 23, 13, 18, 25, 21, 69, 23, 66, 23, 2624, 11, 1737, 1511, 12131, 11, 2534, 25, 1238, 25, 1129, 8, 685, 5653, 34, 410, 13, 1129, 1495, 3933, 1643, 357, 24123, 15437, 319, ...
2.682226
557
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ import pickle, os, json import numpy as np import train from argparse import ArgumentParser from pprint import pprint anomaly_type_num = 10 n_neighbors = 5 # data_explore() # 0"cpu_saturation", # 1"io_saturation", # 2"database_backup", # 3"table_restore", # 4"poorly_physical_design", # 5"poorly_written_query", # 6"workload_spike", # 7"flush_log", # 8"vacuum_analyze", # 9"lock_contention", X_train_path = "./model/X_train.npy" y_train_path = "./model/y_train.npy" alpha_vec_path = "./model/anomaly_vec.npy" if __name__ == "__main__": parser = ArgumentParser(description="") parser.add_argument("--vec_path") args = parser.parse_args() X_train, y_train, alpha_vec = np.array([]), np.array([]), np.array([]) if os.path.isfile(X_train_path)==False or os.path.isfile(y_train_path)==False: train.generate_X_y() if os.path.isfile(alpha_vec_path)==False: train.generate_anomaly_alpha() X_train = np.load(X_train_path) y_train = np.load(y_train_path) alpha_vec = np.load(alpha_vec_path) new_vec = np.load(args.vec_path) root_cause_id = kNN(alpha_vec, X_train, y_train, new_vec) build_description(root_cause_id)
[ 15211, 198, 1635, 15069, 357, 66, 8, 12131, 43208, 21852, 1766, 1539, 43, 8671, 13, 198, 1635, 198, 1635, 1280, 35389, 1046, 318, 11971, 739, 17996, 272, 6599, 43, 410, 17, 13, 198, 1635, 921, 460, 779, 428, 3788, 1864, 284, 262, 28...
2.493544
697
import unittest from gilded_rose import Item, GildedRose if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 308, 46158, 62, 13698, 1330, 9097, 11, 402, 46158, 31087, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.658537
41
import random import string
[ 11748, 4738, 198, 11748, 4731, 628 ]
4.833333
6
from douyin.utils import fetch from douyin.config import hot_trend_url, common_headers from douyin.utils.tranform import data_to_music, data_to_topic from douyin.structures.hot import HotTrend from douyin.utils.common import parse_datetime # define trend query params query = { 'version_code': '2.9.1', 'count': '10', }
[ 6738, 2255, 88, 259, 13, 26791, 1330, 21207, 198, 6738, 2255, 88, 259, 13, 11250, 1330, 3024, 62, 83, 10920, 62, 6371, 11, 2219, 62, 50145, 198, 6738, 2255, 88, 259, 13, 26791, 13, 2213, 272, 687, 1330, 1366, 62, 1462, 62, 28965, ...
2.853448
116
# Import the hashing Library import hashlib # Get the string as input word = input("Enter the word for Hashing: ") # Get the hashing hashed_code = hashlib.sha256(word.encode()) final = hashed_code.hexdigest() # Print the result print("Hashed with 256 bit: ") print(final)
[ 2, 17267, 262, 49544, 10074, 201, 198, 11748, 12234, 8019, 201, 198, 201, 198, 2, 3497, 262, 4731, 355, 5128, 201, 198, 4775, 796, 5128, 7203, 17469, 262, 1573, 329, 367, 2140, 25, 366, 8, 201, 198, 201, 198, 2, 3497, 262, 49544, ...
2.823529
102
from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.dispatch import receiver from django.conf import settings from taggit.managers import TaggableManager import requests
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 198, 6738, 42625, 14208, 13, 6381, 17147, 1330, 9733, 198, 6738, 42625, ...
3.71875
64
""" Vernam Cipher Benjamin D. Miller Takes a key, and a message Encripts the message using the key """ """ * TEST CASES * """ vernam(9,"hello world") vernam(14,"TEST_CASE 34!") vernam("test","test")
[ 37811, 201, 198, 53, 1142, 321, 44334, 201, 198, 11696, 13337, 360, 13, 7920, 201, 198, 51, 1124, 257, 1994, 11, 290, 257, 3275, 201, 198, 4834, 6519, 82, 262, 3275, 1262, 262, 1994, 201, 198, 37811, 201, 198, 201, 198, 37811, 1635,...
2.511905
84
from datetime import datetime as d
[ 6738, 4818, 8079, 1330, 4818, 8079, 355, 288, 198 ]
3.888889
9
from fineract.objects.currency import Currency from fineract.objects.fineract_object import FineractObject from fineract.objects.types import ChargeTimeType, ChargeAppliesTo, ChargeCalculationType, ChargePaymentMode
[ 6738, 38575, 529, 13, 48205, 13, 34415, 1330, 20113, 198, 6738, 38575, 529, 13, 48205, 13, 69, 7274, 529, 62, 15252, 1330, 4463, 263, 529, 10267, 198, 6738, 38575, 529, 13, 48205, 13, 19199, 1330, 20260, 7575, 6030, 11, 20260, 4677, 1...
3.928571
56
from heapq import heapify, heappop, heappush if __name__ == "__main__": main()
[ 6738, 24575, 80, 1330, 24575, 1958, 11, 339, 1324, 404, 11, 339, 1324, 1530, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419 ]
2.59375
32
activate_this = '/var/www/html/venv/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) import sys, os, logging from flask_apscheduler import APScheduler sys.path.insert(0, 'var/www/html/StuffMart/vagrant/catalog') logging.basicConfig(stream=sys.stderr) from server import flask as application application.secret_key = 'qPHE[Cht}*kSCVango3i' application.config['APP_DIR'] = os.path.abspath(os.path.dirname(__file__)) application.config['WHOOSH_BASE'] = 'server/whoosh' application.config['PRODUCT_IMAGES_FOLDER'] = 'vagrant/catalog/server/static/product_images/' application.config['JOBS'] = [ { 'id': 'buildNewlyAddedRSSFeed', 'func': 'server.views:buildNewlyAddedRSSFeed', 'trigger': 'interval', 'seconds': (60*60) }, { 'id': 'buildNewlyAddedAtomFeed', 'func': 'server.views:buildNewlyAddedAtomFeed', 'trigger': 'interval', 'seconds': (60*60) }, { 'id': 'buildNewlyAddedRSSFeedAtStartup', 'func': 'server.views:buildNewlyAddedRSSFeed' }, { 'id': 'buildNewlyAddedAtomFeedAtStartup', 'func': 'server.views:buildNewlyAddedAtomFeed' } ] application.config['SCHEDULER_VIEWS_ENABLED'] = True application.debug = True scheduler = APScheduler() scheduler.init_app(application) scheduler.start()
[ 39022, 62, 5661, 796, 31051, 7785, 14, 2503, 14, 6494, 14, 574, 85, 14, 8800, 14, 39022, 62, 5661, 13, 9078, 6, 198, 18558, 7753, 7, 39022, 62, 5661, 11, 8633, 7, 834, 7753, 834, 28, 39022, 62, 5661, 4008, 198, 198, 11748, 25064, ...
2.208978
646
import unittest from unittest.mock import patch, Mock import pandas as pd from pandas.testing import assert_frame_equal from parameterized import parameterized from dgraphpandas.strategies.horizontal import horizontal_transform
[ 11748, 555, 715, 395, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 11, 44123, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 19798, 292, 13, 33407, 1330, 6818, 62, 14535, 62, 40496, 198, 6738, 11507, 1143, 1330, 11507, ...
3.666667
63
#!/usr/bin/python # This is client.py file import socket # Import socket module s = socket.socket() # Create a socket object #host = socket.gethostname() # Get local machine name host = socket.gethostbyname("localhost") print host port = 53 # Reserve a port for your service. s.connect((host, port)) print s.recv(1024) s.close
[ 2, 48443, 14629, 14, 8800, 14, 29412, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1303, 770, 318, 5456, 13, 9078, 2393, 198, 198, 11748, 17802, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1303, 1726...
2.536913
149
import os import shutil from flask import render_template, redirect, url_for, request from werkzeug.utils import secure_filename from config import Config from application import app from application.model import Model
[ 11748, 28686, 198, 11748, 4423, 346, 198, 6738, 42903, 1330, 8543, 62, 28243, 11, 18941, 11, 19016, 62, 1640, 11, 2581, 198, 6738, 266, 9587, 2736, 1018, 13, 26791, 1330, 5713, 62, 34345, 198, 6738, 4566, 1330, 17056, 198, 6738, 3586, ...
4.226415
53
""" Tests onnxml Imputer converter """ import unittest import warnings import numpy as np import torch from sklearn.impute import SimpleImputer from hummingbird.ml._utils import onnx_ml_tools_installed, onnx_runtime_installed, lightgbm_installed from hummingbird.ml import convert if onnx_runtime_installed(): import onnxruntime as ort if onnx_ml_tools_installed(): from onnxmltools import convert_sklearn from onnxmltools.convert.common.data_types import FloatTensorType as FloatTensorType_onnx if __name__ == "__main__": unittest.main()
[ 37811, 198, 51, 3558, 319, 77, 19875, 1846, 10549, 38394, 198, 37811, 198, 11748, 555, 715, 395, 198, 11748, 14601, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 1341, 35720, 13, 11011, 1133, 1330, 17427, 3546, ...
2.937173
191
import configparser, os, glob, csv, json, hashlib, time import pandas as pd import psycopg2 from pprint import pprint from rs_sql_queries import staging_events_insert, staging_songs_insert from rs_sql_queries import insert_table_queries import boto3 from botocore import UNSIGNED from botocore.config import Config DEND_BUCKET='udacity-dend' # global lookup table NAME_TO_GENDER = {} def load_gender_lookup(): """Load lookup dictionary to find gender given a name. """ base_path = os.getcwd() + '/data/names' for root, dirs, files in os.walk(base_path): file_paths = glob.glob(os.path.join(root,'*.txt')) for file_path in file_paths: print('names: %s' % file_path) with open(file_path) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: # pprint(row) NAME_TO_GENDER[row[0]] = row[1] # pprint(NAME_TO_GENDER) True def get_object_paths(s3, bucket, prefix): """List objects in S3 bucket with given prefix. Uses paginator to ensure a complete list of object paths is returned. """ # r1 = s3.list_objects(Bucket=DEND_BUCKET, Prefix=prefix) # r2 = list(map(lambda obj: obj['Key'], r1['Contents'])) # r3 = list(filter(lambda str: str.endswith('.json'), r2)) # s3 client does not need to be closed object_paths = [] paginator = s3.get_paginator('list_objects') pages = paginator.paginate(Bucket=bucket, Prefix=prefix) for page in pages: # print("len(page['Contents'])=" + str(len(page['Contents']))) r1 = list(map(lambda obj: obj['Key'], page['Contents'])) r2 = list(filter(lambda str: str.endswith('.json'), r1)) object_paths.extend(r2) print('%s/%s total object paths = %d' % (bucket, prefix, len(object_paths))) time.sleep(2) return object_paths def load_staging_log_data(cur, conn): """Load song-play event records into s_songplay_event table. """ # import pdb; pdb.set_trace() # load log_data (events) into s_event table s3 = boto3.client('s3', config=Config(signature_version=UNSIGNED)) file_paths = get_object_paths(s3, DEND_BUCKET, 'log_data') pprint(file_paths) for file_path in file_paths: sql = str(staging_events_insert) print('log_data: %s' % file_path) obj1 = s3.get_object(Bucket='udacity-dend', Key=file_path) str1 = obj1['Body'].read().decode('utf-8').strip() df = pd.read_json(str1, lines=True) df = df[df.page == 'NextSong'] df['timestamp'] = pd.to_datetime(df['ts'], unit='ms') df['year'] = df['timestamp'].dt.year df['week'] = df['timestamp'].dt.weekofyear df['month'] = df['timestamp'].dt.month df['day'] = df['timestamp'].dt.day df['hour'] = df['timestamp'].dt.hour df['weekday'] = df['timestamp'].dt.weekday # pprint(df) for index, row in df.iterrows(): # create a sha256 hash for event's unique id event_id = hashlib.sha256((str(row.userId) + ' ' + str(row.sessionId) + ' ' + row.timestamp.strftime('%Y%m%d%H%M') + ' ' + row.song).encode('utf-8')).hexdigest() str1 = ("(" + "'" + event_id + "', " + "'" + row.artist.replace("'", "''") + "', " + "'" + row.auth + "', " + "'" + row.firstName.replace("'", "''") + "', " + "" + str(row.itemInSession) + ", " + "'" + row.lastName.replace("'", "''") + "', " + "'" + NAME_TO_GENDER[row.firstName] + "', " + "" + str(row.length) + ", " + "'" + row.level + "', " + "'" + row.location.replace("'", "''") + "', " + "'" + row.method + "', " + "'" + row.page + "', " + "'" + str(row.registration) + "', " + "'" + str(row.sessionId) + "', " + "'" + row.song.replace("'", "''") + "', " + "'" + str(row.status) + "', " + "'" + row.timestamp.strftime('%Y-%m-%d %H') + "', " + "" + str(row.year) + ", " + "" + str(row.week) + ", " + "" + str(row.month) + ", " + "" + str(row.day) + ", " + "" + str(row.hour) + ", " + "" + str(row.weekday) + ", " + "'" + row.userAgent.replace("'", "''") + "', " + "'" + str(row.userId) + "'" + "),\n") sql += str1 sql = ''.join(sql).strip()[:-1] + ';' # print(sql) # import pdb; pdb.set_trace() cur.execute(sql) conn.commit() def load_staging_song_data(cur, conn): """Load song records into s_song staging table. """ sql = str(staging_songs_insert) s3 = boto3.client('s3', config=Config(signature_version=UNSIGNED)) file_paths = get_object_paths(s3, DEND_BUCKET, 'song_data') pprint(file_paths) for file_path in file_paths: print('song_data: %s' % file_path) obj1 = s3.get_object(Bucket='udacity-dend', Key=file_path) str1 = obj1['Body'].read().decode('utf-8').strip() data = json.loads(str1) if data['year'] == 0: data['year'] = None # fix link string... if str(data['artist_location']).startswith('<a'): data['artist_location'] = None # pprint(data) str2 = ("(" + "'" + data['artist_id'] + "', " + "" + (str(data['artist_latitude']) if not data['artist_latitude'] == None else 'null') + ", " + "'" + str(data['artist_location']).replace("'", "''") + "', " + "" + (str(data['artist_longitude']) if not data['artist_longitude'] == None else 'null') + ", " + "'" + str(data['artist_name']).replace("'", "''") + "', " + "" + str(data['duration']) + ", " + "" + str(data['num_songs']) + ", " + "'" + data['song_id'] + "', " + "'" + str(data['title']).replace("'", "''") + "', " + "" + (str(data['year']) if not data['year'] == None else 'null') + "" + "),\n") sql += str2 # print(str2) # batch inserts at 8k character threshold if len(sql) > 8192: print(' 8k insert...') sql = ''.join(sql).strip()[:-1] + ';' cur.execute(sql) conn.commit() sql = str(staging_songs_insert) print('last insert...') sql = ''.join(sql).strip()[:-1] + ';' # print(sql) # import pdb; pdb.set_trace() cur.execute(sql) conn.commit() def insert_tables(cur, conn): """Populate staging, dimension and fact tables. The fact table must be the last item in the query list. """ for query in insert_table_queries: if query.strip() != "": pprint(query) cur.execute(query) conn.commit() def main(): """Run Redshift ETL for staging, dimension and fact tables. """ config = configparser.ConfigParser() config.read('rs_dwh.cfg') conn = psycopg2.connect("host={} dbname={} user={} password={} port={}".format(*config['CLUSTER'].values())) cur = conn.cursor() load_gender_lookup() load_staging_tables(cur, conn) insert_tables(cur, conn) conn.close() if __name__ == "__main__": main()
[ 11748, 4566, 48610, 11, 28686, 11, 15095, 11, 269, 21370, 11, 33918, 11, 12234, 8019, 11, 640, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 17331, 22163, 70, 17, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 6738, 44608, 62, 25410,...
2.07507
3,570
#!/usr/bin/python import json, urllib2, datetime from sqlite3 import dbapi2 as sqlite3 # zip codes to log zipcodes = ['07740','11210','33139','90210'] # configuration DATABASE = '../db/weather.db' SECRET_KEY = 'hackerati' DEBUG = True # open database db = sqlite3.connect(DATABASE) for zipcode in zipcodes: # pull weather from API weather_api = urllib2.urlopen('http://api.openweathermap.org/data/2.5/weather?zip='+zipcode+',us') weather_data = weather_api.read() weather_api.close() weather = json.loads(weather_data) # convert from kelvin to fahrenheit temp_val = (((weather['main']['temp']-273.15)*9)/5)+32 humidity_val = weather['main']['humidity'] print zipcode, print temp_val, print humidity_val # insert db entry db.execute('insert into weather (zipcode, temp, humidity, stamp) values (?, ?, ?, ?)', [zipcode, int(temp_val), int(humidity_val), datetime.datetime.utcnow()]) db.commit() # close database db.close()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 33918, 11, 2956, 297, 571, 17, 11, 4818, 8079, 198, 6738, 44161, 578, 18, 1330, 20613, 15042, 17, 355, 44161, 578, 18, 198, 198, 2, 19974, 12416, 284, 2604, 198, 13344, 40148, 7...
2.549618
393
from git import Repo from git_inspector import find_git_directories
[ 198, 6738, 17606, 1330, 1432, 78, 198, 6738, 17606, 62, 1040, 806, 273, 1330, 1064, 62, 18300, 62, 12942, 1749, 628, 628, 198 ]
3.173913
23
#!/usr/bin/env python3 try: from gelpia import bin_dir except: print("gelpia not found, gaol_repl must be in your PATH\n") bin_dir = "" from pass_utils import * from output_flatten import flatten import re import sys import subprocess import os.path as path if __name__ == "__main__": try: runmain() except KeyboardInterrupt: print("\nGoodbye")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 28311, 25, 198, 220, 422, 20383, 79, 544, 1330, 9874, 62, 15908, 198, 16341, 25, 198, 220, 3601, 7203, 25280, 79, 544, 407, 1043, 11, 31986, 349, 62, 35666, 1276, 307, 287, ...
2.764706
136
import os from pip.req import parse_requirements from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # parse_requirements() returns generator of pip.req.InstallRequirement objects install_reqs = parse_requirements( os.path.join(os.path.dirname(__file__), 'requirements.txt'), session=False) reqs = [str(ir.req) for ir in install_reqs] # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-estimators', version='0.2.1', packages=find_packages(), include_package_data=True, install_requires=reqs, license='MIT License', # example license description='A django model to persist and track machine learning models', long_description=README, url='https://github.com/fridiculous/django-estimators', author='Simon Frid', author_email='simon.frid@gmail.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.9', 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', # example license 'Operating System :: OS Independent', 'Programming Language :: Python', # Replace these appropriately if you are stuck on Python 2. 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Version Control', ], keywords='''scikit-learn, sklearn, machine learning, artificial intelligence, ml, ai, estimators, version, versioning, benchmark, persist, storage, track, models, repository, evaluation, workflow''' )
[ 11748, 28686, 198, 198, 6738, 7347, 13, 42180, 1330, 21136, 62, 8897, 18883, 198, 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 198, 4480, 1280, 7, 418, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834...
2.836412
758
import csv import ipaddress import logging.handlers import sys import argparse try: import vat.vectra as vectra import requests except Exception as error: print('\nMissing import requirements: {}\n'.format(str(error))) sys.exit(0) LOG = logging.getLogger(__name__) INVALID_CHARS = ['~', '#', '$', '^', '+', '=', '<', '>', '?', ';'] SUB_CHAR = '_' # Suppress Detect certificate warning requests.packages.urllib3.disable_warnings() def ip_subnet(subnet_string): """ Called with string that represents an IP subnet with CIDR or netmask in dotted decimal format Validates string represents valid subnet and removes host bits Returns string representation of subnet in CIDR format :param subnet_string: string representing subnet in CIDR w.x.y.z/n or netmask w.x.y.z/aa.bb.cc.dd format :return: returns string representation of subnet in CIDR format """ try: ipaddress.IPv4Network(subnet_string) except (ipaddress.AddressValueError, ipaddress.NetmaskValueError) as error: LOG.info('Subnet {} format error, {}'.format(subnet_string, error)) return except ValueError as error: LOG.info('{}, removing host bits'.format(error)) subnet = ipaddress.IPv4Network(subnet_string, strict=False) return str(subnet) def sub_bad_chars(string, sub=SUB_CHAR): """ Substitute unsupported characters in string representing group :param string: original string :param sub: substitution character, default defined in SUB_CHAR :return: returns the original string with any illegal characters substituted """ for bad_char in INVALID_CHARS: string = string.replace(bad_char, sub) return string def group_exists(group_name, brain): """ Determines if group exists Called with initialized vectra client and name of group :param group_name: group name :param brain: initialized Vectra Client object :return: True if group exists, False otherwise """ group_iterator = brain.get_all_groups(name=group_name) for item in group_iterator: if item.json()['count'] > 0: for group in item.json()['results']: if group['name'] == group_name: return {'name': group['name'], 'id': group['id']} return False def create_group(name, subnet, brain, descr=''): """ Creates group and adds supplied subnet, and description if supplied :param name: group name :param subnet: CIDR subnet string :param brain: initialized Vectra Client object :param descr: group description, optional """ if bool(descr): brain.create_group(name=name, description=descr, type='ip', members=list(subnet)) else: brain.create_group(name=name, type='ip', members=list(subnet)) def update_group(grp_id, subnet, brain, descr=''): """ Updates existing group with supplied subnet, and description if supplied :param grp_id: group ID :param subnet: CIDR subnet string :param brain: initialized Vectra Client object :param descr: group description, optional """ if bool(descr): brain.update_group(group_id=grp_id, description=descr, members=subnet, append=True) else: brain.update_group(group_id=grp_id, members=subnet, append=True) def main(): """ Supplied with valid CSV file containing 3 or 4 columns of data, iterates over rows and creates or updates groups Supports CSV files with following format examples with or without header row group 1,192.168.1.0/255.255.255.0,group1 description group 2,10.1.1.0/24,group2 description """ args = obtain_args() sub_char = args.sub_char if args.sub_char else SUB_CHAR log_level = logging.DEBUG if args.verbose else logging.INFO logging.basicConfig(level=log_level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') if len(sys.argv) == 1: print('Run python3 ip_group.py -h for help.') sys.exit() file = args.file with open(file, newline='') as csvfile: vc = vectra.VectraClientV2_1(url='https://' + args.brain, token=args.token, verify=False) reader = csv.reader(csvfile) for row in reader: if len(row) < 3 or len(row) > 4: LOG.info('Invalid number of columns in row, skipping') continue if len(row) == 4: LOG.debug('Number of rows 4: {}'.format(len(row))) subnet = ip_subnet('{}/{}'.format(row[1], row[2])) description = sub_bad_chars(row[3], sub_char) elif len(row) == 3: LOG.debug('Number of rows 3: {}'.format(len(row))) subnet = ip_subnet(row[1]) description = sub_bad_chars(row[2], sub_char) group_name = sub_bad_chars(row[0], sub_char) if subnet is not None: """group_obj False or {'name': 'somename', 'id':'123'}""" group_obj = group_exists(group_name, vc) if not group_obj: # Group does not exist, creating LOG.info('Group does not exist, creating. group:{}, subnet:{}, description:{}'.format( group_name, subnet, description)) create_group(group_name, [str(subnet)], vc, description) else: LOG.info('Group exists, updating. group:{}, subnet:{}, description:{}'.format( group_name, subnet, description)) update_group(group_obj['id'], [str(subnet)], vc, description) else: LOG.info('Invalid subnet, skipping') if __name__ == '__main__': main()
[ 11748, 269, 21370, 198, 11748, 20966, 21975, 198, 11748, 18931, 13, 4993, 8116, 198, 11748, 25064, 198, 11748, 1822, 29572, 628, 198, 28311, 25, 198, 220, 220, 220, 1330, 410, 265, 13, 303, 310, 430, 355, 1569, 310, 430, 198, 220, 220...
2.441603
2,346
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Python # # # Number / String / Tuple # List / Dictionary / Set # Number # Int IntNum = 100 # Float FloatNum = 100.10 # Boolean // True:1 False:0 BoolNum = True # Complex ComplexNum = 1.00j # String Str = "" # List List = ['a', 'b', 1, 2] # Tuple Tup = ('a', 'b', 1, 2) # Set Set = {'a', 'b', 1, 2} # Dictionary Dict = {'key1': 'value1', 'key2': 'value2'}
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 11361, 198, 2, 220, 198, 2, 220, 220, 198, 198, 2, 220, 7913, 1220, 10903, 1220, 309, 29291, 198, 2, ...
2.07109
211
"""Generate Docs for ThreatConnect API""" # standard library import importlib import sys from abc import ABC from typing import Any, Optional # first-party from tcex.api.tc.v3._gen._gen_abc import GenerateABC
[ 37811, 8645, 378, 14432, 82, 329, 25238, 13313, 7824, 37811, 198, 2, 3210, 5888, 198, 11748, 1330, 8019, 198, 11748, 25064, 198, 6738, 450, 66, 1330, 9738, 198, 6738, 19720, 1330, 4377, 11, 32233, 198, 198, 2, 717, 12, 10608, 198, 673...
3.349206
63
#!/usr/bin/python sootv = {} #Read file sootvetstviya for l in open ("filesootv"): data = l.strip().split("\t") if data[0] not in sootv: sootv[data[0]] = data[1] #Read FinalReport file for l in open('Ire30_GP'): data = l.strip().split("\t") if data[1] in sootv: print(data[0]+"\t"+sootv[data[1]]+"\t"+data[2]+"\t"+data[3]+"\t"+"\t"+data[4]+"\t"+data[5])
[ 2, 48443, 14629, 14, 8800, 14, 29412, 201, 198, 201, 198, 568, 313, 85, 796, 23884, 201, 198, 201, 198, 2, 5569, 2393, 523, 313, 16809, 301, 8903, 3972, 201, 198, 1640, 300, 287, 1280, 5855, 16624, 1025, 85, 1, 2599, 201, 198, 197...
1.872549
204
# Quiz01_1.py items = {"":1000,"":900,"":500,"":700,"":800} print("=== ====") print("[][][][][] ") print(" --> ) , ") # item, price item = input() # , items2 = item.strip().split(',') price = pItems(*items2,**items) print(" : {0} ".format(price) )
[ 2, 2264, 528, 486, 62, 16, 13, 9078, 198, 220, 220, 220, 220, 198, 23814, 796, 19779, 1298, 12825, 553, 1298, 12865, 553, 1298, 4059, 553, 1298, 9879, 553, 1298, 7410, 92, 198, 198, 4798, 7203, 18604, 220, 220, 220, 24844, 2625, 8, ...
2.228814
118
""" Copyright 2019 Sangkug Lym Copyright 2019 The University of Texas at Austin Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os from .arch_utils import layerUtil arch = {} arch[0] = {'name':'conv1', 'kernel_size':11, 'stride':4, 'padding':5, 'bias':True} arch[1] = {'name':'conv2', 'kernel_size':5, 'stride':1, 'padding':2, 'bias':True} arch[2] = {'name':'conv3', 'kernel_size':3, 'stride':1, 'padding':1, 'bias':True} arch[3] = {'name':'conv4', 'kernel_size':3, 'stride':1, 'padding':1, 'bias':True} arch[4] = {'name':'conv5', 'kernel_size':3, 'stride':1, 'padding':1, 'bias':True} arch[5] = {'name':'pool', 'kernel_size':2, 'stride':2} arch[6] = {'name':'relu'} arch[7] = {'name':'fc', 'out_chs':'num_classes'}
[ 37811, 198, 15069, 13130, 30043, 74, 1018, 406, 4948, 198, 15069, 13130, 383, 2059, 286, 3936, 379, 9533, 628, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 345, 743, 407, 779, 428, 2393, 28...
2.866197
426
# -*- coding: utf-8 -*- import numpy import csv import re, nltk from sklearn.feature_extraction.text import CountVectorizer from nltk.stem.porter import PorterStemmer from sklearn.linear_model import LogisticRegression # from sklearn.cross_validation import train_test_split from sklearn.externals import joblib from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB if __name__ == "__main__": train_data = { "text": [], "sentiment": [] } raw_count = 0 with open('Sentiment Analysis Dataset.csv', 'r') as csvfile: csvreader = csv.reader(csvfile) headers = next(csvreader, None) for line in csvreader: train_data["text"].append(line[3].strip()) train_data["sentiment"].append(int(line[1])) # raw_count += 1 # if raw_count >= 1000: # break raw_count = 0 with open('training.1600000.processed.noemoticon.csv', 'r') as csvfile: csvreader = csv.reader(csvfile) for line in csvreader: try: train_data["text"].append(line[5].strip()) except Exception as e: print e print "line", line print line[5] exit(0) if int(line[0]) == 4: train_data["sentiment"].append(1) else: train_data["sentiment"].append(0) # raw_count += 1 # if raw_count >= 1000: # break print train_data["text"][:3] print train_data["sentiment"][:3] print numpy.unique(numpy.array(train_data["sentiment"])) print "data extracted" # exit(0) stemmer = PorterStemmer() vectorizer = CountVectorizer( analyzer = 'word', tokenizer = tokenize, lowercase = True, stop_words = 'english', max_features = 100, encoding='utf-8' ) print "creating corpus_data_features" X_train_counts = vectorizer.fit_transform(train_data["text"]) # tf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts) # X_train_tf = tf_transformer.transform(X_train_counts) tfidf_transformer = TfidfTransformer() X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) print "X_train_tfidf.shape", X_train_tfidf.shape print "training" model = MultinomialNB().fit(X_train_tfidf, train_data["sentiment"]) joblib.dump(model, 'twitter_MultinomialNB_model.pkl', compress=1) joblib.dump(vectorizer, 'vectorizer.pkl', compress=1) joblib.dump(tfidf_transformer, 'tfidf_transformer.pkl', compress=1) docs_new = ['God is love', 'OpenGL on the GPU is fast', "it was a very fantastic experience"] X_new_counts = vectorizer.transform(docs_new) X_new_tfidf = tfidf_transformer.transform(X_new_counts) predicted = model.predict(X_new_tfidf) print "predicted", predicted print model.score(X_train_tfidf, train_data["sentiment"])
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 299, 32152, 198, 11748, 269, 21370, 198, 11748, 302, 11, 299, 2528, 74, 198, 6738, 1341, 35720, 13, 30053, 62, 2302, 7861, 13, 5239, 1330, 2764, 38469, 7509,...
2.470211
1,091
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import sys import os from PIL import Image import numpy as np size = None matrix_x = None for image in os.listdir('./washington'): try: print(image) with Image.open(os.path.join('./washington',image)) as im: imgVector = np.array(list(im.getdata())) imgVector = imgVector.reshape(1, imgVector.shape[0]) try: matrix_x = np.vstack((matrix_x, imgVector)) except: matrix_x = imgVector except FileNotFoundError as e: sys.exit("Error : file not found") #matrix_x = np.array([[0,1,1,1], #[0,0,1,0], #[0,0,0,1] #]) #mean vector K = matrix_x.shape[1] print('K', K) nb = matrix_x.shape[0] print('nb', nb) mx = np.zeros((nb, 1)) for x in range(K): for y in range(nb): mx[y] += matrix_x[y, x] mx = mx/K #covar matrix cx = np.zeros((nb,nb)) for x in range(K): tmp = (matrix_x[:,x]) tmp = tmp.reshape(tmp.shape[0],1) cx += np.dot(tmp,tmp.T) - np.dot(mx,mx.T) cx = cx/K eigenvalues, eigenvectors = np.linalg.eig(cx) #tri eival = np.zeros(eigenvalues.shape) eivec = np.zeros(eigenvectors.shape) j = 0 for _ in range(nb): maxval = eigenvalues.max() for i in range(eigenvalues.shape[0]): val = eigenvalues[i] if val == maxval: eival[j] = val eigenvalues[i] = 0 eivec[j] = eigenvectors[i] j += 1 break #pruning eivec pruning = 2 eivec = eivec[:pruning,:] print(eivec) matrix_y = np.zeros((pruning, matrix_x.shape[1])) for i in range(K): tmp = (matrix_x[:,i]).reshape(nb, 1) truc = np.dot(eivec,(tmp-mx)) matrix_y[:, i] = truc.reshape(truc.shape[0]) #reconstruction matrix_x2 = np.zeros(matrix_x.shape) for i in range(K): tmp = (matrix_y[:,i]) tmp = tmp.reshape(tmp.shape[0], 1) matrix_x2[:, i] = np.array((np.dot(eivec.T,tmp)+mx).reshape(nb)) data = np.vsplit(matrix_x2, 6) for i,item in enumerate(data): item = list(rescale(item.reshape(item.shape[1]))) newIm = Image.new(im.mode, im.size) newIm.putdata(item) newIm.show() diff = item - matrix_x[i] epsilon = 0.1 print(diff) for j,val in enumerate(diff): if abs(val) < epsilon: diff[j] = 0 print(diff) diff = rescale(diff) newIm = Image.new(im.mode, im.size) newIm.putdata(list(diff)) newIm.show()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 11748, 25064, 198, 11748, 28686, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 299, 32152, 355, 45941, 198, 198, 7857, ...
1.912105
1,297
import boto3 import sys if __name__ == "__main__": if len(sys.argv) > 2: print("[ERROR] You have passed in an invalid target-id, example target-id is ou-zhz0-prn5fmbc") sys.exit() else: print("[INFO] Valid argument detected, proceeding with account migration") destination_id = str(sys.argv[1]) # Gather source ids with open("source_ids.txt") as f: source_ids = f.read().splitlines() l = len(source_ids) print("[INFO] Detected {} source id(s) to be migrated".format(l)) print("[INFO] Beginning processing of source id(s)...") # Process the source ids for migration client = boto3.client("organizations") for source_id in source_ids: print("[INFO] Now attempting to move source id: {}".format(source_id)) get_parent = client.list_parents(ChildId=source_id) parent_id = get_parent["Parents"][0]["Id"] try: response = client.move_account( AccountId=source_id, SourceParentId=parent_id, DestinationParentId=destination_id ) print( "[INFO] Successfully moved source id: {} to target id: {}".format( source_id, destination_id ) ) except client.exceptions.DuplicateAccountException: print( "[NOTICE] Source id: {} is already migrated to target id: {}".format( source_id, destination_id ) ) print("[INFO] Successfully migrated required accounts.")
[ 11748, 275, 2069, 18, 198, 11748, 25064, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 628, 220, 220, 220, 611, 18896, 7, 17597, 13, 853, 85, 8, 1875, 362, 25, 198, 220, 220, 220, 220, 220, 220, 220, 3601, 720...
2.109434
795
#!/usr/bin/env python3 from sys import argv from sys import stdin from sys import stdout alp = len(argv) if alp > 1 and argv[1] == "--version": print ('version 0.1') quit() if alp > 1 and argv[1] == "--help": print ('ctrl+d to quit') quit() print('todo')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 25064, 1330, 1822, 85, 198, 6738, 25064, 1330, 14367, 259, 198, 6738, 25064, 1330, 14367, 448, 198, 198, 282, 79, 796, 18896, 7, 853, 85, 8, 198, 361, 435, 79, 1875, 352, ...
2.382609
115
# https://rosalind.info/problems/rna/ # Transcribing DNA into RNA exercise from ROSALIND DNA = "ACAACAAAGGATCGGCGAGGAGCTGGTTAATCTCGATTCTAACAAAGGCCTCTTGAGTGACATAAAGTTGCTGTTCGGCCCCCGTTGCAGCCAAGCCTAGACTCGAGCGGGGTCTACCTCTGTAAACCCAAGTCGCAGGCCAAGGGCATTTTAACCCCCAAAGTTAGATACGTCGATTGAGTGCGCACTCCCTAACTTCAGACAGGATGGCGCTTAGCACTGGTTAGGTCCCTCATTAGAGGCTTACACGGGACCCCAGCGATCTGCAGGGCTACATGAACCGGCGATACCTGCAACCCTTCACGTGTGGTGCGAGTGCTGGACCCATGCACGGGCCCAAGAAGCGGGAGCACCCACGGCCTGAGCCTGTAGCTTCATACTTAGAGTAACACCTATAAGTTCTCCGTTTCACGTTATTTTACTTAACAAAGCACATCGATGGGCGGACGTACGAGCCGAGCCTCGTCCCCATTTACTCAAGTAACCAAGTCATTGTTTAGTCTATGGTAGGCTCTTTGATTGGGTACGCCGCAGCCATCCGCACACTTGCAGGGCTTTAGTCCGAACTCGTTCAAAGGGTTCGACGTACAACAGCGCCTACTAAATCCCCGCCTTGTAACGGAAGACGTGTGGGACCTCTTGAAACATCTTCGACCATACATCTCCATTTTAACAATGAAGCTGTATCAGTGGTCAGTCTTACTATGCCTGCACTCAGCAACAAGGGGCGCGATGATGTAGTCAGCGTGCCCAGATTCAGTACGGACAGTCAAGTGCGATCTTTCTGGGTCGCGCGGCTGGTGGTAATGAGAATGTTCTTACCTGACAAGTAATGCTTCTTCCAATCGTGCTGGGGGCAAGGTTTATTCTCTCTTAACCTGTTGCTCATCTCTAGCGATAACTGGTGCATGATCAATTTGCGG" RNA = "" for nucleotide in DNA: if nucleotide == "T": RNA = RNA + "U" else: RNA = RNA + nucleotide print( RNA )
[ 2, 3740, 1378, 4951, 282, 521, 13, 10951, 14, 1676, 22143, 14, 81, 2616, 14, 198, 2, 3602, 66, 23098, 7446, 656, 25897, 5517, 422, 48263, 1847, 12115, 198, 198, 28886, 796, 366, 26576, 2246, 3838, 4760, 38, 1404, 34, 11190, 39816, 4...
1.986087
575
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-08-04 10:44 from __future__ import unicode_literals from django.db import migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 24, 13, 22, 319, 1584, 12, 2919, 12, 3023, 838, 25, 2598, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 19...
2.672727
55
# The MIT License (MIT) # Copyright (c) 2016 Dell Inc. or its subsidiaries. # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import argparse from PyU4V import U4VConn ru = U4VConn(u4v_version='84') PARSER = argparse.ArgumentParser(description='This python scrtipt is a basic ' 'VMAX REST recipe provisioning ' 'multiple sized volume for an ' 'application.\n' 'python provisioning.py -sg TEST ' '-ig initiators.txt -pg ports.txt' ' -cap 1') RFLAGS = PARSER.add_argument_group('Required arguments') RFLAGS.add_argument('-sg', required=True, help='Storage group name, typically ' 'the application name ' 'e.g. oraclefinace') RFLAGS.add_argument('-ig', required=True, help='Filename containing initiators' ',one per line ' 'e.g. 10000000c9873cae') RFLAGS.add_argument('-pg', required=True, help='Filename containing list of ' 'ports one per line, ' 'e.g. FA-1D:25') RFLAGS.add_argument('-cap', required=True, help='Capacity in GB') # Assign parameters to command line arguments ARGS = PARSER.parse_args() sgname = ARGS.sg hba_file = ARGS.ig port_file = ARGS.pg appname = "REST_" + sgname sg_id = appname + "_SG" ig_id = appname + "_IG" pg_id = appname + "_PG" mv_id = appname + "_MV" requested_capacity = ARGS.cap initiator_list = ru.common.create_list_from_file(hba_file) provision_storage()
[ 2, 383, 17168, 13789, 357, 36393, 8, 198, 2, 15069, 357, 66, 8, 1584, 23617, 3457, 13, 393, 663, 34943, 13, 198, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 198, 2, 16727, 257, 4866, 286, 428, ...
2.261283
1,263
import struct import itertools import numpy as np from bitarray import bitarray RANDOM_SEED = 2387613 IMAGE_SIZE = 128 BATCH_SIZE = 2048 # Assign an integer to each word to be predicted. WORD2LABEL = { 'The Eiffel Tower': 0, 'The Great Wall of China': 1, 'The Mona Lisa': 2, 'airplane': 3, 'alarm clock': 4, 'ambulance': 5, 'angel': 6, 'animal migration': 7, 'ant': 8, 'anvil': 9, 'apple': 10, 'arm': 11, 'asparagus': 12, 'axe': 13, 'backpack': 14, 'banana': 15, 'bandage': 16, 'barn': 17, 'baseball': 19, 'baseball bat': 18, 'basket': 20, 'basketball': 21, 'bat': 22, 'bathtub': 23, 'beach': 24, 'bear': 25, 'beard': 26, 'bed': 27, 'bee': 28, 'belt': 29, 'bench': 30, 'bicycle': 31, 'binoculars': 32, 'bird': 33, 'birthday cake': 34, 'blackberry': 35, 'blueberry': 36, 'book': 37, 'boomerang': 38, 'bottlecap': 39, 'bowtie': 40, 'bracelet': 41, 'brain': 42, 'bread': 43, 'bridge': 44, 'broccoli': 45, 'broom': 46, 'bucket': 47, 'bulldozer': 48, 'bus': 49, 'bush': 50, 'butterfly': 51, 'cactus': 52, 'cake': 53, 'calculator': 54, 'calendar': 55, 'camel': 56, 'camera': 57, 'camouflage': 58, 'campfire': 59, 'candle': 60, 'cannon': 61, 'canoe': 62, 'car': 63, 'carrot': 64, 'castle': 65, 'cat': 66, 'ceiling fan': 67, 'cell phone': 68, 'cello': 69, 'chair': 70, 'chandelier': 71, 'church': 72, 'circle': 73, 'clarinet': 74, 'clock': 75, 'cloud': 76, 'coffee cup': 77, 'compass': 78, 'computer': 79, 'cookie': 80, 'cooler': 81, 'couch': 82, 'cow': 83, 'crab': 84, 'crayon': 85, 'crocodile': 86, 'crown': 87, 'cruise ship': 88, 'cup': 89, 'diamond': 90, 'dishwasher': 91, 'diving board': 92, 'dog': 93, 'dolphin': 94, 'donut': 95, 'door': 96, 'dragon': 97, 'dresser': 98, 'drill': 99, 'drums': 100, 'duck': 101, 'dumbbell': 102, 'ear': 103, 'elbow': 104, 'elephant': 105, 'envelope': 106, 'eraser': 107, 'eye': 108, 'eyeglasses': 109, 'face': 110, 'fan': 111, 'feather': 112, 'fence': 113, 'finger': 114, 'fire hydrant': 115, 'fireplace': 116, 'firetruck': 117, 'fish': 118, 'flamingo': 119, 'flashlight': 120, 'flip flops': 121, 'floor lamp': 122, 'flower': 123, 'flying saucer': 124, 'foot': 125, 'fork': 126, 'frog': 127, 'frying pan': 128, 'garden': 130, 'garden hose': 129, 'giraffe': 131, 'goatee': 132, 'golf club': 133, 'grapes': 134, 'grass': 135, 'guitar': 136, 'hamburger': 137, 'hammer': 138, 'hand': 139, 'harp': 140, 'hat': 141, 'headphones': 142, 'hedgehog': 143, 'helicopter': 144, 'helmet': 145, 'hexagon': 146, 'hockey puck': 147, 'hockey stick': 148, 'horse': 149, 'hospital': 150, 'hot air balloon': 151, 'hot dog': 152, 'hot tub': 153, 'hourglass': 154, 'house': 156, 'house plant': 155, 'hurricane': 157, 'ice cream': 158, 'jacket': 159, 'jail': 160, 'kangaroo': 161, 'key': 162, 'keyboard': 163, 'knee': 164, 'ladder': 165, 'lantern': 166, 'laptop': 167, 'leaf': 168, 'leg': 169, 'light bulb': 170, 'lighthouse': 171, 'lightning': 172, 'line': 173, 'lion': 174, 'lipstick': 175, 'lobster': 176, 'lollipop': 177, 'mailbox': 178, 'map': 179, 'marker': 180, 'matches': 181, 'megaphone': 182, 'mermaid': 183, 'microphone': 184, 'microwave': 185, 'monkey': 186, 'moon': 187, 'mosquito': 188, 'motorbike': 189, 'mountain': 190, 'mouse': 191, 'moustache': 192, 'mouth': 193, 'mug': 194, 'mushroom': 195, 'nail': 196, 'necklace': 197, 'nose': 198, 'ocean': 199, 'octagon': 200, 'octopus': 201, 'onion': 202, 'oven': 203, 'owl': 204, 'paint can': 205, 'paintbrush': 206, 'palm tree': 207, 'panda': 208, 'pants': 209, 'paper clip': 210, 'parachute': 211, 'parrot': 212, 'passport': 213, 'peanut': 214, 'pear': 215, 'peas': 216, 'pencil': 217, 'penguin': 218, 'piano': 219, 'pickup truck': 220, 'picture frame': 221, 'pig': 222, 'pillow': 223, 'pineapple': 224, 'pizza': 225, 'pliers': 226, 'police car': 227, 'pond': 228, 'pool': 229, 'popsicle': 230, 'postcard': 231, 'potato': 232, 'power outlet': 233, 'purse': 234, 'rabbit': 235, 'raccoon': 236, 'radio': 237, 'rain': 238, 'rainbow': 239, 'rake': 240, 'remote control': 241, 'rhinoceros': 242, 'river': 243, 'roller coaster': 244, 'rollerskates': 245, 'sailboat': 246, 'sandwich': 247, 'saw': 248, 'saxophone': 249, 'school bus': 250, 'scissors': 251, 'scorpion': 252, 'screwdriver': 253, 'sea turtle': 254, 'see saw': 255, 'shark': 256, 'sheep': 257, 'shoe': 258, 'shorts': 259, 'shovel': 260, 'sink': 261, 'skateboard': 262, 'skull': 263, 'skyscraper': 264, 'sleeping bag': 265, 'smiley face': 266, 'snail': 267, 'snake': 268, 'snorkel': 269, 'snowflake': 270, 'snowman': 271, 'soccer ball': 272, 'sock': 273, 'speedboat': 274, 'spider': 275, 'spoon': 276, 'spreadsheet': 277, 'square': 278, 'squiggle': 279, 'squirrel': 280, 'stairs': 281, 'star': 282, 'steak': 283, 'stereo': 284, 'stethoscope': 285, 'stitches': 286, 'stop sign': 287, 'stove': 288, 'strawberry': 289, 'streetlight': 290, 'string bean': 291, 'submarine': 292, 'suitcase': 293, 'sun': 294, 'swan': 295, 'sweater': 296, 'swing set': 297, 'sword': 298, 't-shirt': 299, 'table': 300, 'teapot': 301, 'teddy-bear': 302, 'telephone': 303, 'television': 304, 'tennis racquet': 305, 'tent': 306, 'tiger': 307, 'toaster': 308, 'toe': 309, 'toilet': 310, 'tooth': 311, 'toothbrush': 312, 'toothpaste': 313, 'tornado': 314, 'tractor': 315, 'traffic light': 316, 'train': 317, 'tree': 318, 'triangle': 319, 'trombone': 320, 'truck': 321, 'trumpet': 322, 'umbrella': 323, 'underwear': 324, 'van': 325, 'vase': 326, 'violin': 327, 'washing machine': 328, 'watermelon': 329, 'waterslide': 330, 'whale': 331, 'wheel': 332, 'windmill': 333, 'wine bottle': 334, 'wine glass': 335, 'wristwatch': 336, 'yoga': 337, 'zebra': 338, 'zigzag': 339, } LABEL2WORD = dict((v, k) for k, v in WORD2LABEL.items()) # https://docs.python.org/3/library/itertools.html#recipes
[ 11748, 2878, 198, 11748, 340, 861, 10141, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1643, 18747, 1330, 1643, 18747, 628, 198, 49, 6981, 2662, 62, 5188, 1961, 796, 32544, 4304, 1485, 198, 198, 3955, 11879, 62, 33489, 796, 13108...
1.990113
3,540
from collections import Counter from Bio import SeqIO import numpy as np import warnings import math warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim') from gensim.models import Word2Vec Max_length = 100 # maximum length of used peptides # AFC-T, AFC-CP # AFC-C based on main dataset # AFC-C based on alternate dataset
[ 6738, 17268, 1330, 15034, 201, 198, 201, 198, 6738, 16024, 1330, 1001, 80, 9399, 201, 198, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 201, 198, 11748, 14601, 201, 198, 11748, 10688, 201, 198, 201, 198, 40539, 654, 13, 24455, 4...
2.31746
189
from .excel4_anti_analysis import *
[ 6738, 764, 1069, 5276, 19, 62, 17096, 62, 20930, 1330, 1635 ]
3.181818
11
import numpy as np import librosa import os from pytorch_sound.data.meta.ljspeech import LJSpeechMeta from torch.utils.data import Dataset, DataLoader from typing import Tuple
[ 11748, 299, 32152, 355, 45941, 198, 11748, 9195, 4951, 64, 198, 11748, 28686, 198, 6738, 12972, 13165, 354, 62, 23661, 13, 7890, 13, 28961, 13, 75, 73, 45862, 1330, 406, 41, 5248, 3055, 48526, 198, 6738, 28034, 13, 26791, 13, 7890, 13...
3.178571
56
"""Get the parsed query from the driver and apply transformation and action based on the query template """ import time import pyspark.sql.functions as f from pyspark.sql import SparkSession from pyspark.sql.types import IntegerType, StringType, StructField, StructType import yaml from schema import schema with open("config.yaml", 'r') as file: data = yaml.load(file, Loader=yaml.FullLoader) baseURI = data['pathconfig']['host_ip_port'] + \ '/' + data['pathconfig']['input_dir'] table_format = '.csv'
[ 37811, 3855, 262, 44267, 12405, 422, 262, 4639, 290, 4174, 13389, 290, 2223, 1912, 319, 262, 198, 220, 220, 220, 12405, 11055, 198, 37811, 198, 11748, 640, 198, 198, 11748, 279, 893, 20928, 13, 25410, 13, 12543, 2733, 355, 277, 198, 6...
3.13253
166
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main_gui.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 201, 198, 2, 5178, 7822, 7560, 422, 3555, 334, 72, 2393, 705, 12417, 62, 48317, 13, 9019, 6, 201, 198, 2, 201, 198, 2, 15622, 416, 25, 9485, 48, 83, 20, 12454...
2.57732
97
import os import yaml DEFAULT_CONFIG = { 'SEED': 10, # random seed 'BATCH_SIZE': 8, # input batch size for training 'INPUT_SIZE': 256, # input image size for training 0 for original size 'MAX_ITERS': 1e6, # maximum number of iterations to train the model 'SAVE_INTERVAL': 1000, # how many iterations to wait before saving model (0: never) 'SAMPLE_INTERVAL': 1000, # how many iterations to wait before sampling (0: never) 'SAMPLE_SIZE': 12, # number of images to sample 'EVAL_INTERVAL': 0, # how many iterations to wait before model evaluation (0: never) 'LOG_INTERVAL': 10, # how many iterations to wait before logging training status (0: never) }
[ 11748, 28686, 198, 198, 11748, 331, 43695, 628, 198, 198, 7206, 38865, 62, 10943, 16254, 796, 1391, 198, 220, 220, 220, 705, 5188, 1961, 10354, 838, 11, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220,...
2.392857
336
# # Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, # Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, # Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, # Jonas Koenemann, Yutao Chen, Tobias Schls, Jonas Schlagenhauf, Moritz Diehl # # This file is part of acados. # # The 2-Clause BSD License # # 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. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.; # from acados_template import * import acados_template as at from export_ode_model import * import numpy as np import scipy.linalg from ctypes import * import json import argparse # set to 'True' to generate test data GENERATE_DATA = False LOCAL_TEST = False TEST_TOL = 1e-8 if LOCAL_TEST is True: FORMULATION = 'LS' SOLVER_TYPE = 'SQP_RTI' QP_SOLVER = 'FULL_CONDENSING_QPOASES' INTEGRATOR_TYPE = 'IRK' else: parser = argparse.ArgumentParser(description='test Python interface on pendulum example.') parser.add_argument('--FORMULATION', dest='FORMULATION', default='LS', help='FORMULATION: linear least-squares (LS) or nonlinear \ least-squares (NLS) (default: LS)') parser.add_argument('--QP_SOLVER', dest='QP_SOLVER', default='PARTIAL_CONDENSING_HPIPM', help='QP_SOLVER: PARTIAL_CONDENSING_HPIPM, FULL_CONDENSING_HPIPM, ' \ 'FULL_CONDENSING_HPIPM (default: PARTIAL_CONDENSING_HPIPM)') parser.add_argument('--INTEGRATOR_TYPE', dest='INTEGRATOR_TYPE', default='ERK', help='INTEGRATOR_TYPE: explicit (ERK) or implicit (IRK) ' \ ' Runge-Kutta (default: ERK)') parser.add_argument('--SOLVER_TYPE', dest='SOLVER_TYPE', default='SQP_RTI', help='SOLVER_TYPE: (full step) sequential quadratic programming (SQP) or ' \ ' real-time iteration (SQP-RTI) (default: SQP-RTI)') args = parser.parse_args() FORMULATION = args.FORMULATION FORMULATION_values = ['LS', 'NLS'] if FORMULATION not in FORMULATION_values: raise Exception('Invalid unit test value {} for parameter FORMULATION. Possible values are' \ ' {}. Exiting.'.format(FORMULATION, FORMULATION_values)) QP_SOLVER = args.QP_SOLVER QP_SOLVER_values = ['PARTIAL_CONDENSING_HPIPM', 'FULL_CONDENSING_HPIPM', 'FULL_CONDENSING_QPOASES'] if QP_SOLVER not in QP_SOLVER_values: raise Exception('Invalid unit test value {} for parameter QP_SOLVER. Possible values are' \ ' {}. Exiting.'.format(QP_SOLVER, QP_SOLVER_values)) INTEGRATOR_TYPE = args.INTEGRATOR_TYPE INTEGRATOR_TYPE_values = ['ERK', 'IRK'] if INTEGRATOR_TYPE not in INTEGRATOR_TYPE: raise Exception('Invalid unit test value {} for parameter INTEGRATOR_TYPE. Possible values are' \ ' {}. Exiting.'.format(INTEGRATOR_TYPE, INTEGRATOR_TYPE_values)) SOLVER_TYPE = args.SOLVER_TYPE SOLVER_TYPE_values = ['SQP', 'SQP-RTI'] if SOLVER_TYPE not in SOLVER_TYPE: raise Exception('Invalid unit test value {} for parameter SOLVER_TYPE. Possible values are' \ ' {}. Exiting.'.format(SOLVER_TYPE, SOLVER_TYPE_values)) # print test setting print("Running test with:\n\tformulation:", FORMULATION, "\n\tqp solver: ", QP_SOLVER,\ "\n\tintergrator: ", INTEGRATOR_TYPE, "\n\tsolver: ", SOLVER_TYPE) # create render arguments ocp = acados_ocp_nlp() # export model model = export_ode_model() # set model_name ocp.model = model Tf = 2.0 nx = model.x.size()[0] nu = model.u.size()[0] ny = nx + nu ny_e = nx N = 50 # set ocp_nlp_dimensions nlp_dims = ocp.dims nlp_dims.nx = nx nlp_dims.ny = ny nlp_dims.ny_e = ny_e nlp_dims.nbx = 0 nlp_dims.nbu = nu nlp_dims.nu = model.u.size()[0] nlp_dims.N = N # set weighting matrices nlp_cost = ocp.cost if FORMULATION == 'LS': nlp_cost.cost_type = 'LINEAR_LS' nlp_cost.cost_type_e = 'LINEAR_LS' elif FORMULATION == 'NLS': nlp_cost.cost_type = 'NONLINEAR_LS' nlp_cost.cost_type_e = 'NONLINEAR_LS' else: raise Exception('Unknown FORMULATION. Possible values are \'LS\' and \'NLS\'.') Q = np.eye(4) Q[0,0] = 1e0 Q[1,1] = 1e2 Q[2,2] = 1e-3 Q[3,3] = 1e-2 R = np.eye(1) R[0,0] = 1e0 unscale = N/Tf Q = Q * unscale R = R * unscale if FORMULATION == 'NLS': nlp_cost.W = scipy.linalg.block_diag(R, Q) else: nlp_cost.W = scipy.linalg.block_diag(Q, R) nlp_cost.W_e = Q/unscale Vx = np.zeros((ny, nx)) Vx[0,0] = 1.0 Vx[1,1] = 1.0 Vx[2,2] = 1.0 Vx[3,3] = 1.0 nlp_cost.Vx = Vx Vu = np.zeros((ny, nu)) Vu[4,0] = 1.0 nlp_cost.Vu = Vu Vx_e = np.zeros((ny_e, nx)) Vx_e[0,0] = 1.0 Vx_e[1,1] = 1.0 Vx_e[2,2] = 1.0 Vx_e[3,3] = 1.0 nlp_cost.Vx_e = Vx_e if FORMULATION == 'NLS': x = SX.sym('x', 4, 1) u = SX.sym('u', 1, 1) ocp.cost_r.expr = vertcat(u, x) ocp.cost_r.x = x ocp.cost_r.u = u ocp.cost_r.name = 'lin_res' ocp.cost_r.ny = nx + nu ocp.cost_r_e.expr = x ocp.cost_r_e.x = x ocp.cost_r_e.name = 'lin_res' ocp.cost_r_e.ny = nx nlp_cost.yref = np.zeros((ny, )) nlp_cost.yref_e = np.zeros((ny_e, )) # setting bounds Fmax = 2.0 nlp_con = ocp.constraints nlp_con.lbu = np.array([-Fmax]) nlp_con.ubu = np.array([+Fmax]) nlp_con.x0 = np.array([0.0, 3.14, 0.0, 0.0]) nlp_con.idxbu = np.array([0]) # set QP solver ocp.solver_options.qp_solver = QP_SOLVER ocp.solver_options.hessian_approx = 'GAUSS_NEWTON' ocp.solver_options.integrator_type = INTEGRATOR_TYPE ocp.solver_options.sim_method_num_stages = 2 ocp.solver_options.sim_method_num_steps = 5 # set prediction horizon ocp.solver_options.tf = Tf ocp.solver_options.nlp_solver_type = SOLVER_TYPE # set header path ocp.acados_include_path = '../../../../include' ocp.acados_lib_path = '../../../../lib' acados_solver = generate_solver(ocp, json_file = 'acados_ocp.json') Nsim = 100 simX = np.ndarray((Nsim, nx)) simU = np.ndarray((Nsim, nu)) for i in range(Nsim): status = acados_solver.solve() if status !=0: print("acados failure! Exiting. \n") sys.exit(status) # get solution x0 = acados_solver.get(0, "x") u0 = acados_solver.get(0, "u") for j in range(nx): simX[i,j] = x0[j] for j in range(nu): simU[i,j] = u0[j] # update initial condition x0 = acados_solver.get(1, "x") acados_solver.set(0, "lbx", x0) acados_solver.set(0, "ubx", x0) # update reference for j in range(N): acados_solver.set(j, "yref", np.array([0, 0, 0, 0, 0])) acados_solver.set(N, "yref", np.array([0, 0, 0, 0])) # dump result to JSON file for unit testing test_file_name = 'test_data/generate_c_code_out_' + FORMULATION + '_' + QP_SOLVER + '_' + \ INTEGRATOR_TYPE + '_' + SOLVER_TYPE + '.json' if GENERATE_DATA: with open(test_file_name, 'w') as f: json.dump({"simX": simX.tolist(), "simU": simU.tolist()}, f, indent=4, sort_keys=True) else: with open(test_file_name, 'r') as f: test_data = json.load(f) simX_error = np.linalg.norm(test_data['simX'] - simX) simU_error = np.linalg.norm(test_data['simU'] - simU) if simX_error > TEST_TOL or simU_error > TEST_TOL: raise Exception("Python acados test failure with accuracies {:.2E} and {:.2E} ({:.2E} required) on pendulum example! Exiting.\n".format(simX_error, simU_error, TEST_TOL)) else: print('Python test passed with accuracy {:.2E}'.format(max(simU_error, simX_error)))
[ 2, 198, 2, 15069, 13130, 30851, 75, 43120, 1305, 1653, 11, 14048, 270, 2442, 30559, 89, 10486, 271, 11, 12325, 18535, 354, 518, 918, 11, 198, 2, 23174, 47022, 23225, 11, 11556, 1424, 5719, 10343, 2926, 365, 918, 11, 11232, 35086, 11, ...
2.185323
4,020
import httplib # Used only for handling httplib.HTTPException (case #26701) import os import sys import platform import re import urllib import urllib2 import traceback import time from StringIO import StringIO from multiprocessing import subprocess from kunai.log import logger from kunai.collector import Collector
[ 11748, 1841, 489, 571, 1303, 16718, 691, 329, 9041, 1841, 489, 571, 13, 40717, 16922, 357, 7442, 1303, 25674, 486, 8, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 3859, 198, 11748, 302, 198, 11748, 2956, 297, 571, 198, 11748, 2956,...
3.595506
89
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' 2017 ICPC at UCSY Problem-H: Sum Square ''' import sys def parse_tc(tc): ''' Input: Test Case Update: Return: None ''' x = list(map(int,tc.infile.readline().split())) tc.dataset = x[0] tc.max_num = x[1] tc.base = x[2] tc.a0 = x[3] return def solve(tc): ''' Input: Test Case Return: None ''' parse_tc(tc) ak = tc.a0 ssd_list = [ak] for i in range(tc.max_num): ssd_val = ssd(tc.base, ak) if ssd_val in ssd_list: index_k = ssd_list.index(ssd_val) print(tc.dataset, len(ssd_list)+1, len(ssd_list)-index_k) ssd_list.append(ssd_val) prt_list(ssd_list[index_k:]) break ssd_list.append(ssd_val) ak = ssd_val else: print(tc.dataset, tc.max_num, 0) print(ak) return ## ## Main routine ## if __name__ == '__main__': tc = TestCase() tc.infile = sys.stdin tc.t = int(tc.infile.readline()) for i in range(tc.t): solve(tc) if tc.infile != sys.stdin: tc.infile.close()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 7061, 6, 198, 220, 220, 220, 2177, 12460, 5662, 379, 49553, 56, 198, 220, 220, 220, 20647, 12, 39, 25, 5060, 9276...
1.792424
660
""" Author: Peng Wu License: MIT """ # Initialize Spark Context: local multi-threads from pyspark import SparkConf, SparkContext output_folder = './csv/' # with open(output_folder+'viz_txedge.csv', 'w') as f: # pass # def formatted_print_2(keyValue): # with open(output_folder+'viz_txedge.csv', 'a') as f: # f.write('{},{},{},{}\n'.format(keyValue[0][0], keyValue[1][1][0], keyValue[1][0][0], keyValue[1][0][2])) # metafinal.foreach(formatted_print_2) # #print metafinal.first() if __name__ == "__main__": import sys if len(sys.argv) != 1: print "\n\tUSAGE:\n\t\tspark-submit spark_mapinput.py" sys.exit() import time start_time = time.time() main() print("--- %s seconds ---" % (time.time() - start_time))
[ 37811, 198, 13838, 25, 42341, 18027, 198, 34156, 25, 17168, 198, 37811, 198, 198, 2, 20768, 1096, 17732, 30532, 25, 1957, 5021, 12, 16663, 82, 198, 6738, 279, 893, 20928, 1330, 17732, 18546, 11, 17732, 21947, 198, 198, 22915, 62, 43551,...
2.25641
351
import torch from torch import nn as nn import numpy as np from .base import Readout def initialize(self, mean_activity=None): """ Initializes the mean, and sigma of the Gaussian readout along with the features weights """ if mean_activity is None: mean_activity = self.mean_activity self.spatial.data.normal_(0, self.init_noise) self._features.data.normal_(0, self.init_noise) if self._shared_features: self.scales.data.fill_(1.0) if self.bias is not None: self.initialize_bias(mean_activity=mean_activity) def initialize_features(self, match_ids=None, shared_features=None): """ The internal attribute `_original_features` in this function denotes whether this instance of the FullGuassian2d learns the original features (True) or if it uses a copy of the features from another instance of FullGaussian2d via the `shared_features` (False). If it uses a copy, the feature_l1 regularizer for this copy will return 0 """ c, w, h = self.in_shape if match_ids is not None: assert self.outdims == len(match_ids) n_match_ids = len(np.unique(match_ids)) if shared_features is not None: assert shared_features.shape == ( n_match_ids, c, ), f"shared features need to have shape ({n_match_ids}, {c})" self._features = shared_features self._original_features = False else: self._features = nn.Parameter( torch.Tensor(n_match_ids, c) ) # feature weights for each channel of the core self.scales = nn.Parameter(torch.Tensor(self.outdims, 1)) # feature weights for each channel of the core _, sharing_idx = np.unique(match_ids, return_inverse=True) self.register_buffer("feature_sharing_index", torch.from_numpy(sharing_idx)) self._shared_features = True else: self._features = nn.Parameter(torch.Tensor(self.outdims, c)) # feature weights for each channel of the core self._shared_features = False # Classes for backwards compatibility
[ 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 355, 299, 77, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 764, 8692, 1330, 4149, 448, 628, 198, 220, 220, 220, 825, 41216, 7, 944, 11, 1612, 62, 21797, 28, 14202, 2599, 198, 220...
2.334356
978
from flask import render_template,request, redirect, url_for from . import main from ..requests import get_articles, get_news_sources,get_top_headlines, get_news_category
[ 6738, 42903, 1330, 8543, 62, 28243, 11, 25927, 11, 18941, 11, 19016, 62, 1640, 198, 6738, 764, 1330, 1388, 198, 6738, 11485, 8897, 3558, 1330, 651, 62, 26845, 11, 651, 62, 10827, 62, 82, 2203, 11, 1136, 62, 4852, 62, 2256, 6615, 11,...
3.541667
48
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 FABRIC Testbed # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # # Author: Komal Thareja (kthare10@renci.org) from fabric_cf.actor.core.util.resource_type import ResourceType
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 17168, 13789, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 376, 6242, 41132, 6208, 3077, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, ...
3.638484
343
from .node_view import NodeView from .node import Node from .nodes_view import NodesView from .nodes import Nodes
[ 6738, 764, 17440, 62, 1177, 1330, 19081, 7680, 198, 6738, 764, 17440, 1330, 19081, 198, 6738, 764, 77, 4147, 62, 1177, 1330, 399, 4147, 7680, 198, 6738, 764, 77, 4147, 1330, 399, 4147, 198 ]
3.352941
34
#!/usr/bin/env python # Author: Christian Vallentin <mail@vallentinsource.com> # Website: http://vallentinsource.com # Repository: https://github.com/MrVallentin/http_request # # Date Created: February 28, 2016 # Last Modified: February 29, 2016 # # Developed and tested using Python 3.5.1 import http.client, urllib.parse
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 6434, 25, 4302, 46929, 31371, 1279, 4529, 31, 85, 439, 298, 1040, 1668, 13, 785, 29, 198, 2, 15887, 25, 2638, 1378, 85, 439, 298, 1040, 1668, 13, 785, 198, 2, 1432, 13264, ...
3.009174
109
import PyPDF2 merger = PyPDF2.PdfFileMerger() merger.append('data/src/pdf/sample1.pdf', pages=(0, 1)) merger.append('data/src/pdf/sample2.pdf', pages=(2, 4)) merger.merge(2, 'data/src/pdf/sample3.pdf', pages=(0, 3, 2)) merger.write('data/temp/sample_merge_page.pdf') merger.close() merger = PyPDF2.PdfFileMerger() merger.append('data/src/pdf/sample1.pdf', pages=PyPDF2.pagerange.PageRange('-1')) merger.append('data/src/pdf/sample2.pdf', pages=PyPDF2.pagerange.PageRange('2:')) merger.merge(2, 'data/src/pdf/sample3.pdf', pages=PyPDF2.pagerange.PageRange('::-1')) merger.write('data/temp/sample_merge_pagerange.pdf') merger.close() reader1 = PyPDF2.PdfFileReader('data/src/pdf/sample1.pdf') reader2 = PyPDF2.PdfFileReader('data/src/pdf/sample2.pdf') writer = PyPDF2.PdfFileWriter() writer.addPage(reader1.getPage(0)) writer.addPage(reader2.getPage(2)) with open('data/temp/sample_merge_wr.pdf', 'wb') as f: writer.write(f)
[ 11748, 9485, 20456, 17, 198, 198, 647, 1362, 796, 9485, 20456, 17, 13, 47, 7568, 8979, 13102, 1362, 3419, 198, 198, 647, 1362, 13, 33295, 10786, 7890, 14, 10677, 14, 12315, 14, 39873, 16, 13, 12315, 3256, 5468, 16193, 15, 11, 352, 4...
2.360202
397
from transformers.data.processors.squad import SquadV1Processor, SquadV2Processor from transformers import squad_convert_examples_to_features import urllib.request import os
[ 6738, 6121, 364, 13, 7890, 13, 14681, 669, 13, 16485, 324, 1330, 11630, 53, 16, 18709, 273, 11, 11630, 53, 17, 18709, 273, 198, 6738, 6121, 364, 1330, 8244, 62, 1102, 1851, 62, 1069, 12629, 62, 1462, 62, 40890, 198, 11748, 2956, 297...
3.48
50
import random import numpy as np import pandas as pd import trading_env # np.set_printoptions(threshold=np.nan) #df = pd.read_hdf('dataset/SGXTW.h5', 'STW') #df = pd.read_hdf('dataset/SGXTWsample.h5', 'STW') df = pd.read_csv('dataset/btc_indexed2.csv') print(df.describe()) env = trading_env.make(env_id='training_v1', obs_data_len=1, step_len=1, df=df, fee=0.0, max_position=5, deal_col_name='close', sample_days=1, feature_names=['low', 'high', 'open', 'close', 'volume', 'datetime']) env.reset() env.render() state, reward, done, info = env.step(1) print state # randow choice action and show the transaction detail while True: state, reward, done, info = env.step(0) env.render() if done: print state, reward break
[ 11748, 4738, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 7313, 62, 24330, 198, 198, 2, 45941, 13, 2617, 62, 4798, 25811, 7, 400, 10126, 28, 37659, 13, 12647, 8, 198, 198, 2, 7568, 796, 279, ...
1.964989
457