"""Support for monitoring energy usage using the DTE energy bridge."""
import logging

from homeassistant.helpers.entity import Entity

_LOGGER = logging.getLogger(__name__)

ICON = 'mdi:flash'

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the DTE energy bridge sensor."""
    ip_address = config.get('ip')
    if not ip_address:
        _LOGGER.error(
            "Configuration Error"
            "'ip' of the DTE energy bridge is required")
        return None
    dev = [DteEnergyBridgeSensor(ip_address)]
    add_devices(dev)

# pylint: disable=too-many-instance-attributes
class DteEnergyBridgeSensor(Entity):
    """Implementation of an DTE Energy Bridge sensor."""

    def __init__(self, ip_address):
        """Initialize the sensor."""
        self._url = "http://{}/instantaneousdemand".format(ip_address)
        self._name = "Current Energy Usage"
        self._unit_of_measurement = "kW"
        self._state = None

    @property
    def name(self):
        """Return the name of th sensor."""
        return self._name

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement of this entity, if any."""
        return self._unit_of_measurement

    @property
    def icon(self):
        """Icon to use in the frontend, if any."""
        return ICON

    def update(self):
        """Get the energy usage data from the DTE energy bridge."""
        import requests

        try:
            response = requests.get(self._url, timeout=5)
        except (requests.exceptions.RequestException, ValueError):
            _LOGGER.warning(
                'Could not update status for DTE Energy Bridge (%s)',
                self._name)
            return

        if response.status_code != 200:
            _LOGGER.warning(
                'Invalid status_code from DTE Energy Bridge: %s (%s)',
                response.status_code, self._name)
            return

        response_split = response.text.split()

        if len(response_split) != 2:
            _LOGGER.warning(
                'Invalid response from DTE Energy Bridge: "%s" (%s)',
                response.text, self._name)
            return

        self._state = float(response_split[0])


import spacy
import pandas as pd
from text_preprocessing.tweet_cleaning import tweet_preprocessing_series,single_tweet_preprocessing
import subprocess

try:
    en = spacy.load('en_core_web_sm')
except:
    _ = subprocess.run(['python', '-m', 'spacy', 'download', 'en_core_web_sm'])
    en = spacy.load('en_core_web_sm')

def tokenize(sentence):
    return [tok.text for tok in en.tokenizer(sentence)]

if __name__=="__main__":
    csv_file = r'C:\Users\Ankan\Downloads\train_tweet.csv'
    df = pd.read_csv(csv_file)
    # df['cleaned'] = tweet_preprocessing_series(df['tweet'])
    # print(df['cleaned'][0])
    sentence = single_tweet_preprocessing(df['tweet'][0])
    print(sentence)
    print(tokenize(sentence))


import streamlit as st
import tensorflow_hub as hub
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import load_model

from PIL import Image
import numpy as np
st.title("Dermatology Disease Classification")

st.write("Predict the skin disease by using the image.")

model = load_model("my_model.h5",custom_objects={'KerasLayer':hub.KerasLayer})
labels = {
        0: 'Hair Loss Photos Alopecia and other Hair Diseases',
        1: 'Melanoma Skin Cancer Nevi and Moles',
        2: 'Nail Fungus and other Nail Disease',
        3: 'Urticaria Hives',
        4: 'Warts Molluscum and other Viral Infections'
    }

uploaded_file = st.file_uploader(
    "Upload an image of a dermalogical disease:", type='jpg'
)
predictions=-1
if uploaded_file is not None:
    image1 = Image.open(uploaded_file)
    image1=image.smart_resize(image1,(224,224))
    img_array = image.img_to_array(image1)
    img_array = np.expand_dims(img_array, axis=0)
    img_array = img_array/255.0
    predictions = model.predict(img_array)
    label=labels[np.argmax(predictions)]

st.write("### Prediction Result")
if st.button("Predict"):
    if uploaded_file is not None:
        image1 = Image.open(uploaded_file)
        st.image(image1, caption="Uploaded Image", use_column_width=True)
        st.markdown(
            f"
Image of {label}
",
            unsafe_allow_html=True,
        )
    else:
        st.write("Please upload file or choose sample image.")

st.write("If you would not like to upload an image, you can use the sample image instead:")
sample_img_choice = st.button("Use Sample Image")

if sample_img_choice:
    image1 = Image.open("hairloss.jpg")
    image1=image.smart_resize(image1,(224,224))
    img_array = image.img_to_array(image1)
    img_array = np.expand_dims(img_array, axis=0)
    img_array = img_array/255.0
    predictions = model.predict(img_array)
    label=labels[np.argmax(predictions)]
    image1 = Image.open("hairloss.jpg")
    st.image(image1, caption="Uploaded Image", use_column_width=True)
    st.markdown(
        f"
{label}
",
        unsafe_allow_html=True,
    )


# 费式
class Solution:
    def fib(self, n: int) -> int:
        # 数值小于2 回传自身
        if n<2:return n
        # 纪录一下，前两个没办法算手填
        nums=[0,1]
        for index in range(2,n+1):
            # 沿途算并加进去
            nums.append(nums[index-1]+nums[index-2])
        return nums[n]
class Solution:
    def fib(self, n: int) -> int:
        # 一样小于2 回传自身
        if n<2:return n
        # 给一个范围放值
        dp=[0]*(n+1)
        def recrusion(n):
            # 跑递回
            if(n==0 or n==1):return n
            # 如果有值就取值别算
            if dp[n]!=0:
                return dp[n]
            # 跑递回
            dp[n]=recrusion(n-1)+recrusion(n-2)
            # 最后记得回传
            return dp[n]
        recrusion(n)
        return dp[n]


# https://www.codechef.com/submit/SALARY
# Hint: Increasing salary of only winners is same as decreasing for just the loser
t=int(input())
for _ in range(t):
    n=int(input())
    s=list(map(int,input().split()))
    turns = 0
    s.sort()
    print(s)
    for i in range(n):
        turns+=s[i]-s[0]
    print(turns)


import os
import numpy as np

import getdist
from getdist import plots
import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['font.family'] = 'serif'
import matplotlib.pyplot as plt

from .phazap import phases_events
from . import utils
from . import tension_utils as tension

_default_plot_filename_str = "phazap_{}_{}_fbest_{}_fhigh_{}_flow_{}.pdf"

def phazap_plot(event1_postprocessed_phase, event2_postprocessed_phase, output_dir="./", output_filename=None):
    """
    Plot the postprocessed phase for two events

    Parameters
    ----------
    event1_postprocessed_phase: PostprocessedPhase
        PostprocessedPhase instance for event 1
    event2_postprocessed_phase: PostprocessedPhase
        PostprocessedPhase instance for event 2
    output_dir: str, optional
        Output directory
    output_filename: str, optional
        Output filename

    Returns
    -------
    matplotlib.figure.Figure
        The figure object

    """
    parameters_1, parameters_2, det_phases_1, det_phases_2, tau_phases_1, tau_phases_2, Dphi_f_1, Dphi_f_2, above_below = phases_events(event1_postprocessed_phase, event2_postprocessed_phase)

    event_name_1 = "event_1"
    if event1_postprocessed_phase.superevent_name is not None:
        event_name_1 = event1_postprocessed_phase.superevent_name
    event_name_2 = "event_2"
    if event2_postprocessed_phase.superevent_name is not None:
        event_name_2 = event2_postprocessed_phase.superevent_name

    nphases = 3
    length = np.shape(parameters_1)[1]

    #Compute volume phases
    vol_phases_1, vol_phases_2 = tension.volume_only_phases(det_phases_1,det_phases_2)

    #Compute distances
    #We divide the samples in two groups, above and below the plane
    #only if the fraction of samples in each group is between 0.05 and 0.95
    frac_samples_below = len(above_below[above_below<0]) / len(above_below)
    frac_limit = 0.05
    if (frac_samples_below>frac_limit) & (frac_samples_below < 1 - frac_limit):
        #All phases
        dist_M = tension.distance_phases_with_shift(parameters_1,parameters_2[above_below<0],nphases)
        dist_P = tension.distance_phases_with_shift(parameters_1,parameters_2[above_below>0],nphases)
        dist_all = np.minimum(dist_M,dist_P)
    else:
        dist_all = tension.distance_phases_with_shift(parameters_1,parameters_2,nphases)

    dist = dist_all

    phase_shifts = np.array([0,1,2,-1])*np.pi/2
    phase_shift = phase_shifts[np.argmin(dist)]*np.hstack((np.ones(nphases),np.zeros(length-nphases)))

    #Event 2 is shifted by the phase shift that minimizes the distance
    parameters_2_shifted = parameters_2 + phase_shift
    parameters_2_shifted[:,:nphases] = np.mod(parameters_2_shifted[:,:nphases],2*np.pi)

    parameters_1_wrap, parameters_2_wrap = utils.wrap_phases(parameters_1,parameters_2_shifted,nphases)

    #labels
    labels = [
        r'\phi_\mathrm{H}',
        r'\phi_\mathrm{L}',
        r'\phi_\mathrm{V}',
        r'\tau_\mathrm{HL}',
        r'\tau_\mathrm{HV}',
        r'\Delta\phi_f',
    ]

    label_1 = event_name_1
    best_phase_shift = utils.format_pretty_phase_shift(phase_shifts[np.argmin(dist)]).replace('0', '0π').replace('π', '\pi').replace('±', '\pm')
    label_2 = fr"{event_name_2} (shifted by ${best_phase_shift}$)"

    color_1 = 'blue'
    color_2 = 'green'

    # Get the getdist MCSamples objects for the samples, specifying same parameter
    # names and labels; if not specified weights are assumed to all be unity
    names = ["x%s"%i for i in range(length)]
    #labels =  ["x_%s"%i for i in range(ndim)]
    samples_1 = getdist.MCSamples(samples=parameters_1_wrap,names=names, labels = labels,label=label_1)
    samples_2 = getdist.MCSamples(samples=parameters_2_wrap,names=names, labels = labels,label=label_2)

    # Start plotting
    g = plots.get_subplot_plotter(width_inch=6, scaling=False, rc_sizes=True)

    # Settings
    g.settings.figure_legend_frame = False

    # Triangle plot
    g.triangle_plot([samples_1, samples_2],
                    filled=True,
                    colors = [color_1, color_2],
                   line_args = [{'color':color_1},{'color':color_2}])

    plt.suptitle(r'Minimum distance = %s' % np.round(np.min(dist),2)+r', volume = %s' % np.round(np.min(vol_phases_1),2), va='bottom')

    if output_filename is None:
        output_filename = _default_plot_filename_str.format(
            event_name_1,
            event_name_2,
            event1_postprocessed_phase.fbest,
            event1_postprocessed_phase.fhigh,
            event1_postprocessed_phase.flow,
        )

    plt.savefig(os.path.join(output_dir, output_filename), bbox_inches='tight', transparent=True)

    return plt.gcf()


n = int(input())

time = []
num_condition = []
conditions = []

for i in range(n):
    a, b, *c = map(int,input().split())
    time.append(a)
    num_condition.append(b)
    conditions.append([*c])

ans = 0

seen = [False]*n

stack = [n]

while stack:
    a = stack.pop()
    seen[a-1]=True
    for elem in conditions[a-1]:
        if seen[elem-1]==False:
            stack.append(elem)

for i in range(n):
    if seen[i]:
        ans+=time[i]

print(ans)


import discord
from discord.ext import commands
import aiohttp
import io
import random
import re
import requests
import asyncio
from asyncio.tasks import sleep

# from discord.utils import get

class Other(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def other(self, ctx):
        embed = discord.Embed(title="**¯ \ _ (°\_o) \_ / ¯**", description="такие дела", color=0xa500ff)
        embed.set_author(name='Господин Ананасик', icon_url='https://i.imgur.com/A7tQuJ1.png')
        embed.set_thumbnail(url="https://i.imgur.com/A7tQuJ1.png")
        embed.add_field(name="**;guess**",
                        value="Игра низкой степни веселости.", inline=False)
        embed.add_field(name="**;shippering ;shipping ;pairing**",
                        value='''Дает двум случайным Ананасикам право не скрывать впредь своих чувств!
                                ***По заказу <@!197381022118051840>***''', inline=False)
        embed.add_field(name="**;countdown**", value="РЧ на пулл!", inline=False)
        embed.add_field(name="**;urban <some words>**", value="Посмотреть значение слов в урбан словаре", inline=False)
        embed.add_field(name="**;defence**", value="Защитный кисулькен!", inline=False)
        embed.add_field(name="**;ping**", value="Ping urself! Ой! Простите...", inline=False)
        embed.add_field(name="**;author**", value="Дает Вам представление о человеке, пишущем Бота.", inline=False)
#        embed.add_field(name="**;add X Y**", value="Сложение **X** и **Y** где **X** и **Y** натуральные числа", inline=False)
#        embed.add_field(name="**;multiply X Y**", value="Умножение **X** и **Y** где **X** и **Y** натуральные числа", inline=False)
#        embed.add_field(name="**;saythanks**", value='''Ссылка на самый благодарный аддон в игре!
#                                               Disclaimer: многие игроки на него негативно реагируют!''', inline=False)
        await ctx.send(embed=embed)

    @commands.command(aliases=['shipping', 'pairing'])
    @commands.cooldown(1, 720, commands.BucketType.guild)
    async def shippering(self, ctx):
            ulist = []
            for user in ctx.channel.members:
                if user.status != discord.Status.offline and user.bot == False:
                    ulist.append(user)
            randomUser = random.choice(ulist)
            ulist1 = []
            for user in ctx.channel.members:
                if user.status != discord.Status.offline and user.bot == False and user != randomUser:
                    ulist1.append(user)
            if len(ulist1) == 0:
               await ctx.send('''Ой-ой! Что-то пошло не так и я не смог выбрать второго ананасика! Вызвайте экзорциста! Или Вы надо мной подтруниваете и решили проверить вызову ли я Вас дважды если Вы один в канале?! Хитро (нет)''')
            else:
                randomUser1 = random.choice(ulist1)
                await ctx.send(f'{randomUser.name} и...')
                await sleep(1)
                await ctx.send(f'...{randomUser1.name}! Нет лучше пары в Ордорейде!')

    @commands.command()
    async def countdown(self, ctx):
        countdown = ['Пять!', 'Четыре!', 'Три!', 'Два!', 'Один!']
        for num in countdown:
            await ctx.send('**{0}**'.format(num))
            await asyncio.sleep(1)
        user_list = []
        for user in ctx.channel.members:
            if user.status != discord.Status.offline and user.bot == False:
                user_list.append(user)
        random_user = random.choice(user_list)
        user = random_user.mention
        await ctx.send(f'**{user} большой молодец!**')

    @commands.command()
    async def guess(self, ctx):
        await ctx.send('Угадайте число от 1 до 5')
        def is_correct(m):
            return m.author == ctx.author and m.content.isdigit()
        answer = random.randint(1, 5)
        try:
            guess = await self.bot.wait_for('message', check=is_correct, timeout=5.0)
        except asyncio.TimeoutError:
            return await ctx.send('Простите! Вы слишком долго думали! Ответ был {}.'.format(answer))
        if int(guess.content) == answer:
            await ctx.send('Вы большой молодец!')
        else:
            await ctx.send('Вы не угадали! Ответ был {}.'.format(answer))

    @commands.command()
    async def urban(self, ctx, *, msg: str):
        word = ''.join(msg)
        api = "http://api.urbandictionary.com/v0/define"
        response = requests.get(api, params=[("term", word)]).json()
        if len(response["list"]) == 0:
            return await ctx.send("Не могу найти такого слова! Может вы не мемный?")

        embed = discord.Embed(title="Urban Dictionary", description=word, color=0xa500ff)
        embed.set_author(name='Господин Ананасик', icon_url='https://i.imgur.com/A7tQuJ1.png')
        embed.set_thumbnail(url="https://i.imgur.com/A7tQuJ1.png")

        embed.add_field(name="Наибольшие совпадения", value=response['list'][0]['definition'])
        embed.add_field(name="Примеры", value=response['list'][0]["example"])

        await ctx.send(embed=embed)

#    @commands.command()
#    async def react(self, ctx):
#        if await ctx.bot.is_owner(ctx.author):
#            await discord.Message.add_reaction(msg, 'Ⓜ')
#            await ctx.message.delete()
#        else:
#            await ctx.send('Боюсь, что этой командой может пользоваться только мой автор. Простите!')

#    @commands.command()
#    async def quote(self, ctx, msg_id):
#        msg = await discord.utils.get_message(ctx.message.channel, msg_id)
#        await ctx.send('{0.timestamp} - {0.content}'.format(msg))

    @commands.command()
    async def ping(self, ctx):
        await ctx.send('Pong!')

    @commands.command()
    async def author(self, ctx):
        async with aiohttp.ClientSession() as session:
            async with session.get('https://i.imgur.com/jH1LRM0.jpg') as resp:
                if resp.status != 200:
                    await ctx.send('Ой-ой! Не могу загрузить картинку!')
                    return
                else:
                    data = io.BytesIO(await resp.read())
                    await ctx.send(file=discord.File(data, 'pic.png'))

    @commands.command()
    async def defence(self, ctx, *name):
        async with aiohttp.ClientSession() as session:
            async with session.get('http://s011.radikal.ru/i318/1611/88/10a8427ad95f.gif') as resp:
                if resp.status != 200:
                    await ctx.send('Ой-ой! Не могу загрузить защитную картинку!')
                    return
                else:
                    data = io.BytesIO(await resp.read())
                    strnames = "".join( repr(e) for e in name)
                    def_object = re.sub('[^A-Za-z0-9А-Яа-я!,.<>@ %]+', ' ', strnames )
                    await ctx.send(f'Протокол защиты {def_object} активирован!')
                    await ctx.send(file=discord.File(data, 'pic.gif'))
#                    await ctx.message.delete()

#    @commands.command()
#    async def add(self, ctx, a: int, b: int):
#        await ctx.send(a+b)

#    @commands.command()
#    async def multiply(self, ctx, a: int, b: int):
#        await ctx.send(a*b)

#    @commands.command()
#    async def saythanks(self, ctx):
#        await ctx.send('Спасибо!')
#        await sleep(5)
#        await ctx.send('Оу! Аддон же еще! Вот ссылка - <https://yadi.sk/d/zcgFOHZb0isZIw> ')

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


"""
A wrapper around pyserial and pyftdi.
Allow to use pyftdi if possible, and else pyserial.
"""
from __future__ import print_function, division
import platform
import os
import time
import re

# pyserial imports
import serial
from . import list_ports

# ftdi imports
try:
    from pyftdi.pyftdi import ftdi
    _pyftdi_available = True
except ImportError:
    _pyftdi_available = False

class PortNotFoundError(Exception):
    def __init__(self, port_path, device_type, serial_id):
        self.port_path = port_path
        self.device_type = device_type
        self.serial_id = serial_id

USB_DEVICES    = {'USB2Serial', 'USB2Dynamixel', 'USB2AX', 'CM-513', 'CM-700',
                  'CM-900', 'OpenCM9.04', 'CM-100', 'CM-100A', 'USB2Serial+CM-5', 'USB2Serial+CM-510', 'Any'}
SERIAL_DEVICES = {'SerialPort', 'CM-5', 'CM-510', 'Any'}

FTDI_VIDPID = ((0x0403, 0x6001), # ft232am, ft232bm, ft232r
               (0x0403, 0x6014), # ft232h,
               (0x0403, 0x6010), # ft2232d, ft232c, ft2232h
               (0x0403, 0x6011)) # ft4232h

def available_ports(enable_pyftdi=True):
    """
    Returns the available ports found.

    Use makerbot's pyserial for port discovery.
    """
    ports = list(list_ports.list_ports_by_vid_pid())
    if enable_pyftdi and _pyftdi_available:
        devs = ftdi.Ftdi.find_all(((0x0403, 0x6001),))
        for dev in devs:
            pid, vid, serial_id, interface, description = dev
            port = {'port':'usbftdi:'+serial_id, 'PID':pid, 'VID':vid,
                    'iSerial':serial_id, 'interface':interface,
                    'desc':description,}
            ports.append(port)
    return ports

def filter_ports(ports, device_type='Any', port_path=None, serial_id=None):
    """
    Filter ports description based on device_type, port, or serial_id:
    * POSIX compliant (Linux, *BSD, HURD):
        if the device is a CM-5 or CM-510 controller:
            /dev/ttyS*
        else, the device is assumed to be a usb/serial adaptater.
            /dev/ttyACM*, /dev/ttyUSB* and usbftdi:*
    * OS X:
        no serial port, only usb/serial adaptaters.
        /dev/cu.usbserial and /dev/tty.usbserial-*
    * Windows:
        not tested.
    """
    plat = platform.system()

    # looking for a specific port
    if port_path is not None:
        port_path = os.path.abspath(port_path)
        ports = [port for port in ports if port['port'] == port_path]
        assert len(ports) <= 1

    if serial_id is not None:
        ports = [port for port in ports if 'iSerial' in port and port['iSerial'] == serial_id]

    if port_path is None and serial_id is None:

        if plat == 'Darwin':
            regex = re.compile('.*\.Bluetooth.*')
            ports = [port for port in ports if regex.search(port['port']) is None]

        elif plat == 'Windows':
            # TODO
            pass

        else: # POSIX
            regex_serial = re.compile('/dev/ttyS[0-9]*')
            regex_usb    = re.compile('(/dev/ttyACM[0-9]*)|(/dev/ttyUSB[0-9]*)|(usbftdi:.*)')
            if device_type in SERIAL_DEVICES:
                ports = [port for port in ports if regex_serial.search(port['port']) is not None]
            elif device_type in USB_DEVICES:
                ports = [port for port in ports if regex_usb.search(port['port']) is not None]

    ports = list({port['port']:port for port in ports}.values())
    return ports

class Serial(object):
    """
    Serial API

    Offer a pyserial-like API that switch to pyftdi when the hardware supports it.
    """

    def __init__(self, port_path=None,
                     device_type='Any',
                       serial_id=None,
                        baudrate=1000000,
                         timeout=10,
                         latency=1,
                   enable_pyftdi=True,
                 **kwargs):
        """
        Create a serial port.

        If possible, create it using pyftdi, and set latency
        :param port:          if not None, should point to a valid /dev path
        :param device_type:   can be any of 'USB2Serial', 'USB2Dynamixel',
                              'USB2AX', 'CM-513', 'CM-700', 'CM-900',
                              'OpenCM9.04', 'CM-100', 'CM-100A', 'SerialPort',
                              'CM-5', 'CM-510'. Specific initialization are
                              then used for each hardware.
        :param serial_id:     in the case of multiple usbserial hardware, use
                              this parameter to specify with one to connect to.
                              (eg. Serial(serial_id='A4008aCD'))
        :param baudrate:      serial baudrate in bps
        :param timeout:       serial read timeout
        :param latency:       set the usb latency timer in ms. (only supported
                              in FTDI hardware)
        :param enable_pyftdi: if True, enable_ftdi. Will fail silently if pyftdi
                              is not available or no FTDI devices are detected.

        Remaining kwargs will be passed to pyserial initialization.
        """
        self._serial = None

        ports = available_ports(enable_pyftdi=enable_pyftdi)
        ports = filter_ports(ports, device_type=device_type,
                                      port_path=port_path,
                                      serial_id=serial_id)
        try:
            port_desc = ports[0] # taking the first one
        except IndexError:
            raise PortNotFoundError(port_path, device_type, serial_id)

        self._baudrate = baudrate
        self._timeout = timeout
        self._latency = latency

        self._device_type = device_type

        self._ftdi_ctrl = False
        if enable_pyftdi and _pyftdi_available:
            print('Trying pyftdi')
            try:
                self._serial = ftdi.Ftdi()
                self._serial.open(port_desc['VID'], port_desc['PID'], port_desc['interface'],
                                  serial=port_desc['iSerial'], description=port_desc['desc'])

                self.serial_id = port_desc['iSerial']
                self._serial.set_baudrate(baudrate)
                self._serial.timeouts = (timeout, 0)
                self._serial.set_latency_timer(latency)
                self._ftdi_ctrl = True

            except KeyError:#KeyError:
                pass

        if not self._ftdi_ctrl: # pyftdi didn't succeed, trying pyserial
            self._serial = serial.Serial(port_desc['port'], baudrate=baudrate,
                                         timeout=timeout/1000.0)
            self.port = port_desc['port']

        self.purge()
        time.sleep(0.1)

        if device_type in ['USB2Serial+CM-5', 'USB2Serial+CM-510','CM-5', 'CM-510']:
            print('tossmode')
            self._toss_mode()

    def __repr__(self):
        if self._ftdi_ctrl:
            return "usbftdi(serial_id={}, bps={}, timeout={}, latency={})".format(
                    self.serial_id, self.baudrate, self.timeout, self.latency)
        else:
            return "serial(port={}, bps={}, timeout={})".format(
                    self.port, self.baudrate, self.timeout)

    def __del__(self):
        """Destructor, close port when serial port instance is freed."""
        self.close()

    @property
    def support_sync_read(self):
        return self._device_type == 'USB2AX'

    @property
    def timeout(self):
        """Return the read timeout (not the write one)"""
        return self._timeout

    @timeout.setter
    def timeout(self, val):
        """Set the read timeout (not the write one)"""
        if val == 0:
            val = float('inf')
        elif round(val) - val != 0.0:
            raise ValueError('timeout are exprimed integer values of ms (you provided {}).'.format(val))
        if self._ftdi_ctrl:
            self._serial.timeouts = (val, self._serial.timeouts[1])
        else:
            self._serial.timeout = val/1000.0

    @property
    def baudrate(self):
        return self._baudrate

    @baudrate.setter
    def baudrate(self, val):
        if self._ftdi_ctrl:
            self._serial.set_baudrate(baudrate)
        else:
            self._serial.baudrate = baudrate

    @property
    def latency(self):
        return self._latency

    @latency.setter
    def latency(self, val):
        """In ms. Supported only by pyftdi."""
        self._latency = val
        if self._ftdi_ctrl:
            self._serial.set_latency_timer(latency)

    def _toss_mode(self):
        """Activate the toss mode in the CM-5 and CM-510."""
        self.write('t\r')
        time.sleep(0.1)
        self.read(100)
        time.sleep(0.1)

    def flush(self):
        """Flush of file like objects. In this case, wait until all data is written.

        Supported only by pyserial.
        """
        if not self._ftdi_ctrl:
            self._serial.flush()

    def purge(self):
        """purge and discard read and write buffers"""
        if self._ftdi_ctrl:
            self._serial.purge_buffers()
        else:
            self._serial.flushInput()
            self._serial.flushOutput()

    def write(self, data):
        """Write data on the serial port"""
        if self._ftdi_ctrl:
            return self._serial.write_data(data)
        else:
            return self._serial.write(data)

    def read(self, size, tries=2):
        """
        Read size bytes from the serial port.
        If a timeout is set it may return less characters as requested. With no timeout
        it will block until the requested number of bytes is read.
        """
        if tries <= 0:
            return bytearray()
        assert type(size) == int
        if self._ftdi_ctrl:
            try:
                # return self._serial.read_data(size) # does not honor timeouts
                start = time.time()
                data = bytearray()
                while (len(data) < size and time.time()-start < self.timeout/1000.0):
                    data +=  bytearray(self._serial.read_data_bytes(size - len(data)))
                    time.sleep(0.0001)
                assert(len(data) <= size)
                return data
            except ftdi.FtdiError: # HACK: fix first packet failing. Need to investigate to understand better.
                return self.read(size, tries=tries-1)
        else:
            return bytearray(self._serial.read(size=size))

    def close(self):
        """Close the serial port
        """
        if self._serial is not None:
            if self._ftdi_ctrl:
                self._serial.purge_buffers()
            self._serial.close()
        self._serial = None


import time

from TestCase import *
from Context import RU,BU

class case_2x2_stopRequests(TestCase):

    def runTest(self):
        testDir="/tmp/evb_test/ramdisk"
        runNumber=time.strftime("%s",time.localtime())
        for instance in range(2):
            buDir = testDir+"/BU"+str(instance)
            self.setAppParam('rawDataDir','string',buDir,'BU',instance)
            self.setAppParam('metaDataDir','string',buDir,'BU',instance)
            self.setAppParam('hltParameterSetURL','string','file://'+buDir,'BU',instance)
        self.prepareAppliance(testDir+"/BU0",runNumber)
        self.prepareAppliance(testDir+"/BU1",runNumber)
        self.configureEvB()
        self.enableEvB(runNumber=runNumber)
        self.writeResourceSummary(testDir+"/BU1",runNumber,stopRequested=True)
        time.sleep(15)
        self.checkAppState("Enabled","BU",0)
        self.checkAppState("Paused","BU",1)
        self.checkEVM(2048)
        self.checkRU(24576)
        self.checkBU(26624,instance=0)
        nbEventsBuiltBU1 = int(self.getAppParam('nbEventsBuilt','unsignedLong','BU',1)['BU1'])
        self.stopEvB()
        nbEventsBuiltBU1afterStop = int(self.getAppParam('nbEventsBuilt','unsignedLong','BU',1)['BU1'])
        if nbEventsBuiltBU1 != nbEventsBuiltBU1afterStop:
            raise ValueException("BU1 built another "+str(nbEventsBuiltBU1afterStop-nbEventsBuiltBU1)+" events after being stopped")
        for instance in range(2):
            buDir = testDir+"/BU"+str(instance)
            self.checkBuDir(buDir,runNumber,eventSize=26648,buInstance=instance)

        runNumber=time.strftime("%s",time.localtime())
        try:
            self.enableEvB(sleepTime=2,runNumber=runNumber)
        except StateException:
            self.checkAppState("Paused","BU",1)
        else:
            raise StateException("EvB should not be Enabled")
        time.sleep(15)
        self.checkEVM(2048)
        self.checkRU(24576)
        self.checkBU(26624,instance=0)
        self.checkAppParam("nbEventsBuilt","unsignedLong",0,operator.eq,"BU",1)
        self.stopEvB()
        for instance in range(2):
            buDir = testDir+"/BU"+str(instance)
            self.checkBuDir(buDir,runNumber,eventSize=26648,buInstance=instance)

        runNumber=time.strftime("%s",time.localtime())
        self.writeResourceSummary(testDir+"/BU1",runNumber,stopRequested=False)
        self.enableEvB(runNumber=runNumber)
        self.checkAppState("Enabled","BU")
        self.checkEVM(2048)
        self.checkRU(24576)
        self.checkBU(26624)
        self.stopEvB()
        for instance in range(2):
            buDir = testDir+"/BU"+str(instance)
            self.checkBuDir(buDir,runNumber,eventSize=26648,buInstance=instance)

    def fillConfiguration(self,symbolMap):
        self._config.add( RU(symbolMap,[
             ('inputSource','string','Local'),
             ('fedSourceIds','unsignedInt',(512,)),
             ('fakeLumiSectionDuration','unsignedInt','4')
            ]) )
        self._config.add( RU(symbolMap,[
             ('inputSource','string','Local'),
             ('fedSourceIds','unsignedInt',range(1,13))
            ]) )
        self._config.add( BU(symbolMap,[
            ('lumiSectionTimeout','unsignedInt','6'),
            ('resourcesPerCore','double','1'),
            ('staleResourceTime','unsignedInt','0')
            ]) )
        self._config.add( BU(symbolMap,[
            ('lumiSectionTimeout','unsignedInt','6'),
            ('resourcesPerCore','double','1'),
            ('staleResourceTime','unsignedInt','0')
            ]) )


from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union

from attrs import define as _attrs_define
from attrs import field as _attrs_field

from ..types import UNSET, Unset

if TYPE_CHECKING:
    from ..models.custom_rate_limit_entity import CustomRateLimitEntity

T = TypeVar("T", bound="ClientRateLimitSetting")

@_attrs_define
class ClientRateLimitSetting:
    """
    Attributes:
        mode (int): Rate limit mode.
0: Custom mode. Apply the given rate limit value to the client.
1: Rate
            limit profile mode. Find the corresponding rate limit file with rate limit id and apply it to the client.
        rate_limit_profile_id (Union[Unset, str]): Rate limit profile id. Required when ratelimit mode is 1
        custom_rate_limit (Union[Unset, CustomRateLimitEntity]): Custom configuration rate limit.
    """

    mode: int
    rate_limit_profile_id: Union[Unset, str] = UNSET
    custom_rate_limit: Union[Unset, "CustomRateLimitEntity"] = UNSET
    additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)

    def to_dict(self) -> Dict[str, Any]:
        mode = self.mode
        rate_limit_profile_id = self.rate_limit_profile_id
        custom_rate_limit: Union[Unset, Dict[str, Any]] = UNSET
        if not isinstance(self.custom_rate_limit, Unset):
            custom_rate_limit = self.custom_rate_limit.to_dict()

        field_dict: Dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update(
            {
                "mode": mode,
            }
        )
        if rate_limit_profile_id is not UNSET:
            field_dict["rateLimitProfileId"] = rate_limit_profile_id
        if custom_rate_limit is not UNSET:
            field_dict["customRateLimit"] = custom_rate_limit

        return field_dict

    @classmethod
    def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
        from ..models.custom_rate_limit_entity import CustomRateLimitEntity

        d = src_dict.copy()
        mode = d.pop("mode")

        rate_limit_profile_id = d.pop("rateLimitProfileId", UNSET)

        _custom_rate_limit = d.pop("customRateLimit", UNSET)
        custom_rate_limit: Union[Unset, CustomRateLimitEntity]
        if isinstance(_custom_rate_limit, Unset):
            custom_rate_limit = UNSET
        else:
            custom_rate_limit = CustomRateLimitEntity.from_dict(_custom_rate_limit)

        client_rate_limit_setting = cls(
            mode=mode,
            rate_limit_profile_id=rate_limit_profile_id,
            custom_rate_limit=custom_rate_limit,
        )

        client_rate_limit_setting.additional_properties = d
        return client_rate_limit_setting

    @property
    def additional_keys(self) -> List[str]:
        return list(self.additional_properties.keys())

    def __getitem__(self, key: str) -> Any:
        return self.additional_properties[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self.additional_properties[key] = value

    def __delitem__(self, key: str) -> None:
        del self.additional_properties[key]

    def __contains__(self, key: str) -> bool:
        return key in self.additional_properties


import argparse
import json
import logging
import sys
sys.path.append('../..')

from storescraper.utils import get_store_class_by_name  # noqa

def main():
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)s %(message)s',
                        filename='products.log',
                        filemode='w')

    parser = argparse.ArgumentParser(
        description='Retrieves the products of the given store.')

    parser.add_argument('store', type=str,
                        help='The name of the store to be parsed')

    parser.add_argument('--categories', type=str, nargs='*',
                        help='Specific categories to be parsed')

    parser.add_argument('--with_async', type=bool, nargs='?', default=False,
                        const=True,
                        help='Use async tasks (celery)')

    parser.add_argument('--extra_args', type=json.loads, nargs='?', default={},
                        help='Optional arguments to pass to the parser '
                             '(usually username/password) for private sites)')

    args = parser.parse_args()
    store = get_store_class_by_name(args.store)

    available_products = 0
    unavailable_products = 0

    products_data = store.products(
        categories=args.categories,
        use_async=args.with_async,
        extra_args=args.extra_args)

    for product in products_data['products']:
        if product.is_available():
            available_products += 1
        else:
            unavailable_products += 1
        print(product, '\n')

    urls_with_error = products_data['discovery_urls_without_products']
    print('Discovery URLs without products:')
    if not urls_with_error:
        print('* No empty URLs found')
    for url_with_error in urls_with_error:
        print('* {}'.format(url_with_error))

    print()
    print('Available: {}'.format(available_products))
    print('Unavailable: {}'.format(unavailable_products))
    print('With error: {}'.format(len(urls_with_error)))
    print('Total: {}'.format(available_products + unavailable_products +
                             len(urls_with_error)))

if __name__ == '__main__':
    main()


from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import json
from pydantic import BaseModel

palabras_1 = {
    "q1": ['z'],
    "q2": ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'],
    "q3": ['r']
}
palabras_2 = {
    "q1": ['r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
    "q2": ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
    "q3": ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r']
}
numeros = ["1" ,"2", "3", "4", "5", "6", "7", "8", "9"]
numeros2 = ["0", "1" ,"2", "3", "4", "5", "6", "7", "8", "9"]
abecedario = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.post("/q0")
async def q0(palabra):
    caracter = palabra[0]
    for clavere, subfamiliasre in palabras_1.items():
        if caracter in subfamiliasre:
            flujo = clavere
            print(flujo)
    return flujo

@app.post("/q1")
async def q1(palabra):
    caracter = palabra[1]
    if caracter in palabras_2["q1"]:
        flujo = "q4"
        print(flujo)
    return flujo

@app.post("/q2")
async def q2(palabra):
    caracter = palabra[1]
    if caracter in palabras_2["q2"]:
        flujo = "q4"
        print(flujo)
    return flujo

@app.post("/q3")
async def q3(palabra):
    caracter = palabra[1]
    if caracter in palabras_2["q3"]:
        flujo = "q4"
        print(flujo)
    return flujo

@app.post("/q4")
async def q4(palabra):
    caracter = palabra[2]
    if caracter == "-":
        print(caracter)
        flujo = "q5"
    return flujo

@app.post("/q5")
async def q5(palabra):
    caracter = palabra[3]
    if caracter == "0":
        flujo = "q6"
    elif caracter in numeros:
        flujo = "q9"
    print(flujo)
    return flujo

@app.post("/q6")
async def q6(palabra):
    caracter = palabra[4]
    if caracter == "0":
        flujo = "q7"
    elif caracter in numeros:
        flujo = "q10"
    print(flujo)
    return flujo

@app.post("/q7")
async def q7(palabra):
    caracter = palabra[5]
    if caracter in numeros:
        flujo = "q8"
    print(flujo)
    return flujo

@app.post("/q8")
async def q8(palabra):
    caracter = palabra[6]
    if caracter == "-":
        print(caracter)
        flujo = "q11"
    return flujo

@app.post("/q9")
async def q9(palabra):
    caracter = palabra[4]
    if caracter in numeros2:
        flujo = "q10"
    print(flujo)
    return flujo

@app.post("/q10")
async def q10(palabra):
    caracter = palabra[5]
    if caracter in numeros2:
        flujo = "q8"
    print(flujo)
    return flujo

@app.post("/q11")
async def q11(palabra):
    caracter = palabra[7]
    if caracter in abecedario:
        flujo = "q12"
    print(flujo)
    return flujo

""" q0(palabra)
q1(palabra)
q2(palabra)
q3(palabra)
q4(palabra)
q5(palabra)
q6(palabra)
q7(palabra)
q8(palabra)
q9(palabra)
q10(palabra)
q11(palabra) """


# Importation des bibliothèques nécessaires
import numpy as np
from keras.models import load_model
import os
import librosa
import soundfile as sf
from pydub import AudioSegment
from datetime import datetime
from flask import Flask, request, jsonify, make_response
import noisereduce as nr
import tensorflow as tf
import matplotlib.pyplot as plt
from flaskext.mysql import MySQL

# Définition du répertoire contenant les données
directory_path = "Data/DATASET_NEW"

# Récupérer les noms des dossiers dans le répertoire donné
def get_folder_names(directory):
    folder_names = []
    for item in os.listdir(directory):
        if os.path.isdir(os.path.join(directory, item)):
            folder_names.append(item)
    return folder_names

# Obtenir la date et l'heure actuelles sous forme de chaîne de caractères
def get_datetime():
    now = datetime.now()

    year = str(now.year)
    month = str(now.month).zfill(2)
    day = str(now.day).zfill(2)
    hours = str(now.hour).zfill(2)
    minutes = str(now.minute).zfill(2)
    seconds = str(now.second).zfill(2)

    datetime_string = f"_{year}_{month}_{day}_{hours}_{minutes}_{seconds}"

    return datetime_string

def denoise_audio(input_file, output_file, reduction_strength=0.5):
    # Charger l'enregistrement audio
    audio, sr = sf.read(input_file)

    # Réduction du bruit
    denoised_audio = nr.reduce_noise(audio, sr, reduction_strength)

    # Sauvegarder le fichier audio débruité
    os.remove(input_file)
    sf.write(output_file, denoised_audio, sr)

    print("Enregistrement débruité avec succès!")

def cut_audio(file_path, output_file_path, duration):
    # Charger l'enregistrement audio
    audio, sr = sf.read(file_path)

    # Calculer le nombre d'échantillons à conserver
    samples_to_keep = int(sr * duration)

    # Couper les derniers échantillons
    cut_audio = audio[samples_to_keep:]

    # Sauvegarder le fichier audio coupé
    os.remove(file_path)
    sf.write(output_file_path, cut_audio, sr)

    print("Enregistrement coupé avec succès!")

#Tracer le graphe d'un audio
def plot_audio_waveform(file_path):
    # Charger l'enregistrement audio
    audio, sr = librosa.load(file_path)

    # Afficher la forme d'onde
    plt.figure(figsize=(12, 4))
    librosa.display.waveshow(audio, sr=sr)
    plt.title('Forme d\'onde audio')
    plt.xlabel('Temps (s)')
    plt.ylabel('Amplitude')
    plt.show()

#Donnée regroupré pour predire la commande suivante
donnees = {
    'etat1': [['active', 'allume', 'arrêt', 'désactiver', 'etat', 'éteint'], ['camera', 'lecteur', 'lecteur', 'télévision', 'lumière', 'climatisation', 'ventilateur', 'cuisinière', 'cuisine', 'gazinière', 'réfrigérateur', 'radio'], ['Salon', 'terrasse', 'balcon', 'chambre']],
    'etat2': [['augmente', 'diminue'], ['volume', 'vitesse', 'chauffage', 'température']],
    'etat3': [['ouvre', 'ferme'], ['rideaux', 'fenêtre', 'porte', 'portail']],
    'etat4': [['passe', 'précédent', 'suivant', 'change'], ['chaîne', 'musique', 'piste', 'radio']],
    'etat5': [['chaîne'], ['radio', 'télévision'], ['passe', 'précédent', 'suivant', 'change']],
}
#Fonction de prediction du choix suivant
def verifier_choix(choix, etape=1):
    res_correspondante = []
    for suivant, reponses in donnees.items():
        if choix in reponses[etape - 1]:
            res_correspondante = reponses[etape]
            return res_correspondante
    return res_correspondante

current_datetime_string = get_datetime()

# Appel de la fonction pour récupérer les noms des dossiers
nameList = get_folder_names(directory_path)

# crée une instance de l'application Flask
app = Flask(__name__)

# Configuration de la base de données MySQL
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'intellihouse'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql = MySQL(app)

# Configuration du répertoire de sauvegarde des fichiers audios recus
app.config['UPLOAD_FOLDER'] = 'file'

# Charger le modèle entraîné
model = load_model('Model/model8.h5')

@app.route('/api/<api_key>/predict', methods=['POST'])
def predict(api_key):
    # Verification de la clé "api_key"

    cursor = mysql.get_db().cursor()
    cursor.execute('SELECT id, nbr_commande FROM users WHERE token = %s', (api_key,))
    data = cursor.fetchall()
    id = 0
    for row in data:
        id = row[0]
        nbr_commande = int(row[1])

    print(id, nbr_commande)

    #Renvoie un status false si la cle ne correspond pas a celui d'un utilisateur de la base de données
    if id == 0 :
        response = {
                'status': False,
                'mots': "",
                'proposition': [],
                'Description': "Clé de l'API Invalide"
            }
        response = make_response(response)
        response.headers.add('Access-Control-Allow-Origin', '*')

        return response

    # Mise a jour du compteur de comande vocal

    nbr_commande += 1
    cursor.execute('UPDATE users SET nbr_commande = %s WHERE id = %s', (nbr_commande, int(id),))

    # Vérifier si un fichier audio a été envoyé dans la requête

    if 'audio' not in request.files:
        return jsonify(error='Aucun fichier audio n\'a été envoyé.')

    audio_file = request.files['audio']

    # Sauvegarder le fichier audio dans le répertoire de sauvegarde
    filename = audio_file.filename
    save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    audio_file

    # Convertir le fichier audio en WAV
    wav_path = os.path.join(app.config['UPLOAD_FOLDER'], 'audio'+get_datetime()+'.wav')
    audio = AudioSegment.from_file(save_path)
    audio = audio.set_sample_width(2)  # 2 bytes = 16 bits
    audio.export(wav_path, format='wav')
    os.remove(save_path)

    denoise_audio(wav_path,wav_path)
    cut_audio(wav_path,wav_path, duration=0.1)

    # Extraire les caractéristiques audio
    data, sampling_rate = librosa.load(wav_path, res_type='kaiser_fast')
    mfccs = np.mean(librosa.feature.mfcc(y=data, sr=sampling_rate, n_mfcc=40).T, axis=0)
    X = np.array([mfccs])

    # prédiction sur l'audio

    predictions = model.predict(X)

    # Obtenir l'index de la classe prédite
    predicted_class = np.argmax(predictions)

    # Renvoyer la prédiction sous forme de réponse JSON

    response = {
                'status': True,
                'mots': nameList[predicted_class],
                'proposition': verifier_choix(nameList[predicted_class])
            }

    response = make_response(response)
    response.headers.add('Access-Control-Allow-Origin', '*')

    return response

if __name__ == '__main__':
    app.run(debug=True)


import json
import ujson
import csv
import re

with open('imdb_movies.json') as json_data:
        data = json.load(json_data)

count = 0
imdb_ids = []

remove_length_movies = ["N/A", "1 min", "2 min", "3 min", "4 min", "5 min", "6 min", "7 min", "8 min", "9 min", "10 min", "11 min", "12 min", "13 min", "14 min", "15 min", "16 min", "17 min", "18 min", "19 min", "20 min"]

"""
AGE RATING INFO: https://en.wikipedia.org/wiki/Motion_picture_content_rating_system
The vast majority of movies have ["N/A", "NOT RATED", "UNRATED", "NR", "Not Rated", "Not rated", "Unrated"], we do not know what kind of age rating they have, they're effectively not curated.
We do filter out 'Adult' genre, and explicit rating movies, we don't filter the above non rated movies. We could perhaps ask our users.
"""
#unwanted_ratings = ["N/A", "NOT RATED", "UNRATED", "X", "(BANNED)", "(Banned)", "BPjM Restricted", "18+", "B15", "NR", "Not Rated", "Not rated", "R-18+", "R18+", "TV-Y7", "Unrated", "VM18"] # We need to filter out inappropriate content
unwanted_ratings = ["X", "(BANNED)", "(Banned)", "BPjM Restricted", "18+", "B15", "NR", "R-18+", "R18+", "TV-Y7", "VM18"] # We need to filter out inappropriate content

filtered_movies = []
genres = []

non_filtered_movies = 0

for entry in data:
    if (entry['Response'] == "True"):
        if (entry['Genre'] != "N/A") and (entry['Genre'] != "Adult") and (entry['Runtime'] not in remove_length_movies):

            #print((entry['Rated'] not in unwanted_ratings))

            if entry['Poster'] == "N/A":
                entry['Poster'] = "https://i.imgur.com/qrMim4w.png"
            if entry['Plot'] == "N/A":
                entry['Plot'] = "Mystery movie! Watch it and find out!"
            if entry['imdbVotes'] == "N/A":
                entry['imdbVotes'] = 0
            if entry['imdbRating'] == "N/A":
                entry['imdbRating'] = 0
            if entry['Metascore'] == "N/A":
                entry['Metascore'] = 0

            output = {}
            output['title'] = entry['Title']
            output['plot'] = entry['Plot']
            output['type'] = entry['Type']
            output['genre'] = entry['Genre'].split(", ")
            output['rate_desc'] = entry['Rated']
            output['year'] = int(re.sub('[^A-Za-z0-9]+','', entry['Year'])),
            output['runtime'] = entry['Runtime']
            output['poster'] = entry['Poster']
            output['language'] = entry['Language'].split(", ")
            output['country'] = entry['Country'].split(", ")

            if hasattr(entry, 'Production'):
                output['production'] = entry['Production']
            else:
                output['production'] = "N/A"

            if hasattr(entry, 'Website'):
                output['website'] = entry['Website']
            else:
                output['website'] = "about:blank"

            output['director'] = entry['Director'].split(", ")
            output['writer'] = entry['Writer'].split(", ")
            output['actors'] = entry['Actors'].split(", ")
            output['released'] = entry['Released']

            if hasattr(entry, 'Awards'):
                output['awards'] = entry['Awards']
            else:
                output['awards'] = "N/A"

            if hasattr(entry, 'BoxOffice'):
                output['boxoffice'] = entry['BoxOffice']
            else:
                output['boxoffice'] = "N/A"

            output['imdbID'] = entry['imdbID']
            output['imdbRating'] = float((entry['imdbRating']))
            output['imdbVotes'] = int(str(entry['imdbVotes']).replace(',', ''))
            output['metascore'] = float((entry['Metascore']))
            output['ratings'] = entry['Ratings']

            genres.append(entry['Genre'].split(", "))

            non_filtered_movies += 1

            filtered_movies.append(output)
        else:
            continue
    else:
        #print("true|false: " + str(entry['Response']) + ", Type: " + str(entry['Type'] == "movie") + ", Genre N/A: " + str(entry['Genre'] != "N/A") + ", Adult?" + str(entry['Genre'] != "Adult") + ", Age: " + str(entry['Rated']))
        continue

difference = len(data) - non_filtered_movies
print("Non-Filtered: {}".format(non_filtered_movies))
print("Filtered out: {}".format(difference))

with open('filtered_movies.json', 'w') as outfile:
    ujson.dump(filtered_movies, outfile,  encode_html_chars=True, escape_forward_slashes=False, ensure_ascii=False, indent=4)

with open("genres.csv", "w") as csv_file:
    check = 0

    flattened_genres = []

    for genre_list in genres:
        for genre in genre_list:
            flattened_genres.append(genre)

    flattened_genres = list(set(flattened_genres))

    for genre in flattened_genres:
        if (check == 0):
            csv_file.write('genre' + '\n')
        else:
            csv_file.write(genre + '\n')
        check += 1


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import tweepy
from config import *
from textblob import TextBlob

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

def find_tweets(key_word, tweets_quantity_to_get, user_to_avoid, max_id=''):
    tweets_list = []
    tweets_quantity = 0
    counter = 0

    public_tweets = api.search(str(key_word), count=99)
    while tweets_quantity < tweets_quantity_to_get:

        length = len(public_tweets)
        for tweet in public_tweets:
            counter += 1

            if tweet._json['user']['name'] != str(user_to_avoid):
                tweets_list.append({'message_id': tweet._json['id'], 'message_text': tweet.text})
                tweets_quantity += 1

            if counter == length:
                max_id = tweet._json['id']
                counter = 0
                public_tweets = api.search(str(key_word), count=99, max_id=max_id)
                break

    return tweets_list

def make_csv(csv_name, tweets_list):
    csv_name = '{}.csv'.format(str(csv_name))
    with open(csv_name, 'w', encoding='utf-8') as f:
        f = csv.writer(f, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for i in tweets_list:
            f.writerow([str(i['message_id']), str(i['message_text'])])


class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        result = []
        i = 0
        n = len(intervals)

        # Add intervals that end before the new interval starts
        while i < n and intervals[i][1] < newInterval[0]:
            result.append(intervals[i])
            i += 1

        # Merge intervals that overlap with the new interval
        while i < n and intervals[i][0] <= newInterval[1]:
            newInterval[0] = min(newInterval[0], intervals[i][0])
            newInterval[1] = max(newInterval[1], intervals[i][1])
            i += 1

        result.append(newInterval)

        # Add intervals that start after the new interval ends
        while i < n:
            result.append(intervals[i])
            i += 1

        return result

75 blind tasks leetcode/Interval/python/1. Insert interval.py


import json
import urllib
from collections import defaultdict

class Argument:

    @classmethod
    def get(cls, cursor, tbl_ext, fid, args_method, func_ep, payload):

        query = "SELECT * FROM `{}func_arg` WHERE".format(tbl_ext)
        query = "{} published=1 AND func_id='{}'".format(query, fid)
        cursor.execute(query)
        result = cursor.fetchall()

        errors = []
        arguments = defaultdict()
        if result is not None:
            for row in result:
                arg_key      = row['arg_key']
                arg_type     = row['arg_type']
                req_arg_key  = row['req_arg_key']
                req_arg_type = row['req_arg_type']
                is_required  = row['is_required']

                if arg_key not in payload and is_required == 1:
                    errors.append({"missingValue": "Field or value is missing for {}.".format(arg_key)})
                elif arg_key in payload:
                    payload_val  = payload[arg_key]
                    payload_type = type(payload_val).__name__
                    if arg_type == payload_type:
                        get_arg = getattr(cls, "type_"+req_arg_type)(payload_val, is_required)
                        if get_arg is not None:
                            arguments[req_arg_key] = get_arg
                        else:
                            errors.append({"missingValue": "Field or value is missing for {}.".format(arg_key)})
                    else:
                        errors.append({"missingType": "Invalid data type for {}.".format(arg_key)})
            if len(errors) < 1:
                arguments = getattr(cls, "ep_"+args_method)(func_ep, arguments)
        else:
            errors.append({"internalError": "Error in Argument"})
        if len(errors) > 0:
            arguments['errors'] = errors

        return arguments

    @classmethod
    def type_comma(cls, data, required):
        return None if required==1 and len(data)<1 else ",".join(data)

    @classmethod
    def type_list(cls, data, required):
        return None if required==1 and len(data)<1 else data

    @classmethod
    def type_dict(cls, data, required):
        return None if required==1 and len(data)<1 else json.loads(data)

    @classmethod
    def type_integer(cls, data, required):
        return None if required==1 and len(data)<1 else int(data)

    @classmethod
    def type_float(cls, data, required):
        return None if required==1 and len(data)<1 else float(data)

    @classmethod
    def type_bool(cls, data, required):
        return None if required==1 and len(data)<1 else bool(data)

    @classmethod
    def type_str(cls, data, required):
        return None if required==1 and len(data)<1 else str(data)

    @classmethod
    def ep_POST(cls, func_ep, args):
        if func_ep.find("=") > 0:
            new_arg = func_ep.split("=")
            args.update({new_arg[0]: new_arg[1]})
            func_ep = ""
        return {"func_ep": func_ep, "args": args}

    @classmethod
    def ep_GET(cls, func_ep, args):
        ep = "{}&{}".format(func_ep, urllib.parse.urlencode(args))
        return {"func_ep": ep, "args": None}


import json
from typing import List
from pymongo import MongoClient

def read_file(file_path: str) -> List[str]:
    with open(file_path, "r") as file:
        lines = file.readlines()
    return [line.strip("\n").strip() for line in lines]

def connect_mongodb() -> MongoClient:
    client = MongoClient("mongodb://localhost:27017")
    return client

def run_query(client: MongoClient, query: str) -> float:

    result = client["adv_db"]["Variants"].find(json.loads(query)).explain()

    execution_time = result["executionStats"]["executionTimeMillis"]
    return execution_time

# get the query execution statistics from MongoDB
def get_stats(client: MongoClient, queries: List[str]) -> dict:
    query_multiplier = 1
    execution_times = []

    for q_index in range(len(queries)):
        if q_index % 20 == 0:
           print(f"\nStarting Query group {q_index // 20 + 1}\n")
        query = queries[q_index]
        query = query.replace("Variants", "Variants_partition")
        # print(f"Running query: {query}")
        for _ in range(query_multiplier):
            execution_time = run_query(client, query)
            execution_times.append(execution_time)

        if q_index % 20 == 19:
            # Print the average, minimum, and maximum execution times
            print("\n", end="")
            print(f"Minimum query execution time: {min(execution_times)} milliseconds.")
            print(f"Median query execution time: {sorted(execution_times)[len(execution_times) // 2]} milliseconds.")
            print(f"Average query execution time: {sum(execution_times) / len(execution_times)} milliseconds.")
            print(f"Maximum query execution time: {max(execution_times)} milliseconds.")
            print("\n", end="")

            execution_times = []

# Connect to MongoDB
mongo_client = connect_mongodb()

# Read the query statements
queries = read_file("query_mongo.txt")

# Get the query execution statistics
print("Running the query without indexes")
get_stats(mongo_client, queries)

mongo_client.close()


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

	def find(self,data,x):
		for i in range(len(self.data)):
			for j in range(len(self.data)):
				if data[i][j]==x:
					return i,j

	def shuffle(self,data,x1,y1,x2,y2):
		if x2>=0 and x2<len(self.data) and  y2>=0 and y2<len(self.data):
			temp_puz = self.copy(data)
			temp_puz[x1][y1],temp_puz[x2][y2] = temp_puz[x2][y2], temp_puz[x1][y1]
			return temp_puz

		else:
			return None

	def copy(self,data):
		temp = []
		for i in data:
			t = []
			for j in i:
				t.append(j)
			temp.append(t)

		return temp

	def gen_child(self):
		x, y = self.find(self.data,'_')
		valList = [[x,y-1],[x,y+1],[x-1,y],[x+1,y]]
		children = []
		for i in valList:
			child = self.shuffle(self.data,x,y,i[0],i[1])

			if child is not None:
				childNode = Node(child,self.level+1,0)
				children.append(childNode)

		return children

class Puzzle:
	def __init__(self,size):
		self.n = size
		self.open = []
		self.close = []

	def accept(self):
		puz = []
		for i in range(self.n):
			t = input().split()
			puz.append(t)

		return puz

	def f(self,start,goal):
		return start.level + self.h(start.data,goal)

	def h(self,start,goal):
		temp = 0
		for i in range(self.n):
			for j in range(self.n):
				if start[i][j]!=goal[i][j] and start[i][j]!='_':
					temp+=1

		return temp

	def process(self):
		print("enter start puz")
		start = self.accept()
		print("enter goal puz")
		goal = self.accept()

		start = Node(start,0,0)
		start.fval = self.f(start,goal)
		self.open.append(start)

		while True:
			cur = self.open[0]
			for i in cur.data:
				for j in i:
					print(j, end=" ")

				print("\n")

			if self.h(cur.data,goal)==0:
				print("solution found")
				break

			elif len(self.open)!=0:
				for i in cur.gen_child():
					i.fval = self.f(i,goal)
					self.open.append(i)

				self.close.append(cur)
				del self.open[0]
				self.open.sort(key=lambda x:x.fval,reverse = False)

			else:
				print("no solution")

puz = Puzzle(3)
puz.process()


'''
Created on Dec 4, 2019

@author: Matthew Cook
'''

import sys
from socket import socket
from uuid import getnode
from ast import literal_eval
import traceback
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox

########################### PyQt5 UI ###############################################################

# -*- coding: utf-8 -*-
#
# Created by: PyQt5 UI code generator 5.13.0

##################### MAIN WINDOW ############################
class Ui_LocalProxyNetwork(object):
    def setupUi(self, LocalProxyNetwork):
        LocalProxyNetwork.setObjectName("LocalProxyNetwork")
        LocalProxyNetwork.resize(837, 659)
        self.centralwidget = QtWidgets.QWidget(LocalProxyNetwork)
        self.centralwidget.setObjectName("centralwidget")

        self.btnRegister = QtWidgets.QPushButton(self.centralwidget)
        self.btnRegister.setGeometry(QtCore.QRect(120, 60, 161, 71))
        self.btnRegister.setObjectName("btnRegister")
        self.btnRegister.clicked.connect(self.registerWindow)

        self.btnDeregister = QtWidgets.QPushButton(self.centralwidget)
        self.btnDeregister.setGeometry(QtCore.QRect(120, 280, 161, 71))
        self.btnDeregister.setObjectName("btnDeregister")
        self.btnDeregister.clicked.connect(self.deregisterWindow)

        self.btnQuery = QtWidgets.QPushButton(self.centralwidget)
        self.btnQuery.setGeometry(QtCore.QRect(560, 280, 161, 71))
        self.btnQuery.setObjectName("btnQuery")
        self.btnQuery.clicked.connect(self.queryWindow)

        self.btnMessage = QtWidgets.QPushButton(self.centralwidget)
        self.btnMessage.setGeometry(QtCore.QRect(560, 60, 161, 71))
        self.btnMessage.setObjectName("btnMessage")
        self.btnMessage.clicked.connect(self.messageWindow)

        self.btnQuit = QtWidgets.QPushButton(self.centralwidget)
        self.btnQuit.setGeometry(QtCore.QRect(330, 180, 161, 71))
        self.btnQuit.setObjectName("btnQuit")
        self.btnQuit.clicked.connect(QUIT)

        self.lbCommand = QtWidgets.QLabel(self.centralwidget)
        self.lbCommand.setGeometry(QtCore.QRect(350, 0, 160, 61))
        font = QtGui.QFont()
        font.setPointSize(18)
        font.setBold(True)
        self.lbCommand.setFont(font)
        self.lbCommand.setObjectName("lbCommand")

        self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
        self.scrollArea.setGeometry(QtCore.QRect(50, 380, 741, 251))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 739, 249))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.lbOutput = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        self.lbOutput.setGeometry(QtCore.QRect(300, 0, 111, 31))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbOutput.setFont(font)
        self.lbOutput.setObjectName("lbOutput")
        self.textBrowser = QtWidgets.QTextBrowser(self.scrollAreaWidgetContents)
        self.textBrowser.setGeometry(QtCore.QRect(10, 30, 721, 211))
        self.textBrowser.setObjectName("textBrowser")
        self.textBrowser.setFont(font)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        LocalProxyNetwork.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(LocalProxyNetwork)
        self.statusbar.setObjectName("statusbar")
        LocalProxyNetwork.setStatusBar(self.statusbar)

        self.retranslateUi(LocalProxyNetwork)
        QtCore.QMetaObject.connectSlotsByName(LocalProxyNetwork)

    def retranslateUi(self, LocalProxyNetwork):
        _translate = QtCore.QCoreApplication.translate
        LocalProxyNetwork.setWindowTitle(_translate("LocalProxyNetwork", "MainWindow"))
        self.btnRegister.setText(_translate("LocalProxyNetwork", "REGISTER"))
        self.btnDeregister.setText(_translate("LocalProxyNetwork", "DEREGISTER"))
        self.btnQuery.setText(_translate("LocalProxyNetwork", "QUERY"))
        self.btnMessage.setText(_translate("LocalProxyNetwork", "MESSAGE"))
        self.btnQuit.setText(_translate("LocalProxyNetwork", "QUIT"))
        self.lbCommand.setText(_translate("LocalProxyNetwork", "Commands:"))
        self.lbOutput.setText(_translate("LocalProxyNetwork", "Console Output"))
        self.textBrowser.setHtml(_translate("LocalProxyNetwork", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"
Welcome to Local Proxy Network UI version 1.0
\n"
"
Output is below:
"))

    def showPop(self):
        msg = QMessageBox()
        msg.setWindowTitle("Register Stuff")
        msg.setText("Do some register stuff")
        ex = msg.exec_()

    def registerWindow(self):
        self.registerWindow = QtWidgets.QMainWindow()
        ui = Ui_RegisterWindow()
        ui.setupUi(self.registerWindow)
        self.registerWindow.show()

    def deregisterWindow(self):
        self.deregisterWindow = QtWidgets.QMainWindow()
        ui = Ui_DeregisterWindow()
        ui.setupUi(self.deregisterWindow)
        self.deregisterWindow.show()

    def messageWindow(self):
        self.messageWindow = QtWidgets.QMainWindow()
        ui = Ui_MessageWindow()
        ui.setupUi(self.messageWindow)
        self.messageWindow.show()

    def queryWindow(self):
        self.queryWindow = QtWidgets.QMainWindow()
        ui = Ui_QueryWindow()
        ui.setupUi(self.queryWindow)
        self.queryWindow.show()

##################### REGISTER WINDOW ############################

class Ui_RegisterWindow(object):
    def setupUi(self, RegisterWindow):
        RegisterWindow.setObjectName("RegisterWindow")
        RegisterWindow.resize(491, 262)
        self.centralwidget = QtWidgets.QWidget(RegisterWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.lblRegister = QtWidgets.QLabel(self.centralwidget)
        self.lblRegister.setGeometry(QtCore.QRect(10, 50, 291, 61))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lblRegister.setFont(font)
        self.lblRegister.setObjectName("lblRegister")

        self.editRegister = QtWidgets.QTextEdit(self.centralwidget)
        self.editRegister.setGeometry(QtCore.QRect(310, 40, 151, 71))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.editRegister.setFont(font)
        self.editRegister.setObjectName("editRegister")

        self.btnRegister = QtWidgets.QPushButton(self.centralwidget)
        self.btnRegister.setGeometry(QtCore.QRect(170, 140, 111, 61))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.btnRegister.setFont(font)
        self.btnRegister.setObjectName("btnRegister")
        self.btnRegister.clicked.connect(lambda: self.registerDevice())

        RegisterWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(RegisterWindow)
        self.statusbar.setObjectName("statusbar")
        RegisterWindow.setStatusBar(self.statusbar)

        self.retranslateUi(RegisterWindow)
        QtCore.QMetaObject.connectSlotsByName(RegisterWindow)

    def retranslateUi(self, RegisterWindow):
        _translate = QtCore.QCoreApplication.translate
        RegisterWindow.setWindowTitle(_translate("RegisterWindow", "MainWindow"))
        self.lblRegister.setText(_translate("RegisterWindow", "Please Enter a nickname for your device:"))
        self.btnRegister.setText(_translate("RegisterWindow", "Register"))

    def registerDevice(self):
        deviceId = self.editRegister.toPlainText()
        REGISTER(deviceId)

##################### DEREGISTER WINDOW ############################

class Ui_DeregisterWindow(object):
    def setupUi(self, DeregisterWindow):
        DeregisterWindow.setObjectName("DeregisterWindow")
        DeregisterWindow.resize(491, 261)
        self.centralwidget = QtWidgets.QWidget(DeregisterWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.lblDeregister = QtWidgets.QLabel(self.centralwidget)
        self.lblDeregister.setGeometry(QtCore.QRect(10, 50, 301, 41))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lblDeregister.setFont(font)
        self.lblDeregister.setObjectName("lblDeregister")

        self.editDeregister = QtWidgets.QTextEdit(self.centralwidget)
        self.editDeregister.setGeometry(QtCore.QRect(320, 40, 151, 71))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.editDeregister.setFont(font)
        self.editDeregister.setObjectName("editDeregister")

        self.btnDeregister = QtWidgets.QPushButton(self.centralwidget)
        self.btnDeregister.setGeometry(QtCore.QRect(170, 140, 111, 61))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.btnDeregister.setFont(font)
        self.btnDeregister.setObjectName("btnDeregister")
        self.btnDeregister.clicked.connect(lambda: self.deregisterDevice())

        DeregisterWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(DeregisterWindow)
        self.statusbar.setObjectName("statusbar")
        DeregisterWindow.setStatusBar(self.statusbar)

        self.retranslateUi(DeregisterWindow)
        QtCore.QMetaObject.connectSlotsByName(DeregisterWindow)

    def retranslateUi(self, DeregisterWindow):
        _translate = QtCore.QCoreApplication.translate
        DeregisterWindow.setWindowTitle(_translate("DeregisterWindow", "MainWindow"))
        self.lblDeregister.setText(_translate("DeregisterWindow", "Please enter the nickname for your device:"))
        self.btnDeregister.setText(_translate("DeregisterWindow", "Deregister"))

    def deregisterDevice(self):
        deviceId = self.editDeregister.toPlainText()
        DEREGISTER(deviceId)

##################### MESSAGE WINDOW ############################

class Ui_MessageWindow(object):
    def setupUi(self, MessageWindow):
        MessageWindow.setObjectName("MessageWindow")
        MessageWindow.resize(487, 380)
        self.centralwidget = QtWidgets.QWidget(MessageWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.lblTitle = QtWidgets.QLabel(self.centralwidget)
        self.lblTitle.setGeometry(QtCore.QRect(170, 10, 131, 31))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lblTitle.setFont(font)
        self.lblTitle.setObjectName("lblTitle")

        self.lblTo = QtWidgets.QLabel(self.centralwidget)
        self.lblTo.setGeometry(QtCore.QRect(110, 50, 31, 16))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lblTo.setFont(font)
        self.lblTo.setObjectName("lblTo")

        self.lblFrom = QtWidgets.QLabel(self.centralwidget)
        self.lblFrom.setGeometry(QtCore.QRect(90, 110, 47, 14))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lblFrom.setFont(font)
        self.lblFrom.setObjectName("lblFrom")

        self.editTo = QtWidgets.QTextEdit(self.centralwidget)
        self.editTo.setGeometry(QtCore.QRect(140, 50, 161, 31))
        self.editTo.setObjectName("editTo")
        self.editTo.setFont(font)

        self.editMessage = QtWidgets.QTextEdit(self.centralwidget)
        self.editMessage.setGeometry(QtCore.QRect(140, 150, 251, 111))
        self.editMessage.setObjectName("editMessage")
        self.editMessage.setFont(font)

        self.editFrom = QtWidgets.QTextEdit(self.centralwidget)
        self.editFrom.setGeometry(QtCore.QRect(140, 100, 161, 31))
        self.editFrom.setObjectName("editFrom")
        self.editFrom.setFont(font)

        self.lblMessage = QtWidgets.QLabel(self.centralwidget)
        self.lblMessage.setGeometry(QtCore.QRect(70, 150, 71, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lblMessage.setFont(font)
        self.lblMessage.setObjectName("lblMessage")

        self.btnDeregister = QtWidgets.QPushButton(self.centralwidget)
        self.btnDeregister.setGeometry(QtCore.QRect(200, 280, 111, 61))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.btnDeregister.setFont(font)
        self.btnDeregister.setObjectName("btnDeregister")
        self.btnDeregister.clicked.connect(lambda: self.messageDevice())

        MessageWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MessageWindow)
        self.statusbar.setObjectName("statusbar")
        MessageWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MessageWindow)
        QtCore.QMetaObject.connectSlotsByName(MessageWindow)

    def retranslateUi(self, MessageWindow):
        _translate = QtCore.QCoreApplication.translate
        MessageWindow.setWindowTitle(_translate("MessageWindow", "MainWindow"))
        self.lblTitle.setText(_translate("MessageWindow", "New Message"))
        self.lblTo.setText(_translate("MessageWindow", "To:"))
        self.lblFrom.setText(_translate("MessageWindow", "From:"))
        self.editMessage.setHtml(_translate("MessageWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"

"))
        self.lblMessage.setText(_translate("MessageWindow", "Message:"))
        self.btnDeregister.setText(_translate("MessageWindow", "Send"))

    def messageDevice(self):
        toId = self.editTo.toPlainText()
        fromId = self.editFrom.toPlainText()
        message = self.editMessage.toPlainText()
        MSG(fromId, toId, message)

##################### QUERY WINDOW ############################

class Ui_QueryWindow(object):
    def setupUi(self, QueryWindow):
        QueryWindow.setObjectName("QueryWindow")
        QueryWindow.resize(474, 332)
        self.centralwidget = QtWidgets.QWidget(QueryWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.lblTitle = QtWidgets.QLabel(self.centralwidget)
        self.lblTitle.setGeometry(QtCore.QRect(190, 10, 111, 31))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lblTitle.setFont(font)
        self.lblTitle.setObjectName("lblTitle")

        self.lblDeviceId = QtWidgets.QLabel(self.centralwidget)
        self.lblDeviceId.setGeometry(QtCore.QRect(70, 50, 111, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lblDeviceId.setFont(font)
        self.lblDeviceId.setObjectName("lblDeviceId")

        self.lblMessage = QtWidgets.QLabel(self.centralwidget)
        self.lblMessage.setGeometry(QtCore.QRect(130, 100, 51, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lblMessage.setFont(font)
        self.lblMessage.setObjectName("lblMessage")

        self.btnQuery = QtWidgets.QPushButton(self.centralwidget)
        self.btnQuery.setGeometry(QtCore.QRect(180, 230, 111, 61))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.btnQuery.setFont(font)
        self.btnQuery.setObjectName("btnQuery")
        self.btnQuery.clicked.connect(lambda: self.queryDevice())

        self.editDeviceId = QtWidgets.QTextEdit(self.centralwidget)
        self.editDeviceId.setGeometry(QtCore.QRect(180, 50, 161, 31))
        self.editDeviceId.setObjectName("editDeviceId")
        self.editDeviceId.setFont(font)

        self.lblType = QtWidgets.QLabel(self.centralwidget)
        self.lblType.setGeometry(QtCore.QRect(190, 100, 201, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.lblType.setFont(font)
        self.lblType.setObjectName("lblType")

        self.sliderType = QtWidgets.QSlider(self.centralwidget)
        self.sliderType.setGeometry(QtCore.QRect(120, 160, 241, 21))
        self.sliderType.setMaximum(1)
        self.sliderType.setOrientation(QtCore.Qt.Horizontal)
        self.sliderType.setObjectName("sliderType")
        self.sliderType.valueChanged.connect(lambda: self.adjustTypeLabel())

        QueryWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(QueryWindow)
        self.statusbar.setObjectName("statusbar")
        QueryWindow.setStatusBar(self.statusbar)

        self.retranslateUi(QueryWindow)
        QtCore.QMetaObject.connectSlotsByName(QueryWindow)

    def retranslateUi(self, QueryWindow):
        _translate = QtCore.QCoreApplication.translate
        QueryWindow.setWindowTitle(_translate("QueryWindow", "MainWindow"))
        self.lblTitle.setText(_translate("QueryWindow", "Data Query"))
        self.lblDeviceId.setText(_translate("QueryWindow", "Target Device:"))
        self.lblMessage.setText(_translate("QueryWindow", "Type:"))
        self.btnQuery.setText(_translate("QueryWindow", "Send"))
        self.lblType.setText(_translate("QueryWindow", "Mailbox"))

    def adjustTypeLabel(self):
        numType = self.sliderType.value()
        if(numType is 0):
            self.lblType.setText("Mailbox")
        elif(numType is 1):
            self.lblType.setText("Device Information")

    def queryDevice(self):
        numType = self.sliderType.value()
        targetDevice = self.editDeviceId.toPlainText()
        QUERY(numType, targetDevice)

########################### CLIENT FUNCTIONS ###############################################################

#Name: REGISTER
#
#Purpose: Sends request to be registered
#
#Param: in: string representing device's Id (deviceId)
#
#Brief: Sends message to the server to request that device
#       be registered in proxy network
#
#ErrorsHandled: N/A
#
def REGISTER(deviceId):
    myMAC = getnode() #gets the MAC address of device
    myMAC = hex(myMAC)
    myMAC = myMAC[2:] # removes '0x' from the hexadecimal number
    myMAC = ':'.join(format(s, '02x') for s in bytes.fromhex(myMAC)) #seperates hexadecimal into MAC address form
    myMessage = (1, deviceId, myMAC)                                 #(borrowed from stackoverflow)
    myMessage = str.encode(str(myMessage))
    socketTCP.send(myMessage)
    recvData = socketTCP.recv(1024)
    recvData = bytes.decode(recvData)
    recvData = literal_eval(recvData)
    if recvData[0] is 0: #Received message is a ACK
        print("ACK: " + recvData[1] + '\n')
        ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "ACK: " + recvData[1] + "\n" + '\n')
    elif recvData[0] is 1: #Received message is a NACK
        print("NACK: " + recvData[1] + '\n')
        ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "NACK: " + recvData[1] + "\n" + '\n')

#Name: DEREGISTER
#
#Purpose: Sends request to be deregistered
#
#Param: in: string representing device's Id (deviceId)
#
#Brief: Sends message to server so that it can handle removing
#       device register from proxy network
#
#ErrorsHandled: N/A
#
def DEREGISTER(deviceId):
    myMAC = getnode() #gets the MAC address of device
    myMAC = hex(myMAC)
    myMAC = myMAC[2:] # removes '0x' from the hexadecimal number
    myMAC = ':'.join(format(s, '02x') for s in bytes.fromhex(myMAC)) #seperates hexadecimal into MAC address form
    myMessage = (2, deviceId, myMAC)
    myMessage = str.encode(str(myMessage))
    socketTCP.send(myMessage)
    recvData = socketTCP.recv(1024)
    recvData = bytes.decode(recvData)
    recvData = literal_eval(recvData)
    if recvData[0] is 0: #Received message is a ACK
        print("ACK: " + recvData[1] + '\n')
        ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "ACK: " + recvData[1] + "\n" + '\n')
    elif recvData[0] is 1: #Received message is a NACK
        print("NACK: " + recvData[1] + '\n')
        ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "NACK: " + recvData[1] + "\n" + '\n')

#Name: MSG
#
#Purpose: Sends message to another device in the network
#
#Param: in: string representing device's Id (deviceId)
#       in: string representing receiver's Id (receiverId)
#       in: string message being sent (message)
#
#Brief: Sends message to the server so that it can be stored in
#       the mailbox table of database
#
#ErrorsHandled: N/A/
#
def MSG(fromId, toID, message):
    myMessage = (3, fromId, toID, message)
    myMessage = str.encode(str(myMessage))
    socketTCP.send(myMessage)
    recvData = socketTCP.recv(1024)
    recvData = bytes.decode(recvData)
    recvData = literal_eval(recvData)
    if recvData[0] is 0: #Received message is a ACK
        print("ACK: " + recvData[1] + '\n')
        ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "ACK: " + recvData[1] + "\n" + '\n')
    elif recvData[0] is 1:#Received message is a NACK
        print("NACK: " + recvData[1] + '\n')
        ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "NACK: " + recvData[1] + "\n" + '\n')

#Name: QUERY
#
#Purpose: Query database for desired information
#
#Param: in: integer representing type of query (qType)
#       in: string representing device's Id (deviceId)
#
#Brief: Query database for desired information requested by
#       the client
#
#ErrorsHandled:
#
def QUERY(qType, deviceId):
    try:
        if qType is 0:
            print("Mailbox Query")
            ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "Mailbox Query" + "\n")
            myMessage = (4, 0, deviceId)
            myMessage = str.encode(str(myMessage))
            socketTCP.send(myMessage)
            recvData = socketTCP.recv(2048)
            recvData = bytes.decode(recvData)
            recvData = literal_eval(recvData)
            if recvData[0] is 0: #Received message is a ACK
                print("ACK: " + recvData[1])
                ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "ACK: " + recvData[1] + "\n")
                printMailQuery(recvData[2])

            elif recvData[0] is 1:#Received message is a NACK
                print("NACK: " + recvData[1])
                ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "NACK: " + recvData[1] + "\n")
        elif qType is 1:
            print("Device Info Query")
            ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "Device Info Query" + "\n")
            myMessage = (4, 1, deviceId)
            myMessage = str.encode(str(myMessage))
            socketTCP.send(myMessage)
            recvData = socketTCP.recv(1024)
            recvData = bytes.decode(recvData)
            recvData = literal_eval(recvData)

            if recvData[0] is 0: #Received message is a ACK
                print("ACK: " + recvData[1])
                ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "ACK: " + recvData[1] + "\n")
                printDevicesQuery(recvData[2])

            elif recvData[0] is 1:#Received message is a NACK
                print("NACK: " + recvData[1])
                ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "ACK: " + recvData[1] + "\n")
        else:
            print("Inputted type is not a valid query type")
            ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "Inputted type is not a valid query type" + "\n")
    except Exception as e:
            print(traceback.format_exc())

#Name: Quit Application
#
#Purpose: Closes socket connection with network
#
#Param: N/A
#
#Brief: N/A
#
#ErrorsHandled: N/A
#
def QUIT():
    print("Quitting proxy network and closing socket connection")
    ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "Quitting proxy network and closing socket connection" + "\n")
    socketTCP.close()
    sys.exit(app.exec_())

#Name: Print Mail Query
#
#Purpose: Prints the result of a database query for mail
#
#Param: in: 2-D Array representing database query (result)
#
#Brief: N/A
#
#ErrorsHandled: N/A
#
def printMailQuery(result):
    if result is not None:
        for row in result:
            myRow = "To: " + row[1] + "   " + "From: " + row[2] + "    Message: " + row[3] + "   " + "Date: " + row[4]
            print(myRow)
            ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + myRow + "\n")
    print("\n")
    ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "\n")

#Name: Print Devices Query
#
#Purpose: Prints the result of a database query for devices
#
#Param: in: 2-D Array representing database query (result)
#
#Brief: N/A
#
#ErrorsHandled: N/A
#
def printDevicesQuery(result):
    if result is not None:
        for row in result:
            myRow = "DeviceId: " + row[1] + "   " + "MAC: " + row[2] + "   IP: " + row[3] + "   " + "Port: " + row[4]
            print(myRow)
            ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + myRow + "\n")
    print("\n")
    ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "\n")

####################### MAIN PROGRAM #######################################################################

#Code for client to connect to server
socketTCP = socket()
myIP = "192.168.5.5"
myPortNumber = 9999
socketTCP.connect((myIP, myPortNumber))

#Create PyQt5 Window
app = QtWidgets.QApplication(sys.argv)
LocalProxyNetwork = QtWidgets.QMainWindow()
ui = Ui_LocalProxyNetwork()
ui.setupUi(LocalProxyNetwork)
LocalProxyNetwork.show()
ui.textBrowser.setPlainText(ui.textBrowser.toPlainText() + "\n\n")
sys.exit(app.exec_())

#Client Information
#userId = "Kamran's Tower"
#userId2 = "Nope"

#Client Functions Testing
#REGISTER(userId)
#REGISTER(userId2)
#MSG(userId, userId2, "Testing test")
#QUERY(0, userId2)
#QUERY(1, userId2)


import csv
import socket
import json

port = 12345

if __name__ == "__main__":
    # file = open('config.csv', mode='r')
    # csv_reader = csv.DictReader(file)
    # line_count = 0
    #
    # seed_list = []
    #
    # for row in csv_reader:
    #     if line_count == 0:
    #         line_count = 1
    #     else:
    #         seed_list.append(row)

    peer = socket.socket()

    peer.connect(('127.0.0.1', port))

    peer.send(b'send CL')

    peer_list = peer.recv(10000)
    peer_list = json.loads(peer_list.decode('ASCII'))

    print(peer_list)
    peer.close()


import re
from collections import OrderedDict

import bs4

from wikicurses import formats
from wikicurses import settings

skipclass = ('wiki-sidebar', 'infobox', 'mw-editsection', 'editsection',
             'wikitable', 'thumb', 'gallery', 'article-thumb', 'infobox_v2',
             'mw-headline-anchor', 'toc', 'noprint', 'wikia-gallery')
skipsection = ('External links', 'See also')

if settings.hide_references:
    skipclass += ('reference',)
    skipsection += ('References',)

def parseArticle(html):
    """Parse article html and return list of  (format, text) tuples."""
    html = html.replace('\t', ' ')
    soup = bs4.BeautifulSoup(html, 'lxml')
    # Turn into tuple since the iterator is being modified
    for i in tuple(soup.strings):
        if not {'pre', 'code'}.intersection(j.name for j in i.parents):
            i.replace_with(i.replace('\n', ''))
    for i in soup.find_all('p'):
        i.insert_after(soup.new_string('\n\n'))
    for i in soup.find_all(['h2', 'h3', 'h4', 'h5', 'h6', 'br', 'pre']):
        i.insert_after(soup.new_string('\n'))
    for i in soup.find_all('div'):
        if i.text and not i.find_all('div'):
            i.insert_after(soup.new_string('\n'))
    for i in soup.find_all('li'):
        if i.parent.name == 'ol':
            num = i.parent.find_all('li').index(i) + 1
            i.insert_before(soup.new_string(str(num) + '. '))
        else:
            i.insert_before(soup.new_string('• '))
        i.insert_after(soup.new_string('\n'))
        if 'li' not in (j.name for j in i.next_siblings): # Last item in list
            i.insert_after(soup.new_string('\n'))

    for i in soup.find_all(True, class_=skipclass):
        i.decompose()
    for i in soup.find_all('script'):
        i.decompose()
    for i in soup.find_all('h2'):
        if i.text in skipsection:
            for j in tuple(i.next_elements):
                # Test it is not a str to avoid using str.find() by accident
                if not isinstance(j, str) and (j.name == 'h2' or j.find('h2')):
                    break
                j.extract()
            i.decompose()

    items = []
    for item in soup.strings:
        if not item:
            continue

        if isinstance(item, bs4.element.Comment):
            continue # Strip out html comments

        partags = {i.name for i in item.parents}
        tformat = sum(
            formats[i] for i in set(i.name for i in formats).intersection(partags))
        if [i for i in partags if re.fullmatch('h[3-6]', i)]:
            tformat |= formats.h
        # Make <strong>/<em> use same formats as <b>/<i>
        if 'strong' in partags:
            tformat |= formats.b
        if 'em' in partags:
            tformat |= formats.i

        # Handle divs with padding or borders defined in css style
        styledivs = item.findParents('div', style=True)
        stylekeys = [i.split(':', 1)[0].strip()
                for div in styledivs for i in div.get('style').split(';')]
        if 'padding' in stylekeys:
            tformat |= formats.divpadding
        if 'border' in stylekeys:
            tformat |= formats.divborder

        # Added specifically for handling spaces between removed references
        if items and items[-1][1] and (items[-1][1][-1] == item[0] == ' '):
            item = item[1:]

        # If format same as previous, combine
        if items and items[-1][0] == tformat:
            items[-1][1] += str(item)
        else:
            items.append([tformat, str(item)])

    return items

def parseFeature(html):
    """Parse featured feed html by striping out html tags."""
    # TODO: Support html tags like <b>
    text = bs4.BeautifulSoup(html, 'lxml').text.strip() + '\n\n'
    text = re.sub('\n\n+', '\n\n', text)
    return text

def _processDisambigSection(section):
    items = []
    for i in section:
        if isinstance(i, str):
            continue
        if i.name == 'h2' or i.find('h2'):
            break
        for item in i.find_all('li'):
            items.append(
                (item.a.text if item.a else '', item.text.split('\n')[0]))
    return items

def parseDisambig(html):
    """Parse disambiguation page and return list of (article, text) tuples."""
    sections = OrderedDict()
    soup = bs4.BeautifulSoup(html, 'lxml')
    for i in soup.find_all(True, class_=skipclass):
        i.decompose()
    sections[''] = _processDisambigSection(soup)
    for i in soup.find_all('h2'):
        if i.text not in ('Contents', 'See also'):
            sections[i.text] = _processDisambigSection(i.next_siblings)
    return sections


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 21 18:09:02 2019

@author: idlirshkurti
"""

# =============================================================================
# Pipeline script
# =============================================================================

import pandas as pd
from src.dataloader import load_incoming, load_outgoing
from tqdm import tqdm

'''
The following scripts builds a data pipeline which adds features to an
analytical base table (ABT). Use the run.py script to run the pipeline
and create the ABT table.
'''

class ABT:
    """Analytical Base Table for building analytical models and predicting
    the future behavior of a subject.
    """
    def __init__(self):
        """Constructor to set-up analytical base table.

        Returns:
            abt (pd.DataFrame): DataFrame acting as analytical base table
                                   with numerical index and sorted by
                                   time column 'transaction_timestamp' column.
        """

        self.df_incoming = load_incoming(path_incoming = './', incoming_data = 'data/incoming.csv')
        self.df_incoming['incoming_outgoing'] = 0
        self.df_outgoing = load_outgoing(path_outgoing = './', outgoing_data = 'data/outgoing.csv')
        self.df_outgoing['incoming_outgoing'] = 1
        self.abt = self.df_incoming.append(self.df_outgoing)
        self.abt = self.abt.sort_values(by='transaction_timestamp')
        self.abt.index = range(self.abt.shape[0])

    def add_ratio(abt, column_name = 'ratio'):

        abt[column_name] = None
        for i in tqdm(range(abt.shape[0])):
            date = abt.loc[i, 'transaction_timestamp']

            assert type(date) is pd._libs.tslibs.timestamps.Timestamp, \
            "Date is not the correct format for row: {} in ABT table!".format(i)

            user = abt.loc[i, 'user_id']
            assert type(user) is str, \
            "User not identified: {} ".format(user)

            tmp = abt[(abt['user_id'] == user) & (abt['transaction_timestamp'] <= date)]

            assert (tmp.shape[0] > 0), \
            "No rows selected for tmp DataFrame in 'ratio' column!"

            abt.loc[i, column_name] = tmp.incoming_outgoing.sum()/tmp.shape[0]

        return(abt)

    def add_prev_trans_time(abt, column_name = 'prev_trans_time'):

        abt[column_name] = None
        for i in tqdm(range(abt.shape[0])):
            date = abt.loc[i, 'transaction_timestamp']

            assert type(date) is pd._libs.tslibs.timestamps.Timestamp, \
            "Date is not the correct format for row: {} in ABT table!".format(i)

            user = abt.loc[i, 'user_id']
            assert type(user) is str, \
            "User not identified: {} ".format(user)

            tmp = abt[(abt['user_id'] == user) & (abt['transaction_timestamp'] <= date)]

            assert (tmp.shape[0] > 0), \
            "No rows selected for tmp DataFrame in 'prev_trans_time' column!"
            abt.loc[i, column_name] = date - tmp.iloc[-1].transaction_timestamp

        return(abt)

    def add_average_time(abt, column_name = 'average_time'):

        abt[column_name] = None
        for i in tqdm(range(abt.shape[0])):

            date = abt.loc[i, 'transaction_timestamp']
            assert type(date) is pd._libs.tslibs.timestamps.Timestamp, \
            "Date is not the correct format for row: {} in ABT table!".format(i)

            user = abt.loc[i, 'user_id']
            assert type(user) is str, \
            "User not identified: {} ".format(user)

            tmp = abt[(abt['user_id'] == user) & (abt['transaction_timestamp'] <= date)]
            assert (tmp.shape[0] > 0), \
            "No rows selected for tmp DataFrame in 'average_time' column!"

            abt.loc[i, column_name] = tmp.transaction_timestamp.append(pd.core.series.Series([date])).diff().dropna().mean()
            assert type(abt.loc[i, column_name]) is pd._libs.tslibs.timedeltas.Timedelta, \
            "Not the correct format for the i={} row in 'average_time' column!".format(i)

        return(abt)

'''
If the data scientist decided to add more features to the model,
they could use a similar format/function as the ones writen
above to add columns to the 'abt' table
'''


#!/usr/bin/env python

# Playin some music

import ckbot.logical as L
from pylab import *
from time import time as now

c = L.Cluster()
c.populate(2)

#plucker_pos = 0.95
plucker_pos = 0.8
tuner_pos = -0.6
tuner_up = True

plucker = c.at.NxE3
tuner = c.at.Nx2A

notes_seq = tuner_pos + array([0.0, 0.2, 0.4, 0.2])
notes_seq2 = tuner_pos + array([0.8,0.0,0.2,0.8,0.2,-0.3,-0.8,-0.3])
notes_ind = 0

pluck_frq = 2.0
pluck_t0 = now()

note_frq = 2.0
note_t0 = now()

while True:
  curtime = now()

  if (curtime - pluck_t0) > 1.0/pluck_frq:
    pluck_t0 = now()
    if tuner_up:
      plucker.set_pos( plucker_pos - 0.4 )
      tuner_up = False
    else:
      plucker.set_pos( plucker_pos )
      tuner_up = True

  if (curtime - note_t0) > 1.0/note_frq:
    note_t0 = curtime
    tuner.set_pos( notes_seq2[notes_ind] )
    notes_ind = (notes_ind+1) % len(notes_seq2)


# -*- coding: UTF-8 -*-

main = {
	'rbTitle': { 'color': ( 255.0, 241.0, 192.0 ), 'text': "技能学习", 'charSpace': 2 },
	'miAbleSkill': { 'text': "可学的技能" },
	'miUnableSkill': { 'text': "不可学的技能" },
	'miAllSkill': { 'text': "全部技能" },
	'miPassive': { 'text': "(被动)" },
	'miNeedItem': { 'text': "需要物品: %s" },
	'miSkillInfo': { 'text': "%s  技能说明:%s%s" },
	'miFrontSkill': { 'text': "%s  需要前置技能: %s " },
	'miNeedContribute': { 'text': "%s  需要帮会贡献度:%s%i" },
	'miNeedPoteneial': { 'text': "%s  学习潜能:%s%i" },
	'miNeedLevel': { 'text': "%s  需要角色等级:%s%i" },
	'miNeedTSkill': { 'text': "%s  学习技能点:%s%i" },
	'miNeedTLevel': { 'text': "%s  需要骑宠等级:%s%i" },
	'miPotential': { 'text': "潜能: %d点" },
	'miContribute': { 'text': "帮会贡献度:%d 点" },
	'miVehicleSkill': { 'text': "骑宠技能点: %d点" },
	'miUnVehicle': { 'text': "您当前没有坐骑" },
	'miNeedSLevel': { 'text': "需要角色等级" },
	'miNeedTSLevel': { 'text': "需要骑宠等级" },
	'miNeedPSLevel': { 'text': "需要宠物等级" },
	'btnSkillName': { 'text': "技 能 名 称" },
	'btnLearn': { 'text': "学 习" },
	'singing': { 'text': "%0.1f秒" },
	'coolDown': { 'text': "%0.1f秒" },
	'skillLevel': { 'text': "%d 级" }
	}