# coding=utf-8
# Androxus bot
# Botinfo.py

__author__ = 'Rafael'

from datetime import datetime
from os import getpid
from sys import version

import discord
import psutil
from discord.ext import commands
from stopwatch import Stopwatch

from Classes import Androxus
from database.Conexao import Conexao
from database.Repositories.ComandoDesativadoRepository import ComandoDesativadoRepository
from database.Repositories.ComandoPersonalizadoRepository import ComandoPersonalizadoRepository
from database.Repositories.InformacoesRepository import InformacoesRepository
from database.Repositories.ServidorRepository import ServidorRepository
from utils.Utils import get_last_commit, capitalize, pegar_o_prefixo
from utils.Utils import get_last_update, datetime_format
from utils.Utils import random_color

class Botinfo(commands.Cog, command_attrs=dict(category='bot_info')):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name='botinfo',
                      aliases=['info', 'detalhes'],
                      description='Mostra algumas informações sobre mim!',
                      examples=['``{prefix}botinfo``'],
                      cls=Androxus.Command)
    @commands.max_concurrency(1, commands.BucketType.user)
    async def _botinfo(self, ctx):
        stopwatch_banco = Stopwatch()
        conexao = Conexao()
        stopwatch_banco.stop()
        # se a pessoa usou o comando, mencionando o bot:
        if ctx.prefix.replace("!", "").replace(" ", "") == self.bot.user.mention:
            # vai pegar o prefixo que está no banco
            prefixo = pegar_o_prefixo(self.bot, ctx, False, conexao)
        else:
            # se a pessoa não marcou o bot:
            prefixo = ctx.prefix
        embed = discord.Embed(title=f'<:Info:756712227221930102> Detalhes sobre mim!',
                              colour=discord.Colour(random_color()),
                              description=f'Caso você queira saber meus outros comandos, use ``{prefixo}cmds``!',
                              timestamp=datetime.utcnow())
        embed.set_author(name='Androxus',
                         icon_url=self.bot.user.avatar_url)
        embed.set_footer(text=f'{ctx.author}',
                         icon_url=ctx.author.avatar_url)
        embed.add_field(name=':calendar: Data que fui criado:',
                        value=f'``{self.bot.user.created_at.strftime("%d/%m/%Y")}``',
                        inline=True)
        embed.add_field(name=':older_adult: Idade:',
                        value=f'``{datetime_format(self.bot.user.created_at)}``',
                        inline=True)
        embed.add_field(name=':robot: Meu perfil:',
                        value=f'``{str(self.bot.user)}``',
                        inline=True)
        embed.add_field(name=':id: Meu id:',
                        value=f'``{self.bot.user.id}``',
                        inline=True)
        embed.add_field(name='<:WumpusCrown:756712226978660392> Meu dono:',
                        value=f'``{self.bot.get_user(self.bot.owner_id)}``',
                        inline=True)
        embed.add_field(name='<a:pato:755774683348992060> Quantos servidores estão me usando:',
                        value=f'``{len(self.bot.guilds)}``',
                        inline=True)
        embed.add_field(name='<a:parrot_dancando:755774679670718575> Quantas pessoas têm acesso a mim:',
                        # observer, que aqui, estamos pegando a lista de membros e jogando para um set
                        # pois, o "set" não permite que haja itens duplicados, ou seja, fazendo desta forma
                        # cada item vai ser único
                        value=f'``{str(len(set(self.bot.get_all_members())))}``',
                        inline=True)
        embed.add_field(name=':ping_pong: Latência da API:',
                        value=f'``{int(self.bot.latency * 1000)}ms``',
                        inline=True)
        embed.add_field(name='<:DatabaseCheck:756712226303508530> Tempo para se conectar ao banco:',
                        value=f'``{stopwatch_banco}``',
                        inline=True)
        this_process = psutil.Process(getpid())
        embed.add_field(name='<a:loading:756715436149702806> Uso da CPU:',
                        value=f'``{this_process.cpu_percent():.2f}%``',
                        inline=True)
        embed.add_field(name=':frog: Memória RAM:',
                        value=f'``{(this_process.memory_info().rss / (1e+6)):.2f}Mb' +
                              '/100Mb``',
                        inline=True)
        embed.add_field(name='<:WumpusPizza:756712226710356122> Versão do discord.py:',
                        value=f'``{discord.__version__}``',
                        inline=True)
        embed.add_field(name='<:python:756712226210971660> Versão do python:',
                        value=f'``{version[0:5]}``',
                        inline=True)
        embed.add_field(name=':bank: Banco de dados que estou usando:',
                        value=f'``{InformacoesRepository().get_sql_version(conexao)[:15]}``',
                        inline=True)
        comandos = 0
        for cog in self.bot.cogs:  # adiciona os comandos padrões no embed
            for command in self.bot.get_cog(cog).get_commands():
                if not command.hidden:  # se o comando não estiver privado
                    comandos += 1
        embed.add_field(name=':desktop: Quantos comandos eu tenho:',
                        value=f'``{comandos}``')
        embed.add_field(name=':stopwatch: Quando eu liguei:',
                        value=f'``{datetime_format(self.bot.uptime)}``',
                        inline=True)
        embed.add_field(name=':watch: Última atualização que tive foi:',
                        value=f'``{datetime_format(get_last_update())}``',
                        inline=True)
        await ctx.send(embed=embed)
        conexao.fechar()

    @commands.command(name='source',
                      aliases=['github', 'programação'],
                      description='Mostra o meu código fonte!',
                      examples=['``{prefix}source``'],
                      cls=Androxus.Command)
    async def _source(self, ctx):
        embed = discord.Embed(title=f'Olá {ctx.author.name}, eu sou um bot feito em python, com ' +
                                    'a API do discord e um banco de dados!',
                              colour=discord.Colour(random_color()),
                              description='Caso você queira ver o meu código fonte, clique [aqui]' +
                                          '(https://github.com/devRMA/Androxus)\n' +
                                          'Caso você queira ver a documentação da API do discord ' +
                                          'para python, clique [aqui](https://discordpy.readthedo' +
                                          'cs.io/en/latest/index.html).',
                              timestamp=datetime.utcnow())
        embed.set_author(name='Androxus', icon_url=f'{self.bot.user.avatar_url}')
        embed.set_footer(text=f'{ctx.author}', icon_url=f'{ctx.author.avatar_url}')
        await ctx.send(embed=embed)

    @commands.command(name='ping',
                      aliases=['latency', 'latência'],
                      description='Mostra a minha latência atual.',
                      examples=['``{prefix}ping``'],
                      cls=Androxus.Command)
    async def _ping(self, ctx):
        from stopwatch import Stopwatch
        stopwatch_banco = Stopwatch()
        conexao = Conexao()
        stopwatch_banco.stop()
        conexao.fechar()
        stopwatch_message = Stopwatch()
        mensagem_do_bot = await ctx.send(f'Calculando ping...')
        stopwatch_message.stop()
        await mensagem_do_bot.edit(content=f'Latência da API do discord: {(self.bot.latency * 1000):.2f}ms!\n'
                                           f'Tempo para se conectar ao banco de dados: {str(stopwatch_banco)}!\n'
                                           f'Tempo para enviar uma mensagem: {str(stopwatch_message)}!\n'
                                           '<a:hello:755774680949850173>')

    @commands.command(name='invite',
                      aliases=['convidar', 'convite'],
                      description='Mostra o link que você usa para me adicionar em seu servidor',
                      examples=['``{prefix}invite``'],
                      cls=Androxus.Command)
    async def _invite(self, ctx):
        e = discord.Embed(title=f'Invite',
                          colour=discord.Colour(random_color()),
                          description=f'Clique [aqui](https://discord.com/oauth2/authorize?client_id={self.bot.user.id}'
                                      '&scope=bot&permissions=604892375) para me adicionar em outro servidor! <a:love:7'
                                      '63523322675068958>',
                          timestamp=datetime.utcnow())
        await ctx.send(embed=e)

    @commands.command(name='changelog',
                      aliases=['ultima_att', 'última_att', 'att_log'],
                      description='Mostra quando foi a minha última atualização e ainda mostra o que foi alterado.',
                      examples=['``{prefix}changelog``'],
                      cls=Androxus.Command)
    @commands.max_concurrency(1, commands.BucketType.user)
    async def _changelog(self, ctx):
        embed = discord.Embed(title=f'Ultima atualização que eu tive:',
                                colour=discord.Colour(random_color()),
                                description=f'```{get_last_commit()}```',
                                timestamp=datetime.utcnow())
        embed.set_footer(text=f'{ctx.author}',
                            icon_url=ctx.author.avatar_url)
        embed.add_field(name='Atualização feita em:',
                        value=f'{datetime_format(get_last_update())}',
                        inline=True)
        await ctx.send(embed=embed)

    @commands.command(name='uptime',
                      aliases=['tempo_on'],
                      description='Mostra a quanto tempo eu estou online!',
                      examples=['``{prefix}uptime``'],
                      cls=Androxus.Command)
    async def _uptime(self, ctx):
        embed = discord.Embed(title=f':timer: Quando eu liguei:',
                              description=f'``{datetime_format(self.bot.uptime)}``',
                              colour=discord.Colour(random_color()),
                              timestamp=datetime.utcnow())
        embed.set_author(name='Androxus', icon_url=f'{self.bot.user.avatar_url}')
        embed.set_footer(text=f'{ctx.author}', icon_url=f'{ctx.author.avatar_url}')
        await ctx.send(embed=embed)

    @commands.command(name='cmds',
                      aliases=['comandos', 'listar_comandos', 'list_cmds'],
                      description='A lista com todos os comandos que eu tenho!',
                      examples=['``{prefix}cmds``', '``{prefix}comandos``'],
                      cls=Androxus.Command)
    @commands.max_concurrency(1, commands.BucketType.user)
    async def _cmds(self, ctx):
        conexao = Conexao()
        e = discord.Embed(title='Todos os meus comandos',
                          colour=discord.Colour(random_color()),
                          description=f'Caso você queira saber mais informações sobre um comando, '
                                      'digite \'help comando\'',
                          timestamp=datetime.utcnow())
        e.set_author(name='Androxus', icon_url=self.bot.user.avatar_url)
        e.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url)
        categories = self.bot.get_all_categories()
        servidor = None
        if ctx.guild:
            servidor = ServidorRepository().get_servidor(conexao, ctx.guild.id)
            comandos_desativados = [c.comando for c in ComandoDesativadoRepository().get_commands(conexao, servidor)]
        for category in categories:
            commands = self.bot.get_commands_from_category(category)
            if len(commands) != 0:
                for i in range(len(commands)):
                    commands[i] = f'``{commands[i]}``'
                if servidor:
                    # vai remover todos os comandos desativados, da lista que vai aparecer na mensagem
                    for cmds_off in comandos_desativados:
                        if cmds_off in commands:
                            try:
                                commands = commands.remove(cmds_off)
                            except:
                                pass
                e.add_field(
                    name=f'{self.bot.get_emoji_from_category(category)} {capitalize(category)} ({len(commands)})',
                    value=f'{", ".join(commands)}.',
                    inline=False)
        if servidor:
            cmds_personalizados = ComandoPersonalizadoRepository().get_commands(conexao, servidor)
            commands = []
            if len(cmds_personalizados) >= 1:
                for comando_personalizado in cmds_personalizados:
                    commands.append(f'``{comando_personalizado.comando}``')
                commands.sort()
                e.add_field(name=f'{self.bot.get_emoji_from_category("personalizado")} Comandos personalizados (são '
                                 'comandos exclusivos deste servidor, e não precisam do prefixo)'
                                 f'({len(commands)})',
                            value=f'{", ".join(commands)}.',
                            inline=False)
        conexao.fechar()
        await ctx.send(embed=e)

def setup(bot):
    bot.add_cog(Botinfo(bot))


#coding:utf-8
from django.shortcuts import render_to_response, RequestContext
from main.models import Blog
from django.http import Http404
from django.views.decorators.cache import cache_page
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
# Create your views here.

@cache_page(86400)
def blog_list(request):
    limit = 6
    topics = Blog.objects.all()
    paginator = Paginator(topics, limit)

    page = request.GET.get('page')
    try:
        topics = paginator.page(page)
    except PageNotAnInteger:
        topics = paginator.page(1)
    except EmptyPage:
        topics = paginator.page(paginator.num_pages)
    return render_to_response("blog_list.html", {"topics": topics})

@cache_page(604800)
def blog_show(request, id=''):
    try:
        blog = Blog.objects.get(id=id)
    except Blog.DoesNotExist:
        raise Http404
    return render_to_response("blog_show.html", {"blog": blog}, context_instance=RequestContext(request))


import numpy as np
import pdb
import mdtraj
import simtk.unit as u
import bilayer_analysis_functions
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt

import plot_ay
plot_ay.setDefaults()

def find_blocks(number):
    max_power = int(np.log10(number))
    all_blocks = [[int(10**num), int(2.5*10**num), int(5*10**num), int(7.5*10**num)]
                        for num in np.arange(0, max_power+1, dtype=int)]
    all_blocks = np.array(all_blocks).flatten()
    all_blocks = np.array([val for val in all_blocks if val <= number])
    return all_blocks

kb = u.BOLTZMANN_CONSTANT_kB
#kb = u.BOLTZMANN_CONSTANT_kB * u.AVOGADRO_CONSTANT_NA
T = 305 * u.kelvin
#traj = mdtraj.load('trajectory.dcd', top='npt.gro')
areas = []
n_frames = 0
for chunk in mdtraj.iterload('trajectory.dcd', top='npt.gro'):
    area_chunk = chunk.unitcell_lengths[:,0] * chunk.unitcell_lengths[:,1]
    areas = np.concatenate((areas, area_chunk))
    n_frames += chunk.n_frames
areas *= u.nanometer**2
avg_area = np.mean(areas)
mean_sq_fluc = np.sum((areas - avg_area)**2)/len(areas)
ka = kb*T*avg_area/mean_sq_fluc
print(ka.in_units_of(u.dyne/u.centimeter))
print(ka.in_units_of(u.newton/u.meter))

#for i, frame in enumerate(traj):
#    frame.time = 10*i

# we have 10,000 frames for 100ns
# we now have 50,000 frames for 500ns
# Let's declare block size
block_sizes = find_blocks(n_frames)
#block_sizes = [100,200,300,400, 500,600,700,800,900, 1000, 2000, 5000,
            #10000, 20000, 25000, n_frames]
fig, ax = plt.subplots(1,2)
for block_size in block_sizes:
    n_blocks = int(n_frames / block_size)
    all_ka = []
    for i in range(n_blocks):
        window_areas = areas[i : i + block_size]
        window_avg = np.mean(window_areas)
        window_fluc = np.sum((window_areas - window_avg)**2)/len(window_areas)
        ka = kb*T*window_avg/window_fluc
        all_ka.append(ka.in_units_of(u.dyne/u.centimeter)._value)
    mean = np.mean(all_ka)
    #se = np.std(all_ka)/np.sqrt(n_blocks)
    se = np.std(all_ka)
    ax[0].scatter([block_size], [se])
    ax[1].scatter([block_size], [mean])
    print("{} blocksize, {} blocks, {} mean, {} se".format(block_size, n_blocks,
                                    mean, se))
ax[0].set_xlabel("Block size (frames)")
ax[0].set_ylabel("Standard error")
ax[1].set_ylabel("Compressibilty Modulus (dyne/cm)")
ax[1].set_xlabel("Block size (frames)")
fig.tight_layout()
fig.savefig('block_comparison.png')
plt.close(fig)

# Look at autocorrelations
# 10000 frames for 100ns, we have
# 50000 frames for 500ns
corr_length = 25000
dt = 10
time_origins = np.arange(0, n_frames - corr_length, step=dt)
all_corrs = []
for origin in time_origins:
    avg_area = np.mean(areas[origin:origin+corr_length])
    area_corr = (((areas[origin]-avg_area)*(areas[origin: origin+corr_length]-avg_area)) /
                    ((areas[origin]-avg_area)**2))
    all_corrs.append(area_corr)
all_corrs = np.asarray(all_corrs)
time_vals = np.arange(0, corr_length)/100
fig, ax = plt.subplots(1,1)
ax.plot(time_vals, np.mean(all_corrs, axis=0))
fig.tight_layout()
fig.savefig('correlations.png')
plt.close(fig)

fig, ax = plt.subplots(1,1)
ax.plot(np.arange(0, len(areas)), areas)
ax.set_xlabel("Frames")
ax.set_ylabel("Box Area")
ax.grid()
fig.tight_layout()
fig.savefig('areas.png')
plt.close(fig)


from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.urls import path
from pictureURL.views import *
from . import views

urlpatterns = [
    path("", dashboard, name="dashboard"),
    path('login/', login_page , name="login_page"),
    path('logout/', logout, name='logout'),
    path('AllCampaigns/', campaign_list, name="campaign_list"),
    path('campaigndetail/<slug:auid>', campaigndetail, name='campaigndetail'),
    path("NewCampaign/", Upload_Campaign.as_view(),  name="new_campaign"),
    path("edit/<int:id>/", EditListView.as_view(), name="edit_campaign"),
    path("Delete_Campaign/<int:pk>/", delete_campaign, name="delete_campaign"),
    path("smsform/", Publish.as_view(),  name="textform"),
    path("result/", search, name="search"),
    # path("Calender/", calender, name="calender")

]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


import os

names = [name for _,_, name in os.walk("./")][0]

names_png = [name.replace("PNG", "png") for name in names]

os.makedirs("to", exist_ok=True)
for i, v in enumerate(names):
    with open(v, "rb") as fp:
        b = fp.read()
    with open("to/" + names_png[i], "wb") as fp:
        fp.write(b)


# Standard library imports
import os
import json
import requests

# Open json file with stored links
with open('stored_links.json', 'r') as data_file:
    data = json.load(data_file)
    for list_with_offers in data:
        for item in list_with_offers:
            print(item)
            offers = os.listdir('offers')
            number_of_offers = len(offers)
            i = number_of_offers + 1
            url = item
            response = requests.get(url)
            content = response.text
            if i<10:
                path = f'offers/offer_000{i}.html'
            elif i<100:
                path = f'offers/offer_00{i}.html'
            elif i<1000:
                path = f'offers/offer_0{i}.html'
            else:
                path = f'offers/offer_{i}.html'
            # Get offers data and save each offer data as separate html file
            with open(path, 'w', encoding='utf-8') as output_data:
                output_data.write(content)


import unittest
import os

from database import MirrorDatabase
from MirrorDownloader import MirrorDownloader

class DatabaseTestCase(unittest.TestCase):
    def setUp(self):
        self.database = MirrorDatabase('test.db')
        self.downloader = MirrorDownloader()

    def test_database_creation(self):
        database = MirrorDatabase('test.db')
        database.create_database()
        assert database.conn.table_exists('mirrors')
        assert database.conn.table_exists('mirror_ip')
        database.conn.close()

    def test_get_mirrors(self):
        lists = self.downloader.get_mirrors_from_modules()
        self.assertIsNotNone(lists)

    def tearDown(self):
        self.database.conn.close()
        os.remove('test.db')


#!/bin/python
#coding=utf-8
#

'''
Input the group name, the script will recognize the service type on it and call related check service
'''

import sys
import os
import re
import string

def getServerType(group):
	'''
	Get the server type depending on the group name
	'''

	if group.find('mmr') != -1 or group.find('bcs') != -1:
		serverType = 'mmr'
	elif group.find('bcz') != -1 or group.find('cmz') != -1 or group.find('mmz') != -1:
		serverType = 'zc'
	elif group.find('roomgw') != -1:
		serverType = 'roomgw'
	elif group.find('lyncgw') != -1:
		serverType = 'lyncgw'
	elif group.find('telgw') != -1:
		serverType = 'telgw'
	else:
		serverType = 'unknown'

	return serverType

def getSpecLineByFile(hostInventory, groupNameDict, configName):
	for groupName, index in groupNameDict.items():
		print('======' + groupName + ', ' + index)
		if index.find(':') != -1:
			indexStart, indexEnd = string.split(index,':',2)
		else:
			indexStart = index

		#[:2]/[0:2]  [:]/[0:]
		if not indexStart or not len(indexStart.strip()):
			indexStart = 0

		if not os.path.isfile(groupName):
			os.system('touch %s' %groupName)

		with open(hostInventory, 'r') as f:
			w_flag = False
			lineNum = 0
			endNum = -1

			with open(groupName, 'w') as g:
				for line in f.readlines():
					if index.find(':') != -1:
						#[:]/[0:], [2:] => [n:], end with blank line
						if not indexEnd or not len(indexEnd.strip()):
							if int(indexStart) != lineNum:
								lineNum = lineNum + 1
						#[1:2], [:2]/[0:2] => [n1:n2], end with n2th line
						elif indexEnd or len(indexEnd.strip()):
							if w_flag:
								endNum = endNum + 1

							if int(indexStart) != lineNum:
								lineNum = lineNum + 1
					#[1]
					elif index.find(':') == -1:
						lineNum = lineNum + 1

					if w_flag and (not len(line.strip()) or not re.search('^[0-9]',line)):
						w_flag = False
					if w_flag and len(line.strip()) and int(indexStart) == lineNum:
						print(string.split(line)[0])
						g.write(string.split(line)[0] + '\n')
					if line.find('['+ groupName + ']') != -1:
						w_flag = True
						lineNum = -1
					if index.find(':') != -1 and (indexEnd or len(indexEnd.strip())):
						if endNum == int(indexEnd):
							w_flag = False

	with open(configName, 'w') as f:
		for groupName in groupNameDict.keys():
			with open(groupName, 'r') as g:
				for line in g.readlines():
					f.write(line)
			os.system('rm -rf %s' %groupName)

def getSpecLine(hostInventory, groupList, configName):
	'''
	write the specified line ip into file
	[index]: [1], [:]/[0:], [2:], [1:2], [:2]/[0:2]
	=======>index out of range
	'''

	if os.path.isfile(hostInventory):
		hostInventory = hostInventory
	elif os.path.isdir(hostInventory):
		if hostInventory.endswith(r'/'):
			hostInventoryPath = hostInventory
		else:
			hostInventoryPath = hostInventory + '/'

		hostInventoryList = os.listdir(hostInventory)

		if os.path.isfile(r'/tmp/mct_test_hosts'):
			os.system('rm -rf /tmp/mct_test_hosts')
		os.system('touch /tmp/mct_test_hosts')

		with open(r'/tmp/mct_test_hosts', 'w') as f:
			for hostInventory in hostInventoryList:
				with open(hostInventoryPath + hostInventory, 'r') as g:
					for line in g.readlines():
						f.write(line)

		hostInventory = '/tmp/mct_test_hosts'
	else:
		print('hostInventory not exist!')
		sys.exit()

	groupNameDict = {}

	for group in groupList:
		if group.find('[') != -1:
			groupName, index, _ = re.split(r'\[|\]', group)
			groupNameDict[groupName] = index
		else:
			index = ':'

			groupName = group.replace('*', '.*')
			groupRe = re.compile('\[(' + groupName + ')\]')
			text = open(hostInventory, 'r').read()

			for groupName in groupRe.findall(text):
				groupNameDict[groupName] = index

	getSpecLineByFile(hostInventory, groupNameDict, configName)

def getIPList(hostInventory, groupList, serverType):
	'''
	Get the ip list depending on the group and write ip and related info into the file
	'''
	mct_root_path = '/opt/src/mct'
	crc_path = mct_root_path + '/crc/'
	lgw_path = mct_root_path + '/lgw_mct/'
	mmrbcszc_path = mct_root_path + '/mmrbcszc/'
	tg_path = mct_root_path + '/tg/'

	for group in groupList:
		if group.find('[') != -1 and group.find('*') != -1:
			print('The usage of ' + group + ' is not suitable, "[" and "*" can not coexist')
			sys.exit()

	if serverType == 'mmr':
		configName = 'mmrlist'
		getSpecLine(hostInventory, groupList, configName)
		os.chdir(mmrbcszc_path)

		cmd = 'nohup ' + mmrbcszc_path + 'mct.sh ' + serverType + ' ' + configName + ' &'
		print(cmd)
		os.popen(cmd)
	elif serverType == 'zc':
		configName = 'zclist'
		getSpecLine(hostInventory, groupList, configName)
		os.chdir(mmrbcszc_path)

		cmd = 'nohup ' + mmrbcszc_path + 'mct.sh ' + serverType + ' ' + configName + ' &'
		print(cmd)
		os.popen(cmd)
	elif serverType == 'roomgw' or serverType == 'lyncgw' or serverType == 'telgw':
		meetingID = raw_input('pls input the meetingID:')

		if not meetingID or not len(meetingID.strip()):
			print('meetingID is empty')
			sys.exit()

		configName = 'list.txt'
		getSpecLine(hostInventory, groupList, configName)

		if serverType == 'roomgw':
			os.chdir(crc_path)
			cmd = 'nohup' + crc_path + 'crctest.sh ' + configName + ' ' + meetingID + ' &'
		if serverType == 'lyncgw':
			os.chdir(lgw_path)
			cmd = 'nohup' + lgw_path + 'lgwtest.sh ' + meetingID + ' ' + configName + ' &'
		if serverType == 'telgw':
			os.chdir(tg_path)
			cmd = 'nohup' + tg_path + 'tgTest.sh ' + meetingID + ' ' + 	 + ' &'

		print(cmd)
		os.popen(cmd)
	else:
		pass

if __name__ == '__main__':
	if len(sys.argv) != 3:
		print('Usage:' + sys.argv[0] + ' hostInventory' + ' groupName')
		sys.exit()
	else:
		hostInventory = sys.argv[1]
		groupName = sys.argv[2]

	groupNameList = string.split(groupName, ',')

	groupsDict = {}

	for group in groupNameList:
		serverType = getServerType(group)

		if serverType not in groupsDict.keys():
			groupsDict[serverType] = []
		groupsDict[serverType].append(group)

	for serverType,groupList in groupsDict.items():
		print(serverType,groupList)
		getIPList(hostInventory, groupList, serverType)


import os
import re

from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.db import transaction
from django.core.exceptions import ValidationError
from django.contrib.auth.decorators import login_required
from django.conf import settings

from subdicts import utils

from dormitory_application_form.models import Applicant, DegreeProgram, Bracket, Attachment, ApplicationMeta
from dormitory_application_form.forms import ApplicantForm
from dormitory_application_form import listeners

def index(request):
    if request.user and request.user.is_authenticated():
        return redirect('application:applicants')

    application_ended = ApplicationMeta.objects.get(pk='application_ended')
    if application_ended.value == 'true':
        return render(request, 'dormitory_application_form/applicants.html', {'applicants': Applicant.objects.accepted()})

    context = {
        'applicant': Applicant(),
        'degree_programs': DegreeProgram.objects.all(),
        'brackets': Bracket.objects.all(),
        'meta': {
            'semester': ApplicationMeta.objects.get(pk='semester'),
            'school_year': ApplicationMeta.objects.get(pk='school_year')
        }
    }

    if request.method == 'POST':
        post = utils.parse(request.POST.copy())
        post['applicant']['father_deceased'] = 'father_deceased' in post['applicant'] and post['applicant']['father_deceased'] == 'on'
        post['applicant']['mother_deceased'] = 'mother_deceased' in post['applicant'] and post['applicant']['mother_deceased'] == 'on'
        if not post['applicant']['scholarship_allowance']:
            del post['applicant']['scholarship_allowance']

        applicant = ApplicantForm(post['applicant'])
        if applicant.is_valid():
            with transaction.atomic():
                applicant = applicant.save()
                for key in request.FILES:
                    applicant.attachment_set.create(
                        filename = request.FILES[key],
                        attachment_type = request.POST[key]
                    )
                applicant.email_application_sent()
            return redirect('application:done')
        else:
            post['applicant']['course'] = DegreeProgram.objects.get(pk=post['applicant']['course'])
            post['applicant']['tuition_discount'] = Bracket.objects.get(pk=post['applicant']['tuition_discount'])
            context['applicant'] = Applicant(**post['applicant'])
            context['errors'] = applicant.errors

    return render(request, 'dormitory_application_form/index.html', context)

def done(request):
    return render(request, 'dormitory_application_form/done.html')

@login_required
def applicants(request):
    applicants = Applicant.objects.order_by('tuition_discount__rank', 'annual_family_income', 'scholarship_allowance')
    return render(request, 'dormitory_application_form/applicants.html', {'applicants': applicants})

@login_required
def show(request, applicant_id):
    applicant = get_object_or_404(Applicant, pk=applicant_id)
    return render(request, 'dormitory_application_form/show.html', {'applicant': applicant})

@login_required
def delete(request, applicant_id):
    applicant = get_object_or_404(Applicant, pk=applicant_id)
    with transaction.atomic():
        applicant.delete()
        for attachment in applicant.attachment_set.all():
            attachment.delete()
    return redirect('application:applicants')

@login_required
def accept(request, applicant_id):
    applicant = get_object_or_404(Applicant, pk=applicant_id)
    applicant.accepted = True
    applicant.save()
    return redirect('application:applicants')

@login_required
def unaccept(request, applicant_id):
    applicant = get_object_or_404(Applicant, pk=applicant_id)
    applicant.accepted = False
    applicant.save()
    return redirect('application:applicants')

@login_required
def notify_accepted(request):
    for applicant in Applicant.objects.accepted():
        applicant.email_applicant_accepted()
    application_ended = ApplicationMeta.objects.get(pk='application_ended')
    application_ended.value = 'true'
    application_ended.save()
    return redirect('application:applicants')


class Solution(object):
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        # There is no integer limit in python, so we need a mask
        mask = 2**32-1
        if b == 0:
            return a if a&(2**31) == 0 else -self.getSum(~a, 1)
        # python don't recognize "0b10000000000000000000000000000000" as a negative number
        x = a^b
        carry = (a&b) << 1
        return self.getSum(x&mask, carry&mask)

"""
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example 1:

Input: a = 1, b = 2
Output: 3
Example 2:

Input: a = -2, b = 3
Output: 1
"""


# encoding: UTF-8
# Autor: Silvia Ferman
# VIDEOJUEGO

import pygame
from random import randint

# DIMENSIONES PANTALLA:
ANCHO = 800
ALTO = 600

# COLORES_
BLANCO = (255, 255, 255)
VERDE_BANDERA = (27, 94, 32)
ROJO = (255, 0, 0)
AZUL = (0, 0, 255)
NEGRO = (0, 0, 0)
MORADO = (74, 35, 90)
ROSA = (255, 93, 133)
NARANJA = (255, 83, 13)

# ESTADOS_
MENU = 1
JUGANDO = 2
REGLAS = 3
RANK = 4
GAMEOVER = 5

# ESTADOS DE MOVIMIENTO
QUIETO = 1
ABAJO = 2
ARRIBA = 3
ATRAS = 4
ADELANTE = 5

# Estructura básica de un programa que usa pygame para dibujar

# Funcion que dibuja al PERSONAJE (Suricata)
def dibujarSuricata(ventana, spritePersonaje):
    ventana.blit(spritePersonaje.image, spritePersonaje.rect)

# Funcion que dibuja la ROCA (Game Over)
def dibujarRoca(ventana, spriteRoca):
    ventana.blit(spriteRoca.image, spriteRoca.rect)
    spriteRoca.rect.left -= 5
    if spriteRoca.rect.left <= -spriteRoca.rect.width:
        spriteRoca.rect.left = ANCHO + randint(20, 50)

# Funcion que dibuja a los ENEMIGOS (Cactus)
def dibujarCactus(ventana, listaEnemigos):
    # VISITAR/ACCEDER DIRECTAMENTE a cada elemento
    for enemigo in listaEnemigos:
        ventana.blit(enemigo.image, enemigo.rect)

# Funcion que mueve a los ENEMIGOS (Cactus)
def moverCactus(listaEnemigos):
    for enemigo in listaEnemigos:
        enemigo.rect.left -= 2

# Funcion que dibuja a los MISILES (Balas)
def dibujarMisiles(ventana, listaMisil):
    for bala in listaMisil:
        ventana.blit(bala.image, bala.rect)

# Funcion que mueve a los MISILES (Balas)
def moverMisiles(listaMisil):
    for bala in listaMisil:
        bala.rect.left += 10

# Funcion que dibuja el MENU
def dibujarMenu(ventana, imgButtonPlay, imgButtonReglas, imgButtonRank):
    ventana.blit(imgButtonPlay, (ANCHO // 2 - 128 , ALTO // 3 - 128))
    ventana.blit(imgButtonReglas, (ANCHO // 2 - 128, ALTO // 3 + 25))
    ventana.blit(imgButtonRank, (ANCHO // 2 - 128, ALTO // 3 + 175))

# Funcion que dibuja el fondo cuando pierdes (GAME OVER)
def dibujarGameOver(ventana, imgGameOver):
    ventanaJuego = ventana
    imagenPerdio = imgGameOver
    ventanaJuego.blit(imagenPerdio, (0,0))

def verificarBoom(listaEnemigos, listaMisil, imgEnemigo, imgEnemigoUno, imgEnemigoDos):
    puntosGanados = 0
    for k in range(len(listaMisil)-1, -1, -1):
        misil = listaMisil[k]
        for e in range(len(listaEnemigos)-1, -1, -1):  # Recorrer con INDICES
            cactus = listaEnemigos[e]
            # bala vs enemigo
            xb = misil.rect.left
            yb = misil.rect.bottom
            xe, ye, ae, alte = cactus.rect
            if xb >= xe and xb <= xe + ae and yb >= ye and yb <= ye + alte :
                # hit
                if cactus.image == imgEnemigo:
                    puntosGanados += 100
                if cactus.image == imgEnemigoUno:
                    puntosGanados += 35
                if cactus.image == imgEnemigoDos:
                    puntosGanados += 75
                listaEnemigos.remove(cactus)
                listaMisil.remove(misil)
                break
    return puntosGanados

def verificarGameOver(listaRocas, spritePersonaje):
    personaje = spritePersonaje
    for e in range(len(listaRocas) - 1, -1, -1):
        roca = listaRocas[e]
        # personaje vs roca
        xb = roca.rect.left
        yb = roca.rect.bottom
        xe, ye, ae, alte = personaje.rect
        if xb >= xe and xb <= xe + ae and yb >= ye and yb <= ye + alte:
            listaRocas.remove(roca)
            break

def dibujarPuntajes(ventana, puntosGanados):
    puntos = "PUNTOS ="
    pygame.font.init()
    fuente = pygame.font.Font(None, 100)
    textoPuntos = fuente.render(puntos, 1, (255, 83, 13), )
    ventana.blit(textoPuntos, (80, 250))

    total = str(puntosGanados)
    pygame.font.init()
    fuente = pygame.font.Font(None, 100)
    textoPuntos = fuente.render(total, 1, (255, 83, 13), )
    ventana.blit(textoPuntos, (450, 250))

def dibujarTop(ventana):
    top = "HIGH SCORE:"
    pygame.font.init()
    fuente = pygame.font.Font(None, 100)                     # Tamaño letra
    textoTop = fuente.render(top, 1, (0,0,0), )              # Color
    ventana.blit(textoTop, (30, 200))                        # Posición

    entrada = open("Puntos.txt", "r")

    puntoAnterior = entrada.readline()

    entrada.close()
    anterior = puntoAnterior
    pygame.font.init()
    fuente = pygame.font.Font(None, 200)
    textoTop = fuente.render(anterior, 1, (0, 0, 0), )
    ventana.blit(textoTop, (250, 375))

def escribirTop(puntosGanados):
    entrada = open("Puntos.txt", "r")

    puntoAnterior = int(entrada.readline())

    entrada.close()

    total = puntosGanados
    if puntoAnterior < total:
        salida = open("Puntos.txt", "w")
        salida.write(str(total))

def dibujar():
    pygame.init()
    # Crea una ventana de ANCHO x ALTO
    ventana = pygame.display.set_mode((ANCHO, ALTO))  # Crea la ventana donde dibujará
    reloj = pygame.time.Clock()  # Para limitar los fps
    termina = False  # Bandera para saber si termina la ejecución, iniciamos suponiendo que no

    # ROCA
    x = ANCHO
    listaRocas = []
    imgRoca = pygame.image.load("roca.png")
    spriteRoca = pygame.sprite.Sprite()
    spriteRoca.image = imgRoca
    spriteRoca.rect = imgRoca.get_rect()
    spriteRoca.rect.left = x
    x += 140 + randint(0, 55)
    spriteRoca.rect.bottom = ALTO - 25
    listaRocas.append(spriteRoca)

    # PERSONAJE
    imgPersonaje = pygame.image.load("suricata2.png")
    spritePersonaje = pygame.sprite.Sprite()
    spritePersonaje.image = imgPersonaje
    spritePersonaje.rect = imgPersonaje.get_rect()
    spritePersonaje.rect.left = 0
    spritePersonaje.rect.bottom = ALTO

    # ENEMIGOS
    x = ANCHO
    listaEnemigos = []
    imgEnemigo = pygame.image.load("cactus.png")
    imgEnemigoUno = pygame.image.load("Cactus2A.png")
    imgEnemigoDos = pygame.image.load("Cactus3A.png")
    for k in range(50):
        spriteEnemigo = pygame.sprite.Sprite()
        spriteEnemigoUno = pygame.sprite.Sprite()
        spriteEnemigoDos = pygame.sprite.Sprite()
        spriteEnemigo.image = imgEnemigo
        spriteEnemigoUno.image = imgEnemigoUno
        spriteEnemigoDos.image = imgEnemigoDos
        spriteEnemigo.rect = imgEnemigo.get_rect()
        spriteEnemigoUno.rect = imgEnemigoUno.get_rect()
        spriteEnemigoDos.rect = imgEnemigoDos.get_rect()
        spriteEnemigo.rect.left = x
        x += 140 + randint(0, 50)
        spriteEnemigoUno.rect.left = x
        x += 140 + randint(0, 35)
        spriteEnemigoDos.rect.left = x
        x += 140 + randint(0, 75)
        spriteEnemigo.rect.bottom = ALTO
        spriteEnemigoUno.rect.bottom = ALTO - 10
        spriteEnemigoDos.rect.bottom = ALTO - 10
        listaEnemigos.append(spriteEnemigo)
        listaEnemigos.append(spriteEnemigoUno)
        listaEnemigos.append(spriteEnemigoDos)

    # PROYECTILES / BALAS
    listaMisil = []
    imgMisil = pygame.image.load("misil.png")

    # MENU
    imgButtonPlay = pygame.image.load("buttonPlay.png")
    imgButtonReglas = pygame.image.load("buttonReglas.png")
    imgButtonRank = pygame.image.load("buttonRanking.png")
    imgGameOver = pygame.image.load("Game Over.png")

    # IMAGENES
    imgFondo = pygame.image.load("desierto.JPG")
    imgReglas = pygame.image.load("reglas.jpg")
    imgRank = pygame.image.load("ranking.jpg")

    estado = MENU

    moviendo = QUIETO

    xFondo = 0

    puntosGanados = 0

    # TIEMPOS
    timer = 0       # Acumulador de tiempo

    # TEXTO
    fuente = pygame.font.SysFont("monospace", 25)

    # AUDIO
    pygame.mixer.init()
    pygame.mixer.music.load("BACKGROUND.mp3")   # archivos largos (mp3)
    pygame.mixer.music.play(-1)

    efecto = pygame.mixer.Sound("shoot.wav")     # archivos cortos

    while not termina:  # Ciclo principal, MIENTRAS la variable termina sea False, el ciclo se repite automáticamente
        # Procesa los eventos que recibe
        for evento in pygame.event.get():
            if evento.type == pygame.QUIT:  # El usuario hizo click en el botón de salir
                termina = True      # Queremos terminar el ciclo
            elif evento.type == pygame.KEYDOWN:
                if evento.key == pygame.K_UP:
                    #spritePersonaje.rect.bottom -= 5    #  Velocidad mov. arriba
                    moviendo = ARRIBA
                elif evento.key == pygame.K_DOWN:
                    #spritePersonaje.rect.bottom += 5    # Velocidad mov. abajo
                    moviendo = ABAJO
                elif evento.key == pygame.K_LEFT:
                    moviendo = ATRAS
                elif evento.key == pygame.K_RIGHT:
                    moviendo = ADELANTE
                elif evento.key == pygame.K_SPACE:
                    # Crear una bala
                    spriteBala = pygame.sprite.Sprite()
                    spriteBala.image = imgMisil
                    spriteBala.rect = imgMisil.get_rect()
                    spriteBala.rect.left = spritePersonaje.rect.left + spritePersonaje.rect.width - 30
                    spriteBala.rect.bottom = spritePersonaje.rect.bottom - 80
                    listaMisil.append(spriteBala)
                    # SONIDO Boom
                    efecto.play()
            elif evento.type == pygame.KEYUP:
                moviendo = QUIETO
            elif evento.type == pygame.MOUSEBUTTONUP:
                xm, ym = pygame.mouse.get_pos()         # dupla: se regresan DOS variables
                print(xm, " , ", ym)
                # Preguntar si solto el mouse dentro del boton (BOTON JUGAR)
                xb = ANCHO // 2 - 128
                yb = ALTO // 3 - 128
                if xm >= xb and xm <= xb + 256 and ym >= yb and ym <= yb + 100:
                    estado = JUGANDO
                # Preguntar si solto el mouse dentro del boton (BOTON REGLAS)
                xb = ANCHO // 2 - 128
                yb = ALTO // 3 + 25
                if xm >= xb and xm <= xb + 256 and ym >= yb and ym <= yb + 100:
                    estado = REGLAS
                # Preguntar si solto el mouse dentro del boton (BOTON RANK)
                xb = ANCHO // 2 - 128
                yb = ALTO // 3 + 178
                if xm >= xb and xm <= xb + 256 and ym >= yb and ym <= yb + 100:
                    estado = RANK

        # Borrar pantalla
        ventana.fill(NEGRO)

        if estado == JUGANDO:
            # TIEMPOS
            if timer >= 2:
                timer = 0
                # Enemigos
                spriteEnemigo = pygame.sprite.Sprite()
                spriteEnemigoUno = pygame.sprite.Sprite()
                spriteEnemigoDos = pygame.sprite.Sprite()
                spriteEnemigo.image = imgEnemigo
                spriteEnemigoUno.image = imgEnemigoUno
                spriteEnemigoDos.image = imgEnemigoDos
                spriteEnemigo.rect = imgEnemigo.get_rect()
                spriteEnemigoUno.rect = imgEnemigoUno.get_rect()
                spriteEnemigoDos.rect = imgEnemigoDos.get_rect()
                spriteEnemigo.rect.left = x
                x += 140 + randint(0, 50)
                spriteEnemigoUno.rect.left = x
                x += 140 + randint(0, 35)
                spriteEnemigoDos.rect.left = x
                x += 140 + randint(0, 75)
                spriteEnemigo.rect.bottom = ALTO
                spriteEnemigoUno.rect.bottom = ALTO - 10
                spriteEnemigoDos.rect.bottom = ALTO - 10
                listaEnemigos.append(spriteEnemigo)
                listaEnemigos.append(spriteEnemigoUno)
                listaEnemigos.append(spriteEnemigoDos)

            # Actualizar ENEMIGOS / BALAS
            # MOVER Personaje
            if moviendo == ARRIBA:
                spritePersonaje.rect.bottom -= 15        # se mueve solo ARRIBA
            elif moviendo == ABAJO:
                spritePersonaje.rect.bottom += 15        # se mueve solo ABAJO
            elif moviendo == ATRAS:
                spritePersonaje.rect.left -= 5
            elif moviendo == ADELANTE:
                spritePersonaje.rect.left += 5
            moverCactus(listaEnemigos)
            moverMisiles(listaMisil)
            pg = verificarBoom(listaEnemigos, listaMisil, imgEnemigo, imgEnemigoUno, imgEnemigoDos)
            puntosGanados += pg
            verificarGameOver(listaRocas, spritePersonaje)
            # GAME OVER
            if len(listaRocas) == 0:
                estado = GAMEOVER

            # Dibujar, aquí haces todos los trazos que requieras
            ventana.blit(imgFondo, (xFondo, 0))
            ventana.blit(imgFondo, (xFondo + ANCHO, 0))
            xFondo -= 1
            if xFondo == -ANCHO:
                xFondo = 0
            dibujarSuricata(ventana, spritePersonaje)
            dibujarRoca(ventana, spriteRoca)
            dibujarCactus(ventana, listaEnemigos)
            dibujarMisiles(ventana, listaMisil)
        elif estado == MENU:
            # Dibujar MENU
            dibujarMenu(ventana, imgButtonPlay, imgButtonReglas, imgButtonRank)
        elif estado == REGLAS:
            ventana.blit(imgReglas, (0,0))
        elif estado == RANK:
            ventana.blit(imgRank, (0,0))
            dibujarTop(ventana)
        elif estado == GAMEOVER:
            dibujarGameOver(ventana, imgGameOver)
            dibujarPuntajes(ventana, puntosGanados)
            escribirTop(puntosGanados)

        # TEXTO PANTALLA
        texto = fuente.render("PUNTOS = %d" % puntosGanados, 1, NEGRO)
        ventana.blit(texto, (ANCHO // 2 - 370, 25))

        pygame.display.flip()  # Actualiza trazos (Si no llamas a esta función, no se dibuja)
        reloj.tick(40)  # 40 fps
        timer += 1/40

    # Después del ciclo principal
    pygame.quit()  # termina pygame

# Función principal
def main():
    dibujar()

# Llama a la función principal
main()


# local imports
from typeclasses.characters import Character

def reset_runner():
    # Get all characters
    characters = [character for character in Character.objects.all()]
    print(characters)
    # for character in characters:
    #     character.reset_stats()

if __name__ == "__main__":
    reset_runner()


#!/usr/bin/env python
# -*-coding:utf-8-*-
# Author:SemaseMing <blog.v-api.cn>
# Email: admin@v-api.cn
# Time: 2016-10-11 13:39
import os
import hashlib

def FileSize(path):
    """

    计算目录下的所有文件的大小

    """
    size = 0
    for root, dirs, files in os.walk(path, True):
        size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
        # 目录下文件大小累加
    return size

def getMD5(path):
    m = hashlib.md5()
    n = 1024*4
    inp = open(path, 'rb')
    while True:
        buf = inp.read(n)
        if buf:
            m.update(buf)
        else:
            break
    return m.hexdigest()


"https://www.practicepython.org/exercise/2014/07/05/18-cows-and-bulls.html"

from random import randint
c=[]
h=[]
for i in range(0,4):
            h.append(randint(0,9))
while len(c) != 4:
    a = input("Enter the number: ")
    if a == "exit" :
        break
    else:
        y=int(a)

        c=[]
        d=[]
        g=0
        g2 = 3
        while  int(y) > 0:
            g=g+1
            j = y%10
            y = y/10
            y=int(y)
            if j== h[g2]:
                c.append(j)
            elif j in h and j!=h[g2]:
                d.append(j)
            g2 = g2-1

        print("cow is: "+str(len(c)))
        print("bull is: "+str(len(d)))
        print(h)


import math
from sklearn.utils import resample

f = open("boostrap.csv", 'r',encoding="utf-8")
listA = f.readlines()
#print(len(listA))

row=[]
i=0
num_sample_row=0
for line in listA:
    if i==0:
        i=1
        continue
    # khi có continue thì sẽ bỏ qua các câu lệnh trong vòng lặp
    x = line.split(",")
    #x là dòng string
    num_sample_row=len(x)
    for i in range(0,len(x)):
        row.append(int(x[i]))
#print(row)
n_size = num_sample_row * 20 + 1;
list_train=[]

for i in range(0,n_size):
    new_row = resample(row, replace=True, n_samples=num_sample_row)
    list_train.append(new_row)
#print(list_train)

def mean(y):
    sum_mean=0
    for i in y:
        sum_mean+=i
    return sum_mean/len(y)

#Median: trung vị
def median(y):
    y.sort()
    if len(y) % 2 == 0:
        return (y[len(y)//2]+y[len(y)//2-1])/2
    else:
        return y[len(y)//2]

#IQR:
def IQR(y):
    y.sort()
    q50_index = len(y)//2
    q25_index = q50_index // 2
    q75_index = int(len(y)/4*3)
    return (y[q75_index] - y[q25_index])

def IQR_New(x):
    x.sort()
    Q3=np.percentile(x,75)
    Q1=np.percentile(x,25)
    return Q3-Q1

def std_deviation(y):
    #độ lệch chuẩn
    sum_std=0;
    for i in range(0,len(y)):
        sum_std+=pow((y[i]-mean(y)),2);
    return math.ceil(math.sqrt(sum_std/(len(y)-1)));
def Mean_distribution(listmean,numbin):
    for mean in listmean:
        for key in numbin:
            if (mean <= key):
                numbin[key]+=1
                break
    return numbin

list_mean = []
list_median = []
list_IQR = []
list_std_deviation = []
#print(list_train[0])
for line in list_train:
    list_mean.append(mean(line))
    list_median.append(median(line))
    list_IQR.append(IQR(line))
    list_std_deviation.append(std_deviation(line))
#print(len(list_mean))
print("")
print("--------------Confident interval of the mean Bootstrap-----------------")
total_sample = len(list_train) #tổng số mẫu : 201
print("Total sample: ",total_sample)
alpha = 0.05
print("alpha: ",alpha)
confident_level = 100*(1-2*alpha) #độ tin cậy
print("Confident level: ",confident_level)
# confidence interval : khoảng tin cậy
list_mean.sort()
lower_bound = list_mean[int(total_sample * alpha)-1] #vị trí của phần tử thứ 10 trong listmean
print("Lower bound: ",lower_bound)
upper_bound = list_mean[int(total_sample * (1-alpha))-1]
print("upper bound: ",upper_bound)

import pandas as pd
from prettytable import PrettyTable
# pd.options.display.max_columns = None
# pd.options.display.max_rows = None
print("--------------Bootstrap Statistic-----------------")
# intialise data of lists.
# data1 = {"Mean":list_mean,
#         "Median":list_median,
#         "Inter quartile range":list_IQR,
#         "Std deviation":list_std_deviation}
# # Create DataFrame
# df1 = pd.DataFrame(data1)
# print(df1)

t = PrettyTable(['STT','Mean', 'Median','IQR', 'Standard Division'])
for i in range(0, n_size):
    t.add_row([i+1,list_mean[i], list_median[i], list_IQR[i],list_std_deviation[i]])
print(t)

num_bin = {10: 0, 20: 0, 30: 0, 40: 0, 50: 0, 60:0, 70:0, 80:0, 90:0, 100:0}
num_bin=Mean_distribution(list_mean,num_bin)
list_bin = list(num_bin.keys())
list_frequency = list(num_bin.values())
list_probability = [round(i/total_sample,2) for i in list_frequency]
# số 2 là lấy 2 chữ số thập phân

# data2 = {"Bin":list_bin,
#         "Frequency":list_frequency,
#         "Probability":list_probability}
# df2 = pd.DataFrame(data2)

# new_row = ["SUM",total_sample,1]
# df2 = df2.append(pd.Series(new_row, index = df2.columns), ignore_index=True)
# print("")
# print("--------------Mean distribution-----------------")
# print(df2.to_string(index=False))

print("--------------Mean distribution-----------------")
df = PrettyTable(['Bin','Frequency', 'Probability'])
# df = pd.DataFrame(columns=['Bin','Frequency', 'Probability'])
i = 0
for key in num_bin:
    # df = df.append({'Bin': key,'Frequency':bin_number[key],'Probability':probability[i]}, ignore_index=True)
    df.add_row([key,num_bin[key], list_probability[i]])
    i += 1
df.add_row(["SUM",total_sample,1])
# df = df.append({'Bin': "SUM",'Frequency':total_sample,'Probability':1}, ignore_index=True)
print(df)
# print(df)

import matplotlib.pyplot as plt
import numpy as np
# x axis values
#tạo mảng từ 0->100 cách đều nhau 10
x = np.arange(0,100,10)
plt.plot(x, list_probability)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('My first graph!')
plt.bar(x, list_probability, color='purple', width = 5)  #vẽ khối trụ

# plt.axvline(lower_bound, linestyle = 'dotted',color='green',label='pyplot vertical line')
plt.axvline(lower_bound, color='green',label='pyplot vertical line')
plt.axvline(upper_bound, color='green',label='pyplot vertical line')
# function to show the plot
plt.show()


class Node:
    def __init__(self, data):
        self.data = data
        self.next = self

class CircularList:
    def __init__(self):
        self.head = Node(None)

    def prepend(self, data):
        node = Node(data)
        old_first_node = self.head.next
        if old_first_node != self.head:
            self.head.next = node
            node.next = old_first_node
        else:
            self.head.next = node
            node.next = self.head

    def delete(self, data):
        node = self.head.next
        while node != self.head:
            if node.next is not None:
                next_node = node.next
                if next_node.data == data:
                    # this is my node to delete
                    node.next = next_node.next
            node = node.next

    def print_list(self):
        node = self.head.next
        while node != self.head:
            print(node.data)
            node = node.next

def main():
    lst = range(10)
    cll = CircularList()
    for i in lst:
        cll.prepend(i)
    cll.print_list()

if __name__ == "__main__":
    main()


"""Class to manage a result."""
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List

import pandas as pd

from xplogger import utils as xplogger_utils
from xplogger.parser.experiment import ExperimentSequence  # type: ignore

# error: Module 'xplogger.parser.experiment' does not explicitly export attribute 'ExperimentSequence'; implicit reexport disabled
from xplogger.utils import to_json_serializable

@dataclass
class Result:
    id: str
    name: str
    label: str
    config_ids: List[str]
    mongo_ids: List[str]
    experiment_sequence: ExperimentSequence
    metrics: Dict[str, pd.DataFrame]
    info: Dict[str, Any]

    def _get_json_dump(self) -> str:
        return json.dumps(
            {
                "id": self.id,
                "name": self.name,
                "label": self.label,
                "config_ids": self.config_ids,
                "mongo_ids": self.mongo_ids,
                "info": self.info,
            },
            indent=4,
            sort_keys=True,
            default=to_json_serializable,
        )

    def serialize(self, dir_path: Path) -> Path:
        """Serialize the result object and save at a given path."""
        dir_path = dir_path.joinpath(self.name)
        xplogger_utils.make_dir(dir_path)
        data = self._get_json_dump()
        data_path = dir_path.joinpath("data.json")
        with open(data_path, "w") as f:
            f.write(data)
        metric_dir = dir_path.joinpath("metric")
        xplogger_utils.make_dir(metric_dir)
        for key in self.metrics:
            path_to_save = metric_dir.joinpath(key)
            if self.metrics[key].empty:
                pass
            else:
                self.metrics[key].to_feather(path=path_to_save)
        return dir_path

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Result):
            return NotImplemented
        return (
            (
                self.id == other.id
                and self.name == other.name
                and self.label == other.label
                and self.config_ids == other.config_ids
                and self.mongo_ids == other.mongo_ids
                and self.info == other.info
            )
            and self.metrics.keys() == other.metrics.keys()
            and all(
                self.metrics[key].equals(other.metrics[key]) for key in self.metrics
            )
        )

def deserialize(dir_path: Path) -> Result:
    """Deserialize the result object, given a path."""
    data_dir = dir_path.joinpath("data.json")
    with open(data_dir, "r") as f:
        json_dump = f.read()
    data = json.loads(json_dump)
    metric_dir = dir_path.joinpath("metric")
    metrics: Dict[str, pd.DataFrame] = {}
    for path_to_load_metric in metric_dir.iterdir():
        if path_to_load_metric.is_file():
            key = path_to_load_metric.parts[-1]
            metrics[key] = pd.read_feather(path_to_load_metric)
    if not metrics:
        metrics["all"] = pd.DataFrame()
    return Result(
        **data,
        experiment_sequence=None,
        metrics=metrics,
    )


from libs.node import Node
from ast.NAME import NAME
from ast.PITCH import PITCH
from ast.APP_VISITOR import Visitor
# SET_CHORD   ::=  "chord " STRING "= {" (PITCH "-")* PITCH "}"

class SET_CHORD(Node):
  # FIELDS:
  # list of pitches
  # name of chord

  def parse(self):
    self.pitches = []

    self.name = NAME()
    self.name.parse()

    self.tokenizer.getAndCheckNext("=")
    self.tokenizer.getAndCheckNext("{")
    print("============= Inside SET_CHORD")

    p = PITCH()
    p.parse()
    self.pitches.append(p)

    while self.tokenizer.checkToken("-"):
        self.tokenizer.getNext()
        p = PITCH()
        p.parse()
        self.pitches.append(p)

    self.tokenizer.getAndCheckNext("}")
    return

  def accept(self, visitor: Visitor) -> None:
    print("====SET_CHORD.accept====")
    return visitor.visit_set_chord(self)


# Copyright (c) 2012 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from neutron_lib.api.definitions import l3
from neutron_lib import constants as lib_constants
from neutron_lib.plugins import constants as plugin_consts

ROUTER_PORT_OWNERS = lib_constants.ROUTER_INTERFACE_OWNERS_SNAT + \
    (lib_constants.DEVICE_OWNER_ROUTER_GW,)

ROUTER_STATUS_ACTIVE = 'ACTIVE'
ROUTER_STATUS_ALLOCATING = 'ALLOCATING'
ROUTER_STATUS_ERROR = 'ERROR'

VALID_ROUTER_STATUS = (ROUTER_STATUS_ACTIVE,
                       ROUTER_STATUS_ALLOCATING,
                       ROUTER_STATUS_ERROR)

HA_ROUTER_STATE_KEY = '_ha_state'
METERING_LABEL_KEY = '_metering_labels'
FLOATINGIP_AGENT_INTF_KEY = '_floatingip_agent_interfaces'
SNAT_ROUTER_INTF_KEY = '_snat_router_interfaces'

HA_NETWORK_NAME = 'HA network tenant %s'
HA_SUBNET_NAME = 'HA subnet tenant %s'
HA_PORT_NAME = 'HA port tenant %s'
HA_ROUTER_STATE_ACTIVE = 'active'
HA_ROUTER_STATE_STANDBY = 'standby'
HA_ROUTER_STATE_UNKNOWN = 'unknown'
VALID_HA_STATES = (HA_ROUTER_STATE_ACTIVE, HA_ROUTER_STATE_STANDBY,
                   HA_ROUTER_STATE_UNKNOWN)

PAGINATION_INFINITE = 'infinite'

SORT_DIRECTION_ASC = 'asc'
SORT_DIRECTION_DESC = 'desc'

ETHERTYPE_NAME_ARP = 'arp'
ETHERTYPE_ARP = 0x0806
ETHERTYPE_IP = 0x0800
ETHERTYPE_IPV6 = 0x86DD

IP_PROTOCOL_NAME_ALIASES = {lib_constants.PROTO_NAME_IPV6_ICMP_LEGACY:
                            lib_constants.PROTO_NAME_IPV6_ICMP}

IP_PROTOCOL_NUM_TO_NAME_MAP = {
    str(v): k for k, v in lib_constants.IP_PROTOCOL_MAP.items()}

# When using iptables-save we specify '-p {proto}',
# but sometimes those values are not identical.  This is a map
# of known protocol numbers that require a name to be used and
# protocol names that require a different name to be used,
# because that is how iptables-save will display them.
#
# This is how the list was created, so there is a possibility
# it will need to be updated in the future:
#
# $ for num in {0..255}; do iptables -A INPUT -p $num; done
# $ iptables-save
#
# These cases are special, and were found by inspection:
# - 'ipv6-encap' uses 'ipv6'
# - 'icmpv6' uses 'ipv6-icmp'
# - 'pgm' uses '113' instead of its name
# - protocol '0' uses no -p argument
IPTABLES_PROTOCOL_NAME_MAP = {lib_constants.PROTO_NAME_IPV6_ENCAP: 'ipv6',
                              lib_constants.PROTO_NAME_IPV6_ICMP_LEGACY:
                                  'ipv6-icmp',
                              lib_constants.PROTO_NAME_PGM: '113',
                              '0': None,
                              '1': 'icmp',
                              '2': 'igmp',
                              '3': 'ggp',
                              '4': 'ipencap',
                              '5': 'st',
                              '6': 'tcp',
                              '8': 'egp',
                              '9': 'igp',
                              '12': 'pup',
                              '17': 'udp',
                              '20': 'hmp',
                              '22': 'xns-idp',
                              '27': 'rdp',
                              '29': 'iso-tp4',
                              '33': 'dccp',
                              '36': 'xtp',
                              '37': 'ddp',
                              '38': 'idpr-cmtp',
                              '41': 'ipv6',
                              '43': 'ipv6-route',
                              '44': 'ipv6-frag',
                              '45': 'idrp',
                              '46': 'rsvp',
                              '47': 'gre',
                              '50': 'esp',
                              '51': 'ah',
                              '57': 'skip',
                              '58': 'ipv6-icmp',
                              '59': 'ipv6-nonxt',
                              '60': 'ipv6-opts',
                              '73': 'rspf',
                              '81': 'vmtp',
                              '88': 'eigrp',
                              '89': 'ospf',
                              '93': 'ax.25',
                              '94': 'ipip',
                              '97': 'etherip',
                              '98': 'encap',
                              '103': 'pim',
                              '108': 'ipcomp',
                              '112': 'vrrp',
                              '115': 'l2tp',
                              '124': 'isis',
                              '132': 'sctp',
                              '133': 'fc',
                              '135': 'mobility-header',
                              '136': 'udplite',
                              '137': 'mpls-in-ip',
                              '138': 'manet',
                              '139': 'hip',
                              '140': 'shim6',
                              '141': 'wesp',
                              '142': 'rohc'}

# A length of a iptables chain name must be less than or equal to 11
# characters.
# <max length of iptables chain name> - (<binary_name> + '-') = 28-(16+1) = 11
MAX_IPTABLES_CHAIN_LEN_WRAP = 11
MAX_IPTABLES_CHAIN_LEN_NOWRAP = 28

# Timeout in seconds for getting an IPv6 LLA
LLA_TASK_TIMEOUT = 40

# length of all device prefixes (e.g. qvo, tap, qvb)
LINUX_DEV_PREFIX_LEN = 3
# must be shorter than linux IFNAMSIZ (which is 16)
LINUX_DEV_LEN = 14

# Possible prefixes to partial port IDs in interface names used by the OVS,
# Linux Bridge, and IVS VIF drivers in Nova and the neutron agents. See the
# 'get_ovs_interfaceid' method in Nova (nova/virt/libvirt/vif.py) for details.
INTERFACE_PREFIXES = (lib_constants.TAP_DEVICE_PREFIX,
                      lib_constants.VETH_DEVICE_PREFIX,
                      lib_constants.SNAT_INT_DEV_PREFIX)

ATTRIBUTES_TO_UPDATE = 'attributes_to_update'

# TODO(amuller): Re-define the RPC namespaces once Oslo messaging supports
# Targets with multiple namespaces. Neutron will then implement callbacks
# for its RPC clients in order to support rolling upgrades.

# RPC Interface for agents to call DHCP API implemented on the plugin side
RPC_NAMESPACE_DHCP_PLUGIN = None
# RPC interface for the metadata service to get info from the plugin side
RPC_NAMESPACE_METADATA = None
# RPC interface for agent to plugin security group API
RPC_NAMESPACE_SECGROUP = None
# RPC interface for agent to plugin DVR api
RPC_NAMESPACE_DVR = None
# RPC interface for reporting state back to the plugin
RPC_NAMESPACE_STATE = None
# RPC interface for agent to plugin resources API
RPC_NAMESPACE_RESOURCES = None

# Default network MTU value when not configured
DEFAULT_NETWORK_MTU = 1500
IPV6_MIN_MTU = 1280

ROUTER_MARK_MASK = "0xffff"

VALID_ETHERTYPES = (lib_constants.IPv4, lib_constants.IPv6)

IP_ALLOWED_VERSIONS = [lib_constants.IP_VERSION_4, lib_constants.IP_VERSION_6]

PORT_RANGE_MIN = 1
PORT_RANGE_MAX = 65535

# Configuration values for accept_ra sysctl, copied from linux kernel
# networking (netdev) tree, file Documentation/networking/ip-sysctl.txt
#
# Possible values are:
#         0 Do not accept Router Advertisements.
#         1 Accept Router Advertisements if forwarding is disabled.
#         2 Overrule forwarding behaviour. Accept Router Advertisements
#           even if forwarding is enabled.
ACCEPT_RA_DISABLED = 0
ACCEPT_RA_WITHOUT_FORWARDING = 1
ACCEPT_RA_WITH_FORWARDING = 2

# Some components communicate using private address ranges, define
# them all here. These address ranges should not cause any issues
# even if they overlap since they are used in disjoint namespaces,
# but for now they are unique.
# We define the metadata cidr since it falls in the range.
PRIVATE_CIDR_RANGE = '169.254.0.0/16'
DVR_FIP_LL_CIDR = '169.254.64.0/18'
L3_HA_NET_CIDR = '169.254.192.0/18'
METADATA_CIDR = '169.254.169.254/32'

# The only defined IpamAllocation status at this stage is 'ALLOCATED'.
# More states will be available in the future - e.g.: RECYCLABLE
IPAM_ALLOCATION_STATUS_ALLOCATED = 'ALLOCATED'

VALID_IPAM_ALLOCATION_STATUSES = (IPAM_ALLOCATION_STATUS_ALLOCATED,)

# Port binding states for Live Migration
PORT_BINDING_STATUSES = (lib_constants.ACTIVE,
                         lib_constants.INACTIVE)

VALID_FLOATINGIP_STATUS = (lib_constants.FLOATINGIP_STATUS_ACTIVE,
                           lib_constants.FLOATINGIP_STATUS_DOWN,
                           lib_constants.FLOATINGIP_STATUS_ERROR)

# Floating IP host binding states
FLOATING_IP_HOST_UNBOUND = "FLOATING_IP_HOST_UNBOUND"
FLOATING_IP_HOST_NEEDS_BINDING = "FLOATING_IP_HOST_NEEDS_BINDING"

# Possible types of values (e.g. in QoS rule types)
VALUES_TYPE_CHOICES = "choices"
VALUES_TYPE_RANGE = "range"

# Units base
SI_BASE = 1000
IEC_BASE = 1024

# Port bindings handling
NO_ACTIVE_BINDING = 'no_active_binding'

# Registered extension parent resource check mapping
# If we want to register some service plugin resources into policy and check
# the owner when operating their subresources. We can write here to use
# existing policy engine for parent resource owner check.
# Each entry here should be PARENT_RESOURCE_NAME: SERVICE_PLUGIN_NAME,
# PARENT_RESOURCE_NAME is usually from api definition.
# SERVICE_PLUGIN_NAME is the service plugin which introduced the resource and
# registered the service plugin name in neutron-lib.
EXT_PARENT_RESOURCE_MAPPING = {
    l3.FLOATINGIP: plugin_consts.L3
}
EXT_PARENT_PREFIX = 'ext_parent'

RP_BANDWIDTHS = 'resource_provider_bandwidths'
RP_INVENTORY_DEFAULTS = 'resource_provider_inventory_defaults'


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

from time import time
from common import JsonDict, b64decode, b64encode

class ParamError(BaseException):pass

class Base64(str):
    def __repr__(self) -> str:
        return f'[Base64] size:{len(self)}'

def Source(
        id,
        t=None
    ):
    params = JsonDict(type="Source")
    params.id = id
    params.time = t or int(time())
    return params

def Quote(
        sender:int,
        target:int,
        *message:dict,
        id:int=None
    ):
    r'''回复对象
sender  | Int    | 被引用回复的原消息的发送者的QQ号
target  | Int    | 被引用回复的原消息的接收者者的QQ号（或群号）
id      | Int    | 被引用回复的原消息的messageId
message | Object | 被引用回复的原消息的消息链对象'''
    params = JsonDict(type="Quote")
    if sender:params.senderId = sender
    if target:params.targetId = target
    if id:params.id = id
    if message:params.origin = list(message)
    return params

def At(
        id:int
    ) -> list:
    r'''At
target | Int | 群员QQ号'''
    return JsonDict(type="At",target=id)

def AtAll() -> dict:
    return JsonDict(type="AtAll")

def Face(
        id:int=None,
        name:str=None
    ):
    r'''表情
id   | Int | QQ表情编号，可选，优先高于name
name | Str | QQ表情拼音，可选'''
    params = JsonDict(type="Face")
    if id:params.faceId = id
    if name:params.name = name
    return params

def Plain(s:str) -> dict:
    r'''文本
text | Str | 文字消息'''
    return JsonDict(type="Plain",text=str(s))

def Image(
        url:str=None,
        path:str=None,
        base64:str|bytes|dict=None,
        id=None
    ) -> dict:
    r'''图片
url    | Str | 图片的URL，发送时可作网络图片的链接；接收时为腾讯图片服务器的链接，可用于图片下载
path   | Str | 图片的路径，发送本地图片，路径相对于 JVM 工作路径（默认是当前路径，可通过 `-Duser.dir=...`指定），也可传入绝对路径
base64 | Str | 图片的 str 或 bytes 类型的Base64编码或二进制
id     | Str | 图片的id，群图片与好友图片格式不同。不为空时将忽略url属性'''
    params = JsonDict(type="Image")
    if url:params.url = url
    if path:params.path = path
    if id:params.imageId = id
    if base64:
        try:b64decode(base64)
        except: base64 = b64encode(base64)
        params.base64 = Base64(base64)
    return params

def FlashImage(
        url:str=None,
        path:str=None,
        base64:str|bytes|dict=None,
        id=None
    ) -> dict:
    r'''闪图
url    | Str | 图片的URL，发送时可作网络图片的链接；接收时为腾讯图片服务器的链接，可用于图片下载
path   | Str | 图片的路径，发送本地图片，路径相对于 JVM 工作路径（默认是当前路径，可通过 `-Duser.dir=...`指定），也可传入绝对路径
base64 | Str | 图片的 str 或 bytes 类型的Base64编码或二进制
id     | Str | 图片的id，群图片与好友图片格式不同。不为空时将忽略url属性'''
    params = JsonDict(type="FlashImage")
    if url:params.url = url
    if path:params.path = path
    if id:params.imageId = id
    if base64:
        try:b64decode(base64)
        except: base64 = b64encode(base64)
        params.base64 = Base64(base64)
    return params

def Voice(
        url:str=None,
        path:str=None,
        base64:str|bytes|dict=None,
        id=None
    ) -> dict:
    r'''语音
url    | Str | 语音的URL，发送时可作网络语音的链接；接收时为腾讯语音服务器的链接，可用于语音下载
path   | Str | 语音的路径，发送本地语音，路径相对于 JVM 工作路径（默认是当前路径，可通过 `-Duser.dir=...`指定），也可传入绝对路径。
base64 | Str | 语音的 str 或 bytes 类型的Base64编码或二进制
id     | Str | 语音的id，不为空时将忽略url属性

#> 参数任选其一，出现多个参数时，按照id > url > path > base64的优先级'''
    params = JsonDict(type="Voice")
    if url:params.url = url
    if path:params.path = path
    if id:params.voiceId = id
    if base64:
        try:b64decode(base64)
        except: base64 = b64encode(base64)
        params.base64 = Base64(base64)
    return params

def Xml(xml:str) -> dict:
    r'''XML
xml | Str | XML文本'''
    return JsonDict(type="Xml",xml=xml)

def Json(json:str):
    r'''JSON
json | Str | Json文本'''
    return JsonDict(type="Json",json=json)

def App(content:str):
    r'''小程序
content | Str | 内容'''
    return JsonDict(type="App",content=content)

def Poke(name:str):
    r'''戳一戳
name | Str | 戳一戳名称
1. "Poke": 戳一戳
2. "ShowLove": 比心
3. "Like": 点赞
4. "Heartbroken": 心碎
5. "SixSixSix": 666
6. "FangDaZhao": 放大招'''
    return JsonDict(type="Poke",name=name)

def Dice(value:int):
    r'''骰子
value | Int | 点数'''
    return JsonDict(type="Dice",value=value)

def MusicShare(
        kind=None,
        title=None,
        summary=None,
        jumpUrl=None,
        pictureUrl=None,
        musicUrl=None,
        brief=None
    ):
    r'''音乐分享
kind       | Str | 类型
title      | Str | 标题
summary    | Str | 概括
jumpUrl    | Str | 跳转路径
pictureUrl | Str | 封面路径
musicUrl   | Str | 音源路径
brief      | Str | 简介'''
    params = JsonDict(type="MusicShare")
    if kind:params.kind = kind
    if title:params.title = title
    if summary:params.summary = summary
    if jumpUrl:params.jumpUrl = jumpUrl
    if pictureUrl:params.pictureUrl = pictureUrl
    if musicUrl:params.musicUrl = musicUrl
    if brief:params.brief = brief
    return params

def Forward(
    *node:dict,
    title:str=None,
    brief:str=None,
    summary:str=None,
    preview:list=None,
    source:str=None
) -> dict:
    r'''聊天记录
nodeList | object | 消息节点
title    | Str    | 标题（群聊的聊天记录）
brief    | Str    | 简介（[聊天记录]）
summary  | Str    | 总结（查看x条转发消息）
preview  | List   | 预览（["msg1", "msg2", "msg3", "msg4"]）
source   | Str    | 来源（聊天记录）'''
    params = JsonDict(type="Forward",nodeList=list(node))
    if title or brief or source or preview or summary:
        params.display = JsonDict()
        if title:params.display.title = title
        if brief:params.display.brief = brief
        if source:params.display.source = source
        if preview:params.display.preview = preview
        if summary:params.display.summary = summary
    return params

def Node(
    sender:int=None,
    name:str=None,
    *message:dict,
    t:int=None,
    target:int=None,
    id:int=None,
    ref:dict|list|tuple=None
) -> dict:
    r'''聊天记录节点
senderid   | Int             | 发送人QQ号
time       | Int             | 发送时间
senderName | Str             | 显示名称
message    | List            | 消息数组
id         | Int             | 可以只使用消息id，从缓存中读取一条消息作为节点
target     | Int             | 引用的上下文目标，群号、好友账号
ref        | Dict|List|Tuple | {'id' or 'messageId':Int,'target':Int} 或者 [target:Int,messageId:Int]'''
    params = JsonDict()
    if sender:params.senderId = sender
    if not name:name = str(sender)
    if name:params.senderName = name
    params.messageChain = list(message)
    params.time = t or (int(time())if not id else None)

    if ref:
        if type(ref) in [list,tuple]:
            params.messageRef = JsonDict(target=ref[0], messageId=ref[1])
        else:
            if 'messageId' in ref and 'target' in ref:
                params.messageRef = JsonDict(ref)
            elif 'id' in ref and 'target' in ref:
                params.messageRef = JsonDict(target=ref.target, messageId=ref.id)
            else:
                raise ParamError('Error:The key of ref is only (id or messageId) and target')
    elif target:
        if id:
            params.messageRef = {'messageId':id,'target':target}
        else:
            raise ParamError('Error:id is None')
    elif id:
        params.messageId = id
    return params

def File(
    id=None,
    name=None,
    size=None
):
    r'''文件类型
id   | Str | 文件识别id
name | Str | 文件名
size | Int   | 文件大小'''
    return JsonDict({
        "type": "File",
        "id": id,
        "name": name,
        "size": size
    })

def MiraiCode(MiraiCode):
    r'''Mirai命令行
code | Str | MiraiCode
MiraiCode的使用(https://github.com/mamoe/mirai/blob/dev/docs/Messages.md#%E6%B6%88%E6%81%AF%E5%85%83%E7%B4%A0)'''
    return JsonDict(type="MiraiCode",code=MiraiCode)


import webbrowser
query = input("Co chces hledat?: ")
#moje url
def vyskakovac_oken(query):
    url_list = [f"https://www.google.com/?gws_rd=cr,ssl&ei=NCZFWIOJN8yMsgHCyLV4&fg=1#q={query}",
                f"https://www.google.com/?gws_rd=cr,ssl&ei=NCZFWIOJN8yMsgHCyLV4&fg=1#q={query}",
                f"https://twitter.com/search?q=%23{query}&src=typeahead_click",
                f"https://www.youtube.com/results?search_query={query}",
                f"https://www.facebook.com/search/pages/?q={query}&epa=SEARCH_BOX",
                f"https://www.reddit.com/r/{query}/"
               ]
    #reseni u wikipedie
    if " " in query:
        nove_query = "_".join(query.split())
        url_wikipedie = f"https://cs.wikipedia.org/wiki/{nove_query}"
        url_list.append(url_wikipedie)
    else:
        url_wikipedie = f"https://cs.wikipedia.org/wiki/{query}"
        url_list.append(url_wikipedie)
    for url in url_list:
      #otevreni stranek
      webbrowser.open_new(url)
vyskakovac_oken(query)


import turtle

r = 150
angle1 = 70
angle2 = 40

# Initializing the turtle
wn = turtle.Screen()
wn.setup(500, 500)
wn.delay(25)
t = turtle.Turtle()

t1 = turtle.Turtle()

t1.color("red")
t1.fillcolor("red")
t1.begin_fill()
t1.circle(r, angle1)
t1.goto(0, r)
t1.penup()
t1.end_fill()
t1.penup()
t1.goto(0,0)
t1.right(angle1)
t1.circle(r, angle1)
t1.pendown()

t1.fillcolor("blue")
t1.begin_fill()
t1.circle(r, angle2)
t1.goto(0, r)
t1.penup()
t1.end_fill()
t1.penup()
t1.goto(0,0)
t1.right(angle1 + angle2)
t1.circle(r, angle1 + angle2)
t1.pendown()

wn.exitonclick()


import numpy as np
from PIL import Image
import random
import torch
from torchvision import datasets, transforms

class LeftOutScaleMNIST(datasets.MNIST):
    # pct_to_keep: percentage of possible combinations to keep between 0 and 1, rounded down to nearest multiple of 1/9
    def __init__(self, root, train=True, transform=None, target_transform=None, download=False, pct_to_keep=1, color_indices=None):
        super().__init__(root, train, transform, target_transform, download)
        print(pct_to_keep)
        pct = pct_to_keep * 3
        print(pct)
        self.max_left_dist = int(pct / 2)
        self.max_right_dist = int(pct / 2) if pct % 2 == 0 else int(pct / 2) + 1
        self.held_out = [(0, 1), (1, 2), (2, 0), (3, 1), (4, 2), (5, 0), (6, 1), (7, 2), (8, 0)]
        self.control = [(0, 0), (1, 1), (2, 2), (3, 0), (4, 1), (5, 2), (6, 0), (7, 1), (8, 2)]
        self.held_out_val = self.held_out[:2]
        self.held_out_test = self.held_out[2:]
        self.control_val = self.control[:2]
        self.control_test = self.control[2:]
        self.combination_space_shape = (9, 3)
        self.class_names = ("shape", "scale")
        self.name = "left_out_scale_mnist"

    def __getitem__(self, index):
        """
        Args:
            index (int): Index

        Returns:
            tuple: (image, target) where target is index of the target class.
        """
        if self.train:
            img, target = self.train_data[index], self.train_labels[index]
        else:
            img, target = self.test_data[index], self.test_labels[index]
        assert target.item() < 9

        # Put grayscale image in RGB space
        img_array = np.stack((img.numpy(),) * 3, axis=-1)

        # Determine image size
        number_class = target.item()
        lower_bound = number_class - self.max_left_dist
        upper_bound = number_class + self.max_right_dist
        scale_class = random.randrange(lower_bound, upper_bound) % 3
        size = [28, 18, 8][scale_class]

        img = Image.fromarray(img_array)
        img.thumbnail((size, size))
        img_array = np.zeros((28, 28, 3))

        vert_offset = int((28 - size) / 2)
        horiz_offset = int((28 - size) / 2)

        img_array[vert_offset:(vert_offset + size), horiz_offset:(horiz_offset + size), :] = np.array(img)
        img_array = np.clip(img_array, 0, 254)
        img_array = img_array.astype(dtype=np.uint8)

        # 28x28 to 32x32
        zeros = np.zeros((img_array.shape[0] + 4, img_array.shape[1] + 4, img_array.shape[2]), dtype="uint8")
        zeros[2:img_array.shape[0] + 2, 2:img_array.shape[1] + 2, :] = img_array
        img_array = zeros

        img = Image.fromarray(img_array)

        # Perform any non-color transformations
        if self.transform is not None:
            img = self.transform(img)

        if self.target_transform is not None:
            target = self.target_transform(target)

        return transforms.ToTensor()(img), torch.tensor([target.item(), scale_class])


# -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 10:58:54 2020

@author: palar
"""

def bisec(l,h):
    print("low= "+str(l)+" y high= "+str(h))
    return (high+low)//2

low=0.0
high=100
ans=(high+low)/2.0
tru=True

print("Please think of a number between 0 and 100!")
while tru==True:
    print("Is yout secret number "+str(ans)+"?")
    dec=input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
    if dec=='l':
        low=ans
        print("Muy bajo. Ahora low=",ans)
        ans=bisec(low,high)
    elif dec=='h':
        high=ans
        print("Muy alto. Ahora high=",ans)
        ans=bisec(low,high)
    elif dec=='c':
        tru=False
    else:
        print("Sorry, I did not understand your input.")
print("Game over. Your secret number was:",ans)

#Este es el print que va dentro del ciclo
#value= input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")


import logging

class AutoLogger(object):
    def setupLogger(loggerName, logFile, level=logging.INFO):
        l = logging.getLogger(loggerName)
        formatter = logging.Formatter('%(asctime)s : %(message)s')
        fileHandler = logging.FileHandler(logFile, mode='w')
        fileHandler.setFormatter(formatter)

        l.setLevel(level)
        l.addHandler(fileHandler)


import json
import random
import numpy as np

from paddlehub_dataprocess import write_by_lines,read_by_lines,regrex_data,read_label
from paddlehub_dataprocess import write_title
from paddlehub_dataprocess import write_log,get_submit_cross_validation_vote

from config import *

from paddlehub_buildtask import *

def one(args, schema_labels, predict_data, predict_sents, id):
    seq_label_task, reader = get_task(args, schema_labels, id)
    # 加载PaddleHub 预训练模型ERNIE Tiny/RoBERTa large
    # 更多预训练模型 https://www.paddlepaddle.org.cn/hublist?filter=en_category&value=SemanticModel
    # model_name = "ernie_tiny"

    # PaddleHub Finetune API
    # 将自动训练、评测并保存模型
    if args.do_train:
        print("start finetune and eval process")
        seq_label_task.finetune_and_eval()
        write_log('./work/log/' + args.do_model + '.txt', args, id + ',' + str(seq_label_task.best_score))

    if args.do_predict:
        print("start predict process")
        ret = []
        id2label = {val: key for key, val in reader.label_map.items()}
        input_data = [[d] for d in predict_data]
        # print(input_data[:10])
        run_states = seq_label_task.predict(data=input_data)
        results = []
        for batch_states in run_states:
            batch_results = batch_states.run_results
            # print('batch_infers',batch_results )
            batch_infers = batch_results[0].reshape([-1]).astype(np.int32).tolist()
            seq_lens = batch_results[1].reshape([-1]).astype(np.int32).tolist()
            current_id = 0
            for length in seq_lens:
                seq_infers = batch_infers[current_id:current_id + length]
                seq_result = list(map(id2label.get, seq_infers[1: -1]))
                current_id += length if args.add_crf else args.max_seq_len
                results.append(seq_result)

        ret = []
        for sent,input, r_label in zip(predict_sents,input_data,results):
            sent["input"]=input
            sent["labels"] = r_label
            ret.append(json.dumps(sent, ensure_ascii=False))
        write_by_lines("{}.{}.{}.pred".format(output_predict_data_path, args.do_model, id), ret)
        get_submit_postprocess(args, id)
        get_submit_postprocess(args, id,check=True)

def cross_validation(args,id):
    begid=id
    for i in range(args.cross_validation_num):
        if (id < 40):
            id += 1
            continue
        schema_labels, predict_data, predict_sents = process_data(args, i)
        args.checkpoint_dir = 'models/' + args.do_model + str(id)
        one(args, schema_labels, predict_data, predict_sents, str(id))
        get_submit_postprocess(args, id, check=True)
        get_submit_postprocess(args, id, check=False)

        id += 1
    get_submit_cross_validation_vote(cross_validation_num=args.cross_validation_num, begid=begid,
                                     type=args.change_event)
    return id

def testone():##按默认执行
    # get_data()
    args = parser.parse_args()
    np.random.seed(args.random_seed)
    random.seed(args.random_seed)
    args.do_model = 'mcls'
    schema_labels, predict_data, predict_sents = process_data(args)
    shiyan = """
    mcls
        """
    write_title('./work/log/' + args.do_model + '.txt', args, shiyan)
    args.checkpoint_dir = 'models/' + args.do_model + str(id)
    one(args, schema_labels, predict_data, predict_sents, str(id))

def findlr():
    id=9
    args = parser.parse_args()
    np.random.seed(args.random_seed)
    random.seed(args.random_seed)
    args.do_model = 'role'
    schema_labels, predict_data, predict_sents = process_data(args)

    for lr in [1e-5,5e-5,3e-4,3e-6]:
        if(id<10):
            continue
        args.learning_rate=lr
        args.checkpoint_dir = 'models/' + args.do_model + str(id)
        one(args, schema_labels, predict_data, predict_sents, str(id))
        id+=1

def change_event_label():
    id=40
    args = parser.parse_args()
    np.random.seed(args.random_seed)
    random.seed(args.random_seed)
    args.do_model = 'role'
    # shiyan = """
    # 增加一列：change_event
    #     """
    # write_title('./work/log/' + args.do_model + '.txt', args, shiyan)
    for event_label in ['BIO_event','BIO','no']:
        if(event_label=='BIO_event'):
            args.add_rule=True
        else:
            args.add_rule=False
        args.change_event=event_label
        if(args.use_cross_validation):
            id=cross_validation(args,id)
        else:
            schema_labels, predict_data, predict_sents = process_data(args, i)
            args.checkpoint_dir = 'models/' + args.do_model + str(id)
            one(args, schema_labels, predict_data, predict_sents, str(id))
            get_submit_postprocess(args, id, check=True)
            get_submit_postprocess(args, id, check=False)
            id += 1
if __name__ == "__main__":
    # findlr()
    # id=17
    # testone()
    change_event_label()


# PLACE YOUR CODE HERE
import re

f = open('faculty.csv', 'r')

data = []

degrees = {}

# Question 1
for line in f:
    professor = line.replace('\n','').split(',')
    data.append(professor)
    degs = professor[1].replace('.','').split(' ')
    for deg in degs:
        if deg not in degrees:
            degrees[deg] = 1
        else:
            degrees[deg] += 1

print(degrees)

titles = {}
# Question 2
for professor in data:
    title = ' '.join(professor[2].split(' ')[:-2])
    if title not in titles:
        titles[title] = 1
    else:
        titles[title] += 1

print(titles)

# Question 3
emails = []
for professor in data:
    emails.append(professor[3])

print(emails[1:])

# Question 4:
domains = {}
for email in emails:
    domain = '@' + email.split('@')[-1]
    if domain not in domains:
        domains[domain] = 1
    else:
        domains[domain] += 1

print(domains)

# Question 5

w = open('emails.csv', 'w')

for email in emails[1:]:
    w.write(email + '\n')

w.close()


'''
Database
interacts with the database via files formatted from csv files
'''
# import sys
# sys.path.append("./hp_norton_inventory")
import logging
import time
import cProfile, pstats
import linear_csv_handler as csvh
from mongo_connect import *
from timeit import timeit as timer

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def import_data(directory_name, customer_file, product_file, rentals_file):
    ''' import data from csv files into database to be used in functions '''
    mongo = MongoDBConnection()
    csv_handler = csvh.CsvHandler()

    ERROR_COUNT = {
        'PRODUCT_ERROR': 0,
        'CUSTOMER_ERROR': 0,
        'RENTALS_ERROR': 0
    }

    INVENTORY_COUNT = {
        'product_totals': 0,
        'customer_totals': 0,
        'rental_totals': 0
    }

    product_file = f'{directory_name}/{product_file}'
    customer_file = f'{directory_name}/{customer_file}'
    rentals_file = f'{directory_name}/{rentals_file}'

    with mongo:
        # generate hpnorton_db
        hpnorton_db = mongo.connection.hpnorton_db

        # collections in database
        product_db = hpnorton_db['product']
        customer_db = hpnorton_db['customer']
        rentals_db = hpnorton_db['rental']

        try:
            products = csv_handler.generate_document_list(product_file, "product")
        except FileNotFoundError as error:
            logger.info(f' File not found {error}')
            ERROR_COUNT['PRODUCT_ERROR']+=1

        try:
            customers = csv_handler.generate_document_list(customer_file, "customer")
        except FileNotFoundError as error:
            logger.info(f' File not found {error}')
            ERROR_COUNT['CUSTOMER_ERROR']+=1

        try:
            rentals = csv_handler.generate_document_list(rentals_file, "rental")
        except FileNotFoundError as error:
            logger.info(f' File not found {error}')
            ERROR_COUNT['RENTALS_ERROR']+=1

        # write to database
        try:
            product_db.insert_many(products)
            product_totals = [product_id for product_id in product_db.find()]
            INVENTORY_COUNT['product_totals'] = len(product_totals)
        except UnboundLocalError as error:
            logger.info(f' {error}')
            ERROR_COUNT['PRODUCT_ERROR']+=1

        try:
            customer_db.insert_many(customers)
            customer_totals = [customer_id for customer_id in customer_db.find()]
            INVENTORY_COUNT['customer_totals'] = len(customer_totals)
        except UnboundLocalError as error:
            logger.info(f' {error}')
            logger.info(ERROR_COUNT['CUSTOMER_ERROR'])
            ERROR_COUNT['CUSTOMER_ERROR']+=1

        try:
            rentals_db.insert_many(rentals)
            rental_totals = [rental_id for rental_id in rentals_db.find()]
            INVENTORY_COUNT['rental_totals'] = len(rental_totals)
        except UnboundLocalError as error:
            logger.info(f' {error}')
            ERROR_COUNT['RENTALS_ERROR']+=1

        inventory_count = [INVENTORY_COUNT['product_totals'],
                           INVENTORY_COUNT['customer_totals'],
                           INVENTORY_COUNT['rental_totals']]

        error_count = [ERROR_COUNT['PRODUCT_ERROR'],
                       ERROR_COUNT['CUSTOMER_ERROR'],
                       ERROR_COUNT['RENTALS_ERROR']]

        return [tuple(inventory_count), tuple(error_count)]

def show_available_products():
    ''' returns a list of items available for rent '''
    mongo = MongoDBConnection()
    #available_units = {}

    with mongo:
        hpnorton_db = mongo.connection.hpnorton_db
        product_totals = [product for product in hpnorton_db.products.find()]
        available = list(filter(lambda units: int(units['quantity_available']) > 0, product_totals))

        return available

def show_rentals(product_id):
    ''' returns the matching fields information based on product id '''
    mongo = MongoDBConnection()

    with mongo:
        hpnorton_db = mongo.connection.hpnorton_db
        rental_totals = [rental for rental in hpnorton_db.rentals.find()]
        rented_unit = list(filter(lambda units: units['product_id'] == product_id, rental_totals))

        return rented_unit

def main():
    ''' main method to interact with mongodb '''
    mongo = MongoDBConnection()
    output = import_data('data', 'customer.csv', 'product.csv', 'rental.csv')

    logger.info(f' Total number of invetory and errors {output}')

    with mongo:
        database = mongo.connection.hpnorton_db
        yorn = input("Drop data?")
        if yorn.upper() == 'Y':
            database['customers'].drop()
            database['rentals'].drop()
            database['products'].drop()

if __name__ == "__main__":
    output_code = '''
output = import_data('data', 'customer.csv','product.csv','rental.csv')
    '''
    print(timer(output_code,globals=globals(),number=1))
    main()
    # profiler = cProfile.Profile()
    # profiler.run('main()')
    # profiler.print_stats()
    # pstats.Stats(profiler).sort_stats('time').print_stats()


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

"""Main module. Launch by running python -m rest_uploader.cli"""

import os
import platform
import time
import base64
import mimetypes
import json
import requests
import csv
from tabulate import tabulate
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from .img_process import (
    extract_text_from_image,
    extract_text_from_pdf,
    pdf_page_to_image,
    pdf_valid,
)
from .settings import SERVER, JOPLIN_NOTEBOOK, TEMP_PATH
from .api_token import get_token_suffix
from pathlib import Path

"""
2018-09-24 JRK
This program was created to upload files from a folder specified in the
PATH variable to Joplin. The following resource was helpful in figuring out
the logic for Watchdog:
https://stackoverflow.com/questions/18599339/python-watchdog-monitoring-file-for-changes

Tested with the following extensions:
.md
.txt
.pdf
.png
.jpg
.url

Caveat
Uploader only triggered upon new file creation, not modification
"""

class MyHandler(FileSystemEventHandler):
    def _event_handler(self, path):
        filename, ext = os.path.splitext(path)
        if ext not in (".tmp", ".crdownload") and ext[:2] not in (".~"):
            for i in range(10):
                filesize = os.path.getsize(path)
                if filesize < 1 or (ext == ".pdf" and not pdf_valid(path)):
                    print("Incomplete file. Retrying...")
                    if i == 9:
                        print("timeout error, invalid file")
                        return False
                    time.sleep(5)
                elif filesize > 10000000:
                    print(f"Filesize = {filesize}. Too big for Joplin, skipping upload")
                    break
                else:
                    upload(path)
                    return True
        else:
            print("Detected temp file. Temp files are ignored.")

    def on_created(self, event):
        print(event.event_type + " -- " + event.src_path)
        self._event_handler(event.src_path)

    def on_moved(self, event):
        print(event.event_type + " -- " + event.dest_path)
        self._event_handler(event.dest_path)

# Set working Directory
def set_working_directory():
    if os.getcwd() != os.chdir(os.path.dirname(os.path.realpath(__file__))):
        os.chdir(os.path.dirname(os.path.realpath(__file__)))

def set_token():
    global TOKEN
    TOKEN = get_token_suffix()

def read_text_note(filename):
    with open(filename, "r") as myfile:
        text = myfile.read()
        print(text)
    return text

def read_csv(filename):
    return csv.DictReader(open(filename))

def get_notebook_id():
    # Find the ID of the destination folder
    # adapted logic from jhf2442 on Joplin forum
    # https://discourse.joplin.cozic.net/t/import-txt-files/692
    res = requests.get(SERVER + "/folders" + TOKEN)
    folders = res.json()

    notebook_id = 0
    for folder in folders:
        if folder.get("title") == JOPLIN_NOTEBOOK:
            notebook_id = folder.get("id")
    if notebook_id == 0:
        for folder in folders:
            if "children" in folder:
                for child in folder.get("children"):
                    if child.get("title") == JOPLIN_NOTEBOOK:
                        notebook_id = child.get("id")
    return notebook_id

def create_resource(filename):
    basefile = os.path.basename(filename)
    title = os.path.splitext(basefile)[0]
    files = {
        "data": (json.dumps(filename), open(filename, "rb")),
        "props": (None, '{{"title":"{}", "filename":"{}"}}'.format(title, basefile)),
    }
    response = requests.post(SERVER + "/resources" + TOKEN, files=files)
    print(response.json())
    return response.json()

def delete_resource(resource_id):
    apitext = SERVER + "/resources/" + resource_id + TOKEN
    response = requests.delete(apitext)
    return response

def get_resource(resource_id):
    apitext = SERVER + "/resources/" + resource_id + TOKEN
    response = requests.get(apitext)
    return response

def encode_image(filename, datatype):
    encoded = base64.b64encode(open(filename, "rb").read())
    img = "data:{};base64,{}".format(datatype, encoded.decode())
    return img

def set_json_string(title, notebook_id, body, img=None):
    if img is None:
        return '{{ "title": {}, "parent_id": "{}", "body": {} }}'.format(
            json.dumps(title), notebook_id, json.dumps(body)
        )
    else:
        return '{{ "title": "{}", "parent_id": "{}", "body": {}, "image_data_url": "{}" }}'.format(
            title, notebook_id, json.dumps(body), img
        )

def upload(filename):
    """ Get the default Notebook ID and process the passed in file"""
    notebook_id = get_notebook_id()
    basefile = os.path.basename(filename)
    title, ext = os.path.splitext(basefile)
    body = basefile + " uploaded from " + platform.node() + "\n"
    datatype = mimetypes.guess_type(filename)[0]
    if datatype is None:
        # avoid subscript exception if datatype is None
        if ext in (".url", ".lnk"):
            datatype = "text/plain"
        else:
            datatype = ""
    if datatype == "text/plain":
        body += read_text_note(filename)
        values = set_json_string(title, notebook_id, body)
    if datatype == "text/csv":
        table = read_csv(filename)
        body += tabulate(table, headers="keys", numalign="right", tablefmt="pipe")
        values = set_json_string(title, notebook_id, body)
    elif datatype[:5] == "image":
        img = encode_image(filename, datatype)
        body += "\n<!---\n"
        body += extract_text_from_image(filename)
        body += "\n-->\n"
        values = set_json_string(title, notebook_id, body, img)
    else:
        response = create_resource(filename)
        body += "[{}](:/{})".format(basefile, response["id"])
        values = set_json_string(title, notebook_id, body)
        if response["file_extension"] == "pdf":
            # Special handling for PDFs
            body += "\n<!---\n"
            body += extract_text_from_pdf(filename)
            body += "\n-->\n"
            previewfile = TEMP_PATH + "preview.png"
            if not os.path.exists(previewfile):
                previewfile = pdf_page_to_image(filename)
            img = encode_image(previewfile, "image/png")
            os.remove(previewfile)
            values = set_json_string(title, notebook_id, body, img)

    response = requests.post(SERVER + "/notes" + TOKEN, data=values)
    print(response)
    print(response.text)
    print(response.json())

def watcher(path=None):
    set_working_directory()
    set_token()
    if path is None:
        path = str(Path.home())

    event_handler = MyHandler()
    print("Monitoring directory {} for files".format(path))
    observer = Observer()
    observer.schedule(event_handler, path=path, recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == "__main__":
    watcher()