import re
import sys

keywords = [
    'class',
    'constructor',
    'function',
    'method',
    'field',
    'static',
    'var',
    'int',
    'char',
    'boolean',
    'void',
    'true',
    'false',
    'null',
    'this',
    'let',
    'do',
    'if',
    'else',
    'while',
    'return'
]

symbols = [r'{',
           r'}',
           r'(',
           r')',
           r'[',
           r']',
           r'.',
           r',',
           r';',
           r'+',
           r'-',
           r'*',
           r'/',
           r'&',
           r'|',
           r'<',
           r'>',
           r'=',
           r'~']

# symbols = r'[&\)\[\]\+\*\-,\<.}({;~=\|>]'

class Tokenizer:
    reg_intConst = re.compile(r'(\d+)')
    reg_strConst = re.compile(r'"([^"]*)"')
    reg_identifier = re.compile(r'[A-Za-z_]\w*')
    reg_keywords = re.compile(r'(' + r'|'.join(keywords) + r')[^\w]')
    #    reg_symbols = re.compile(symbols)
    reg_whitespace = re.compile(r'[\s]+')

    TYPE_SYM = "symbol"
    TYPE_KEY = "keyword"
    TYPE_ID = "identifier"
    TYPE_INT = "integerConstant"
    TYPE_STR = "stringConstant"

    def __init__(self, pathToFile):
        '''
        open the file,
        maybe also read first line,
        maybe also tokenize already?
        '''
        self.linum = 0
        self.srcFile = open(pathToFile)
        self.isEOF = False
        self.tokens = self.__tokenizeNextValidLine__()

    def __readline__(self):
        line = self.srcFile.readline()
        self.linum += 1
        if line == "":
            self.isEOF = True
        return line

    def __tknizeNextLine__(self):
        if self.isEOF:
            return []

        lineStr = self.__readline__()
        lineTkns = []
        while lineStr != "":
            #  first remove preceding whitespace
            wsM = self.reg_whitespace.match(lineStr)
            if wsM:
                lineStr = lineStr[len(wsM.group(0)):]
                continue
            #  figure out if we got to a comment, and if so, remove all relevant lines
            if lineStr.startswith('//'):
                lineStr = ''
                continue
            if lineStr.startswith('/*'):
                lineStr = self.__removeNextMultiCom__(lineStr)
                continue

            if lineStr[0] in symbols:
                lineTkns.append((self.TYPE_SYM, lineStr[0]))
                lineStr = lineStr[1:]
                continue
            keyM = self.reg_keywords.match(lineStr)
            if keyM:
                lineTkns.append((self.TYPE_KEY, keyM.group(1)))  # we want to add only the keyword, and not the following char
                lineStr = lineStr[len(keyM.group(1)):]
                continue
            intM = self.reg_intConst.match(lineStr)
            if intM:
                lineTkns.append((self.TYPE_INT, intM.group(0)))
                lineStr = lineStr[len(intM.group(0)):]
                continue
            strM = self.reg_strConst.match(lineStr)
            if strM:
                lineTkns.append(
                    (self.TYPE_STR, strM.group(1)))  # group 1 is the string without the quotes
                lineStr = lineStr[len(
                    strM.group(0)):]  # when we remove the prefix we want to remove the quotes too
                continue
            idM = self.reg_identifier.match(lineStr)
            if idM:
                lineTkns.append((self.TYPE_ID, idM.group(0)))
                lineStr = lineStr[len(idM.group(0)):]
                continue

            print("Bad Syntax in line %d, wasn't able to tokenize: %s" % (self.linum, lineStr), file=sys.stderr)
            raise SyntaxError

        return lineTkns

    def __cleanLine__(self, line):
        lineComInd = line.find("//")
        if lineComInd > -1:  # cut out the line comments
            line = line[:lineComInd]

        while line.find("/*") > -1:  # we have an opening of a multiline comment
            line = self.__removeNextMultiCom__(line)  # remove it

        return line

    def __removeNextMultiCom__(self, line):
        multLineComStart = line.find("/*")
        if multLineComStart > -1:
            lineStart = line[:multLineComStart]
            multLineComEnd = line.find("*/")
            while not multLineComEnd > -1:  # no closing comment found
                line = self.__readline__()  # read a new line
                if line == "":
                    return lineStart
                multLineComEnd = line.find("*/")  # look for a closing comment

            # if we're here then we found a closing comment
            line = lineStart + line[multLineComEnd + 2:]
        return line

    def nextToken(self):

        nextTkn = self.tokens[0]
        self.tokens = self.tokens[1:]
        if not self.hasMoreTokens():
            self.tokens = self.__tokenizeNextValidLine__()

        return nextTkn

    def __tokenizeNextValidLine__(self):
        nextTkns = []
        while nextTkns == [] and not self.isEOF:
            nextTkns = self.__tknizeNextLine__()

        return nextTkns

    def hasMoreTokens(self):
        return self.tokens != []

    def __iter__(self):
        return self

    def __next__(self):
        if self.hasMoreTokens():
            return self.nextToken()
        else:
            raise StopIteration

    def closeFile(self):
        self.srcFile.close()


# -*- coding: utf-8 -*-
#!/usr/bin/env python3

import json
import logging
import os
import sys
import time

import asyncio
import aiohttp
import discord
import requests
from discord.ext import commands

cogs_list = ['cogs.' + x.replace('.py', '') for x in os.listdir('cogs') if x.endswith('.py')]

async def fetch_newest_db(CONFIG_DATA):
    """
    Fetch the newest naoTimes database from github
    """
    print('@@ Fetching newest database')
    if CONFIG_DATA['gist_id'] == "":
        return print('@@ naoTimes are not setted up, skipping...')
    url = 'https://gist.githubusercontent.com/{u}/{g}/raw/nao_showtimes.json'
    async with aiohttp.ClientSession() as session:
        while True:
            try:
                async with session.get(url.format(u=CONFIG_DATA['github_info']['username'], g=CONFIG_DATA['gist_id'])) as r:
                    try:
                        r_data = await r.text()
                        js_data = json.loads(r_data)
                        with open('nao_showtimes.json', 'w') as f:
                            json.dump(js_data, f, indent=4)
                        print('@@ Fetched and saved.')
                        return
                    except IndexError:
                        continue
            except session.ClientError:
                continue

def prefixes(bot, message):
    """
    A modified version of discord.ext.command.when_mentioned_or
    """
    server = message.server

    with open('prefixes.json') as f:
        pre = json.load(f)
    default_ = "!"

    id_srv = server.id
    pre_data = []
    pre_ = pre_data.append(pre.get(id_srv, default_))
    if default_ not in pre_data:
        pre_data.append(default_)
    if '.' not in pre_data:
        pre_data.append('.')
    if server is not None:
        pre_data.append('{0.me.mention} '.format(server))
    pre_data.append('{0.user.mention} '.format(bot))

    return pre_data

async def init_bot():
    """
    Start loading all the bot process
    Will start:
        - Logging
        - discord.py and the modules
        - Fetching naoTimes main database
        - Setting some global variable
    """
    print('@@ Loading logger...')
    logger = logging.getLogger('discord')
    logger.setLevel(logging.ERROR)
    handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
    handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
    logger.addHandler(handler)

    print('@@ Set global start time')
    global_start_time = time.time()

    print('@@ Looking up config')
    with open('config.json', 'r') as fp:
        config = json.load(fp)

    try:
        print('@@ Initiating discord.py')
        description = '''Penyuruh Fansub biar kerja cepat\nversi 1.4.1 || Dibuat oleh: N4O#8868'''
        bot = commands.Bot(command_prefix=prefixes, description=description)
        bot.remove_command('help')
        await fetch_newest_db(config)
        for load in internal_modules():
            bot.load_extension(load)
            print('Loaded ' + load + ' Modules')
        print('### Success Loading Discord.py ###')
    except Exception as exc:
        print('### Failed to load Discord.py ###')
        print(exc)
    return bot, config, logger, global_start_time

# Initiate everything
print('@@ Initiating bot...')
async_loop = asyncio.get_event_loop()
bot, bot_config, logger, global_start_time = async_loop.run_until_complete(init_bot())

@bot.event
async def on_ready():
    """Bot loaded here"""
    print('Connected to discord.')
    presence = 'Mengamati rilisan fansub | !help'
    await bot.change_presence(game=discord.Game(name=presence))
    print('---------------------------------------------------------------')
    print('Logged in as:')
    print('Bot name: ' + bot.user.name)
    print('With Client ID: ' + bot.user.id)
    print('---------------------------------------------------------------')

def is_owner():
    """Check if owner"""
    def predicate(ctx):
        return int(ctx.message.author.id) == int(bot_config['owner_id'])
    return commands.check(predicate)

async def other_ping_test():
    """Github and anilist ping test"""
    async with aiohttp.ClientSession() as session:
        print('Menjalankan tes ping github')
        t1_git = time.time()
        while True:
            try:
                async with session.get('https://api.github.com') as r:
                    try:
                        await r.json()
                        break
                    except IndexError:
                        continue
            except session.ClientError:
                continue
        t2_git = time.time()
        print('Selesai')
        git_time = round((t2_git-t1_git)*1000)
        print('Menjalankan tes ping anilist')
        t1_ani = time.time()
        while True:
            try:
                async with session.get('https://graphql.anilist.co') as r:
                    try:
                        await r.json()
                        break
                    except IndexError:
                        continue
            except session.ClientError:
                continue
        t2_ani = time.time()
        print('Selesai')
        ani_time = round((t2_ani-t1_ani)*1000)

    return {'github': git_time, 'anilist': ani_time}

def create_uptime():
    current_time = time.time()
    up_secs = int(round(current_time - global_start_time)) # Seconds

    up_months = int(up_secs // 2592000) # 30 days format
    up_secs -= up_months * 2592000
    up_weeks = int(up_secs // 604800)
    up_secs -= up_weeks * 604800
    up_days = int(up_secs // 86400)
    up_secs -= up_days * 86400
    up_hours = int(up_secs // 3600)
    up_secs -= up_hours * 3600
    up_minutes = int(up_secs // 60)
    up_secs -= up_minutes * 60

    return_text = ''
    if up_months != 0:
        return_text += '{} bulan '.format(up_months)

    return return_text + '{} minggu {} hari {} jam {} menit {} detik'.format(up_weeks, up_days, up_hours, up_minutes, up_secs)

@bot.command(pass_context=True)
async def ping(ctx):
    """
    pong!
    """
    channel = ctx.message.channel
    print('Melakukan tes ping keseluruhan')

    other_test = await other_ping_test()

    print('Menjalankan tes ping discord')
    t1 = time.time()
    await bot.send_typing(channel)
    t2 = time.time()
    print('Selesai')

    print('Menghitung hasil')
    dis_test = round((t2-t1)*1000)

    pingbed = discord.Embed(title="Ping Test", color=0xffffff)
    pingbed.set_thumbnail(url="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/240/twitter/180/satellite-antenna_1f4e1.png")
    pingbed.add_field(name='Discord', value='{}ms'.format(dis_test), inline=False)
    pingbed.add_field(name='GitHub', value='{}ms'.format(other_test['github']), inline=False)
    pingbed.add_field(name='Anilist.co', value='{}ms'.format(other_test['anilist']), inline=False)
    pingbed.set_footer(text="Tested using \"sophisticated\" ping method ")
    await bot.say(embed=pingbed)

@bot.command(pass_context=True)
async def info():
    """
    Melihat Informasi bot
    """
    infog = discord.Embed(title="naoTimes", description="Sang penagih utang fansub agar fansubnya mau gerak", color=0xde8730)
    infog.set_author(name="naoTimes", icon_url="https://slwordpress.rutgers.edu/wp-content/uploads/sites/98/2015/12/Info-I-Logo.png")
    infog.set_thumbnail(url="https://puu.sh/D3x1l/7f97e14c74.png")
    infog.add_field(name="Info", value="Dijalankan di Heroku server US", inline=False)
    infog.add_field(name="Dibuat", value="Gak tau, tiba-tiba jadi.", inline=False)
    infog.add_field(name="Pembuat", value="N4O#8868", inline=False)
    infog.add_field(name="Bahasa", value="Discord.py dengan Python 3.6", inline=False)
    infog.add_field(name="Fungsi", value="Menagih utang fansub (!help)", inline=False)
    infog.add_field(name="Uptime", value=create_uptime())
    infog.set_footer(text="naoTimes versi 1.4.1 || Dibuat oleh N4O#8868", icon_url='https://p.n4o.xyz/i/nao250px.png')
    await bot.say(embed=infog)

@bot.command(pass_context=True)
@is_owner()
async def bundir():
    """
    Mematikan bot, owner only
    """
    try:
        await bot.say(":gun: Membunuh bot...")
        print('!!!! Memulai proses')
        for unload in cogs_list:
            bot.unload_extension(unload)
            print('Unloaded ' + unload + ' Modules')
        print('### Modules unloaded')
        await bot.logout()
        await bot.close()
        async_loop.close()
        print('### Connection closed')
        exit(0)
    except commands.CheckFailure:
        await bot.say("Kamu tidak bisa menjalankan perintah ini\n**Alasan:** Bukan Owner Bot")

@bot.command(pass_context=True)
@is_owner()
async def reinkarnasi():
    """
    Mematikan lalu menghidupkan bot, owner only
    """
    try:
        await bot.say(":sparkles: Proses Reinkarnasi Dimulai...")
        print('!!!! Memulai proses')
        for reload_mod in cogs_list:
            bot.unload_extension(reload_mod)
            print('Unloaded ' + reload_mod + ' Modules')
        print('### Modules unloaded')
        await bot.logout()
        await bot.close()
        print('### Connection closed')
        async_loop.close()
        os.execv(sys.executable, ['python'] + sys.argv)
    except commands.CheckFailure:
        await bot.say("Kamu tidak bisa menjalankan perintah ini\n**Alasan:** Bukan Owner Bot")

@bot.command(pass_context=True)
@is_owner()
async def reload(ctx, *, module=None):
    """
    Restart salah satu module bot, owner only
    """
    if not module:
        helpmain = discord.Embed(title="Reload", description="versi 1.4.1", color=0x00aaaa)
        helpmain.set_thumbnail(url="https://image.ibb.co/darSzH/question_mark_1750942_640.png")
        helpmain.set_author(name="naoTimes", icon_url="https://p.n4o.xyz/i/naotimes_ava.png")
        helpmain.add_field(name='Module/Cogs List', value="\n".join(['- ' + cl for cl in cogs_list]), inline=False)
        helpmain.set_footer(text="Dibawakan oleh naoTimes || Dibuat oleh N4O#8868 versi 1.4.1")
        return await bot.say(embed=helpmain)
    timetext = 'Started process at'
    rel1 = discord.Embed(title="Reload Module", color=0x8ceeff)
    rel1.set_thumbnail(url="https://d30y9cdsu7xlg0.cloudfront.net/png/4985-200.png")
    rel1.add_field(name=module, value="Status: PROCESSING", inline=False)
    rel1.set_footer(text=timetext)
    sayd = await bot.say(embed=rel1)
    if 'cogs.' not in module:
        module = 'cogs.' + module
    try:
        ctx.bot.unload_extension(module)
        ctx.bot.load_extension(module)
        timetext = 'Module reloaded'
        rel2 = discord.Embed(title="Reload Module", color=0x6ce170)
        rel2.set_thumbnail(url="https://d30y9cdsu7xlg0.cloudfront.net/png/4985-200.png")
        rel2.add_field(name=module, value="Status: SUCCESS", inline=False)
        rel2.set_footer(text=timetext)
        await bot.edit_message(sayd, embed=rel2)
    except Exception as e:
        timetext = 'Failed'
        rel3 = discord.Embed(title="Module", color=0xe73030)
        rel3.set_thumbnail(url="https://d30y9cdsu7xlg0.cloudfront.net/png/4985-200.png")
        rel3.add_field(name=module, value="Status: ERROR - {}".format(str(e)), inline=False)
        rel3.set_footer(text=timetext)
        await bot.edit_message(sayd, embed=rel3)
        print(e)

@bot.command(pass_context=True)
@is_owner()
async def load(ctx, *, module=None):
    """
    Load salah satu module bot, owner only
    """
    if not module:
        helpmain = discord.Embed(title="Load", description="versi 1.4.1", color=0x00aaaa)
        helpmain.set_thumbnail(url="https://image.ibb.co/darSzH/question_mark_1750942_640.png")
        helpmain.set_author(name="naoTimes", icon_url="https://p.n4o.xyz/i/naotimes_ava.png")
        helpmain.add_field(name='Module/Cogs List', value="\n".join(['- ' + cl for cl in cogs_list]), inline=False)
        helpmain.set_footer(text="Dibawakan oleh naoTimes || Dibuat oleh N4O#8868 versi 1.4.1")
        return await bot.say(embed=helpmain)
    timetext = 'Started process at'
    rel1 = discord.Embed(title="Load Module", color=0x8ceeff)
    rel1.set_thumbnail(url="https://d30y9cdsu7xlg0.cloudfront.net/png/4985-200.png")
    rel1.add_field(name=module, value="Status: PROCESSING", inline=False)
    rel1.set_footer(text=timetext)
    sayd = await bot.say(embed=rel1)
    if 'cogs.' not in module:
        module = 'cogs.' + module
    try:
        ctx.bot.load_extension(module)
        timetext = 'Module Loaded'
        rel2 = discord.Embed(title="Load Module", color=0x6ce170)
        rel2.set_thumbnail(url="https://d30y9cdsu7xlg0.cloudfront.net/png/4985-200.png")
        rel2.add_field(name=module, value="Status: SUCCESS", inline=False)
        rel2.set_footer(text=timetext)
        await bot.edit_message(sayd, embed=rel2)
    except Exception as e:
        timetext = 'Failed'
        rel3 = discord.Embed(title="Load Module", color=0xe73030)
        rel3.set_thumbnail(url="https://d30y9cdsu7xlg0.cloudfront.net/png/4985-200.png")
        rel3.add_field(name=module, value="Status: ERROR - {}".format(str(e)), inline=False)
        rel3.set_footer(text=timetext)
        await bot.edit_message(sayd, embed=rel3)
        print(e)

@bot.command(pass_context=True)
@is_owner()
async def unload(ctx, *, module=None):
    """
    Unload salah satu module bot, owner only
    """
    if not module:
        helpmain = discord.Embed(title="Unload", description="versi 1.4.1", color=0x00aaaa)
        helpmain.set_thumbnail(url="https://image.ibb.co/darSzH/question_mark_1750942_640.png")
        helpmain.set_author(name="naoTimes", icon_url="https://p.n4o.xyz/i/naotimes_ava.png")
        helpmain.add_field(name='Module/Cogs List', value="\n".join(['- ' + cl for cl in cogs_list]), inline=False)
        helpmain.set_footer(text="Dibawakan oleh naoTimes || Dibuat oleh N4O#8868 versi 1.4.1")
        return await bot.say(embed=helpmain)
    timetext = 'Started process at'
    rel1 = discord.Embed(title="Unload Module", color=0x8ceeff)
    rel1.set_thumbnail(url="https://d30y9cdsu7xlg0.cloudfront.net/png/4985-200.png")
    rel1.add_field(name=module, value="Status: PROCESSING", inline=False)
    rel1.set_footer(text=timetext)
    sayd = await bot.say(embed=rel1)
    if 'cogs.' not in module:
        module = 'cogs.' + module
    try:
        ctx.bot.unload_extension(module)
        timetext = 'Module unloaded'
        rel2 = discord.Embed(title="Unload Module", color=0x6ce170)
        rel2.set_thumbnail(url="https://d30y9cdsu7xlg0.cloudfront.net/png/4985-200.png")
        rel2.add_field(name=module, value="Status: SUCCESS", inline=False)
        rel2.set_footer(text=timetext)
        await bot.edit_message(sayd, embed=rel2)
    except Exception as e:
        timetext = 'Failed'
        rel3 = discord.Embed(title="Unload Module", color=0xe73030)
        rel3.set_thumbnail(url="https://d30y9cdsu7xlg0.cloudfront.net/png/4985-200.png")
        rel3.add_field(name=module, value="Status: ERROR - {}".format(str(e)), inline=False)
        rel3.set_footer(text=timetext)
        await bot.edit_message(sayd, embed=rel3)
        print(e)

bot.run(bot_config['bot_token'])


# Copyright (C) 2013 Canonical Ltd.
# Author: Colin Watson <cjwatson@ubuntu.com>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Build a Click source package."""

from __future__ import print_function

from optparse import OptionParser
import os
import sys

from click.build import ClickBuildError, ClickSourceBuilder

def run(argv):
    parser = OptionParser("%prog buildsource [options] DIRECTORY")
    parser.add_option(
        "-m", "--manifest", metavar="PATH",
        help="read package manifest from PATH")
    parser.add_option(
        "-I", "--ignore", metavar="file-pattern", action='append',
        default=[],
        help="Ignore the given pattern when building the package")
    options, args = parser.parse_args(argv)
    if len(args) < 1:
        parser.error("need directory")
    directory = args[0]
    if not os.path.isdir(directory):
        parser.error('directory "%s" does not exist' % directory)
    if not options.manifest:
        options.manifest = os.path.join(directory, "manifest.json")
    if os.path.isdir(os.path.join(directory, options.manifest)):
        options.manifest = os.path.join(options.manifest, "manifest.json")
    if not os.path.exists(os.path.join(directory, options.manifest)):
        parser.error(
            'directory "%s" does not contain manifest file "%s"' %
            (directory, options.manifest))
    builder = ClickSourceBuilder()
    builder.add_file(directory, "./")
    for ignore in options.ignore:
        builder.add_ignore_pattern(ignore)
    try:
        path = builder.build(".", manifest_path=options.manifest)
    except ClickBuildError as e:
        print(e, file=sys.stderr)
        return 1
    print("Successfully built source package in '%s'." % path)
    return 0


import datetime
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

class MtLibDebug:

    """
    符号说明：https://geek-docs.com/matplotlib/matplotlib-tutorial/matplotlib-numpy.html
    """

    def draw_plot(self):
        """
        绘制图表

        只传递数组传递给plt.plot()函数，matplotlib会假定你所传入的是图表y值，
        于是将其跟一个序列的x值对应起来，x的取值依次为0，1，2，3

        图形表示的是一对(x, y)定义两个数组，其中第一个数组为x轴的各个值，第二个数组为y轴的值。
        此外plot()函数还可以接收第三个参数，它描述的是数据点在图表中的显示方式 默认 用蓝色线条连接各数据点

        """

        # 1. 只传递一个数组

        # plt.plot([1, 2, 3, 4])

        # 2. 传递 x值 y值并用红点显示各数据

        # plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')

        # 3. axis() 和 title

        # 定义x, y轴取值范围 把该列表作为参数传递给axis()函数
        # plt.axis([0, 5, 0, 20])

        # 设置标题 fontsize文本大小
        # plt.title("PlotExamples", fontsize=20)

        # 4. xlabel()和ylabel() 为x轴和y轴添加文本标签

        # plt.axis([0, 5, 0, 20])

        # plt.title("PlotExamples")

        # plt.xlabel("x_value")
        # plt.ylabel("y_value")

        # 5. text() 函数  在每个数据点旁边添加描述

        plt.figure(figsize=(10, 4), dpi=80)  # 图片长宽和清晰度
        plt.axis([0, 5, 0, 20])

        plt.title("PlotExamples")

        plt.xlabel("x_value")
        plt.ylabel("y_value")

        plt.text(1, 2.5, 'First')
        plt.text(2, 4.5, 'Second')
        plt.text(3, 9.5, 'Third')
        plt.text(4, 16.5, 'Fourth')

        # 添加表达式 表达式内容置于两个$符号之间

        plt.text(1.1, 12, r'$y=x^2$', fontsize=20, bbox={
            'facecolor': 'yellow', 'alpha': 0.2})

        # 6. 添加网格 grid() 函数

        # grid()函数 参数设置为True, 默认是实线

        # plt.grid(True)

        # 设置成虚线, 修改linestyle 参数  color:网格颜色
        plt.grid(True, linestyle="--", color='k')

        # 7. 设置图例 legend()

        plt.plot([1, 2, 3, 4], [1.8, 3.5, 8, 15], 'g^')
        plt.plot([1, 2, 3, 4], [1.5, 2.5, 4, 12], 'b*')

        plt.plot([1, 2, 3, 4], [2, 4, 9, 16], 'ro')   # b 折线图

        plt.legend(['First series', 'Second Series', 'Third series'], loc=2)

        plt.show()

        return

    def draw_plot_dk(self):
        """
        两条轴穿过原点(0,0)，就是笛卡儿坐标轴

        使用gca()函数获取Axes对象，通过这个对象指定每条边的位置：上、下、左、右。
        使用set_color()函数，把颜色设置为none，删除跟坐标轴不符合的边(右和上)，
        然后用set_position()函数移动跟x轴和y轴相符的边框，使其穿过原点（0，0）
        """
        x = np.arange(-2*np.pi, 2*np.pi, 0.01)
        y = np.sin(x*3)/x
        y2 = np.sin(x*2)/x
        y3 = np.sin(x*1)/x

        plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman")
        plt.plot(x, y, color='b')
        plt.plot(x, y2, color='r')
        plt.plot(x, y3, color='g')

        # x轴, y轴的取值范围：

        plt.xticks(
                [-2*np.pi, -np.pi, 0, np.pi, 2*np.pi],
                [r'$-2\pi$', r'$-\pi$', r'$0$', r'$+\pi$', r'$+2\pi$']
            )

        plt.yticks(
            [-1, 0, +1, +2, +3],
            [r'$-1$', r'$0$', r'$+1$', r'$+2$', r'$+3$']
        )

        """
        用注释和箭头标明曲线上某个数据点的位置，这一功能非常有用。matplotlib库的annotate()函数特别适用于添加注释。
        它的参数设置略显繁琐，第一个参数为含有LaTex表达式，要在图形中显示的字符串。xy属性表示注释在图表中的位置。
        xytext属性表示文本注释跟它解释的数据点之间的距离。arrowprops属性表示箭头的属性。
        """

        plt.annotate(
                r'$\lim_{x\to 0}\frac{sin(x)}{x}=1$',
                xy=[0, 1],
                xycoords='data',
                xytext=[40, 40],
                fontsize=20,
                textcoords='offset points',
                arrowprops=dict(arrowstyle='->', connectionstyle="arc3, rad=.2")
            )

        ax = plt.gca()

        # 去掉上方和右边边框
        ax.spines['right'].set_color('None')
        ax.spines['top'].set_color('None')

        ax.xaxis.set_ticks_position('bottom')
        ax.spines['bottom'].set_position(('data', 0))
        ax.yaxis.set_ticks_position('left')
        ax.spines['left'].set_position(('data', 0))

        plt.show()

        return

    def frame2plot(self):
        """将DataFrame转换成图表"""

        data = {
            'series1': [1, 3, 4, 3, 5],
            'series2': [2, 4, 5, 2, 4],
            'series3': [3, 2, 3, 1, 3]
        }

        df = pd.DataFrame(data)

        x = np.arange(5)
        plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman")
        plt.axis([0, 5, 0, 7])
        plt.plot(x, df)

        plt.legend(data, loc=2)
        plt.show()

        return

    def draw_hist(self):
        """绘制直方图
        hist 参数：

            data: 必选参数，绘图数据
            bins: 直方图的长条形数目，可选项，默认为10
            facecolor: 长条形的颜色
            edgecolor: 长条形边框的颜色
            alpha:透明度

        x轴区间范围为info的取值范围
        y轴区间范围为各个元素数量的统计

        """

        # info = [
        #     1, 1, 5, 5, 2, 4, 4, 4, 8, 6
        # ]

        # plt.hist(info, bins=10)
        # plt.show()

        # 设置matplotlib正常显示中文和负号
        matplotlib.rcParams['font.sans-serif'] = ['SimHei']   # 用黑体显示中文
        matplotlib.rcParams['axes.unicode_minus'] = False     # 正常显示负号

        # 随机生成（10000,）服从正态分布的数据
        data = np.random.randn(100)
        plt.hist(data, bins=40, facecolor="blue", edgecolor="black", alpha=0.7)

        # 显示横轴标签
        plt.xlabel("区间")

        # 显示纵轴标签
        plt.ylabel("频数/频率")

        # 显示图标题
        plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman")

        plt.show()

        return

    def draw_bar(self):
        """
        绘制条形图
        """

        # index, values = [0, 1, 2, 3, 4], [10, 20, 30, 40, 50]

        # plt.title("geek_docs.com", fontsize=20, fontname="Times New Roman")

        # plt.bar(index, values)

        # plt.xticks(index, ['A', 'B', 'C', 'D', 'E'])

        # plt.show()

        # 添加图例
        """
        把标准差的列表传给yerr参数，就能添加标准差。

        error_kw：用于接收其他可用于显示误差线的关键字参数。eColor参数指定误差线的颜色，capsize参数指定误差线两头横线大的宽度。
        alpha：控制彩色条形图的透明度，取值范围是0-1，0表示完全透明，随alpha的增加，对象逐渐清晰起来，到1时不透明。
        label：为图表中的序列指定名称。
        """

        index, values = [0, 1, 2, 3, 4], [10, 20, 30, 40, 50]

        std1 = [0.8, 1, 0.4, 0.9, 1.3]

        plt.title("geek_docs.com", fontsize=20, fontname="Times New Roman")

        plt.bar(index, values, yerr=std1, error_kw={'ecolor': '0.1', 'capsize': 6}, alpha=0.7, label='First')

        plt.xticks(index, ['A', 'B', 'C', 'D', 'E'])
        plt.legend(loc=2)
        plt.show()

        return

    def draw_barh(self):
        """
        水平条形图

        类别分布在y轴上，数值显示在x轴上

        """

        index = np.arange(5)
        values1 = [5, 7, 3, 4, 6]
        std1 = [0.8, 1, 0.4, 0.9, 1.3]

        plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman")
        plt.barh(index, values1, xerr=std1, error_kw={'ecolor': '0.1', 'capsize': 6}, alpha=0.7, label='First')

        plt.yticks(index, ['A', 'B', 'C', 'D', 'E'])
        plt.legend(['First series'], loc=5)
        plt.show()

        return

    def draw_date(self):
        """处理日期"""

        # 获取每月数据
        months = mdates.MonthLocator()

        # 获取每日数据
        days = mdates.DayLocator()

        events = [
            datetime.date(2015, 1, 23), datetime.date(2015, 1, 28),
            datetime.date(2015, 2, 3), datetime.date(2015, 2, 21),
            datetime.date(2015, 3, 15), datetime.date(2015, 3, 24),
            datetime.date(2015, 4, 8), datetime.date(2015, 4, 24)
        ]

        readings = [12, 22, 25, 20, 18, 15, 17, 14]

        fig, ax = plt.subplots()

        plt.plot(events, readings)

        # 设定主/次刻度
        ax.xaxis.set_major_locator(months)
        ax.xaxis.set_minor_locator(days)

        # 设定格式
        timeFmt = mdates.DateFormatter('%Y-%m')
        ax.xaxis.set_major_formatter(timeFmt)

        # 如果日期过长, 可设置旋转 rotation：旋转的大小
        plt.setp(ax.get_xticklabels(), rotation=5, horizontalalignment='right')

        plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman")

        plt.show()

        return

    def draw_pie(self):
        """
        绘制饼图

        labeldistance: 文本的位置离远点有多远，1.1指1.1倍半径的位置

        autopct: 圆里面的文本格式，%3.1f%%表示小数有三位，整数有一位的浮点数

        shadow: 饼是否有阴影

        startangle: 起始角度，0，表示从0开始逆时针转，为第一块。一般选择从90度开始比较好看

        pctdistance: 百分比的text离圆心的距离

        plt.pie的返回值：
            patches, l_texts, p_texts, 为了得到饼图的返回值,
            p_texts饼图内部文本的, l_texts饼图外label的文本
        """

        labels = ['frogs', 'hogs', 'dogs', 'logs']

        # 每个标签占多大，会自动去算百分比
        sizes = [15, 20, 35, 25]

        colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']

        # 将某部分爆炸出来， 使用括号，将第一块分割出来，数值的大小是分割出来的与其他的间隙
        explode = (0, 0.1, 0, 0)

        plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman")

        plt.pie(
            sizes, explode=explode, labels=labels, colors=colors,
            autopct='%1.1f%%', shadow=False, startangle=90
            )

        plt.axis('equal')

        plt.show()

        return

    def three_d_surface(self):
        """
        3D绘图： 曲面图, 散点图, 条形图
        """
        # 1. 曲面图 plot_surface()

        def f(x, y):

            return (1 - y**5 + x**5)*np.exp(-x**2-y**2)

        fig = plt.figure()
        ax = Axes3D(fig)

        X = np.arange(-2, 2, 0.1)
        Y = np.arange(-2, 2, 0.1)
        X, Y = np.meshgrid(X, Y)

        # cmap指定颜色
        ax.plot_surface(X, Y, f(X, Y), rstride=1, cstride=1, cmap=plt.cm.hot)
        # view_init()函数旋转曲面 elev指定从哪个高度查看曲面，azim参数指定曲面旋转的角度
        ax.view_init(elev=30, azim=125)

        plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman")

        plt.show()

        return

    def three_d_scatter(self):
        """
        3D散点图
        """

        xs = np.random.randint(30, 40, 100)
        ys = np.random.randint(20, 30, 100)
        zs = np.random.randint(10, 20, 100)

        xs2 = np.random.randint(50, 60, 100)
        ys2 = np.random.randint(30, 40, 100)
        zs2 = np.random.randint(50, 70, 100)

        xs3 = np.random.randint(10, 30, 100)
        ys3 = np.random.randint(40, 50, 100)
        zs3 = np.random.randint(40, 50, 100)

        fig = plt.figure()
        ax = Axes3D(fig)

        ax.scatter(xs, ys, zs)
        ax.scatter(xs2, ys2, zs2, c='r', marker='^')
        ax.scatter(xs3, ys3, zs3, c='g', marker='*')

        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z label')

        plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman")
        plt.show()

        return

    def three_d_bar(self):
        """
        条形图
        """
        x = np.arange(8)
        y = np.random.randint(0, 10, 8)
        y2 = y + np.random.randint(0, 3, 8)
        y3 = y2 + np.random.randint(0, 3, 8)
        y4 = y3 + np.random.randint(0, 3, 8)
        y5 = y4 + np.random.randint(0, 3, 8)
        clr = ['#4bb2c5', '#c5b47f', '#EAA228', '#579575', '#839557', '#958c12', '#953579', '#4b5de4']

        fig = plt.figure()
        ax = Axes3D(fig)

        ax.bar(x, y, 0, zdir='y', color=clr)
        ax.bar(x, y2, 10, zdir='y', color=clr)
        ax.bar(x, y3, 20, zdir='y', color=clr)
        ax.bar(x, y4, 30, zdir='y', color=clr)
        ax.bar(x, y5, 40, zdir='y', color=clr)

        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z label')

        ax.view_init(elev=40)

        plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman")
        plt.show()

        return

if __name__ == "__main__":

    application = MtLibDebug()
    application.three_d_scatter()


import tensorflow as tf

from ..ops import optimizer as opt
from ..ops import layer_collection as lc
from ..ops import sampler as sp
from ..network.registry import get_model
from .base_model import BaseModel
from . import MODE_CLASSIFICATION, MODE_REGRESSION, MODE_IRD

class KFACModel(BaseModel):
    def __init__(self, config, input_dim, n_data):
        super().__init__(config)
        self.layer_collection = lc.LayerCollection()
        self.input_dim = input_dim
        self.n_data = n_data
        self.cov_update_op = None
        self.inv_update_op = None

        self.build_model()
        self.init_optim()
        self.init_saver()

    def build_model(self):
        self.inputs = tf.placeholder(tf.float32, [None] + self.input_dim,
                name="inputs")
        self.aux_inputs = tf.placeholder(tf.float32, [None] + self.input_dim,
                name="aux_inputs")
        self.is_training = tf.placeholder(tf.bool, name="is_training")
        self.n_particles = tf.placeholder(tf.int32, name="n_particles")

        net = get_model(self.config.model_name)

        self.sampler = sp.Sampler(self.config, self.n_data, self.n_particles)
        outputs, aux_outputs, l2_loss, mode = net(self.inputs, self.aux_inputs,
                              self.sampler, self.is_training,
                              self.config.batch_norm, self.layer_collection,
                              self.n_particles)

        self.aux_outputs = aux_outputs
        self.outputs = outputs
        self.mode = mode

        if mode == MODE_REGRESSION:
            self.targets = tf.placeholder(tf.float32, [None])
            targets_ = tf.tile(self.targets, [self.n_particles])
            self.loss = tf.losses.mean_squared_error(targets_,
                    tf.squeeze(outputs, 1))
            self.acc = self.loss
        elif mode == MODE_IRD:
            self.targets = None
            self.aux_lse = tf.reduce_logsumexp(self.aux_outputs, name="aux_lse")
            self.loss = -tf.reduce_mean(tf.subtract(self.outputs, self.aux_lse, name="loss"))
            self.acc = self.loss
        elif mode == MODE_CLASSIFICATION:
            self.targets = tf.placeholder(tf.int64, [None])
            targets_ = tf.tile(self.targets, [self.n_particles])
            logits_ = tf.reduce_mean(
                tf.reshape(outputs, [self.n_particles, -1, tf.shape(outputs)[-1]]
                    ), 0)
            self.acc = tf.reduce_mean(tf.cast(tf.equal(
                self.targets, tf.argmax(logits_, axis=1)), dtype=tf.float32))
            self.loss = tf.reduce_mean(
                tf.nn.sparse_softmax_cross_entropy_with_logits(
                    labels=targets_, logits=outputs))
        else:
            raise TypeError("Illegal mode: {}".format(mode))

        coeff = self.config.kl / (self.n_data * self.config.eta)
        self.total_loss = self.loss + coeff * l2_loss

    def init_optim(self):
        self.optim = opt.KFACOptimizer(
            var_list=self.trainable_variables,
            learning_rate=self.config.learning_rate,
            cov_ema_decay=self.config.cov_ema_decay,
            damping=self.config.damping,
            layer_collection=self.layer_collection,
            norm_constraint=tf.train.exponential_decay(self.config.kl_clip,
                                                       self.global_step_tensor,
                                                       390, 0.95,
                                                       staircase=True),
            momentum=self.config.momentum)

        self.cov_update_op = self.optim.cov_update_op
        self.inv_update_op = self.optim.inv_update_op

        with tf.control_dependencies([self.inv_update_op]):
            self.var_update_op = self.sampler.update(
                    self.layer_collection.get_blocks())

        update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
        with tf.control_dependencies(update_ops):
            self.train_op = self.optim.minimize(self.total_loss,
                    global_step=self.global_step_tensor)


from matplotlib import pyplot as plt
from os import listdir
import numpy as np
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
from keras.applications.inception_v3 import InceptionV3
from keras.applications.mobilenet import MobileNet
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten, GlobalAveragePooling2D
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras import backend as K
from keras import optimizers
from keras import metrics
from keras.utils import np_utils
from keras.models import load_model
from keras.models import save_model
from keras.models import Model
np.random.seed(1)
K.set_image_dim_ordering('tf')
from sys import stdout
from models import *

files=listdir('./data/edited_train')
fileGroups=[]
split=4

for i in range(split):
    fileGroups.append([])

for i in range(split):
    for j in range(int(len(files)/split)):
        fileGroups[np.random.randint(0,split)].append(files[i*int(len(files)/split)+j])

for i in range(len(files)-split*int(len(files)/split)):
    fileGroups[split-1].append(files[split*int(len(files)/split)+i])

model=inception()

acc_x_tst_list=[]
acc_y_tst_list=[]

for k in range(split):
    x_trn_list=[]
    y_trn_list=[]
    x_tst_list=[]
    y_tst_list=[]
    for i,val in enumerate(fileGroups[k]):
        pixelList=[]
        with open('./data/edited_train/'+val, "rb") as f:
            byte=f.read(1)
            while byte:
                pixelList.append(int.from_bytes(byte,byteorder='little',signed=False))
                byte=f.read(1)

        label=pixelList.pop(299*299*3)
        if i%5==0:
            acc_x_tst_list.append(pixelList)
            acc_y_tst_list.append(label)
            x_tst_list.append(pixelList)
            y_tst_list.append(label)

            stdout.write('%r/%d\r'%(i+1,len(fileGroups[k])))
            stdout.flush()
        else:
            x_trn_list.append(pixelList)
            y_trn_list.append(label)

    x_trn=np.reshape(np.array(x_trn_list, dtype=np.float32),[len(x_trn_list),299,299,3])
    y_trn=to_categorical(np.array(y_trn_list),5)
    x_tst=np.reshape(np.array(x_tst_list, dtype=np.float32),[len(x_tst_list),299,299,3])
    y_tst=to_categorical(np.array(y_tst_list),5)

    x_trn/=255.0
    x_tst/=255.0
    print (x_trn.shape)
    print (x_tst.shape)
    print (y_trn.shape)
    print (y_tst.shape)

    history=model.fit(x_trn,y_trn,validation_data=(x_tst,y_tst),epochs=12,batch_size=16,verbose=1)
    print(k+1)

    # # Plot training & validation accuracy values
    # plt.plot(history.history['acc'])
    # plt.plot(history.history['val_acc'])
    # plt.title('Model accuracy')
    # plt.ylabel('Accuracy')
    # plt.xlabel('Epoch')
    # plt.legend(['Train', 'Test'], loc='upper left')
    # plt.show()

    # # Plot training & validation loss values
    # plt.plot(history.history['loss'])
    # plt.plot(history.history['val_loss'])
    # plt.title('Model loss')
    # plt.ylabel('Loss')
    # plt.xlabel('Epoch')
    # plt.legend(['Train', 'Test'], loc='upper left')
    # plt.show()
print(len(acc_x_tst_list))

acc_x_tst_list=np.array(acc_x_tst_list, dtype=np.float32)
acc_x_tst=np.reshape(acc_x_tst_list,[int(len(acc_x_tst_list.flatten())/(3*299*299)),299,299,3])
acc_y_tst=to_categorical(np.array(acc_y_tst_list),5)
acc_x_tst/=255.0
scores=model.evaluate(acc_x_tst,acc_y_tst)

for i,val in enumerate(scores):
    print("%s: %.2f%%" % (model.metrics_names[i], val*100))

model.save_weights('inception_weights.h5')


import unittest

from streamlink.plugins.trovo import Trovo

class TestPluginTrovo(unittest.TestCase):
    def test_can_handle_url(self):
        should_match = [
            'https://trovo.live/Ler_GG',
            'http://trovo.live/Ler_GG'
        ]
        for url in should_match:
            self.assertTrue(Trovo.can_handle_url(url))

    def test_can_handle_url_negative(self):
        should_not_match = [
            'https://www.dummywebsite.com/',
            'http://www.trovo.com/'
        ]
        for url in should_not_match:
            self.assertFalse(Trovo.can_handle_url(url))


# -*- coding: utf-8 -*-

# -- Sheet --

# System testing

import csv
import pytest
import pickle
from github import Github

def parse_url(url):
    new_url = url
    repo_url = new_url.split('/')
    if (len(repo_url) < 5 or len(repo_url) > 5):
        raise (Exception("Sorry, Invalid Url Please enter the url of the main github page..."))
    repo_url = repo_url[3] + '/' + repo_url[4]
    return repo_url

def load_repo_from_file(file):
    with open(file, 'rb') as config_dictionary_file:
        # Step 3
        repo = pickle.load(config_dictionary_file)

    return repo

def get_repo_test(url):
    new_url=parse_url(url)
    github = Github()

    repo = github.get_repo(new_url)

    name=repo.name
    name = str(name)

    with open(name+'.pkl', 'wb') as output:
        pickle.dump(repo, output, pickle.HIGHEST_PROTOCOL)

import statistics

questions_list = ["Are labels used for issue management?",
                    "Is the default set of labels sufficient for issue management?",
                    "Is every contributor active in issue management?",
                    "Is the responsibility of opening and closing issues equally distributed among contributors?",
                    "Are the life times of the issues consistent?",
                    "Are the comments made by the contributors equally distributed among contributors?",
                    "Is commenting used consistently in all issues?",
                    "Are the issues with assigneee completed earlier to compared the ones without assignee?",
                    "What is the ratio of the opened issues grouped under milestone and those not grouped?",
                    "What does the average time between opening and closing the issue?",
                    "What does the average time between opening and closing the milestone?",
                    "Are the comments be posted after the issues are closed or during the process?",
                    "Are the issues grouped under milestone completed earlier compared to the ones not grouped?"]

selectionArray=questions_list
answers_list=[]
def calculate_questions(Repo):
    global selectionArray

    global answers_list
    answers_list = []

    open_issues = Repo.get_issues(state = "open")
    closed_issues = Repo.get_issues(state = "closed")

    for item in selectionArray:
        if (item == "Are labels used for issue management?"):
            labelName = []
            labelCount = 0
            Total_open_issues=[]
            Total_closed_issues=[]
            for issue in open_issues:
                Total_open_issues.append(issue)
            for issue in closed_issues:
                Total_closed_issues.append(issue)

            total_issues = Total_open_issues + Total_closed_issues

            for issue in total_issues:
                total_labels = issue.get_labels()
                for label in total_labels:
                    if(label != None):
                        labelCount += 1
            totalIssues = len(total_issues)
            control = totalIssues/2

            if labelCount >= control:
                answer = "Yes, labels are important for this repository."
                answers_list.append([item, "Yes"])
            else:
                answer = "No, labels are NOT important for this repository."
                answers_list.append([item, "No"])

        elif (item == "Is the default set of labels sufficient for issue management?"):
            control = 0
            defaultLableSet = ["bug", "documentation", "duplicate", "enhancement", "good first issue", "help wanted", "invalid", "question", "wontfix"]
            labelName = []
            for label in Repo.get_labels():
                labelName.append(label.name)
            for tempLabel in labelName:
                if tempLabel not in defaultLableSet:
                    control = control + 1

            if control > 0:
                answer = "No, default set of labels is NOT sufficient for issue management"
                answers_list.append([item, "No"])
            else:
                answer = "Yes, default set of labels is sufficient for issue management"
                answers_list.append([item, "Yes"])

        elif (item == "Is every contributor active in issue management?"):

            open_issue_comment_writer = []
            open_issue_contributors = []
            closed_issue_comment_writer = []
            closed_issue_contributors = []
            all_issue_comment_writer = []
            all_issue_contributors = []

            for issue in open_issues:
                for comment in issue.get_comments():
                    open_issue_comment_writer.append(comment.user.login)

            for issue in open_issues:
                open_issue_contributors.append(issue.user.login)

            for issue in closed_issues:
                for comment in issue.get_comments():
                    closed_issue_comment_writer.append(comment.user.login)

            for issue in closed_issues:
                open_issue_contributors.append(issue.user.login)

            all_issue_comment_writer.extend(open_issue_comment_writer)
            all_issue_comment_writer.extend(closed_issue_comment_writer)
            all_issue_contributors.extend(open_issue_contributors)
            all_issue_contributors.extend(closed_issue_contributors)
            answer = ""
            for i in all_issue_contributors:
                flag = 0
                for j in all_issue_comment_writer:
                    if(i==j):
                        flag=1
                if(flag==0):
                    answer = "No, not every contributor active in issue management"
                    answers_list.append([item, "No"])
                    break

            if(answer==""):
                answer = "Yes, every contributor active in issue management"
                answers_list.append([item, "Yes"])

        elif (item == "Is the responsibility of opening and closing issues equally distributed among contributors?"):#buna bir bakalım
            open_issue_openers = []
            closed_issue_openers = []
            all_issue_openers = []
            open_issue_closers = []
            closed_issue_closers = []
            all_issue_closers = []
            all_issue_openers_and_closers = []
            #issue openers
            for issue in open_issues:
                open_issue_openers.append(issue.user.login)

            for issue in closed_issues:
                closed_issue_openers.append(issue.user.login)

            all_issue_openers.extend(open_issue_openers)
            all_issue_openers.extend(closed_issue_openers)
            total_opening_an_issue = len(all_issue_openers)
            unique_list = []
            for x in all_issue_openers:
                if x not in unique_list:
                    unique_list.append(x)

            #issue closers
            for issue in open_issues:
                if(issue.closed_by!=None):
                    open_issue_closers.append(issue.closed_by.login)

            for issue in closed_issues:
                if(issue.closed_by!=None):
                    closed_issue_closers.append(issue.closed_by.login)

            all_issue_closers.extend(open_issue_closers)
            all_issue_closers.extend(closed_issue_closers)
            total_closing_an_issue = len(all_issue_closers)
            for x in all_issue_closers:
                if x not in unique_list:
                    unique_list.append(x)

            number_of_contributors = len(unique_list)

            all_issue_openers_and_closers.extend(all_issue_openers)
            all_issue_openers_and_closers.extend(all_issue_closers)

            distribution_of_opening_and_closing_issue = (total_opening_an_issue+total_closing_an_issue) / number_of_contributors

            for contributor in unique_list:
                contribution_count = all_issue_openers_and_closers.count(contributor)
                if(((contribution_count-distribution_of_opening_and_closing_issue)<2) and ((distribution_of_opening_and_closing_issue-contribution_count)<2)):
                    answer = "Yes,the responsibility of opening and closing issues is equally distributed among contributors"
                else:
                    answer = "No,the responsibility of opening and closing issues is NOT equally distributed among contributors"
                    break
            if(answer=="Yes,the responsibility of opening and closing issues is equally distributed among contributors"):
                answers_list.append([item, "Yes"])
            elif(answer=="No,the responsibility of opening and closing issues is NOT equally distributed among contributors" ):
                answers_list.append([item, "No"])

        elif (item == "Are the life times of the issues consistent?"):
            issues=[]
            duration_list=[]
            for issue in closed_issues:
                created = issue.created_at
                closed = issue.closed_at
                duration = closed - created
                duration_list.append(duration)
            Mean_duration=0
            for x in duration_list:
                Mean_duration = Mean_duration + x.days
            Mean_duration = Mean_duration/len(duration_list)

            lower_bound = Mean_duration-7
            if(lower_bound<0):
                lower_bound=0
            upper_bound = Mean_duration +7

            count=0
            for i in duration_list:
                if (float(i.days)>=lower_bound and float(i.days)<=upper_bound):
                    count = count +1
            lenght = len(duration_list)

            if ((count/lenght)>=0.8):
                answer = "Yes, life times of the issues are consistent for this Repo"
                answers_list.append([item, "Yes"])
            else:
                answer = "No, life times of the issues are not consistent for this Repo"
                answers_list.append([item, "No"])

        elif (item == "Are the comments made by the contributors equally distributed among contributors?"):

            open_issue_contributors = []
            closed_issue_contributors = []
            all_issue_contributors = []
            opened_issues_total_comments=0
            closed_issues_total_comments=0
            number_of_total_comment=0

            for issue in open_issues:
                opened_issues_total_comments = opened_issues_total_comments + issue.comments

            for issue in closed_issues:
                closed_issues_total_comments = closed_issues_total_comments + issue.comments

            number_of_total_comment =  opened_issues_total_comments + closed_issues_total_comments

            for issue in open_issues:
                open_issue_contributors.append(issue.user.login)

            for issue in closed_issues:
                open_issue_contributors.append(issue.user.login)

            all_issue_contributors.extend(open_issue_contributors)
            all_issue_contributors.extend(closed_issue_contributors)

            unique_list = []
            for x in all_issue_contributors:
                if x not in unique_list:
                    unique_list.append(x)

            number_of_contributors = len(unique_list)

            distribution_of_comments = number_of_total_comment/number_of_contributors

            open_issue_comment_writer = []
            closed_issue_comment_writer = []
            all_issue_comment_writer = []

            for issue in open_issues:
                for comment in issue.get_comments():
                    open_issue_comment_writer.append(comment.user.login)

            for issue in closed_issues:
                for comment in issue.get_comments():
                    closed_issue_comment_writer.append(comment.user.login)

            all_issue_comment_writer.extend(open_issue_comment_writer)
            all_issue_comment_writer.extend(closed_issue_comment_writer)
            answer=""

            for writer in all_issue_comment_writer:
                count = 0
                for ele in all_issue_comment_writer:
                    if (ele == writer):
                        count = count + 1
                count = count - 1
                if(distribution_of_comments!=count):
                    answer = "No,the comments made by the contributors NOT equally distributed among contributors"
                    answers_list.append([item, "No"])
                    break
                if(answer!=""):
                    break

            if(answer==""):
                answer = "Yes,the comments made by the contributors equally distributed among contributors"
                answers_list.append([item, "Yes"])

        elif (item == "Is commenting used consistently in all issues?"):
            check = 0

            for i in open_issues:
                if(i.comments == 0):
                    check = 1
            if(check ==1 ):
                answer = "No, commenting is NOT used consistently in all issues"
                answers_list.append([item, "No"])
            else:
                for i in closed_issues:
                    if(i.comments == 0):
                        check = 1

                if(check ==1 ):
                    answer = "No, commenting is NOT used consistently in all issues"
                    answers_list.append([item, "NO"])
                else:
                    answer = "Yes, commenting is used consistently in all issues"
                    answers_list.append([item, "Yes"])

        elif (item == "Are the issues with assigneee completed earlier to compared the ones without assignee?"):
            issue_number=0
            with_assignee=0
            without_assignee=0
            without_assignee_time=0
            with_assignee_time=0
            total_issues = []
            for i in closed_issues:
                issue_number+=1
                if(i.assignee == None):
                    without_assignee +=1

                    without_assignee_time += (i.closed_at.timestamp() - i.created_at.timestamp())
                else:
                    with_assignee +=1
                    with_assignee_time += i.closed_at.timestamp() - i.created_at.timestamp()

            average_with_assignee = with_assignee_time / with_assignee
            average_without_assignee = without_assignee_time / without_assignee

            if(average_with_assignee > average_without_assignee):
                answer = "No, issues without assignees has been completed earlier"
                answers_list.append([item, "No"])
            else:
                answer = "Yes, issues with assignees has been completed earlier"
                answers_list.append([item, "Yes"])

        elif (item == "What is the ratio of the opened issues grouped under milestone and those not grouped?"):
            open_issue_number = 0
            with_milestone_number = 0
            without_milestone_nnumber = 0

            open_issues_milestone_none = Repo.get_issues(state="open",milestone="none")

            for i in open_issues:
                open_issue_number +=1
            for i in open_issues_milestone_none:
                without_milestone_nnumber +=1
            with_milestone_number = open_issue_number - without_milestone_nnumber
            if(without_milestone_nnumber == 0 and with_milestone_number !=0):
                percentage = 100
            if(without_milestone_nnumber == 0 and with_milestone_number ==0):
                percentage = 0
            if(without_milestone_nnumber != 0):
                percentage = (with_milestone_number / without_milestone_nnumber) * 100

            answers_list.append([item, percentage])

        elif (item == "What does the average time between opening and closing the issue?"):
            Total_closed_issues=[]
            duration = []
            Avg_duration = 0
            for issue in closed_issues:
                Total_closed_issues.append(issue)
            for issue in Total_closed_issues:
                opened = issue.created_at
                closed = issue.closed_at
                temp_duration = closed - opened
                duration.append(temp_duration)
            for x in duration:
                Avg_duration = Avg_duration + x.days
            Avg_duration = Avg_duration/len(Total_closed_issues)

            answers_list.append([item, Avg_duration])

        elif (item == "What does the average time between opening and closing the milestone?"):
            Total_closed_milestones=[]
            duration = []
            closed_milestones = Repo.get_milestones(state='closed')
            Avg_duration = 0
            for milestone in closed_milestones:
                Total_closed_milestones.append(milestone)
            for issue in Total_closed_milestones:
                opened = milestone.created_at
                closed = milestone.due_on
                temp_duration = closed - opened
                duration.append(temp_duration)
            for x in duration:
                Avg_duration = Avg_duration + x.days
            Avg_duration = Avg_duration/len(Total_closed_milestones)

            answers_list.append([item, Avg_duration])

        elif (item == "Are the comments be posted after the issues are closed or during the process?"):
            open_total_comments = 0
            before_closed_comments = 0
            after_closed_comments = 0
            for issue in open_issues:
                comments = issue.comments
                open_total_comments += comments
            for issue in closed_issues:
                total_closed_comments = issue.comments
                comments2 = issue.get_comments(since=issue.closed_at)
                for comment in comments2:
                    after_closed_comments += len(comment)
                    before_closed_comments += (total_closed_comments - after_closed_comments)

            before_closed_comments += open_total_comments

            if(before_closed_comments >= after_closed_comments):
                answer = "No, the comments are generally posted during the process for this Repo."
                answers_list.append([item, "No"])
            else:
                answer = "Yes, the comments are generally posted after the issues are closed for this Repo."
                answers_list.append([item, "Yes"])

        elif (item == "Are the issues grouped under milestone completed earlier compared to the ones not grouped?"):
            Total_milestones=[]
            Total_Issues=[]
            grouped = []
            notgrouped = []

            opened_milestones = Repo.get_milestones(state='open')
            closed_milestones = Repo.get_milestones(state='closed')

            for milestone in opened_milestones:
                Total_milestones.append(milestone)
            for milestone in closed_milestones:
                Total_milestones.append(milestone)

            for issue in closed_issues:
                Total_Issues.append(issue)

            for issue in Total_Issues:
                if issue.milestone in Total_milestones:
                    grouped.append(issue)
                else:
                    notgrouped.append(issue)

            grouped_time = 0
            notgrouped_time = 0

            for elem in grouped:
                opened = elem.created_at
                closed = elem.closed_at
                temp_duration = closed - opened
                grouped_time += temp_duration.days
            grouped_time = grouped_time / len(grouped)

            for elem in notgrouped:
                opened = elem.created_at
                closed = elem.closed_at
                temp_duration = closed - opened
                notgrouped_time += temp_duration.days
            notgrouped_time = notgrouped_time / len(notgrouped)

            if(grouped_time >= notgrouped_time):
                answer = "Yes, the issues grouped under milestone completed earlier compared to the ones not grouped."
                answers_list.append([item, "Yes"])
            else:
                answer = "No, the issues not grouped under milestone completed earlier compared to the ones grouped."
                answers_list.append([item, "No"])

        else:
            print("Error...")

def Test_Function(index,control_type,value):
    global answers_list

    item=answers_list[index]
    item=item[1]

    if(item):
        if(type(item)==control_type):
            if(item==value):
                pass
            else:
                return False
        else:
           return False
    else:
        return False
    return True

if __name__ == "__main__":
    get_repo_test("https://github.com/DIP-Group/GithubTracker")

    repo=load_repo_from_file("GithubTracker.pkl")

    testResult=[]
    calculate_questions(repo)
    testResult.append(Test_Function(0,str,"No"))
    testResult.append(Test_Function(1,str,"Yes"))
    testResult.append(Test_Function(2,str,"No"))
    testResult.append(Test_Function(3,str,"No"))
    testResult.append(Test_Function(4,str,"No"))
    testResult.append(Test_Function(5,str,"No"))
    testResult.append(Test_Function(6,str,"No"))
    testResult.append(Test_Function(7,str,"No"))
    testResult.append(Test_Function(8,int,100))
    testResult.append(Test_Function(9,float,36.0))
    testResult.append(Test_Function(10,float,7.0))
    testResult.append(Test_Function(11,str,"No"))
    testResult.append(Test_Function(12,str,"Yes"))

    counter = 1
    for element in testResult:
        print("Question Calculation {}:".format(counter))
        if(element):
            print("Test Success")
        else:
            print("Test Failed")
        counter += 1


import requests
from operator import itemgetter

url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
print('status:',r.status_code)

submission_ids = r.json()
submission_dicts = []

for submission_id in submission_ids[:30]:
    url = ('https:/hacker-news.firebaseio.com/v0/item'+str(submission_id)+'.json')
    submission_r = requests.get(url)
    print(submission_r.status_code)
    response_dict = submission_r.json()

    submission_dict = {
        'title':response_dict['title'],
        'link': 'https:/news.ycombinator.com/item?id='+str(submission_id),
        'comments':response_dict.get('descendants',0)
    }
submission_dicts.append(submission_dict)

submission_dicts.sorted(submission_dicts,key = itemgetter('comments'),reverse = True)

for submission_dict in submission_dicts:
    print('\nTitles:',submission_dict['title'])
    print('Discussion link: ',submission_dict['link'])
    print('Comments:',submission_dict['comments'])


import os
import signal
import threading
import time
from pynput import keyboard
from pynput import mouse

print('ESC=退出程序 F11=停止程序 F12=开始程序')
flag = True

def stop():
    def on_press(key):
        pass
    def on_release(key):
        global flag
        if key == keyboard.Key.esc:
            print('退出')
            os.kill(os.getpid(), signal.SIGTERM)
        elif key == keyboard.Key.f12:
            print('开始')
            flag = True
        elif key == keyboard.Key.f11:
            print('停止')
            flag = False
        else:
            pass
    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

t = threading.Thread(target=stop)
t.start()

def main():
    print('正在..')
    c = keyboard.Controller()
    while True:
        if flag:
            print('start')
            print(mouse.Controller().position)
            mouse.Controller().press(mouse.Button.left)
            mouse.Controller().move(0, -30)
            time.sleep(1)
            mouse.Controller().release(mouse.Button.left)
            # mouse.Controller().move(0, 10)
            time.sleep(3)
            mouse.Controller().move(0, 30)
            print(mouse.Controller().position)
            print('end')
            time.sleep(25)
        else:
            continue

print('10s后自动开始程序')
main()


"""This example creates a curved center column with a few different sizes.
The shape is then converted into a neutronics geometry and the heat deposited
is simulated for a few different sizes of ceter column"""

import matplotlib.pyplot as plt
import openmc
import paramak

def main():

    # makes the component with a few different size mid radius values
    my_shape = paramak.CenterColumnShieldHyperbola(
        height=500,
        inner_radius=50,
        mid_radius=70,
        outer_radius=100,
        material_tag='center_column_shield_mat',
        method='pymoab',
    )

    my_shape.export_stp('my_shape.stp')

    # makes the openmc neutron source at x,y,z 0, 0, 0 with isotropic
    # diections
    source = openmc.Source()
    source.space = openmc.stats.Point((0, 0, 0))
    source.angle = openmc.stats.Isotropic()

    # converts the geometry into a neutronics geometry
    my_model = paramak.NeutronicsModel(
        geometry=my_shape,
        source=source,
        materials={'center_column_shield_mat': 'WB'},  # WB is tungsten boride
        cell_tallies=['heating', 'TBR'],
        mesh_tally_2d=['heating'],
        mesh_tally_3d=['heating'],
        simulation_batches=10,  # should be increased for more accurate result
        simulation_particles_per_batch=10,  # settings are low to reduce time required
    )

    # performs an openmc simulation on the model
    my_model.simulate()

if __name__ == "__main__":
    main()


import ipaddress

class SMBTarget:
	def __init__(self):
		self.ip = None
		self.port = 445
		self.hostname = None
		self.timeout = 1
		self.dc_ip = None
		self.domain = None

	def to_target_string(self):
		return 'cifs/%s@%s' % (self.hostname, self.domain)

	@staticmethod
	def from_connection_string(s):
		port = 445
		dc = None

		t, target = s.rsplit('@', 1)
		if target.find('/') != -1:
			target, dc = target.split('/')

		if target.find(':') != -1:
			target, port = target.split(':')

		st = SMBTarget()
		st.port = port
		st.dc_ip = dc
		st.domain, t = s.split('/', 1)

		try:
			st.ip = str(ipaddress.ip_address(target))
		except:
			st.hostname = target

		return st

	def get_ip(self):
		if not self.ip and not self.hostname:
			raise Exception('SMBTarget must have ip or hostname defined!')
		return self.ip if self.ip is not None else self.hostname

	def get_hostname(self):
		raise Exception('Not implemented!')

	def get_hostname_or_ip(self):
		if self.hostname:
			return self.hostname
		return self.ip

	def get_port(self):
		return self.port

	def __str__(self):
		t = '==== SMBTarget ====\r\n'
		for k in self.__dict__:
			t += '%s: %s\r\n' % (k, self.__dict__[k])

		return t

def test():
	s = 'TEST/victim/ntlm/nt:AAAAAAAA@10.10.10.2:445'
	creds = SMBTarget.from_connection_string(s)
	print(str(creds))

	s = 'TEST/victim/sspi@10.10.10.2:445/aaaa'
	creds = SMBTarget.from_connection_string(s)

	print(str(creds))

if __name__ == '__main__':
	test()


# uncompyle6 version 3.7.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-x86_64/egg/ztfy/base/path.py
# Compiled at: 2014-05-08 10:20:31
__docformat__ = 'restructuredtext'
from ztfy.base.interfaces import IPathElements, IBaseContent
from zope.component import adapts
from zope.interface import implements
from zope.traversing.api import getPath

class PathElementsAdapter(object):
    adapts(IBaseContent)
    implements(IPathElements)

    def __init__(self, context):
        self.context = context

    @property
    def paths(self):
        result = []
        path = getPath(self.context)
        if not path.startswith('/'):
            return None
        else:
            elements = path.split('/')
            for index in range(len(elements)):
                result.append(('/').join(elements[0:index + 1]))

            return result[1:]


import cocos
import cocos.euclid as eu
import cocos.collision_model as cm
import cocos.director as cd
from pyglet.window import key

class Actor(cocos.sprite.Sprite):
    def __init__(self, x, y, color):
        super(Actor, self).__init__('img/ball.png',
                                    color=color)
        pos = eu.Vector2(x, y)
        self.position = pos
        self.cshape = cm.CircleShape(pos, self.width / 2)

        self.speed = 200

class MainLayer(cocos.layer.Layer):
    def __init__(self):
        super(MainLayer, self).__init__()

        self.player = Actor(320, 240, (0, 0, 255))
        self.add(self.player)

        self.points = 0
        self.elapsed_game_time = 0

        self.pickups = []

        for pos in [(100, 100), (540, 380), (540, 100), (100, 300)]:
            red_ball = Actor(pos[0], pos[1], (255, 0, 0))
            self.add(red_ball)
            self.pickups.append(red_ball)

        self.schedule(self.update)

        w, h = cd.director.get_window_size()

        cell = self.player.width * 1.25
        self.collman = cm.CollisionManagerGrid(0, w, 0, h, cell, cell)

    def update(self, delta_time):
        print(delta_time)
        if self.points < 4:
            self.elapsed_game_time += delta_time
            hud.update_time(self.elapsed_game_time)

        self.collman.clear()

        for _, actor in self.children:
            self.collman.add(actor)

        for other in self.collman.iter_colliding(self.player):
            self.remove(other)
            self.points += 1
            hud.update_point(self.points)

        horizontal_movement = keyboard[key.RIGHT] - keyboard[key.LEFT]
        vertical_movement = keyboard[key.UP] - keyboard[key.DOWN]

        pos = self.player.position  # (x, y)

        new_x = pos[0] + (self.player.speed * horizontal_movement * delta_time)
        new_y = pos[1] + (self.player.speed * vertical_movement * delta_time)

        w, h = cd.director.get_window_size()

        if 0 <= new_x <= w and 0 <= new_y <= h:
            self.player.position = (new_x, new_y)
            self.player.cshape.center = self.player.position

class HUD(cocos.layer.Layer):
    def __init__(self):
        super(HUD, self).__init__()
        w, h = cd.director.get_window_size()

        self.points_text = cocos.text.Label('Points: 0', font_size=18,
                                            anchor_x='center',
                                            anchor_y='center')
        self.points_text.position = (w / 2, h - 50)
        self.add(self.points_text)

        self.time_text = cocos.text.Label('Time: 0', font_size=18,
                                            anchor_x='center',
                                            anchor_y='center')
        self.time_text.position = (w / 2, h - 100)
        self.add(self.time_text)

    def update_point(self, points):
        self.points_text.element.text = 'Points: {}'.format(points)

    def update_time(self, time):
        self.time_text.element.text = 'Time: {:.2f}'.format(time)

if __name__ == '__main__':
    cd.director.init(caption='Cocos Demo')
    keyboard = key.KeyStateHandler()
    cd.director.window.push_handlers(keyboard)

    hud = HUD()
    layer = MainLayer()
    scene = cocos.scene.Scene()
    scene.add(hud)
    scene.add(layer)
    cd.director.run(scene)


# Copyright 2016 Google Inc.
#
# 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 webapp2
import random

class MainPage(webapp2.RequestHandler):
    def get(self):
        movie_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write('<title>Test</title>')
        self.response.write(random.choice(movie_list))
        self.response.write('')

app = webapp2.WSGIApplication([
    ('/', MainPage),
], debug=True)


import os
import pickle
import sys
sys.path.insert(0,'../module')
from gen_dataset_region import GenDatasetRegion
from options import opts
# TO-D0:
# 1. Loading data for SL training must return a train/test split

def load_data(data_path, img_home, arg=None):
    with open(data_path, 'rb') as f:
        data = pickle.load(f)

    K = len(data)
    print("Data length: {}".format(K))
    dataset = [None] * K

    # TO-DO:
    # - GenDatasetRegion will be different for RL/SL/OL training.
    # - Use arg (str) to determine.
    #print(arg)

    for k, (seq_name, seq) in enumerate(data.items()):
        img_list, gt = seq['images'], seq['gt']

        img_dir = os.path.join(img_home, seq_name)
        ##print("img_dir: ", img_dir)
        dataset[k] = GenDatasetRegion(img_dir, img_list, gt, opts, arg)

    return dataset


# Python3 program to find the length
# of the longest substrring without
# repeating characters

# This functionr eturns true if all
# characters in strr[i..j] are
# distinct, otherwise returns false
def areDistinct(strr, i, j):

    # Note : Default values in visited are false
    visited = [0] * (26)

    for k in range(i, j + 1):
        if (visited[ord(strr[k]) -
                   ord('a')] == True):
            return False

        visited[ord(strr[k]) -
                ord('a')] = True

    return True

# Returns length of the longest substrring
# with all distinct characters.
def longestUniqueSubsttr(strr):

    n = len(strr)

    # Result
    res = 0

    for i in range(n):
        for j in range(i, n):
            if (areDistinct(strr, i, j)):
                res = max(res, j - i + 1)

    return res

# Driver code
if __name__ == '__main__':

    strr = "geeksforgeeks"
    print("The input is ", strr)

    len = longestUniqueSubsttr(strr)
    print("The length of the longest "
          "non-repeating character substring is ", len)


# -*- coding: utf-8 -*-

# IO-4 Bricklet communication config

com = {
    'author': 'Olaf Lüke <olaf@tinkerforge.com>',
    'version': [1, 0, 1],
    'category': 'Bricklet',
    'name': ('IO4', 'io4', 'IO-4'),
    'manufacturer': 'Tinkerforge',
    'description': 'Device for controlling up to 4 general purpose input/output pins',
    'packets': []
}

com['packets'].append({
'type': 'function',
'name': ('SetValue', 'set_value'),
'elements': [('value_mask', 'uint8', 1, 'in')],
'doc': ['bf', {
'en':
"""
Sets the output value (high or low) with a bit mask. The bit mask
is 4 bit long, *true* refers to high and *false* refers to low.

For example: The value 0b0011 will turn the pins 0-1 high and the
pins 2-3 low.

.. note::
 This function does nothing for pins that are configured as input.
 Pull-up resistors can be switched on with :func:`SetConfiguration`.
""",
'de':
"""
Setzt den Ausgangszustand (logisch 1 oder logisch 0) mittels einer Bitmaske.
Die Bitmaske hat eine Länge von 4 Bit, *true* bedeutet logisch 1 und *false*
logisch 0.

Beispiel: Der Wert 0b0011 setzt die Pins 0-1 auf logisch 1 und die Pins 2-3
auf logisch 0.

.. note::
 Diese Funktion bewirkt keine Änderung an Pins die als Eingang konfiguriert sind.
 Pull-Up Widerstände können mit :func:`SetConfiguration` zugeschaltet werden.
"""
}]
})

com['packets'].append({
'type': 'function',
'name': ('GetValue', 'get_value'),
'elements': [('value_mask', 'uint8', 1, 'out')],
'doc': ['bf', {
'en':
"""
Returns a bit mask of the values that are currently measured.
This function works if the pin is configured to input
as well as if it is configured to output.
""",
'de':
"""
Gibt eine Bitmaske der aktuell gemessenen Zustände zurück.
Diese Funktion gibt die Zustände aller Pins zurück, unabhängig ob diese als
Ein- oder Ausgang konfiguriert sind.
"""
}]
})

com['packets'].append({
'type': 'function',
'name': ('SetConfiguration', 'set_configuration'),
'elements': [('pin_mask', 'uint8', 1, 'in'),
             ('direction', 'char', 1, 'in'),
             ('value', 'bool', 1, 'in')],
'doc': ['bf', {
'en':
"""
Configures the value and direction of the specified pins. Possible directions
are "i" and "o" for input and output.

If the direction is configured as output, the value is either high or low
(set as *true* or *false*).

If the direction is configured as input, the value is either pull-up or
default (set as *true* or *false*).

For example:

* (15, 'i', true) will set all pins of as input pull-up.
* (8, 'i', false) will set pin 3 of as input default (floating if nothing is connected).
* (3, 'o', false) will set pins 0 and 1 as output low.
* (4, 'o', true) will set pin 2 of as output high.
""",
'de':
"""
Konfiguriert den Zustand und die Richtung eines angegebenen Pins. Mögliche
Richtungen sind "i" und "o" für Ein- und Ausgang.

Wenn die Richtung als Ausgang konfiguriert ist, ist der Zustand entweder
logisch 1 oder logisch 0 (gesetzt als *true* oder *false*).

Wenn die Richtung als Eingang konfiguriert ist, ist der Zustand entweder
Pull-Up oder Standard (gesetzt als *true* oder *false*).

Beispiele:

* (15, 'i', true) setzt alle Pins als Eingang mit Pull-Up.
* (8, 'i', false) setzt Pin 3 als Standard Eingang (potentialfrei wenn nicht verbunden).
* (3, 'o', false) setzt die Pins 0 und 1 als Ausgang im Zustand logisch 0.
* (4, 'o', true) setzt Pin 2 als Ausgang im Zustand logisch 1.
"""
}]
})

com['packets'].append({
'type': 'function',
'name': ('GetConfiguration', 'get_configuration'),
'elements': [('direction_mask', 'uint8', 1, 'out'),
             ('value_mask', 'uint8', 1, 'out')],
'doc': ['bf', {
'en':
"""
Returns a value bit mask and a direction bit mask.

For example: A return value of 0b0011 and 0b0101 for
direction and value means that:

* pin 0 is configured as input pull-up,
* pin 1 is configured as input default,
* pin 2 is configured as output high
* and pin 3 is are configured as output low.
""",
'de':
"""
Gibt eine Bitmaske für die Richtung und eine Bitmaske für den Zustand der Pins
zurück.

Beispiel: Ein Rückgabewert von 0b0011 und 0b0101 für Richtung und Zustand
bedeutet:

* Pin 0 ist als Eingang mit Pull-Up konfiguriert,
* Pin 1 ist als Standard Eingang konfiguriert,
* Pin 2 ist als Ausgang im Zustand logisch 1 konfiguriert
* und Pin 3 ist als Ausgang im Zustand logisch 0 konfiguriert.
"""
}]
})

com['packets'].append({
'type': 'function',
'name': ('SetDebouncePeriod', 'set_debounce_period'),
'elements': [('debounce', 'uint32', 1, 'in')],
'doc': ['ccf', {
'en':
"""
Sets the debounce period of the :func:`Interrupt` callback in ms.

For example: If you set this value to 100, you will get the interrupt
maximal every 100ms. This is necessary if something that bounces is
connected to the IO-4 Bricklet, such as a button.

The default value is 100.
""",
'de':
"""
Setzt die Entprellperiode der :func:`Interrupt` Callback in ms.

Beispiel: Wenn dieser Wert auf 100 gesetzt wird, erhält man den Interrupt
maximal alle 100ms. Dies ist notwendig falls etwas prellendes an
das IO-4 Bricklet angeschlossen ist, wie z.B. eine Taste.

Der Standardwert ist 100.
"""
}]
})

com['packets'].append({
'type': 'function',
'name': ('GetDebouncePeriod', 'get_debounce_period'),
'elements': [('debounce', 'uint32', 1, 'out')],
'doc': ['ccf', {
'en':
"""
Returns the debounce period as set by :func:`SetDebouncePeriod`.
""",
'de':
"""
Gibt die Entprellperiode zurück, wie von :func:`SetDebouncePeriod`
gesetzt.
"""
}]
})

com['packets'].append({
'type': 'function',
'name': ('SetInterrupt', 'set_interrupt'),
'elements': [('interrupt_mask', 'uint8', 1, 'in')],
'doc': ['ccf', {
'en':
"""
Sets the pins on which an interrupt is activated with a bit mask.
Interrupts are triggered on changes of the voltage level of the pin,
i.e. changes from high to low and low to high.

For example: An interrupt bit mask of 9 will enable the interrupt for
pins 0 and 3.

The interrupt is delivered with the callback :func:`Interrupt`.
""",
'de':
"""
Setzt durch eine Bitmaske die Pins für welche der Interrupt aktiv ist.
Interrupts werden ausgelöst bei Änderung des Spannungspegels eines Pins,
z.B. ein Wechsel von logisch 1 zu logisch 0 und logisch 0 zu logisch 1.

Beispiel: Eine Interrupt Bitmaske von 9 aktiviert den Interrupt für die
Pins 0 und 3.

Der Interrupt wird mit der Callback :func:`Interrupt` zugestellt.
"""
}]
})

com['packets'].append({
'type': 'function',
'name': ('GetInterrupt', 'get_interrupt'),
'elements': [('interrupt_mask', 'uint8', 1, 'out')],
'doc': ['ccf', {
'en':
"""
Returns the interrupt bit mask as set by :func:`SetInterrupt`.
""",
'de':
"""
Gibt die Interrupt Bitmaske zurück, wie von :func:`SetInterrupt` gesetzt.
"""
}]
})

com['packets'].append({
'type': 'callback',
'name': ('Interrupt', 'interrupt'),
'elements': [('interrupt_mask', 'uint8', 1, 'out'),
             ('value_mask', 'uint8', 1, 'out')],
'doc': ['c', {
'en':
"""
This callback is triggered whenever a change of the voltage level is detected
on pins where the interrupt was activated with :func:`SetInterrupt`.

The values are a bit mask that specifies which interrupts occurred
and the current value bit mask.

For example:

* (1, 1) means that an interrupt on pin 0 occurred and
  currently pin 0 is high and pins 1-3 are low.
* (9, 14) means that interrupts on pins 0 and 3
  occurred and currently pin 0 is low and pins 1-3 are high.
""",
'de':
"""
Dieser Callback wird ausgelöst sobald eine Änderung des Spannungspegels
detektiert wird, an Pins für welche der Interrupt mit :func:`SetInterrupt`
aktiviert wurde.

Die Rückgabewerte sind eine Bitmaske der aufgetretenen Interrupts und der
aktuellen Zustände.

Beispiele:

* (1, 1) bedeutet, dass ein Interrupt am Pin 0 ist aufgetreten ist und aktuell
  Pin 0 logisch 1 ist und die Pins 1-3 logisch 0 sind.
* (9, 14) bedeutet, dass Interrupts an den Pins 0 und 3 aufgetreten sind und
  aktuell Pin 0 logisch 0 ist und die Pins 1-3 logisch 1 sind.
"""
}]
})

com['packets'].append({
'type': 'function',
'name': ('SetMonoflop', 'set_monoflop'),
'elements': [('pin_mask', 'uint8', 1, 'in'),
             ('value_mask', 'uint8', 1, 'in'),
             ('time', 'uint32', 1, 'in')],
'doc': ['af', {
'en':
"""
Configures a monoflop of the pins specified by the first parameter as 4 bit
long bit mask. The specified pins must be configured for output. Non-output
pins will be ignored.

The second parameter is a bit mask with the desired value of the specified
output pins (*true* means high and *false* means low).

The third parameter indicates the time (in ms) that the pins should hold
the value.

If this function is called with the parameters ((1 << 0) | (1 << 3), (1 << 0), 1500):
Pin 0 will get high and pin 3 will get low. In 1.5s pin 0 will get low and pin
3 will get high again.

A monoflop can be used as a fail-safe mechanism. For example: Lets assume you
have a RS485 bus and an IO-4 Bricklet connected to one of the slave
stacks. You can now call this function every second, with a time parameter
of two seconds and Pin 0 set to high. Pin 0 will be high all the time. If now
the RS485 connection is lost, then Pin 0 will get low in at most two seconds.

.. versionadded:: 1.1.1
""",
'de':
"""
Konfiguriert einen Monoflop für die Pins, wie mittels der 4 Bit langen Bitmaske
des ersten Parameters festgelegt. Die festgelegten Pins müssen als Ausgänge
konfiguriert sein. Als Eingänge konfigurierte Pins werden ignoriert.

Der zweite Parameter ist eine Bitmaske mit den gewünschten Zustanden der
festgelegten Ausgangspins (*true* bedeutet logisch 1 und *false* logisch 0).

Der dritte Parameter stellt die Zeit (in ms) dar, welche die Pins den Zustand
halten soll.

Wenn diese Funktion mit den Parametern ((1 << 0) | (1 << 3), (1 << 0), 1500)
aufgerufen wird: Pin 0 wird auf logisch 1 und Pin 3 auf logisch 0 gesetzt.
Nach 1,5s wird Pin 0 wieder logisch 0 und Pin 3 logisch 1 gesetzt.

Ein Monoflop kann zur Ausfallsicherung verwendet werden. Beispiel:
Angenommen ein RS485 Bus und ein IO-4 Bricklet ist an ein Slave Stapel verbunden.
Jetzt kann diese Funktion sekündlich, mit einem Zeitparameter von 2 Sekunden,
aufgerufen werden. Der Pin wird die gesamte Zeit im Zustand logisch 1 sein.
Wenn jetzt die RS485 Verbindung getrennt wird, wird der Pin nach spätestens zwei
Sekunden in den Zustand logisch 0 wechseln.

.. versionadded:: 1.1.1
"""
}]
})

com['packets'].append({
'type': 'function',
'name': ('GetMonoflop', 'get_monoflop'),
'elements': [('pin', 'uint8', 1, 'in'),
             ('value', 'uint8', 1, 'out'),
             ('time', 'uint32', 1, 'out'),
             ('time_remaining', 'uint32', 1, 'out')],
'doc': ['af', {
'en':
"""
Returns (for the given pin) the current value and the time as set by
:func:`SetMonoflop` as well as the remaining time until the value flips.

If the timer is not running currently, the remaining time will be returned
as 0.

.. versionadded:: 1.1.1
""",
'de':
"""
Gibt (für den angegebenen Pin) den aktuellen Zustand und die Zeit, wie von
:func:`SetMonoflop` gesetzt, sowie die noch verbleibende Zeit bis zum
Zustandswechsel, zurück.

Wenn der Timer aktuell nicht läuft, ist die noch verbleibende Zeit 0.

.. versionadded:: 1.1.1
"""
}]
})

com['packets'].append({
'type': 'callback',
'name': ('MonoflopDone', 'monoflop_done'),
'elements': [('pin_mask', 'uint8', 1, 'out'),
             ('value_mask', 'uint8', 1, 'out')],
'doc': ['c', {
'en':
"""
This callback is triggered whenever a monoflop timer reaches 0. The
:word:`parameters` contain the involved pins and the current value of the pins
(the value after the monoflop).

.. versionadded:: 1.1.1
""",
'de':
"""
Dieser Callback wird ausgelöst wenn ein Monoflop Timer abläuft (0 erreicht).
:word:`parameters` enthalten die beteiligten Pins als Bitmaske und den aktuellen
Zustand als Bitmaske (der Zustand nach dem Monoflop).

.. versionadded:: 1.1.1
"""
}]
})


# since we don't have access to the flask app at the global level
# we must use the blueprint
from app.pet_site.models import Pet
from app.pet_site import pets
from app import db
from flask_login import login_required
from flask import render_template, flash, request, redirect, url_for
from app.pet_site.forms import CreatePetForm, EditPetForm
from sqlalchemy import exc
from datetime import date

site_name = "Gianna's Dog House"

@pets.route('/')
@pets.route('/pet_site')
def display_home():
    return render_template('home.html', site_name=site_name)

@pets.route('/pet_site/delete/<pet_id>', methods=['GET','POST'])
@login_required
def delete_pet(pet_id):
    pet = Pet.query.get(pet_id)
    if request.method == 'POST':
        db.session.delete(pet)
        db.session.commit()
        msg = 'pet with id of ' + pet_id + ' deleted successfully'
        flash(msg)
        return redirect(url_for('pets.display_pets'))
    # get request
    return  render_template('delete_pet.html', pet=pet, pet_id=pet.id, site_name=site_name)

@pets.route('/pet_site/pets/')
def display_pets():

    pets = Pet.query.all()
    today = date.today()

    # calculate the pet's age and store in the pet object attribute
    for pet in pets:
        born = pet.birthdate
        age = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
        pet.age = age
    return  render_template('pets.html', pets=pets, site_name=site_name) # pass pets instance

@pets.route('/pet_site/reg_pet', methods=['GET', 'POST'])
@login_required
def create_pet():

    # create the form
    form = CreatePetForm()

    # form.owner_id = owner_id

    if form.validate_on_submit():
        pet = Pet(owner=form.owner.data,
                name=form.name.data,
                breed=form.breed.data,
                phone=form.phone.data,
                sex=form.sex.data,
                neutered=form.neutered.data,
                vetinfo=form.vetinfo.data,
                feeding=form.feeding.data,
                exercise=form.exercise.data,
                notes=form.notes.data,
                birthdate=form.birthdate.data)
        try:
            db.session.add(pet)
            db.session.commit()
        except exc.IntegrityError as i:
            flash(i)
            return redirect(url_for('pets.display_home'))
        msg = 'Pet registration data added successfully'
        flash(msg)
        return redirect(url_for('pets.display_home'))
    # get request
    return  render_template('register_pet.html', form=form, site_name="Gianna's Dog House")

@pets.route('/pet_site/edit/<pet_id>', methods=['GET','POST'])
@login_required
def edit_pet(pet_id):
    pet = Pet.query.get(pet_id)
    form = EditPetForm(obj=pet)
    # post request
    if form.validate_on_submit():
        pet.owner = form.owner.data
        pet.name = form.name.data
        pet.breed = form.breed.data
        pet.rating = form.rating.data
        pet.notes = form.notes.data
        pet.birthdate = form.birthdate.data

        try:

            db.session.add(pet)
            db.session.commit()
        except exc.IntegrityError:
            msg = 'Unable to DB commit! '
        msg = 'pet edited successfully'
        flash(msg)
        return redirect(url_for('pets.display_pets'))
    # get request
    return  render_template('edit_pet.html', form=form ,site_name=site_name)


from django.conf.urls import url, include
from django.contrib import admin

from whatyouspend.transactions.views import *
from whatyouspend.constants import *

urlpatterns = [
    # categories
    url(r'^category/$', CategoryListView.as_view(), name="category-list"),
    url(r'^category/new/$',
        CreateCategoryView.as_view(), name="new-category"),
    url(r'^category/(?P<category>[-\w]+)/edit/$',
        UpdateCategoryView.as_view(),
        name="edit-category"),
    url(r'^category/(?P<category>[-\w]+)/remove/$',
        DeleteCategoryView.as_view(),
        name="remove-category"),
    url(r'^category/(?P<category>[-\w]+)$',
        CategoryDetailView.as_view(),
        {'period': 'this-quarter'},
        name="category-detail"),
    url(r'^category/(?P<category>[-\w]+)/for/(?P<period>[-\w]+)$',
        CategoryDetailView.as_view(),
        name="category-detail"),

    url(r'^guess-transaction-category/$',
        GuessTransactionCategoryView.as_view(),
        name="guess-transaction-category"),

    # transactions
    url(r'^item/new/$',
        TransactionFormView.as_view(),
        name="new-transaction"),
    url(r'^(?P<transaction_type>[-\w]+)/(?P<transaction>[-\w]+)/edit/$',
        TransactionUpdateView.as_view(),
        name="edit-transaction"),
    url(r'^(?P<transaction_type>[-\w]+)/(?P<transaction>[-\w]+)/delete/$',
        TransactionDeleteView.as_view(),
        name="delete-transaction"),
    url(r'^search/$',
        TransactionSearchView.as_view(),
        name="search"),

    # Expenses
    url(r'^expense/$',
        TransactionListView.as_view(),
        {'transaction_type': EXPENSE, 'period': 'this-month'},
        name="expense-list"),
    url(r'^expense/for/(?P<period>[\w-]+)/$',
        TransactionListView.as_view(),
        {'transaction_type': EXPENSE},
        name="expense-list"),
    url(r'^expense/(?P<transaction>[-\w]+)$',
        TransactionDetailView.as_view(),
        {'transaction_type': EXPENSE}, name="expense-detail"),

    # Income Urls
    url(r'^income/$',
        TransactionListView.as_view(),
        {'transaction_type': INCOME,
         'period': 'this-month'}, name="income-list"),
    url(r'^income/for/(?P<period>[\w-]+)/$',
        TransactionListView.as_view(),
        {'transaction_type': INCOME}, name="income-list"),
    url(r'^income/(?P<transaction>[-\w]+)$',
        TransactionDetailView.as_view(),
        {'transaction_type': INCOME}, name="income-detail"),
]


from minecraft.networking.packets import Packet

from minecraft.networking.types import (
    VarInt, UUID, Byte, Double, Integer, UnsignedByte, Short, Enum, Vector,
    PositionAndLook
)

class SpawnObjectPacket(Packet):
    @staticmethod
    def get_id(context):
        return 0x00 if context.protocol_version >= 67 else \
               0x0E

    packet_name = 'spawn object'

    class EntityType(Enum):
        BOAT = 1
        ITEM_STACK = 2
        AREA_EFFECT_CLOUD = 3
        MINECART = 10
        ACTIVATED_TNT = 50
        ENDERCRYSTAL = 51
        ARROW = 60
        SNOWBALL = 61
        EGG = 62
        FIREBALL = 63
        FIRECHARGE = 64
        ENDERPERL = 65
        WITHER_SKULL = 66
        SHULKER_BULLET = 67
        LLAMA_SPIT = 68
        FALLING_OBJECT = 70
        ITEM_FRAMES = 71
        EYE_OF_ENDER = 72
        POTION = 73
        EXP_BOTTLE = 75
        FIREWORK_ROCKET = 76
        LEASH_KNOT = 77
        ARMORSTAND = 78
        EVOCATION_FANGS = 79
        FISHING_HOOK = 90
        SPECTRAL_ARROW = 91
        DRAGON_FIREBALL = 93

    def read(self, file_object):
        self.entity_id = VarInt.read(file_object)
        if self.context.protocol_version >= 49:
            self.object_uuid = UUID.read(file_object)
        self.type_id = Byte.read(file_object)

        xyz_type = Double if self.context.protocol_version >= 100 else Integer
        for attr in 'x', 'y', 'z':
            setattr(self, attr, xyz_type.read(file_object))
        for attr in 'pitch', 'yaw':
            setattr(self, attr, UnsignedByte.read(file_object))

        self.data = Integer.read(file_object)
        if self.context.protocol_version >= 49 or self.data > 0:
            for attr in 'velocity_x', 'velocity_y', 'velocity_z':
                setattr(self, attr, Short.read(file_object))

    def write_fields(self, packet_buffer):
        VarInt.send(self.entity_id, packet_buffer)
        if self.context.protocol_version >= 49:
            UUID.send(self.object_uuid, packet_buffer)
        Byte.send(self.type_id, packet_buffer)

        xyz_type = Double if self.context.protocol_version >= 100 else Integer
        for coord in self.x, self.y, self.z:
            xyz_type.send(coord, packet_buffer)
        for coord in self.pitch, self.yaw:
            UnsignedByte.send(coord, packet_buffer)

        Integer.send(self.data, packet_buffer)
        if self.context.protocol_version >= 49 or self.data > 0:
            for coord in self.velocity_x, self.velocity_y, self.velocity_z:
                Short.send(coord, packet_buffer)

    # Access the entity type as a string, according to the EntityType enum.
    def type(self, type_name):
        self.type_id = getattr(self.EntityType, type_name)
    type = property(lambda p: p.EntityType.name_from_value(p.type_id), type)

    # Access the fields 'x', 'y', 'z' as a Vector.
    def position(self, position):
        self.x, self.y, self.z = position
    position = property(lambda p: Vector(p.x, p.y, p.z), position)

    # Access the fields 'x', 'y', 'z', 'yaw', 'pitch' as a PositionAndLook.
    # NOTE: modifying the object retrieved from this property will not change
    # the packet; it can only be changed by attribute or property assignment.
    def position_and_look(self, position_and_look):
        self.x, self.y, self.z = position_and_look.position
        self.yaw, self.pitch = position_and_look.look
    position_and_look = property(lambda p: PositionAndLook(
                            x=p.x, y=p.y, z=p.z, yaw=p.yaw, pitch=p.pitch),
                            position_and_look)

    # Access the fields 'velocity_x', 'velocity_y', 'velocity_z' as a Vector.
    def velocity(self, velocity):
        self.velocity_x, self.velocity_y, self.velocity_z = velocity
    velocity = property(lambda p: Vector(p.velocity_x, p.velocity_y,
                                         p.velocity_z), velocity)

    # This alias is retained for backward compatibility.
    def objectUUID(self, object_uuid):
        self.object_uuid = object_uuid
    objectUUID = property(lambda self: self.object_uuid, objectUUID)