# Download the helper library from https://www.twilio.com/docs/python/install
import os
from os import environ
import sys
from twilio.rest import Client
# from dotenv import load_dotenv

# load_dotenv()

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure

def send_informational_message(receiving_phone_num_str, person_name, time ):
    # account_sid = os.getenv('TWILIO_ACCOUNT_SID')
    # auth_token = os.getenv('TWILIO_AUTH_TOKEN')
    account_sid = 'xxxxxxxxxx'
    auth_token = 'xxxxxxxxxx'
    client = Client(account_sid, auth_token)
    message = client.messages \
                    .create(
                        body="your friend {0} has started a trip. they plan to reach in {1} minutes. just thought you should know :) ".format(person_name, time),
                        from_='+14703478946',
                        to=receiving_phone_num_str
                    )
    print(message.sid)

def send_emergency_message(receiving_phone_num_str, person_name):
    account_sid = 'xxxxxxxxxx'
    auth_token = 'xxxxxxxxxx'
    print(account_sid, auth_token)
    client = Client(account_sid, auth_token)
    message = client.messages \
                    .create(
                        body="your friend {} has not indicated that they have reached their destination on time. danger!!! ".format(person_name),
                        from_='+14703478946',
                        to=receiving_phone_num_str
                    )
    print(message.sid)


from bot_func_abc import BotFunctionABC
import telebot
from telebot import types
from telebot.callback_data import CallbackData, CallbackDataFilter
from typing import List
import bot_func_dictionary
from bot_func import BotFunction
import time

class StartInfoBotFunction(BotFunctionABC):
    slip_time = 0.2

    def set_handlers(self, bot: telebot.TeleBot, commands: List[str]):
        self.bot = bot
        self.start_keyboard_factory = CallbackData('start_f_button', prefix=commands[0])

        @bot.message_handler(commands=commands)
        def start_message_hendler(message: types.Message):
            msg = f'Привет {message.from_user.full_name}! \nВот список доступных функций:'
            bot.send_message(text=msg, chat_id=message.chat.id)
            self.send_messages_bf2(message)
            self.send_messages_bf(message)

        @bot.callback_query_handler(func=None, config=self.start_keyboard_factory.filter())
        def start_keyboard_callback(call: types.CallbackQuery):
            callback_data: dict = self.start_keyboard_factory.parse(callback_data=call.data)
            start_f_button = callback_data['start_f_button']
            function = self.find_function_info(start_f_button)
            self.send_detail_messages(call.message, function)

    def send_messages_bf2(self, message: types.Message):
        for key, val in bot_func_dictionary.BOT_FUNCTIONS_2.items():
            if val.state:
                txt = f'{val.about} \n'
                for command in val.commands:
                    txt += f' - `/{command}` \n'
                #txt += "\n  - /".join(val.commands)
                self.bot.send_message(text=txt, chat_id=message.chat.id, reply_markup=self.gen_markup(key), parse_mode='Markdown')
                time.sleep(self.slip_time)

    def send_messages_bf(self, message: types.Message):
        for key, val in bot_func_dictionary.BOT_FUNCTIONS.items():
            txt = f'{val.about} \n'
            for command in val.commands:
                txt += f' - `/{command}` \n'
            self.bot.send_message(text=txt, chat_id=message.chat.id, reply_markup=self.gen_markup(key), parse_mode='Markdown')
            time.sleep(self.slip_time)

    def find_function_info(self, key: str) -> BotFunction:
        if key in bot_func_dictionary.BOT_FUNCTIONS_2:
            return bot_func_dictionary.BOT_FUNCTIONS_2[key]

        if key in bot_func_dictionary.BOT_FUNCTIONS:
            return bot_func_dictionary.BOT_FUNCTIONS[key]

    def send_detail_messages(self, message: types.Message, bot_function: BotFunction):
        txt = f'*{bot_function.about}* \n'
        for command in bot_function.commands:
            txt += f' - `/{command}` \n'
        txt += f'{bot_function.description} \n\n*Contributors:* \n'
        for author in bot_function.authors:
            txt += f' - [{author}](https://github.com/{author}) \n'

        self.bot.send_message(text=txt, chat_id=message.chat.id, parse_mode='Markdown')

    def gen_markup(self, key: str):
        markup = types.InlineKeyboardMarkup()
        markup.row_width = 1
        markup.add(types.InlineKeyboardButton("Подробнее", callback_data=self.start_keyboard_factory.new(start_f_button=key)))
        return markup


import configparser
from files.definitions import execute_sql, is_object, add_customer
try:
    import mysql.connector as cn
except ImportError:
    print("Install mysql connector to start \"pip3 install mysql.connector\"")
    #print("This module can require OS packages: postgres, postgres-devel, gcc, python3-devel")
    exit(101)
try:
    from faker import Faker
except ImportError:
    print("Install faker to start \"pip3 install faker\"")
    exit(101)

def cleanup_schema_mysql(conn: cn.connection, config: configparser.ConfigParser):
    cur = conn.cursor()
    for user in config.get('settings', 'app_users').split(','):
        if is_object(cur, "SELECT COUNT(*) FROM mysql.user WHERE user='{}' AND host='%'".format(user)) == 1:
            execute_sql(cur, "DROP USER {}".format(user))
    for user in config.get('settings', 'db_admins').split(','):
        if is_object(cur, "SELECT COUNT(*) FROM mysql.user WHERE user='{}' AND host='%'".format(user)) == 1:
            execute_sql(cur, "DROP USER {}".format(user))
    for table in ['customers', 'credit_cards', 'features', 'extras', 'transactions']:
        execute_sql(cur, "DROP TABLE IF EXISTS gn_app.{} CASCADE".format(table))
    execute_sql(cur, "DROP ROLE IF EXISTS gn_users")
    execute_sql(cur, "DROP ROLE IF EXISTS app_users")
    cur.close()

def deploy_schema_mysql(conn: cn.connection, config: configparser.ConfigParser):
    fake = Faker(config.get('settings', 'language'))
    cur = conn.cursor()
    # create schema
    execute_sql(cur, "CREATE ROLE IF NOT EXISTS gn_users")
    execute_sql(cur, "CREATE ROLE IF NOT EXISTS app_users")
    for user in config.get('settings', 'app_users').split(','):
        execute_sql(cur, "CREATE USER IF NOT EXISTS {}@'%' IDENTIFIED BY '{}' DEFAULT ROLE app_users"
                    .format(user, config.get('settings', 'default_password')))
        execute_sql(cur, "GRANT app_users TO {}".format(user))
    for user in config.get('settings', 'db_admins').split(','):
        execute_sql(cur, "CREATE USER IF NOT EXISTS {}@'%' IDENTIFIED BY '{}' DEFAULT ROLE gn_users"
                    .format(user, config.get('settings', 'default_password')))
        execute_sql(cur, "GRANT gn_users TO {}".format(user))
    # create customers table
    sql = "CREATE TABLE IF NOT EXISTS gn_app.customers (" \
          "customer_id varchar(40) DEFAULT (uuid())," \
          "customer_fname varchar(50)," \
          "customer_lname varchar(50)," \
          "birthday date," \
          "citizen_id varchar(20)," \
          "birth_place varchar(50)," \
          "street varchar(50)," \
          "flat_number varchar(10)," \
          "city varchar(50)," \
          "zipcode varchar(10)," \
          "driving_license varchar(30)," \
          "passport_id varchar(30)," \
          "citizen_doc_id varchar(30)," \
          "mail varchar(50)," \
          "phone varchar(30), " \
          "PRIMARY KEY (customer_id))"
    execute_sql(cur, sql)
    execute_sql(cur, "CREATE TABLE IF NOT EXISTS gn_app.credit_cards (card_id varchar(40) DEFAULT (uuid()), "
                     "customer_id varchar(40) REFERENCES gn_app.customers (customer_id), "
                     "card_number varchar(30), card_validity varchar(12), PRIMARY KEY (card_id))")
    execute_sql(cur, "CREATE TABLE IF NOT EXISTS gn_app.features (feature_id varchar(40) DEFAULT (uuid()), "
                      "feature_name varchar(40), feature_price real, PRIMARY KEY (feature_id))")
    prices = config.get('game_addons', 'feature_prices').split(',')
    i = 0
    for feature in config.get('game_addons', 'feature_descriptions').split(','):
        execute_sql(cur, "INSERT INTO gn_app.features (feature_name, feature_price) VALUES ('{}', {})".format(
            feature, prices[i]))
        i += 1
    execute_sql(cur, "CREATE TABLE IF NOT EXISTS gn_app.extras (extra_id varchar(40) DEFAULT (uuid()), "
                     "extra_name varchar(40), extra_price real, PRIMARY KEY (extra_id))")
    prices = config.get('game_addons', 'extra_prices').split(',')
    i = 0
    for feature in config.get('game_addons', 'extra_descriptions').split(','):
        execute_sql(cur, "INSERT INTO gn_app.extras (extra_name, extra_price) VALUES ('{}', {})".format(
            feature, prices[i]))
        i += 1
    execute_sql(cur, "CREATE TABLE IF NOT EXISTS gn_app.transactions ("
                     "trans_id varchar(40) DEFAULT (uuid()), "
                     "feature_id varchar(40) REFERENCES gn_app.features (feature_id), "
                     "extra_id varchar(40) REFERENCES gn_app.extras (extra_id), "
                     "price real, "
                     "customer_id varchar(40) REFERENCES gn_app.customers (customer_id), "
                     "card_id varchar(40) REFERENCES gn_app.credit_cards (card_id), "
                     "transaction_time TIMESTAMP DEFAULT now(), "
                     "PRIMARY KEY (trans_id))"
                )
    execute_sql(cur, "GRANT SELECT ON gn_app.* TO gn_users")
    execute_sql(cur, "GRANT SELECT, INSERT, UPDATE ON gn_app.* TO app_users")
    if is_object(cur, "SELECT COUNT(*) FROM gn_app.customers") < config.getint('settings', 'minimal_customer_count'):
        for i in range(config.getint('settings', 'minimal_customer_count')):
            add_customer(config, cur)
    cur.close()


from civicboom.model.member  import Member, User, Group, GroupMembership
from civicboom.model.content import Content, Tag, License, MemberAssignment
from civicboom.model.media   import Media
from civicboom.model.message import Message
from civicboom.model.meta    import Session

from sqlalchemy         import and_,  select
from sqlalchemy.orm     import joinedload
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc     import InvalidRequestError

from sqla_hierarchy import *

from cbutils.misc import make_username, debug_type

import logging
log = logging.getLogger(__name__)

# This global variable is set by parent calling modles. If this is set, the module will use the cache
#  cache regions instances are added to the cache dictonary
from civicboom.lib.cache import _cache

#-------------------------------------------------------------------------------
# Database Object Gets
#-------------------------------------------------------------------------------

def get_media(id=None, hash=None):
    if id:
        return Session.query(Media).get(id)
    if hash:
        try:
            return Session.query(Media).filter_by(hash=hash).first()
        except NoResultFound:
            return None

#@cache_this
def get_licenses():
    return Session.query(License).all()

# AllanC - primarly used in setup of test data, not normally used in main site operation
def get_license(code):
    code = code or u"Unspecified" # get_license(None) should return the default
    assert type(code) in [str, unicode], debug_type(code)
    return Session.query(License).get(code)

# TODO: it might be nice to specify eager load fields here, so getting the logged in user eagerloads group_roles and groups to be show in the title bar with only one query
def get_member(member):
    if not member:
        return None
    if isinstance(member, Member):
        return member

    assert type(member) in [str, unicode], debug_type(member)

    member = make_username(member)

    def get_member_nocache(member_id):
        try:
            return Session.query(Member).with_polymorphic('*').get(member_id)
        except NoResultFound:
            return None

    cache      = _cache.get('member')
    cache_func = lambda: get_member_nocache(member)
    if cache:
        result = cache.get(key='member:%s' % member, createfunc=cache_func)
        #try:
            #Session.add(result)
            #return result
        #except InvalidRequestError:
        return Session.merge(result, load=False)
    return cache_func()

def get_member_email(member):
    if not member:
        return None
    if isinstance(member, Member):
        return member
    assert type(member) in [str, unicode], debug_type(member)
    try:
        return Session.query(User).filter_by(email=member).one()
    except NoResultFound:
        return None

def get_group(group):
    if isinstance(group, Group):
        return group
    group = get_member(group)
    if isinstance(group, Group):
        return group
    return None

def get_membership(group, member):
    member = get_member(member)
    group  = get_group(group)

    if not (member and group):
        return None

    try:
        return Session.query(GroupMembership).filter(
            and_(
                GroupMembership.group_id  == group.id,
                GroupMembership.member_id == member.id
            )
        ).one()
    except NoResultFound:
        return None

def get_group_member_username_list(group, members=None, exclude_list=None):
    """
    Get linear list of all members and sub members - list is guaranteeded to
     - contain only user objects
     - have no duplicates
    """
    if members == None:
        members = {}
    if exclude_list == None:
        exclude_list = []
    for member in [mr.member for mr in group.members_roles if mr.status=='active' and mr.member.status=='active' and mr.member.username not in members and mr.member.username not in exclude_list]:
        if   member.__type__ == 'user':
            members[member.username] = member
        elif member.__type__ == 'group':
            exclude_list.append(member.username)
            get_group_member_username_list(member, members, exclude_list)
    return members.keys()

def get_members(members, expand_group_members=True):
    """
    Aquire a list of all submembers e.g
    Group Test1 has 3 members
    Group Test2 has 2 members
    passing [Test1,Test2] will return 5 member objects of the submembers

    members can be
      group object - All user member users (including recursive sub members) of a group
      list of username strings
      a comma separated list of strings

    AllanC - Note ignors and does not error on members that do not exist? is this right?

    TODO - optimisation - lazy load settings and other large feilds from these users
    """

    if not members:
        return []

    # split comma list of string members
    if isinstance(members, basestring):
        members = [member.strip() for member in members.split(',')]
        #if len(members) == 1 and expand_group_members: # member list has one member, check if this single member is a group
        #    member = get_member(members[0])
        #    if member and member.__type__ == 'group':
        #        members = member
            # else it's a user and is valid, do nothing

    if isinstance(members, Group) and expand_group_members:
        members = get_group_member_username_list(members)

    # No need to process members list if members is a single member
    #  note: any group object will have been converted into a member list above is needed
    if isinstance(members, Member):
        return [members]

    # normalize member names
    members = [member if not hasattr(member, 'id') else member.id for member in members]

    member_objects = Session.query(Member).with_polymorphic('*').filter(Member.id.in_(members)).filter(Member.status=='active').all()

    if expand_group_members:
        group_members = []
        for group in [member for member in member_objects if isinstance(member, Group)]:
            group_members += get_group_member_username_list(group) # , exclude_list=group_members
        member_objects += get_members(list(set(group_members)))
        member_objects =              list(set(member_objects))

    return member_objects

# GregM: Dirty, do not cache, see redmine #414
def get_membership_tree(group, member, iter = 0):
    if iter > 5:
        return None
    member = get_member(member)
    group  = get_group(group)

    if not (member and group):
        return None

    try:
        return Session.query(GroupMembership).filter(
            and_(
                GroupMembership.group_id  == group.id,
                GroupMembership.member_id == member.id
            )
        ).one()
    except NoResultFound:
        try:
            groups = Session.query(GroupMembership).filter(
                and_(
                    GroupMembership.group_id == group.id,
                    GroupMembership.member_id != member.id,
#                    isinstance(GroupMembership.member, Group)
                )
            ).all()
            for p_group in groups:
                p_result = get_membership_tree(p_group.member.id, member.id, iter + 1)
                if p_result:
                    return p_result
            return None
        except NoResultFound:
            return None

def get_follower_type(member, follower):
    member   = get_member(member)
    follower = get_member(follower)

    if not (member and follower):
        return None

    try:
        return Session.query(Follow).filter(
            and_(
                Follow.member_id   == member.id,
                Follow.follower_id == follower.id,
            )
        ).one().type
    except NoResultFound:
        return None

def get_assigned_to(content, member):
    content = get_content(content)
    member  = get_member(member)

    if not (content and member):
        return None
    try:
        return Session.query(MemberAssignment).filter(
            and_(
                MemberAssignment.content_id  == content.id,
                MemberAssignment.member_id   == member.id
            )
        ).one()
    except NoResultFound:
        return None

def get_message(message_id):
    assert str(message_id).isdigit(), debug_type(message_id)
    return Session.query(Message).options(joinedload('source')).options(joinedload('target')).get(int(message_id))

def get_content(content):
    if not content:
        return None
    if isinstance(content,Content):
        return content

    try:
        content = int(content)
    except:
        return None

    def get_content_nocache(content_id):
        #http://www.sqlalchemy.org/docs/mappers.html#controlling-which-tables-are-queried
        # could use .with_polymorphic([DraftContent, ArticleContent, AssignmentContent]), will see if this is needed

        #assert str(content_id).isdigit(), debug_type(content_id)

        try:
            result = Session.query(Content).with_polymorphic('*').get(content_id) #Session.query(Content).with_polymorphic('*').filter_by(id=int(content_id)).one()
            #Session.expunge(result)
            return result
        except NoResultFound:
            return None  # used to have NoResultFound but didnt want a 500 error raised, the caller code can detect NONE and just say "not found" neatly

    cache      = _cache.get('content')
    cache_func = lambda: get_content_nocache(content)
    if cache:
        result = cache.get(key='content:%s' % content, createfunc=cache_func)
        #try:
            #Session.add(result)
            #return result
        #except InvalidRequestError:
            #log.warn('Content object already in session, but how do we get a reference to the exisitng object in the session?')
        return Session.merge(result, load=False)

    return cache_func()

def find_content_root(content):
    content = get_content(content)

    if not content:
        raise action_error(_('unable to find content'), code=404)

    if not content.parent:
        return False

    qry = Hierarchy(
        Session,
        Content.__table__,
        select([Content.__table__.c.id, Content.__table__.c.parent_id]),
        starting_node=content.id,
        return_leaf=True,
    ) # FIXME: Greg
    #print qry
    ev = Session.execute(qry).first()

    if ev:
        return get_content(ev.id) or False
    else:
        return False

def get_tag(tag):
    """
    Returns a tag object for the string passed to it
    If it does not appear in the database then return a new tag object
    If it does exisit in the data then return the database object
    """
    tag = tag.lower()
    try:
        return Session.query(Tag).filter_by(name=unicode(tag)).one()
    except NoResultFound as nrf:
        t = Tag(unicode(tag))
        Session.add(t)
        return t


import pandas
import base_helper
import global_vars

df = base_helper.read_csv()
summary_dict = {}

for index, row in df.iterrows():
    accounting_text = row[global_vars.column_accounting_text]
    # Check for blacklist entries, that should be ignored
    if any(accounting_text in item for item in global_vars.blacklist):
        continue
    # Check for cash withdrawal
    elif accounting_text == global_vars.withdrawal_text:
        name = "Cash withdrawal"
    else:
        name = row[global_vars.column_name_of_creditor_debtor]
    name = base_helper.format_name(name)  # format name in case of different spelling on multiple transfers
    # Get amount
    amount_string = row[global_vars.column_amount]
    amount = base_helper.convert_to_float(amount_string)
    # Build the dict
    summary_dict = base_helper.sum_dictionary(summary_dict, name, amount)

print(summary_dict)


"""
调用Worker的API
"""

import os, sys
from pathlib import Path
import requests

try:
    import yshs
except:
    here = Path(__file__).parent
    sys.path.append(str(here.parent.parent))
    import yshs

class ChatModel:

    @staticmethod
    def chat(model, messages=None, **kwargs):
        """Create a LLM instance.

        :param model: The model name.
        :param messages: The messages.
        :return: The LLM instance.
        """
        api_key = kwargs.pop("api_key", None)
        api_key = api_key or yshs.api_key

        url = kwargs.pop("url", None)
        if not url:
            host = kwargs.pop("host", "www.yshs.vip")
            port = kwargs.pop("port", None)
            if port is not None:
                url = f"http://{host}:{port}"
            else:
                url = f"https://{host}"

        data = dict()
        data['model'] = model
        data['messages'] = messages
        data['stream'] = kwargs.pop('stream', True)
        data.update(kwargs)

        assert api_key, """
The API-KEY is required. Please set the environment variable `YSHS_API_KEY` via `export YSHS_API_KEY=xxx`.
Alternatively, it can be provided by passing in the `api_key` parameter when calling the `chat` method.
"""
        session = requests.Session()
        response = session.post(
            # f'{url}/v1/chat/completions',
            f'{url}/v1/inference',
            headers={"Authorization": f"Bearer {api_key}"},
            json=data,
            stream=True,
            timeout=60,
            )
        # print(f'llm response: {response}')
        full_response = ""
        # return 'xx'
        # print('llm streaming:')
        for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
            if not chunk:
                continue
            chunk = chunk.decode('utf-8')
            if chunk == "[DONE]":
                break
            full_response += chunk
            # print(f'\r{full_response}', end='')
            yield chunk

        # print('\n')
        # print(f'full_response: {full_response}')
        # print(model, messages)

if __name__ == '__main__':
    import sys
    model = 'openai/gpt-3.5-turbo'
    api_key = os.getenv('YSHS_API_KEY')
    messages = [
        {'role': 'system', 'content': 'You are a bot.'},
        {'role': 'user', 'content': 'Hello, how are you?'}
    ]
    # messages = [
    #     {"role": "system", "content": 'Yo'},
    #     {"role": "user", "content": 'Hello'},
    #     ## 如果有多轮对话，可以继续添加，"role": "assistant", "content": "Hello there! How may I assist you today?"
    #     ## 如果有多轮对话，可以继续添加，"role": "user", "content": "I want to buy a car."
    # ]
    result =  ChatModel.chat(
        model,
        api_key=api_key,
        messages=messages,
        # host="aiapi.ihep.ac.cn", port=42901,
        )
    full_result = ""
    for i in result:
        full_result += i
        sys.stdout.write(i)
        sys.stdout.flush()
    print()


import turtle

tur=turtle.Turtle()
scr=turtle.Screen()
scr.bgcolor('black')
tur.pencolor('white')

x=0
y=0

tur.speed(0)
tur.penup()
tur.goto(0,200)
tur.pendown()

while True:

	tur.forward(x)
	tur.right(y)

	x +=3
	y +=1

turtle.done()


import pickle
import numpy as np
import os
import scipy
from Utilities import *
from Tokenizer_kit import *

'''
This module implements an alternate way of clipping, since we found chat speed to be unreliable.
It measures emotions within time intervals of the stream and clips based on how similar those emotions are.
'''

vod_chrono = 'data/teo7.pkl'
kv_path = 'data/teo.pkl'

# compute magnitude of numpy vector
def Magnitude_of(vector:np.ndarray):
    assert len(vector.shape)==1, "passed a multi-dimention vector"
    return np.sqrt(vector.dot(vector))

# Normalize a vector to be magnitude of 1
def Normalize_vector(vector:np.ndarray) -> np.ndarray:
    ''' This function normalize the passed vector to have magnitude of 1'''
    return vector/(Magnitude_of(vector)+np.finfo(dtype=np.float32).eps)

# Turns a list of tokens into a normalized vector
def Token_list_to_vec(token_list:list, kv:dict) -> np.ndarray:
    to_return = np.zeros(300, dtype=np.float32)
    for token in token_list:
        to_return = to_return + kv.get(token,np.zeros(300,dtype=np.float32))
    to_return = Normalize_vector(to_return)
    return to_return

with open(vod_chrono,'rb') as f:
    data = pickle.load(f)

with open(kv_path, 'rb') as f:
    kv = pickle.load(f)

interval = data[1][0]-data[0][0]
vod_duration = data[-1][0]-data[0][0]
vod_intervals = np.zeros(len(data), dtype=np.float32)
print(f"processing data")
chats = [i[1] for i in data]
for i in range(len(chats)):
    c = chats[i].split(os.linesep)[1:]
    if len(c)<6:
        vod_intervals[i]=0
        i+=1
        continue
    c = [Token_list_to_vec(Embedding_tokenize(s), kv) for s in c]
    c = np.array(c)
    mean = np.mean(c,axis=0)
    mean = mean/np.linalg.norm(mean)
    c = c-mean
    c = np.mean(np.linalg.norm(c,axis=1))
    if c>0.5:
        vod_intervals[i]=0
    else:
        vod_intervals[i]=1
    i+=1

mask = np.ones(2*interval,dtype=np.float32)
mask = mask/np.sum(mask)
assert np.abs(np.sum(mask)-1)<0.1
# print(f"prediction sum is [{np.sum(vod_intervals)}]/[{len(chats)}]")

vod_intervals = scipy.ndimage.correlate(vod_intervals,mask,mode='constant',cval=0)
vod_intervals = (vod_intervals>0.1)

clip_list = list()
ind = 0
start=0
end=0
clipping=False
print(f"clipping vod")
while ind<vod_intervals.shape[0]:
    if not(clipping or vod_intervals[ind]):
        pass
    elif not(clipping) and vod_intervals[ind]:
        clipping=True
        start=ind*interval
    elif clipping and not(vod_intervals[ind]):
        clipping=False
        end=ind*interval
        clip_list.append((int(start),int(end)))

    ind+=1

results=list()
first=True
start=0
end=-1
clip_list = [(i[0]-20,i[1]+20) for i in clip_list]
for interval in clip_list:
    if interval[0]<=end:
        end=results[-1][1]=interval[1]
        continue
    else:
        start=interval[0]
        end=interval[1]
        clip=[int(start),int(end)]
        results.append(clip)
        continue

print(f"clip for file [{vod_chrono}]")
print(f"number of clips found: [{len(results)}]")
total_time=0
for i,interval in enumerate(results):
    if interval[1]-interval[0]>180:
        continue
    print(f"Clip number [{i+1}] is: [{time_to_str(interval[0])}] -> [{time_to_str(interval[1])}]")
    total_time+=(interval[1]-interval[0])

print(f"total time to edit is [{time_to_str(total_time)}]")
print(f"original vod duration is [{time_to_str(vod_duration)}]")


class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        queue = [[root, 1]]

        while queue:
            node, depth = queue.pop(0)
            if not node:
                continue

            if not node.left and not node.right:
                return depth

            queue.append([node.left, depth + 1])
            queue.append([node.right, depth + 1])

        return 0


class Produto:

    def __init__(self, nome, preco, quantidade):
        self.nome = nome
        self.preco = preco
        self.quantidade = quantidade

    def calcular_total(self):
        valor = self.preco * self.quantidade
        return print(f'o produto: {self.nome} custa R${valor}')

produto = Produto('crack', 15, 3)
produto.calcular_total()


#!/usr/bin/python3

import os
import sys
import re
import json
import requests
import argparse
import tldextract
from colored import fg, bg, attr

w_blacklist = [ 'privacy', 'redacted', 'destination', 'dnstination', 'west', 'select request email', 'markmonitor' ]

# https://twitter.com/intigriti/status/1639610098954932225
def searchDomainBuiltwith( _domain ):
    global _verbose, t_data

    if _verbose:
        sys.stdout.write( '%s[+] calling builtwith targeting domain%s\n' % (fg('green'),attr(0)) )

    try:
        url = 'https://builtwith.com/relationships/'+_domain
        r = requests.get( url )
    except Exception as e:
        sys.stdout.write( "%s[-] error occurred: %s%s\n" % (fg('red'),e,attr(0)) )
        return

    rgxp = r'("https://builtwith.com/relationships/[^"]+)'
    matches = re.findall( rgxp, r.text, re.IGNORECASE )

    if matches:
        for m in matches:
            if not '/tag/' in m:
                domain = m.replace('https://builtwith.com/relationships/','').replace('"','')
                domain = domain.lower()
                if not domain in t_data['domains']:
                    t_data['domains'].append( domain )
                    print( domain )

def searchDomainCrtsh( _domain ):
    global _verbose, t_data

    if _verbose:
        sys.stdout.write( '%s[+] calling crtsh targeting domain%s\n' % (fg('green'),attr(0)) )

    parse = tldextract.extract( _domain )
    # print(parse)
    url = 'https://crt.sh/?q=%25'+parse.domain+'%25&output=json'
    if _verbose:
        sys.stdout.write( '%s[+] %s%s\n' % (fg('white'),url,attr(0)) )

    try:
        r = requests.get( url )
        t_json = r.json()
        # print(t_json)
    except Exception as e:
        sys.stdout.write( "%s[-] error occurred: %s%s\n" % (fg('red'),e,attr(0)) )
        return

    # f = open("crtsh.json")
    # t_json = json.load(f)
    # f.close()

    for item in t_json:
        if 'common_name' in item:
            try:
                parse = tldextract.extract( item['common_name'] )
                domain = parse.domain + '.' + parse.suffix
                domain = domain.lower()
                if not domain in t_data['domains']:
                    t_data['domains'].append( domain )
                    print( domain )
            except Exception as e:
                pass

def searchCompanyWhoxy( _whoxy_key ):
    global _verbose, t_data

    if _verbose:
        sys.stdout.write( '%s[+] whoxy key found, calling whoxy api targeting company%s\n' % (fg('green'),attr(0)) )

    for company in t_data['companies']:
        page = 1
        company = company.replace( ' ', '+' )
        if _verbose:
            sys.stdout.write( '%s[+] search for company: %s%s\n' % (fg('green'),company,attr(0)) )

        while True:
            url = 'http://api.whoxy.com/?key='+_whoxy_key+'&reverse=whois&company='+company+'&mode=micro&page='+str(page)
            page = page + 1
            if _verbose:
                sys.stdout.write( '%s[+] %s%s\n' % (fg('white'),url,attr(0)) )

            try:
                r = requests.get( url )
                t_json = r.json()
                # print(t_json)
            except Exception as e:
                sys.stdout.write( "%s[-] error occurred: %s%s\n" % (fg('red'),e,attr(0)) )
                continue

            if 'search_result' in t_json and len(t_json['search_result']):
                for result in t_json['search_result']:
                    if not result['domain_name'] in t_data['domains']:
                        t_data['domains'].append( result['domain_name'] )
                        print( result['domain_name'] )
            else:
                break

def searchEmailWhoxy( _whoxy_key ):
    global _verbose, t_data

    if _verbose:
        sys.stdout.write( '%s[+] whoxy key found, calling whoxy api targeting email%s\n' % (fg('green'),attr(0)) )

    for email in t_data['emails']:
        page = 1
        if _verbose:
            sys.stdout.write( '%s[+] search for email: %s%s\n' % (fg('green'),email,attr(0)) )

        while True:
            url = 'http://api.whoxy.com/?key='+_whoxy_key+'&reverse=whois&email='+email+'&mode=micro&page='+str(page)
            page = page + 1
            if _verbose:
                sys.stdout.write( '%s[+] %s%s\n' % (fg('white'),url,attr(0)) )

            try:
                r = requests.get( url )
                t_json = r.json()
                # print(t_json)
            except Exception as e:
                sys.stdout.write( "%s[-] error occurred: %s%s\n" % (fg('red'),e,attr(0)) )
                continue

            if 'search_result' in t_json and len(t_json['search_result']):
                for result in t_json['search_result']:
                    if not result['domain_name'] in t_data['domains']:
                        t_data['domains'].append( result['domain_name'] )
                        print( result['domain_name'] )
            else:
                break

def searchDomainWhoxy( _domain, _whoxy_key ):
    global _verbose, t_data

    if _verbose:
        sys.stdout.write( '%s[+] whoxy key found, calling whoxy api targeting domain%s\n' % (fg('green'),attr(0)) )

    url = 'http://api.whoxy.com/?key='+_whoxy_key+'&whois='+_domain
    if _verbose:
        sys.stdout.write( '%s[+] %s%s\n' % (fg('white'),url,attr(0)) )

    try:
        r = requests.get( url )
        t_json = r.json()
        # print(t_json)
    except Exception as e:
        sys.stdout.write( "%s[-] error occurred: %s%s\n" % (fg('red'),e,attr(0)) )
        return

    extractDatasWhoxy( t_json )
    if _verbose:
        print(t_data['companies'])
        print(t_data['emails'])

def extractDatasWhoxy( t_json ):
    global _verbose, t_data

    for index in ['technical_contact','registrant_contact','administrative_contact']:
        if index in t_json:
            company,email = extractDataWhoxy( t_json, t_json[index] )
            if company and company not in t_data['companies']:
                t_data['companies'].append( company )
            if email and email not in t_data['emails']:
                t_data['emails'].append( email )

    return

def extractDataWhoxy( t_json, tab ):
    global _verbose, t_data

    if not 'company_name' in tab:
        company = False
    elif 'registrant_contact' in t_json and 'company_name' in t_json['registrant_contact']:
        company = t_json['registrant_contact']['company_name']
        for wbl in w_blacklist:
            if wbl in company.lower():
                company = False
                break
    else:
        company = False

    if not 'email_address' in tab:
        email = False
    elif 'registrant_contact' in t_json and 'email_address' in t_json['registrant_contact']:
        email = t_json['registrant_contact']['email_address']
        for wbl in w_blacklist:
            if wbl in email.lower():
                email = False
                break
    else:
        email = False

    return company,email

parser = argparse.ArgumentParser()
parser.add_argument( "-e","--email",help="email you are looking for (required or -d or -c)" )
parser.add_argument( "-b","--builtwith",help="use builtwith as an additional source", action="store_true" )
parser.add_argument( "-c","--company",help="company you are looking for (required or -d or -e)" )
parser.add_argument( "-d","--domain",help="domain you already know (required or -c)" )
parser.add_argument( "-k","--key",help="whoxy api key (required)" )
parser.add_argument( "-s","--source",help="list of sources separated by comma, available sources are: builtwith,crtsh,whoxy (default=whoxy)" )
parser.add_argument( "-v","--verbose",help="enable verbose mode, default off", action="store_true" )
parser.parse_args()
args = parser.parse_args()

t_data = { 'domains':[], 'companies':[], 'emails':[] }

if args.verbose:
    _verbose = True
else:
    _verbose = False

if args.company:
    t_data['companies'].append( args.company )

if args.email:
    t_data['emails'].append( args.email )

if args.domain:
    _domain = args.domain
else:
    _domain = False

if not _domain and not len(t_data['companies']) and not len(t_data['emails']):
    parser.error( 'domain or company or email required' )

if not args.source:
    t_sources = "whoxy"
else:
    t_sources = args.source.split(',')

if "whoxy" in t_sources:
    if args.key:
        _whoxy_key = args.key
    else:
        _whoxy_key =  os.getenv('WHOXY_KEY')
        if not _whoxy_key:
            _whoxy_key = ""

if _domain:
    if _verbose:
        sys.stdout.write( '%s[+] search for domain: %s%s\n' % (fg('green'),_domain,attr(0)) )

    if "crtsh" in t_sources:
        searchDomainCrtsh( _domain )

    if "builtwith" in t_sources:
        searchDomainBuiltwith( _domain )

    if "whoxy" in t_sources:
        if len(_whoxy_key):
            searchDomainWhoxy( _domain, _whoxy_key )

if "whoxy" in t_sources:
    if len(_whoxy_key) and len(t_data['companies']):
        searchCompanyWhoxy( _whoxy_key )

    if len(_whoxy_key) and len(t_data['emails']):
        searchEmailWhoxy( _whoxy_key )


from embedding_evaluation.evaluate_similarity import EvaluationSimilarity
from embedding_evaluation.evaluate_feature_norm import EvaluationFeatureNorm
from embedding_evaluation.evaluate_concreteness import EvaluationConcreteness
import json

class Evaluation:

    def __init__(self, vocab_path=None, entity_subset=None, vocab=None, eval_conc=True, benchmark_subset=False):
        self.sim = EvaluationSimilarity(entity_subset=entity_subset, benchmark_subset=benchmark_subset)

        self.eval_conc = eval_conc
        if self.eval_conc:
            self.conc = EvaluationConcreteness(entity_subset=None)

        self.fn = None
        if (vocab_path is not None) or (vocab is not None):
            self.fn = EvaluationFeatureNorm(entity_subset=entity_subset, vocab_path=vocab_path, vocab=vocab)

    def evaluate(self, my_embedding):
        results = {}
        results["similarity"] = self.sim.evaluate(my_embedding)

        if self.fn is not None:
            results["feature_norm"] = self.fn.evaluate(my_embedding)

        if self.eval_conc:
            results["concreteness"] = self.conc.evaluate(my_embedding)
        return results

    def evaluate_to_file(self, my_embedding, file_path=None):
        """ save results to a json """
        results = self.evaluate(my_embedding)
        self.save_to_file(results, file_path)

    def save_to_file(self, results, file_path=None):
        assert file_path is not None
        with open(file_path, "w") as fp:
            json.dump(results, fp, sort_keys=True, indent=4)


#!/usr/bin/env python
import sys
import unittest
import time
import rostest
import rospy
from  araig_msgs.msg import BoolStamped
import os

class TestFolderLogger(unittest.TestCase):

    def setUp(self):
        _pub_topic_start = '/test/start'
        _pub_topic_stop = '/test/stop'
        _pub_topic_success = '/test/test_succeeded'
        _pub_topic_fail = '/test/test_failed'

        rospy.init_node('test_folder_logger', anonymous=True)
        self.pub_start = rospy.Publisher(_pub_topic_start, BoolStamped, latch=True, queue_size=10)
        self.pub_stop = rospy.Publisher(_pub_topic_stop, BoolStamped, latch=True, queue_size=10)
        self.pub_success = rospy.Publisher(_pub_topic_success, BoolStamped, latch=True, queue_size=10)
        self.pub_fail = rospy.Publisher(_pub_topic_fail, BoolStamped, latch=True, queue_size=10)

        module = "/calculators"

        while (not rospy.has_param(module + "/robot_type") and \
            not rospy.has_param(module + "/test_type")):
            time.sleep(0.1)

        if (not rospy.has_param(module + "/dest_dir") or rospy.get_param(module + "/dest_dir") == "") :
            self.dest_dir = os.path.expanduser("~")
        else:
            self.dest_dir = rospy.get_param(module + "/dest_dir")

        self.robot_type = rospy.get_param(module + "/robot_type")
        self.test_type = rospy.get_param(module + "/test_type")

        self.i = 0

    def test_expected(self):
        print(self.robot_type)
        self.path = self.dest_dir + "/" + self.robot_type + "/" + self.test_type + "/"
        while self.i < 3:
            pub_msg = BoolStamped()
            pub_msg.header.stamp = rospy.Time.now()
            pub_msg.data = True
            self.pub_start.publish(pub_msg)

            rospy.sleep(3)
            if os.listdir(self.path):
                self.result = True
            else:
                self.result = False

            self.assertTrue(self.result, msg='there is no folder')

            rospy.sleep(2)
            pub_msg.header.stamp = rospy.Time.now()
            pub_msg.data = False
            self.pub_start.publish(pub_msg)

            rospy.sleep(1)
            pub_msg.header.stamp = rospy.Time.now()
            pub_msg.data = True
            self.pub_stop.publish(pub_msg)

            rospy.sleep(1)
            pub_msg.header.stamp = rospy.Time.now()
            pub_msg.data = False
            self.pub_stop.publish(pub_msg)

            rospy.sleep(1)
            pub_msg.header.stamp = rospy.Time.now()
            pub_msg.data = True
            self.pub_success.publish(pub_msg)

            rospy.sleep(3)
            for i in os.listdir(self.path):
                try:
                    os.rmdir(self.path + i)
                except:
                    files = os.listdir(self.path + i)
                    for f in files:
                        os.remove(os.path.join(self.path + i, f))
                        os.rmdir(self.path + i)
            self.i += 1

if __name__ == '__main__':
    pkg = 'araig_calculators'
    name = 'test_folder_bagger'
    rostest.rosrun(pkg, name, TestFolderLogger)


import argparse
import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
import nltk
import re
import os
import tarfile
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans,AgglomerativeClustering,DBSCAN
from sklearn.metrics import adjusted_mutual_info_score, adjusted_rand_score, completeness_score
import numpy as np
stopwords = set(stopwords.words('english'))

# Define function to preprocess text
def preprocess_text(text):
    # If the input is a dictionary, get the text content
    if isinstance(text, dict):
        text = text.get('content', '')

    # Convert byte-like object to string
    if isinstance(text, bytes):
        text = text.decode('utf-8')

    # Remove punctuation
    text = re.sub(r'[^\w\s]', '', text)
    # Convert to lowercase
    text = text.lower()
    # Split into words
    words = nltk.word_tokenize(text)
    # Remove stop words
    words = [word for word in words if word not in stopwords]
    # Stem words
    stemmer = PorterStemmer()
    words = [stemmer.stem(word) for word in words]
    # Return preprocessed text
    return ' '.join(words)

# Define function to represent documents as word frequency vectors
def create_word_frequency_vectors(docs):
    vectors=[]
    for doc in docs:
        doc=preprocess_text(doc)
        vectorizer = TfidfVectorizer()
        vectorizer.fit([doc])
        tfidf_vector = vectorizer.transform([doc])
        vectors.append(tfidf_vector)
        #print(tfidf_vector.toarray())
    return vectors

def cluster_news(ncluster,kmeans,whc,ac,dbscan):

    # open and read dataset
    # filename = "20_newsgroups.tar.gz"
    # tar = tarfile.open("20_newsgroups.tar.gz", "r:gz")
    # if not os.path.exists("20_newsgroups"):
    #     with tarfile.open(filename, "r:gz") as tar:
    #         tar.extractall()
    # #create array of strings where each string is a document
    # documents = []
    # newsgroup_names = os.listdir("20_newsgroups")
    # for newsgroup_name in newsgroup_names:
    #     newsgroup_path = os.path.join("20_newsgroups", newsgroup_name)
    #     if os.path.isdir(newsgroup_path):
    #         for filename in os.listdir(newsgroup_path):
    #             file_path = os.path.join(newsgroup_path, filename)
    #             with open(file_path, "r", encoding="ISO-8859-1") as f:
    #                 document = f.read()
    #                 documents.append(document)
    # tar.close()
    #create vectors

    documents=["The city was the administrative centre of Chernobyl Raion (district) from 1923. After the disaster, in 1988, the raion was dissolved and administration was transferred to the neighbouring Ivankiv Raion. The raion was abolished on 18 July 2020 as part of the administrative reform of Ukraine, which reduced the number of raions of Kyiv Oblast to seven. The area of Ivankiv Raion was merged into Vyshhorod Raion."]
    vectors = create_word_frequency_vectors(documents)

    arr=np.array(vectors)
    for k in ncluster:
        if (kmeans==True):
            kmeans = KMeans(k, random_state=0).fit(arr)
            predicted_k=kmeans.labels_
            print("Adjusted Mutual Information Score:") #{}".format(adjusted_mutual_info_score(true_labels, predicted_k)))
            print("Adjusted Random Score: ")#{}".format(adjusted_rand_score(true_labels, predicted_k))
            print("Completeness Score: ")#{}".format(completeness_score(true_labels, predicted_k))
        if (whc==True):
            ward=AgglomerativeClustering(k,linkage='ward').fit(arr)
            predicted_w=ward.labels_
            print("Adjusted Mutual Information Score:") #{}".format(adjusted_mutual_info_score(true_labels, predicted_w)))
            print("Adjusted Random Score: ")#{}".format(adjusted_rand_score(true_labels, predicted_w))
            print("Completeness Score: ")#{}".format(completeness_score(true_labels, predicted_w))
        if (ac==True):
            aggl=AgglomerativeClustering(k).fit(arr)
            predicted_a=aggl.labels_
            print("Adjusted Mutual Information Score:") #{}".format(adjusted_mutual_info_score(true_labels, predicted_a)))
            print("Adjusted Random Score: ")#{}".format(adjusted_rand_score(true_labels, predicted_a))
            print("Completeness Score: ")#{}".format(completeness_score(true_labels, predicted_a))
        if (dbscan==True):
            dbscan = DBSCAN(eps=0.5, min_samples=2).fit(arr)
            predicted_db=dbscan.labels_
            print("Adjusted Mutual Information Score:") #{}".format(adjusted_mutual_info_score(true_labels, predicted_db)))
            print("Adjusted Random Score: ")#{}".format(adjusted_rand_score(true_labels, predicted_db))
            print("Completeness Score: ")#{}".format(completeness_score(true_labels, predicted_db))

        print("Predicted kmeans labels: {}".format(predicted_k))
        print("Predicted ward labels: {}".format(predicted_w))
        print("Predicted agglomerative labels: {}".format(predicted_a))
        print("Predicted dbscan labels: {}".format(predicted_db))

    #calculate ground_truth labels for each,calculate and print them
    #ami = adjusted_mutual_info_score(true_labels, predicted_labels)
    #ars = adjusted_rand_score(true_labels, predicted_labels)
    #completeness = completeness_score(true_labels, predicted_labels)

parser = argparse.ArgumentParser()
parser.add_argument('--ncluster',type=int,nargs = '+',default=[20])
parser.add_argument('--kmeans', type=bool, default=True)
parser.add_argument('--whc', type=bool, default=False)
parser.add_argument('--ac', type=bool, default=False)
parser.add_argument('--dbscan',type=bool,default=False)
args = parser.parse_args()

cluster_news(args.ncluster,args.kmeans,args.whc,args.ac,args.dbscan)


import base64
import time
import pickle
from typing import Dict

from networking import DictServer

class GameServer:
  """ An example game server. Your game server should handle requests in a
      similar fashion to _handle_request.
  """
  def __init__(self, url, game):
    self._url = url
    self._game = game

  def run(self):
    self._server = DictServer(self._url)
    self.serve_until_exit_requested()
    self.close()

  def close(self):
    # hack: give some time for the client to close. otherwise tests hang
    time.sleep(0.1)
    self._server.close()

  def serve_until_exit_requested(self):
    done = False
    while not done:
      request = self._server.recv()
      response = self._handle_request(request)
      self._server.send(response)
      if request['type'] == 'exit':
        done = True

  def _handle_request(self, request: Dict):
    """ Handle a request from a game-playing agent """
    if request['type'] == 'apply_action':
      return self._handle_apply_action(request)
    if request['type'] == 'game_type':
      return self._handle_game_type()
    if request['type'] == 'game_info':
      return self._handle_game_info()
    if request['type'] == 'new_initial_state':
      return self._handle_new_initial_state()
    if request['type'] == 'exit':
      return self._handle_exit()
    raise RuntimeError(f'unknown request: {request["type"]}')

  def _handle_apply_action(self, request: Dict):
    state = pickle.loads(base64.b64decode(request['state_str']))
    state.apply_action(request['action'])
    return self._state_as_dict(state)

  def _state_as_dict(self, state):
    return {
      # state_str: A string that the server can use to rebuild the state.
      #            Clients need to store this for searching game graphs.
      'state_str': base64.b64encode(pickle.dumps(state)).decode('UTF-8'),
      'current_player': state.current_player(),
      'legal_actions': state.legal_actions(),
      'is_terminal': state.is_terminal(),
      'is_chance_node': state.is_chance_node(),
      'returns': state.returns(),
      'pretty_str': str(state)
    }

  def _handle_game_type(self):
    type = self._game.get_type()
    # see https://github.com/deepmind/open_spiel/blob/master/open_spiel/spiel.h
    # GameType for the values of these fields
    return {
      "short_name" : type.short_name,
      "long_name" : type.long_name,
      "dynamics" : type.dynamics.value,
      "chance_mode" : type.chance_mode.value,
      "information" : type.information.value,
      "utility" : type.utility.value,
      "reward_model" : type.reward_model.value,
      "max_num_players" : type.max_num_players,
      "min_num_players" : type.min_num_players,
      "provides_information_state_string" : type.provides_information_state_string,
      "provides_information_state_tensor" : type.provides_information_state_tensor,
      "provides_observation_string" : type.provides_observation_string,
      "provides_observation_tensor" : type.provides_observation_tensor,
      'parameter_specification' : type.parameter_specification
    }

  def _handle_game_info(self):
    return {
      'num_distinct_actions' : self._game.num_distinct_actions(),
      'max_chance_outcomes' : self._game.max_chance_outcomes(),
      'num_players' : self._game.num_players(),
      'min_utility' : self._game.min_utility(),
      'max_utility' : self._game.max_utility(),
      'utility_sum' : self._game.utility_sum(),
      'max_game_length' : self._game.max_game_length()
    }

  def _handle_new_initial_state(self):
    state = self._game.new_initial_state()
    return self._state_as_dict(state)

  def _handle_exit(self):
    return "bye!"


# CASE BUAT NILAI TRUE KURANG DARI 5 DAN LEBIH DARI 10
print(10*'=', 'CASE OR', 10*'=')
inputt = int(input('Masukkan angka kurang dari 5 atau lebih dari 10 : '))

kurang = inputt < 5

lebih = inputt > 10

benar = kurang or lebih

print('Nilai : ', benar)

# KESIMPULANNYA JIKA FALSE DIMULAI DARI ANGKA 5 - 10

# CASE MEMBUAT IRISAN 5 - 10
print(10*'=', 'CASE AND', 10*'=')

inputt = int(input('Masukkan angka antara 5 - 10 : '))

lebih = inputt >= 5

kurang = inputt <=10

benar = lebih and kurang

print('Nilai : ', benar)

# KESIMPULANNYA AKAN TRUE JIKA NILAI 5 - 10


from app import db
from app.models import User
from flask_login import current_user

def test():
    print(User.query.all())
    print(current_user.id)
    print(current_user.datapoints.all())
    return transform_datapoints(datapoints=current_user.datapoints.all(), field='weight')

def transform_datapoints(datapoints, field): # wie macht man das genereller?
    """ Transform the datapoint list into x and y data for the plotting."""
    x = []
    y = []
    for i in datapoints:
        x.append(i.timestamp)
        y.append(i.weight)
    return x, y


import logging

# Create and Configure Logger
logging.basicConfig(
    filename = 'app.log',
    format = '%(asctime)s %(message)s',
    filemode = 'a+'
)

# Create Logger Object
logger = logging.getLogger()

# Setting the threshold of logger to INFO
logger.setLevel(logging.INFO)


import pytest

from bs4 import BeautifulSoup
from datetime import datetime
from pathlib import Path

from ojd_daps.flows.extract.indeed import (
    get_indeed_details,
    indeed_detail_parser,
    regex_search,
)

PATH = Path(__file__).parent
EXAMPLE_QUERY = PATH / "resources" / "example_indeed_ad.html"
AD_CONTENT = open(EXAMPLE_QUERY, "r").read()
EXPECTED_DETAILS = {
    "id": "837b8affdf31b9e7",
    "data_source": "Indeed",
    "created": str(datetime.today().strftime("%Y-%m-%d")),
}

def test_get_indeed_details():
    ad_dict = get_indeed_details(AD_CONTENT)
    assert ad_dict["id"] == EXPECTED_DETAILS["id"]
    assert ad_dict["data_source"] == EXPECTED_DETAILS["data_source"]
    assert ad_dict["created"] == EXPECTED_DETAILS["created"]

def test_indeed_detail_parser():
    soup = BeautifulSoup(AD_CONTENT, "lxml")
    assert indeed_detail_parser(soup, "span", "icl-u-xs-mr--xs") == "£9 an hour"
    assert (
        indeed_detail_parser(
            soup, "span", "indeed-apply-widget", "data-indeed-apply-joburl"
        )
        == "https://www.indeed.co.uk/viewjob?jk=837b8affdf31b9e7"
    )

def test_regex_search():
    assert regex_search('"jobTitle":(.*?),', AD_CONTENT) == "Warehouse Labourer"


import sys

import pycommand

from cipg import versionStr
import cipg.core

def main():
    try:
        cmd = Command(sys.argv[1:])
        if cmd.error:
            print('error: {0}'.format(cmd.error))
            return 1
        else:
            return cmd.run()
    except KeyboardInterrupt:
        print('\ncipg successfully exited.')
        return 0

class Command(pycommand.CommandBase):
    '''Argument handler based on pycommand'''
    usagestr = 'Usage: cipg <options>'
    description = __doc__
    optionList = (
        ('help', ('h', False, 'show this help information')),
        ('version', ('', False, 'show version information')),
    )

    def run(self):
        '''Run from shell; main application program flow.'''

        # Flags that will print and exit
        if self.flags['help']:
            print(self.usage)
            return
        elif self.flags['version']:
            print(versionStr)
            return

        # Regular behaviour
        files = cipg.core.Files.walkdir('.')
        for fn in files:
            print(fn)

if __name__ == '__main__':
    sys.exit(main())


import copy
import json
import requests
import unittest
from test_base import BaseTest

class JobAPITest(BaseTest):

    ENDPOINT = 'api/jobs'
    CLIENT_ENDPOINT = 'api/clients'

    def _register_client(self, client):
        """Creates a new client and returns the expected object as a copy.
        """
        new_client = copy.deepcopy(client)
        client1_id = self.create_object(self.CLIENT_ENDPOINT, new_client)
        # Add the new id to the original description of client
        new_client['id'] = client1_id
        new_client['job_ids'] = []
        new_client['total_spend'] = 0
        return new_client

    def setUp(self):
        """We create two clients to use during all tests.
        """
        super(JobAPITest, self).setUp()
        self.client1 = self._register_client(self.valid_clients[0])
        self.client2 = self._register_client(self.valid_clients[1])

    def _register_job(self, job, client):
        """Creates a new job and returns the expected object as a copy.
        """
        new_job = copy.deepcopy(job)
        new_job['client_id'] = client['id']

        job1_id = self.create_object(self.ENDPOINT, new_job)
        # Add the new id to the original description of job
        new_job['id'] = job1_id
        return new_job

    def test_post_job(self):
        """
        Tests POST /api/jobs.
        Creates jobs @job1 and @job2, registers them by means
        of the endpoint, and finally checks if they are contained
        in your database by means of a GET.

        @job1 = { "title":"job1", "client_id": 1, "category_id":1,
                "preferred_expertise":"junior", "preferred_country":"AR",
                "hourly_price":40 }
        @job2 = { "title":"job2", "client_id": 2, "category_id":2,
                  "preferred_expertise":"junior", "preferred_country":"AR",
                  "hourly_price":40 }
        """
        job1 = self.valid_jobs[0]
        job2 = self.valid_jobs[1]

        new_job1 = self._register_job(job1, self.client1)
        self.check_get_api(self.ENDPOINT, new_job1)

        new_job2 = self._register_job(job2, self.client1)
        self.check_get_api(self.ENDPOINT,
                           new_job1)
        self.check_get_api(self.ENDPOINT,
                           new_job2)

    def test_post_job_key_id_error(self):
        """
        Tests POST /api/jobs.
        Creates a @job with an existing id and checks if a 400 response code
        is returned by the server.

        @job = { "id":10, "title":"job1", "category_id":1,
                 "client_id":1, "preferred_expertise":"junior",
                 "preferred_country":"AR", "hourly_price":40 }
        """
        registered_job = self._register_job(
            self.valid_jobs[0], self.client1)
        job = self.job_key_id_error
        job['id'] = registered_job['id']

        response = requests.post(self.BASE_API + self.ENDPOINT,
                                 data=json.dumps(job))

        self.assertEqual(400, response.status_code,
                         msg=(f'Able to register job with existing id '
                              f'Response code: {response.status_code}'))

    def test_post_job_no_category_error(self):
        """
        Tests POST /api/jobs.
        Creates a @job which contains a non existing category_id.
        Checks if a 400 response code is returned by the server.
        """
        non_existing_category_id = len(self.categories) + 1

        job = self.valid_jobs[1]
        job['category_id'] = non_existing_category_id
        response = requests.post(self.BASE_API + self.ENDPOINT,
                                 data=json.dumps(job))
        self.assertEqual(400, response.status_code,
                         msg=(f'Able to register job with non existing category_id '
                              f'Response code: {response.status_code}'))

    def test_post_job_no_client_error(self):
        """
        Tests POST /api/jobs.
        Creates a @job which contains a non existing client_id.
        Checks if a 400 response code is returned by the server.
        """
        client_id = self.create_object('api/clients', self.valid_clients[0])
        non_existing_client_id = client_id + 1
        job = self.valid_jobs[0]
        job['client_id'] = non_existing_client_id

        response = requests.post(self.BASE_API + self.ENDPOINT,
                                 data=json.dumps(job))
        self.assertEqual(400, response.status_code,
                         msg=(f'Able to register job with non existing client_id'
                              f'Response code: {response.status_code}'))

    def test_get_jobs(self):
        """
        Tests GET /api/jobs
        Creates a few jobs and as they are created calls the get
        endpoint with the same object to check if it returns it correctly.
        """

        for job in self.valid_jobs:
            registered_job = self._register_job(job, self.client1)
            self.check_get_api(self.ENDPOINT, registered_job)

    def test_get_filtered_jobs(self):
        """
        Tests GET api/jobs/ (filter)
        Registers @job1 and @job2, and requests them and requests all
        the jobs that hold the following conditions:

        {'preferred_country': 'AR'}
        {'preferred_country': 'AR', 'category_id': 1, 'hourly_price': 40}

        Checks if they actually hold the condition and
        if the response contains the expected jobs.

        @job1 = { "title":"job1", "client_id": 1,
                  "category_id":1, "preferred_expertise":"junior",
                  "preferred_country":"AR", "hourly_price":40}
        @job2 = { "title":"job2", "client_id": 2, "category_id":2,
                  "preferred_expertise":"junior", "preferred_country":"AR",
                  "hourly_price":40}
        """
        job1 = copy.deepcopy(self.valid_jobs[0])
        job1['hourly_price'] = 100
        registered_job1 = self._register_job(job1, self.client1)
        registered_job2 = self._register_job(
            self.valid_jobs[1], self.client1)
        registered_job1['preferred_country'] = 'AR'
        registered_job2['preferred_country'] = 'AR'

        condition = {'preferred_country': 'AR'}

        self.check_get_api_filter([registered_job1, registered_job2],
                                  self.ENDPOINT, condition)

        condition = {'preferred_country': 'AR',
                     'category_id': registered_job1['category_id'],
                     'hourly_price': registered_job1['hourly_price']}

        self.check_get_api_filter([registered_job1], self.ENDPOINT, condition)

    def test_list_clients_with_jobs(self):
        client1 = self._register_client(self.valid_clients[0])
        self.check_get_api(self.CLIENT_ENDPOINT, client1)

        job1 = self.valid_jobs[0]
        new_job1 = self._register_job(job1, client1)

        client1['job_ids'] = [new_job1['id']]
        client1_id = client1['id']
        self.check_get_api_id(f'{self.CLIENT_ENDPOINT}/{client1_id}', client1)

if __name__ == '__main__':
    unittest.main()


from azure.servicebus import ServiceBusService, Message, Queue

# Create ServiceBus client.
queue_client = ServiceBusService(
    # The name you assign to your servicebus instance during creation.
    service_namespace='<YOUR-SERVICEBUS-NAMESPACE>',
    # You can have multiple named keys, this parameter if the name of the key.
    # The value below is the name of the default key.
    # This can be found on the portal.
    shared_access_key_name='RootManageSharedAccessKey',
    # The key's value.
    # This can be found on the portal.
    shared_access_key_value='<YOUR-KEY>')

# The name we gave to our queue
queue_name = "<YOUR-SERVICEBUS-QUEUE-NAME>"

# You can create a queue from the portal or programmatically
def createQueue(queue_name):
    # Create Queue
    queue_options = Queue()

    # A queue can have a max size of 5GB.
    # i.e. the total size of messages we didn't consume cannot exceed 5GB.
    queue_options.max_size_in_megabytes = '5120'

    # Message time to live determines how long a message will stay in the queue before it expires and is removed or dead lettered.
    # Defaults to 14 days
    queue_options.default_message_time_to_live = 'PT1M'

    queue_client.create_queue(queue_name, queue_options)

def sendMessage(message):
    msg = Message(message)
    queue_client.send_queue_message(queue_name, msg)

def receiveMessage():
    # Receive message from queue. The message is removed from queue automatically.
    msg = queue_client.receive_queue_message(queue_name, peek_lock=False)
    print(msg.body)

def receiveMessageWithPeekLock():
    # Receive the message with peek lock enabled.
    msg = queue_client.receive_queue_message(queue_name, peek_lock=True)
    print(msg.body)

    # Remove the message from queue. If we didn't call this, the message would be released
    # back to the queue after the lock period. The lock period defaults to 30 seconds but
    # can be configured during queue creation to between 1 second and 5 minutes.
    msg.delete()

receiveMessage()


import pygame
import random
import math
from pygame import mixer

pygame.init()  # ahora ya podemos usar los recursos de la libreria
pantalla = pygame.display.set_mode(
    (800, 600)
)  # se crea la pantalla y su tamaño alto y ancho

# Titulo de ventana- FLATICON para descargar iconocs 32 pixeles recomendados
pygame.display.set_caption("INVASION ESPACIAL")
icono = pygame.image.load(
    "C:\\Users\\julio\\OneDrive\\Documentos\\Cesar\\Cursopython\\Python\\Dia10\\Iconos\\ovni.png"
)
# Asigna icono
pygame.display.set_icon(icono)
fondo = pygame.image.load(
    "C:\\Users\\julio\\OneDrive\\Documentos\\Cesar\\Cursopython\\Python\\Dia10\\Iconos\\fondo.jpg"
)

# Agregar musica
mixer.music.load(
    "C:\\Users\\julio\\OneDrive\\Documentos\\Cesar\\Cursopython\\Python\\Dia10\\Iconos\\MusicaFondo.mp3"
)
mixer.music.set_volume(1)  # volumen va de o a 1
mixer.music.play(-1)  # repetir cada vez que termina

# Jugador
ima_jugador = pygame.image.load(
    "C:\\Users\\julio\\OneDrive\\Documentos\\Cesar\\Cursopython\\Python\\Dia10\\Iconos\\astronave.png"
)
jugador_x = 368
jugador_y = 500
jugador_cambioX = 0
jugador_cambioy = 0

# Enemigo
ima_enemigo = []
enemigo_x = []
enemigo_y = []
enemigo_cambioX = []
enemigo_cambioy = []
cantidad_enemigos = 10
for e in range(cantidad_enemigos):
    ima_enemigo.append(
        pygame.image.load(
            "C:\\Users\\julio\\OneDrive\\Documentos\\Cesar\\Cursopython\\Python\\Dia10\\Iconos\\nave-espacial.png"
        )
    )
    enemigo_x.append(random.randint(0, 736))
    enemigo_y.append(random.randint(0, 200))
    enemigo_cambioX.append(2)
    enemigo_cambioy.append(50)

# bala
ima_bala = pygame.image.load(
    "C:\\Users\\julio\\OneDrive\\Documentos\\Cesar\\Cursopython\\Python\\Dia10\\Iconos\\bala.png"
)
bala_x = 0
bala_y = 500
bala_cambioX = 0
bala_cambioy = 5
bala_visible = False

# puntaje
puntaje = 0
fuente = pygame.font.Font(
    "C:\\Users\\julio\\OneDrive\\Documentos\\Cesar\\Cursopython\\Python\\Dia10\\Iconos\\CollegiateOutlineFLF.ttf",
    30,
)  # fuente
# Descargar fuentes https://www.1001freefonts.com/
texto_x = 10
texto_y = 10

# texto final
fuente_final = pygame.font.Font(
    "C:\\Users\\julio\\OneDrive\\Documentos\\Cesar\\Cursopython\\Python\\Dia10\\Iconos\\CollegiateFLF.ttf",
    40,
)

def texto_final():
    mi_fuente_final = fuente_final.render("JUEGO TERMINADO", True, (68, 68, 68))
    pantalla.blit(mi_fuente_final, (200, 200))

# funcion que muestra el puntaje
def mostrar_puntaje(x, y):
    texto = fuente.render(f"Puntaje: {puntaje}", True, (68, 68, 68))
    pantalla.blit(texto, (x, y))

# Funcion que inicializa el movimiento
def jugador(x, y):
    pantalla.blit(ima_jugador, (x, y))

def enemigo(x, y, ene):
    pantalla.blit(ima_enemigo[ene], (x, y))

# funcion disparar bala
def bala(x, y):
    global bala_visible
    bala_visible = True
    pantalla.blit(ima_bala, (x + 22, y + 10))

# Detectar colision
def hay_colision(x1, y1, x2, y2):
    distancia = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y2 - y1, 2))
    if distancia < 27:
        return True
    else:
        return False

# Este codigo muestra la pantalla y la mantiene hasta que la cerramos X =pygame.QUIT
se_ejecuta = True
while se_ejecuta == True:
    # pantalla.fill((9, 49, 118))  # RGB Color en pagina https://www.colorspire.com/rgb-color-wheel/
    # h www.freepik. para buscar fondos
    # Fondo de pantalla imagen
    pantalla.blit(fondo, (0, 0))  # imagen y ubicacion

    # Eventos iterar
    for evento in pygame.event.get():
        # Evento Cerrar
        if evento.type == pygame.QUIT:  # cierra la pantalla
            se_ejecuta = False

        # Evento de movimiento
        if evento.type == pygame.KEYDOWN:  # Presiona boton
            if evento.key == pygame.K_LEFT:
                jugador_cambioX = -0.6
            if evento.key == pygame.K_RIGHT:
                jugador_cambioX = +0.6
            if evento.key == pygame.K_SPACE:
                # sonido de disparo
                sonido_bala = mixer.Sound(
                    "C:\\Users\\julio\\OneDrive\\Documentos\\Cesar\\Cursopython\\Python\\Dia10\\Iconos\\disparo.mp3"
                )
                sonido_bala.play()
                if not bala_visible:
                    bala_x = jugador_x
                    bala(bala_x, bala_y)

        # detener movimiento
        if evento.type == pygame.KEYUP:  # Suelta el boton
            if evento.key == pygame.K_LEFT:
                jugador_cambioX = 0
            if evento.key == pygame.K_RIGHT:
                jugador_cambioX = 0

    # Actualizar jugador
    jugador_x += jugador_cambioX  # Asignar nuevo movimiento
    # Mantener dentro de los bordes jugador
    if jugador_x <= 0:
        jugador_x = 0
    elif jugador_x >= 736:
        jugador_x = 736

    # jugador(jugador_x,jugador_y)
    # enemigo(enemigo_x[e],enemigo_y[e])

    # Actualizar enemigo
    for e in range(cantidad_enemigos):
        # Fin del juego
        if enemigo_y[e] > 500:
            for k in range(cantidad_enemigos):
                enemigo_y[k] = 1000
                texto_final()
            break

        enemigo_x[e] += enemigo_cambioX[e]  # Asignar nuevo movimiento

        # Mantener dentro de los bordes enemigo
        if enemigo_x[e] <= 0:
            enemigo_cambioX[e] = 2
            enemigo_y[e] += enemigo_cambioy[e]
        elif enemigo_x[e] >= 736:
            enemigo_cambioX[e] = -2
            enemigo_y[e] += enemigo_cambioy[e]

        # Verificar colision
        colision = hay_colision(enemigo_x[e], enemigo_y[e], bala_x, bala_y)
        if colision == True:
            sonido_colision = mixer.Sound(
                "C:\\Users\\julio\\OneDrive\\Documentos\\Cesar\\Cursopython\\Python\\Dia10\\Iconos\\mi_explosion_03_hpx.mp3"
            )
            sonido_colision.play()
            bala_y = 500
            bala_visible = False
            puntaje += 1
            enemigo_x[e] = random.randint(0, 736)
            enemigo_y[e] = random.randint(0, 200)
        enemigo(enemigo_x[e], enemigo_y[e], e)

    # movimiento bala
    if bala_y <= -64:
        bala_y = 500
        bala_visible = False

    if bala_visible:
        bala(bala_x, bala_y)
        bala_y -= bala_cambioy

    jugador(jugador_x, jugador_y)

    mostrar_puntaje(texto_x, texto_y)

    # Actualiza la pantalla
    pygame.display.update()  # actualizamos diplayt


from lib.src.domain.image_resizer import (
    MagickProgram,
    ConvertCommand,
    ResizeOption,
)

def test_build_magick_program():
    resize = ResizeOption(200, 200)
    command = ConvertCommand("images/image.png", "scaled_image", options=[resize])
    magick = MagickProgram(command=command)

    assert magick.get_program_name() == "magick"
    assert magick.get_command() == command
    assert magick.get_command().get_command_name() == "convert"
    options = magick.get_command().get_options()
    assert len(options) == 1
    option = options[0]
    assert option == resize
    assert option.get_option_name() == "resize"


from internal.tests.base_test import BaseAPITestCase, BaseProvider
from library.models import (
    Artist,
    Song,
    SongTag,
    SongWorkLink,
    Work,
    WorkAlternativeTitle,
    WorkType,
)

class LibraryProvider(BaseProvider):
    """Provides helper functions for library tests."""

    def create_test_data(self):
        """Populate the library with dummy data."""
        # Create work types
        self.wt1 = WorkType(
            name="WorkType1", name_plural="WorkTypes1", query_name="wt1"
        )
        self.wt1.save()
        self.wt2 = WorkType(name="WorkType2", query_name="wt2")
        self.wt2.save()

        # Create works
        self.work1 = Work(title="Work1", work_type=self.wt1)
        self.work1.save()
        self.work2 = Work(title="Work2", work_type=self.wt1)
        self.work2.save()
        self.work3 = Work(title="Work3", work_type=self.wt2)
        self.work3.save()

        # Create work titles
        WorkAlternativeTitle(title="AltTitle1", work=self.work1).save()
        WorkAlternativeTitle(title="AltTitle2", work=self.work1).save()
        WorkAlternativeTitle(title="AltTitle2", work=self.work2).save()

        # Create artists
        self.artist1 = Artist(name="Artist1")
        self.artist1.save()
        self.artist2 = Artist(name="Artist2")
        self.artist2.save()

        # Create song tags
        self.tag1 = SongTag(name="TAG1")
        self.tag1.save()
        self.tag2 = SongTag(name="TAG2")
        self.tag2.save()

        # Create songs

        # Song with no tag, artist or work
        self.song1 = Song(title="Song1", filename="file.mp4", directory="directory")

        self.song1.save()

        # Song associated with work, artist, tag and details
        self.song2 = Song(
            title="Song2",
            filename="file.mp4",
            version="Version2",
            detail="Detail2",
            detail_video="Detail_Video2",
            has_instrumental=True,
        )
        self.song2.save()
        self.song2.tags.add(self.tag1)
        self.song2.artists.add(self.artist1)
        SongWorkLink(
            song_id=self.song2.id, work_id=self.work1.id, link_type=SongWorkLink.OPENING
        ).save()

    def check_song_json(self, json, expected_song):
        """Method to test a song representation against the expected song."""
        self.assertEqual(json["id"], expected_song.id)
        self.assertEqual(json["title"], expected_song.title)
        self.assertEqual(json["filename"], expected_song.filename)
        self.assertEqual(json["directory"], expected_song.directory)
        self.assertEqual(json["version"], expected_song.version)
        self.assertEqual(json["detail"], expected_song.detail)
        self.assertEqual(json["detail_video"], expected_song.detail_video)
        self.assertEqual(json["has_instrumental"], expected_song.has_instrumental)

        # tags
        expected_tags = expected_song.tags.all()
        self.assertEqual(len(json["tags"]), len(expected_tags))
        for tag, expected_tag in zip(json["tags"], expected_tags):
            self.check_tag_json(tag, expected_tag)

        # artists
        expected_artists = expected_song.artists.all()
        self.assertEqual(len(json["artists"]), len(expected_artists))
        for artist, expected_artist in zip(json["artists"], expected_artists):
            self.check_artist_json(artist, expected_artist)

        # works
        expected_works = expected_song.songworklink_set.all()
        self.assertEqual(len(json["works"]), len(expected_works))
        for work, expected_work in zip(json["works"], expected_works):
            self.check_work_json(work["work"], expected_work.work)
            self.assertEqual(work["link_type"], expected_work.link_type)
            self.assertEqual(work["link_type_number"], expected_work.link_type_number)
            self.assertEqual(work["episodes"], expected_work.episodes)

    def check_tag_json(self, json, expected_tag):
        """Method to test an representation against the expected tag."""
        self.assertEqual(json["id"], expected_tag.id)
        self.assertEqual(json["name"], expected_tag.name)
        self.assertEqual(json["color_hue"], expected_tag.color_hue)
        self.assertEqual(json["disabled"], expected_tag.disabled)

    def check_artist_json(self, json, expected_artist):
        """Method to test an representation against the expected artist."""
        self.assertEqual(json["id"], expected_artist.id)
        self.assertEqual(json["name"], expected_artist.name)

    def check_work_json(self, json, expected_work):
        """Method to test an representation against the expected work."""
        self.assertEqual(json["id"], expected_work.id)
        self.assertEqual(json["title"], expected_work.title)
        self.assertEqual(json["subtitle"], expected_work.subtitle)
        self.check_work_type_json(json["work_type"], expected_work.work_type)
        # alternative titles
        expected_alt_titles = expected_work.alternative_titles.all()
        self.assertEqual(len(json["alternative_titles"]), len(expected_alt_titles))
        for alt_title, expected_alt_title in zip(
            json["alternative_titles"], expected_alt_titles
        ):
            self.assertEqual(alt_title["title"], expected_alt_title.title)

    def check_work_type_json(self, json, expected_work_type):
        """Method to test an representation against the expected work type."""
        self.assertEqual(json["name"], expected_work_type.name)
        self.assertEqual(json["name_plural"], expected_work_type.name_plural)
        self.assertEqual(json["query_name"], expected_work_type.query_name)
        self.assertEqual(json["icon_name"], expected_work_type.icon_name)

class LibraryAPITestCase(BaseAPITestCase, LibraryProvider):
    """Base library test class for Unittest."""


import cv2
import numpy as np
import os
from os.path import isfile, join
# pathIn= './best/results/' #NN out
# pathIn = './../GibData/depth_selection/image/val/'

def create(pathIn, pathOut):
    fps = 60
    frame_array = []
    files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]

    #for sorting the file names properly
    files.sort(key = lambda x: x[5:-4])
    files.sort()
    frame_array = []
    files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
    #for sorting the file names properly
    files.sort(key = lambda x: x[5:-4])
    for i in range(len(files)):
        filename=pathIn + files[i]
        # print("filename", filename)
        #reading each files
        img = cv2.imread(filename)

        height, width, layers = img.shape

        size = (width,height)

        #inserting the frames into an image array
        frame_array.append(img)
    # out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), fps, size)
    out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'MPEG'), fps, size)
    for i in range(len(frame_array)):
        # writing to a image array
        out.write(frame_array[i])
    out.release()

def depth_read(img, sparse_val):
    # loads depth map D from png file
    # and returns it as a numpy array,
    # for details see readme.txt
    depth_png = np.array(img, dtype=int)
    y = depth_png
    depth_png = (65535*((y - y.min())/y.ptp())).astype(np.uint16)
    depth_png = np.expand_dims(depth_png, axis=2)
    # make sure we have a proper 16bit depth map here.. not 8bit!
    assert(np.max(depth_png) > 255)
    depth = depth_png.astype(np.float) / 256.
    depth[depth_png == 0] = sparse_val
    return depth

pathIn, pathOut  = 'Gib4/depth_selection/image/val/', 'Gib3/v_image.mp4'
create(pathIn, pathOut)

pathIn, pathOut  = 'Gib4/depth_selection/groundtruth_depth/val/', 'Gib3/v_groundtruth_depth.mp4'
create(pathIn, pathOut)

pathIn, pathOut  = 'Gib4/depth_selection/velodyne_raw_depth/val/', 'Gib3/v_velodyne_raw_depth.mp4'
create(pathIn, pathOut)

# pathIn, pathOut  = 'Saved/best_sj/gib3_results/', 'Gib3/v_gib_results_sj.mp4'
# create(pathIn, pathOut)


# -----------------------------------------------------------------------------
# scanner.py
#
# Author: Ricardo Canales and Gabriel Berlanga
#
# The module contains lexical rules used by the parser.
# -----------------------------------------------------------------------------

reserved = {
    # Basic tokens
    'craft' : 'CRAFT',
    'var' : 'VAR',
    'true' : 'TRUE',
    'false' : 'FALSE',
    'and' : 'AND',
    'or' : 'OR',
    'input' : 'INPUT',
    'output' : 'OUTPUT',
    'outputln' : 'OUTPUTLN',

    # Functions tokens
    'return' : 'RETURN',
    'function' : 'FUNCTION',
    'void' : 'VOID',

    # Conditional tokens
    'if' : 'IF',
    'else' : 'ELSE',

    # Cycle tokens
    'while' : 'WHILE',
    'break' : 'BREAK',
    'continue' : 'CONTINUE',

    # Primitive types
    'int' : 'INT',
    'float' : 'FLOAT',
    'char' : 'CHAR',
    'bool' : 'BOOL',
    'string' : 'STRING'
}

tokens = [
    'CTE_INT',
    'CTE_FLOAT',
    'CTE_CHAR',
    'CTE_STRING',
    'ID',
    'EQ',
    'UNEQ',
    'LESS_EQ',
    'GREATER_EQ'
] + list(reserved.values())

# Regular expressions for tokens
t_EQ  = r'=='
t_UNEQ  = r'!='
t_GREATER_EQ  = r'>='
t_LESS_EQ  = r'<='
t_CTE_INT = r'\d+'
t_CTE_FLOAT = r'[-+]?[0-9]+\.[0-9]+([Ee][\+-]?[0-9+])?'
t_CTE_CHAR = r'\'(?:\\.|[^\'\\])\''
t_CTE_STRING = r'\"((?:\\.|[^"\\])*)\"'

# Literals
literals = [ '+','-','*','/', '%','=','(',')','{','}','[',']','<','>', ',']

# Regular expressions with action code

def t_ID(t):
    r'[a-zA-Z_][a-zA-Z_0-9]*'
    t.type = reserved.get(t.value,'ID')    # Check for reserved words
    return t

# Ignored characters (spaces and tabs)
t_ignore = " \t"

def t_COMMENT(t):
    r'\#.*'
    pass
    # No return value. Token discarded

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)


import torch.nn as nn
import torch

class TNet(nn.Module):
    def __init__(self, in_dim, hidden_dim):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(in_dim, hidden_dim), nn.ReLU(inplace=True),
            nn.Linear(hidden_dim, hidden_dim), nn.ReLU(inplace=True),
            nn.Linear(hidden_dim, 1)
        )

    def forward(self, x, z):
        x = torch.cat((x, z), dim=1)
        return self.net(x)

    # def forward(self, x):
    #     return self.net(x)


input_lines = open("input.txt", "r").read().split("\n")

# [horizontal, depth]
positioning = [0, 0]
aim = 0

for current_line in input_lines:
    command = current_line.split(" ")[0]
    instruction = int(" ".join(current_line.split(" ")[1::]))

    if command == "forward":
        positioning[0] += instruction
        positioning[1] += instruction * aim
    elif command == "down":
        aim += instruction
    elif command == "up":
        aim -= instruction

print(positioning[0] * positioning[1])


class Action(object):

    class Dialog(object):

        class Field(object):
            def __init__(self, *args, **kwargs):
                self.name = kwargs.get('name')
                self.disabled = kwargs.get('disabled', False)
                self.attr = None

            @classmethod
            def create(cls, *args, **kwargs):
                return cls(*args, **kwargs)

        def __init__(self, *args, **kwargs):
            self.fields = []
            for field in kwargs.get('fields'):
                self.fields.append(self.Field.create(**field))
            self.title = kwargs.get('title')

        @classmethod
        def create(cls, *args, **kwargs):
            return cls(*args, **kwargs)

    def __init__(self, *args, **kwargs):
        self.name = kwargs.get('name')
        self.display = kwargs.get('display')
        self._class = kwargs.get('class')
        self.type = kwargs.get('type')
        if self.type == 'dialog':
            self.dialog = self.Dialog.create(**kwargs.get('dialog'))

    @classmethod
    def create(cls, *args, **kwargs):
        return cls(*args, **kwargs)

    def load_model(self, model):
        for field in self.dialog.fields:
            for attr in model.attributes:
                if field.name == attr.name:
                    field.attr = attr

class Table(object):
    class Column(object):

        def __init__(self, *args, **kwargs):
            self.name = kwargs.get('name')
            self.display = kwargs.get('display')
            self.width = kwargs.get('width', 0)
            self.align = kwargs.get('align', '')
            self.templet = kwargs.get('templet', '')

        @classmethod
        def create(cls, *args, **kwargs):
            return cls(*args, **kwargs)

    def __init__(self, *args, **kwargs):
        self.columns = []
        for column in kwargs.get('columns', []):
            self.columns.append(self.Column.create(**column))
        self.actions = []
        for action in kwargs.get('actions'):
            self.actions.append(Action.create(**action))
        self.row_actions = []
        for action in kwargs.get('row_actions'):
            self.row_actions.append(Action.create(**action))

    @classmethod
    def create(cls, *args, **kwargs):
        return cls(*args, **kwargs)

class Attribute(object):
    class Option(object):
        def __init__(self, *args, **kwargs):
            self.display = kwargs.get('display')
            self.value = kwargs.get('value')

        @classmethod
        def create(cls, *args, **kwargs):
            return cls(*args, **kwargs)

    def __init__(self, *args, **kwargs):
        self.name = kwargs.get('name')
        self.display = kwargs.get('display')
        self.tag = kwargs.get('tag')
        if self.tag == 'select':
            self.options = []
            for option in kwargs.get('options'):
                self.options.append(self.Option.create(**option))

    @classmethod
    def create(cls, *args, **kwargs):
        return cls(*args, **kwargs)

class Model(object):
    def __init__(self, *args, **kwargs):
        self.name = kwargs.get('name')
        self.title = kwargs.get('title')
        self.attributes = []
        for attribute in kwargs.get('attributes', []):
            self.attributes.append(Attribute.create(**attribute))
        self.table = Table.create(**kwargs.get('table', {}))

    @classmethod
    def create(cls, *args, **kwargs):
        model = cls(*args, **kwargs)
        for action in model.table.actions:
            action.load_model(model)
        for action in model.table.row_actions:
            action.load_model(model)
        return model

def load_models():
    jiandan_ooxx_model = {
        'name': 'jiandan_ooxx',
        'title': '煎蛋图片',
        'attributes': [
            {'name': 'id', 'display': 'ID', 'tag': 'input'},
            {'name': 'url', 'display': '地址', 'tag': 'input'},
            {'name': 'status', 'display': '状态', 'tag': 'select',
                'options': [{'display': '新抓取', 'value': 'new'}, {'display': '已下载', 'value': 'download'}]},
            {'name': 'date', 'display': '日期', 'tag': 'input'},
        ],
        'table': {
            'columns': [
                {'name': 'id', 'display': 'ID', 'width': 80},
                {'name': 'url', 'display': '地址'},
                {'name': 'status', 'display': '状态', 'width': 80, 'align': 'center',
                 'templet': """ function(res) { if (res.status == 'download') { return '<i class="layui-icon layui-icon-ok-circle"></i>' }} """},
                {'name': 'date', 'display': '日期', 'width': 180}
            ],
            'actions': [
                {'name': 'create', 'display': '创建', 'type': 'dialog',
                 'dialog': {'title': '创建实例',
                            'fields': [{'name': 'id'}, {'name': 'url'}, {'name': 'status'}, {'name': 'date'}]
                            }
                },
                {'name': 'batch_delete', 'display': '批量删除', 'type': 'dialog', 'class': 'layui-btn-danger',
                 'dialog': {'title': '创建实例',
                            'fields': [{'name': 'id'}, {'name': 'url'}, {'name': 'status'}, {'name': 'date'}]
                            }
                }
            ],
            'row_actions': [
                {'name': 'view', 'display': '查看', 'type': 'dialog', 'class': 'layui-btn-primary',
                 'dialog': {'title': '创建实例',
                            'fields': [{'name': 'id', 'disabled': True},
                                       {'name': 'url', 'disabled': True},
                                       {'name': 'status', 'disabled': True},
                                       {'name': 'date', 'disabled': True}]
                            }
                 },
                {'name': 'edit', 'display': '编辑', 'type': 'dialog',
                 'dialog': {'title': '编辑实例',
                            'fields': [{'name': 'id', 'disabled': True},
                                       {'name': 'url'},
                                       {'name': 'status'},
                                       {'name': 'date'}]
                            }
                 },
                {'name': 'delete', 'display': '删除', 'type': 'dialog', 'class': 'layui-btn-danger',
                 'dialog': {'title': '删除实例',
                            'fields': [{'name': 'id', 'disabled': True},
                                       {'name': 'url', 'disabled': True},
                                       {'name': 'status', 'disabled': True},
                                       {'name': 'date', 'disabled': True}]
                            }
                 }
            ]
        }
    }

    models = [
        Model.create(**jiandan_ooxx_model)
    ]
    return models


from abc import abstractmethod
from string import Template
from typing import Protocol

from src.exceptions import NoTransactionsToPrint
from src.transaction import Transaction, Deposit, Withdraw

class StatementPrinter(Protocol):
    @abstractmethod
    def print(self, transactions: list[Transaction]) -> None:
        pass  # pragma: no cover

class ConsoleStatementPrinter(StatementPrinter):
    def print(self, transactions: list[Transaction]) -> None:
        self.__ensure_has_transactions(transactions)
        header = 'Date | Amount | Balance'
        transaction_template = Template('$date | $amount | $balance')
        transaction_statements = []
        running_balance = 0
        for _transaction in transactions:
            amount = -_transaction.amount if isinstance(_transaction, Withdraw) \
                else _transaction.amount
            running_balance = self.__calculate_running_balance(running_balance, _transaction)
            transaction_statements.append(transaction_template.safe_substitute(
                date=_transaction.date,
                amount=amount,
                balance=running_balance,
            ))
        transaction_statements.append(header)
        transaction_statements.reverse()

        print('\n'.join(transaction_statements))

    @staticmethod
    def __calculate_running_balance(running_balance: int, transaction: Transaction) -> int:
        if isinstance(transaction, Deposit):
            running_balance += transaction.amount
        else:
            running_balance -= transaction.amount
        return running_balance

    @staticmethod
    def __ensure_has_transactions(transactions: list[Transaction]) -> None:
        if len(transactions) == 0:
            raise NoTransactionsToPrint("No transactions to print")


from typing import Union, Optional
from nextcord.abc import GuildChannel
from nextcord.ext import commands
from nextcord import Guild, Member, User, Message, Role
from nextcord.ext import commands
from aiosqlite.core import Connection

class BotBaseBot(commands.Bot):
	db: Connection

	async def getch_guild(self, guild_id: int) -> Optional[Guild]:
		"""Looks up a guild in cache or fetches if not found."""
		guild: Union[Guild, None] = self.get_guild(guild_id)
		if guild:
			return guild

		try:
			guild: Union[Guild, None] = await self.fetch_guild(guild_id)
		except:
			return False
		return guild

	async def getch_role(self, guild_id: int, role_id: int) -> Optional[Role]:
		"""Looks up a guild in cache or fetches if not found."""
		guild: Optional[Guild] = self.getch_guild(guild_id)
		if not guild:
			return False
		role: Optional[Role] = guild.get_role(role_id)
		if role:
			return role
		else:
			try:
				role = await guild.fetch_role(role_id)
			except:
				return False
		return role

	async def getch_user(self, user_id: int) -> Optional[User]:
		"""Looks up a user in cache or fetches if not found."""
		user: Union[User, None] = self.get_user(user_id)
		if user:
			return user
		try:
			user: Union[User, None] = await self.fetch_user(user_id)
		except:
			return False
		return user

	async def getch_member(self, guild_id: int, member_id: int) -> Optional[Member]:
		"""Looks up a member in cache or fetches if not found."""

		guild: Union[Member, None] = await self.getch_guild(guild_id)
		if not guild:
			return False

		member: Union[Member, None] = guild.get_member(member_id)
		if member is not None:
			return member

		try:
			member: Union[Member, None] = await guild.fetch_member(member_id)
		except:
			return False

		return member

	async def getch_channel(self, channel_id: int) -> Optional[GuildChannel]:
		"""Looks up a channel in cache or fetches if not found."""
		channel: Union[GuildChannel, None] = self.get_channel(channel_id)
		if channel:
			return channel

		try:
			channel: Union[GuildChannel, None] = await self.fetch_channel(channel_id)
		except:
			return False

		return channel

	async def getch_message(self, channel_id: int, message_id: int) -> Optional[Message]:
		"""Looks up a channel in cache or fetches if not found."""
		channel = await self.getch_channel(channel_id)
		if not channel:
			return None

		try:
			message = await channel.fetch_message(message_id)
			return message
		except:
			return None

	async def resync_slash_commands(self) -> None:
		for app_cmd in self.get_all_application_commands():
			if not app_cmd.command_ids:
				if app_cmd.is_guild:
					for guild_id in app_cmd.guild_ids_to_rollout:
						guild = self.get_guild(guild_id)
						await guild.rollout_application_commands()


#Crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista composta. No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas de cada aluno individualmente.
aluno = []
notas = []
continua = ''
while True:
    nome = str(input('Nome:'))
    n1 = float(input('Nota 1: '))
    n2 = float(input('Nota 2: '))
    media = (n1 + n2) / 2
    aluno.append(nome)
    aluno.append(n1)
    aluno.append(n2)
    aluno.append(media)
    notas.append(aluno[:])
    aluno.clear()
    continua = str(input('Continua?[S/N] ')).upper().strip()[0]
    if continua in 'N':
        break
print('-=' * 20)
print(f'{"id":<4}{"Nome":<10}{"Média":>8}')
print('-' * 22)
for n, aluno in enumerate(notas):
    print(f'{n:<4}', end='')
    print(f'{aluno[0]:<10}', end='')
    print(f'{aluno[3]:>8}')
print('-' * 22)
while True:
    ver_notas = int(input('id Aluno:[999 para parar] '))
    if ver_notas == 999:
        break
    print(f'notas do aluno {notas[ver_notas][0]}: {notas[ver_notas][1:3]}')
    print('-' * 20)

Curso em Vídeo/089 Boletim com listas compostas.py


from src.plumberhub.Client import PlumberHubClient
import time

global cnt
cnt = 0

def p(sample):
    print(sample)

def p1(sample):
    global cnt
    cnt+=1
    if(cnt %100 == 0):
        print(cnt)

def onclose():
    print(88)

def onready():
    print('hello')

    device = client.get_device()
    gain = client.get_gain()
    sampling_rate = client.get_sampling_rate()

    print(device)
    print(gain)
    print(sampling_rate)

    time.sleep(10)
    client.start()

    master = client.is_master()
    print(master)

client = PlumberHubClient(
    hostname = '127.0.0.1',
    port = 8080,
    client_id = '0c3eb6949ed2368bf338e3ab08653621ff6f65564a306ddd8bf2966f1fecfa25',
    onsample = p1,
    onevent = p,
    onerror = p,
    onclose = onclose,
    onready = onready
)

time.sleep(2)
# client.set_gain(24)
newgain = client.get_gain()

print('\nnew gain:' + str(newgain) + '\n')

client.stop()
client.close()


from functools import reduce

class Category:
  ledger = None
  category = None
  balance = None

  def __init__(self, category):
    self.ledger = []
    self.balance = 0
    self.category = category

  def deposit(self, amount, description=''):

    self.ledger.append({
      'amount': amount,
      'description': description
    })

    # add new amount to balance
    self.balance += amount

  def withdraw(self, amount, description=''):

    # if not enough balance, do not add new transaction
    if not self.check_funds(amount):
      return False

    self.ledger.append({
      'amount': amount * -1,
      'description': description
    })
    # subtract new amount from balance
    self.balance -= amount
    return True

  def get_balance(self):
    return self.balance

  def transfer(self, amount, category):
    # ignore transfer if there are not enough foundings
    if not self.check_funds(amount):
      return False

    self.withdraw(amount, f"Transfer to {category.category}")
    category.deposit(amount, f"Transfer from {self.category}")

    return True

  def check_funds(self, amount):
    return self.get_balance() >= amount

  def __str__(self):
    resume = self.category.center(30, '*') + '\n'

    for transaction in self.ledger:
      description = transaction['description'][:23]
      amount = str("{:.2f}".format(transaction['amount'])).rjust(30 - len(description), ' ')
      resume += description + amount + '\n'

    total = f'Total: {self.get_balance()}'
    resume += total

    return resume

def _get_withdraw(total_wihdraw, transaction):
  amount = transaction['amount']
  if amount < 0:
    total_wihdraw += amount * -1
  return total_wihdraw

def create_spend_chart(categories):
    total_spendings = 0
    spendings_by_category = {}

    for category in categories:
      # retrieve only negative values
      total_spending_in_category = reduce(_get_withdraw, category.ledger, 0)
      spendings_by_category[category.category] = total_spending_in_category

      total_spendings += total_spending_in_category

    chart = 'Percentage spent by category\n'

    spendings = spendings_by_category.values()
    percentages = list(
      map(
        lambda value: value * 100 / total_spendings,
        spendings
      )
    )

    for percentage_indicator in range(100, -10, -10):
      indicator = str(percentage_indicator) + '|'
      chart += indicator.rjust(4)

      placeholder = ''
      for percentage in percentages:
        placeholder += 'o' if (percentage_indicator <= percentage) else ' '

      chart += ' ' + ('  '.join(list(placeholder))) + '  \n'

    indicator_sep = ' ' * 4
    divider =  indicator_sep + (('-' * 3) * len(spendings)) + '-'
    chart += divider + '\n'

    categories_names = spendings_by_category.keys()
    highest_category_name = max(map(len, categories_names))

    names_formatted = list(
        map(
          lambda c: list(c) if len(c) >= highest_category_name else list(c) + ([False] * (highest_category_name - len(c))),
      categories_names
    ))

    for index in range(0, highest_category_name):
      letter_line = ''

      for name in names_formatted:
        letter = name[index]
        letter_line += letter or ' '

      chart += indicator_sep + ' ' + ('  '.join(list(letter_line))) + '  \n'

    return chart[:len(chart)-1]

Scientific Computing with Python/Budget App/budget.py