# -*- coding:utf-8 -*-
import datetime
import time
import sys, os
import logging
import threading
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
try:
    import webapi.beluga_api as beluga_api
    import webapi.tell as tell
except ImportError:
    print("from __main__ start")

logger = logging.getLogger(__name__)

class Bot(threading.Thread):
    def __init__(self, name, password):
        threading.Thread.__init__(self)
        self._client = beluga_api.BelugaTool(name, password)
        self._reply_id_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "reply_id.txt")
        self._last_reply_id = 0
        try:
            with open(self._reply_id_file, 'r+') as f:
                for s in f:
                    self._last_reply_id = int(s)
        except FileNotFoundError:
            with open(self._reply_id_file, 'w') as f:
                logger.info('Can not open file %s', self._reply_id_file)

    def run(self):
        self.loop()

    def loop(self):
        while True:
            self._check_reply()
            time.sleep(10)

    def _check_reply(self):
        """ リプライで特定の文字に反応させる
        """
        reply_tws = self._client.get_mention_timeline(self._last_reply_id)
        for tw in reversed(reply_tws):
            # 前回取得したリプライよりも新規のリプライかチェック
            if tw.tweet_id > self._last_reply_id:
                if "best" in tw.text:
                    self._post_best_tweet(tw.screen_name)
                if "follow" in tw.text:
                    self._post_follow_info(tw.screen_name)
                if "fortune" in tw.text:
                    self._post_urani(tw)

                self._last_reply_id = tw.tweet_id

        if len(reply_tws) > 0:
            with open(self._reply_id_file, 'w') as f:
                f.write(str(self._last_reply_id))

    def _post_best_tweet(self, screen_name):
        """ いいね、ふぁぼ、それぞれの最多投稿をリプライ相手に飛ばす
            重い、連投されたら死ぬ　でもいいや
        """
        likes_t, favs_t, likes_num, favs_num = self._client.get_best_star_and_fav(screen_name)
        post_msg = "@{0} \n".format(screen_name)
        if likes_t:
            post_msg += "likes: {0} \n{{{1}}}\n".format(likes_t.likes_count, likes_t.tweet_id)
        else:
            post_msg += "likes not found.\n"

        if favs_t:
            post_msg += "favs: {0} \n{{{1}}}\n".format(favs_t.favorites_count, favs_t.tweet_id)
        else:
            post_msg += "favs not found.\n"

        post_msg += "\ntotal \nlikes :{0}  fav:{1}\n".format(likes_num, favs_num)

        self._client.update(post_msg)

    def _post_follow_info(self, screen_name):
        """ リプライ相手のフォロー関係を投稿
        """
        no_following_L, no_followed_L = self._client.get_follow_info(screen_name)

        post_msg = "@{0} \nフォローされていないユーザー\n".format(screen_name)
        for user in no_following_L:
            post_msg += user.screen_name + ", "

        post_msg += "\nフォローしていないユーザー\n".format(screen_name)
        for user in no_followed_L:
            post_msg += user.screen_name + ", "

        self._client.update(post_msg)

    def _post_urani(self, timeline):
        """ 占いを投稿
        """
        text = tell.getUranai(timeline.text)
        post_msg = "@{0} {1}".format(timeline.screen_name, text)
        self._client.update(post_msg)

if __name__ =="__main__":
    # debug用
    import sys, os
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    import webapi.beluga_api as beluga_api
    import webapi.tell as tell
    import settings

    b = Bot(settings.BELUGA_BOT_NAME, settings.BELUGA_BOT_PASSWORD)
    b.run()


import numpy as np
import pandas as pd
import streamlit as st
import plotly.graph_objects as go
import plotly.express as px
import seaborn as sns
import os

def data_visualization(side_bar_input):
    data = side_bar_input["data"]

    if data is not None:
        # Web App Title
        st.subheader("I. Dataset Visualization")
        st.set_option('deprecation.showPyplotGlobalUse', False)

        # EDA:

        # Part 1:
        st.markdown(f"
Dataset Information
", unsafe_allow_html=True)

        # Show Dataset:
        if st.checkbox("Preview Data", value=True):
            st.text("Head of dataset: ")
            st.write(data.head())
            st.text("Tail of dataset:")
            st.write(data.tail())

        # Dimensions:
        data_dim = st.radio("What dimension do you want to show ?", ('Rows', 'Columns'))
        if data_dim == 'Rows':
            st.write("The Length of Rows is:", len(data))
        if data_dim == 'Columns':
            st.write("The Length of Columns is :", data.shape[1])
        if st.checkbox("Show All Data"):
            st.dataframe(data)

        st.markdown("
", unsafe_allow_html=True)

        st.markdown(f"
Unidimensional analysis of variables
",
                    unsafe_allow_html=True)

        # Type of variable:
        # numeric_data = data.select_dtypes(include=[np.number])
        # categorical_data = data.select_dtypes(exclude=[np.number])

        numeric_data = side_bar_input["quantitative_variables"]
        categorical_data = side_bar_input["qualitative_variables"]

        col_quan, col_qual = st.columns(2)

        with col_quan:
            st.markdown("- Quantitative Variables:")
            st.write("Count : ", len(numeric_data))
            if st.button("Show Quantitative Features", disabled=False):
                st.write(numeric_data)

        with col_qual:
            st.markdown("- Qualitative Variables:")
            st.write("Count :", len(categorical_data))
            if st.button("Show Qualitative Features", disabled=False):
                st.write(categorical_data)

        # percentage of pie chart:
        labels = ['Quantitative variables', 'Qualitative variables']
        if numeric_data and categorical_data is not None:
            values = [len(numeric_data), len(categorical_data)]
        else :
            values = [1,1]
        fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.3, pull=[0, 0, 0.2, 0])])
        # st.header('Percentage')
        st.plotly_chart(fig)

        # Summary
        if st.checkbox("Show Summary of Quantitative Variables"):
            if numeric_data and categorical_data is not None:
                st.write(data.describe())
                option = st.selectbox(
                "Which column do you want to visualise as a boxplot?",
                numeric_data)
                fig = px.box(data, y=option)
                st.plotly_chart(fig, use_container_width=True)
            else:
                st.markdown(f"
Please select the quantitative variables in the left sidebar
",
                            unsafe_allow_html=True)

        """
       if st.checkbox("Show Summary of Qualitative Variables"):
           option = st.selectbox(
               "Which column would you like to visualise?",
               categorical_data)

           fig = px.bar(categorical_data,x=0)
           st.plotly_chart(fig,use_container_width=True)

           st.markdown("
", unsafe_allow_html=True)
        """

        # Two-dimension
        st.markdown("
", unsafe_allow_html=True)
        st.markdown(f"
 Two-dimensional analysis of variables
",
                    unsafe_allow_html=True)
        col_x, col_y = st.columns(2)
        with col_x:
            option_x = st.multiselect(
                'Select X axis',
                data.columns)
        with col_y:
            option_y = st.selectbox(
                'Select Y axis',
                data.columns)

        # scatter plot:
        if st.checkbox("Show the sactter plot"):
            fig = px.scatter(data, x=option_x, y=option_y)
            st.plotly_chart(fig)

        st.markdown("
", unsafe_allow_html=True)
        st.markdown(f"
 Missing Data Detection
",
                    unsafe_allow_html=True)

        st.markdown(f"
 The number of missing values in each column is :
", unsafe_allow_html=True)
        series_missing = (data == '?').astype(int).sum()
        st.write(series_missing.sum())
        if st.checkbox("Show the heatmap"):
            st.write(sns.heatmap(data == '?', cbar=False), weight=150, height=200)
            st.pyplot()


from __future__ import print_function
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *

ARP_REQUEST_THRESHOLD=1
ARP_RESPONSE_THRESHOLD=3

HELP="""
pip3 install scapy-python3
"""

class ArpFaker(object):
    @staticmethod
    def arp_request_trigger(pkt):
        msg = 'Request [who-has]: {} ({}) is asking ({}) about {} '.format(
                                                                pkt[ARP].psrc,
                                                                pkt[ARP].hwsrc,
                                                                pkt[ARP].hwdst,
                                                                pkt[ARP].pdst,
                                                                )
        print(msg)

    @staticmethod
    def arp_response_trigger(pkt):
        msg = '*Response [is-at]: {} ({}) has address {} ({})'.format(
                                                               pkt[ARP].pdst,
                                                               pkt[ARP].hwsrc,
                                                               pkt[ARP].psrc,
                                                               pkt[ARP].hwdst,
                                                               )
        print(msg)

    @classmethod
    def arp_filter(cls, pkt):
        if not pkt[ARP]: return False
        #~ print(pkt[ARP].__dict__)
        #~ for x,y in pkt[ARP].fields.items():
            #~ print(x, y)
        if pkt[ARP].op == 1:  # who-has (request)
            cls.arp_request_trigger(pkt)
        elif pkt[ARP].op == 2:  # is-at (response)
            cls.arp_response_trigger(pkt)

    @classmethod
    def arp_listen(cls, stype):
        if stype == 'request':
            req = sniff(prn=cls.arp_filter, filter='arp', store=0, count=ARP_REQUEST_THRESHOLD)
        elif stype == 'response':
            res = sniff(prn=cls.arp_filter, filter='arp', store=0, count=ARP_RESPONSE_THRESHOLD)

    @staticmethod
    def arp_reply(pkt):
        packet = Ether()/ARP(op="who-has",hwsrc=my_mac,psrc=sys.argv[2],pdst=sys.argv[1])

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()

    # By default it will fail with multiple arguments.
    parser.add_argument('--default')

    # This is the correct way to handle accepting multiple arguments.
    # '+' == 1 or more.
    # '*' == 0 or more.
    # '?' == 0 or 1.
    # An int is an explicit number of arguments to accept.
    parser.add_argument('-ip', nargs='+')
    parser.add_argument('-req', action="store_true", help="listen only for requests")
    parser.add_argument('-res', action="store_true", help="listen for requests and responses")
    #~ parser.add_argument('-h', action="store_true", required=0)
    args = parser.parse_args()

    #~ if args.h:
        #~ print(HELP)

    if args.ip:
        print(args.ip)

    if args.req:
        while 1:
            #~ try:
            res = ArpFaker.arp_listen('request')
            #~ except Exception as e: print(e)
    elif args.res:
        while 1:
            #~ try:
            res = ArpFaker.arp_listen('response')
            #~ except Exception as e: print(e)


from django.contrib.auth.models import User
from accounts.models import Profile
from datetime import datetime

print('cron page running......')

def registration_expiry_check():
    today = datetime.today()
    profiles = Profile.objects.filter(signup_confirmation=False)
    for p in profiles:
        print(p)
        print(p.user)
        expdate = p.expiration_date
        if expdate < today:
            p.user.delete()


import requests
from twilio.rest import Client

STOCK = "TSLA"
COMPANY_NAME = "Tesla Inc"
from datetime import datetime, timedelta
from bs4 import BeautifulSoup

# set twilio application (you must have to register first and use your individual identification)
phone_number = "TWILIO PHONE NUMBER"
account_sid = "YOUR ACCOUNT SID"
auth_token = "YOUR AUTH TOKEN"
client = Client(account_sid, auth_token)

# formatting the date
y_day = datetime.now() - timedelta(days=1)
yesterday = y_day.strftime('%Y-%m-%d')
y2_day = datetime.now() - timedelta(days=2)
before_yesterday = y2_day.strftime('%Y-%m-%d')

# tesla parameters
parameters = {
    "function": "TIME_SERIES_DAILY",
    "symbol": "TSLA",
    "apikey": "YOUR API HERE",
}

# query the data from yesterday and before yesterday
response = requests.get("https://www.alphavantage.co/query", params=parameters)
data = response.json()
yesterday_data = data['Time Series (Daily)'][yesterday]
before_yesterday_data = data['Time Series (Daily)'][before_yesterday]

# query the final data
stock_yesyerday = yesterday_data['4. close']
stock_before_yesyerday = before_yesterday_data['4. close']

# count the percentage
price_inc_or_dec = float(stock_before_yesyerday) * 100 / float(stock_yesyerday) - 100
percentage = (round(price_inc_or_dec))

# newsapi parameters
parameters_tesla = {
    "q": "tesla",
    "from": yesterday,
    "sortBy": "relevancy",
    "apiKey": "YOUR API KEY",
}

# query the information from newsapi website
response2 = requests.get("https://newsapi.org/v2/everything", params=parameters_tesla)
response2.raise_for_status()
tesla_news = response2.json()
title_list = []
description_list = []
#  the 3 most relecant news
for i in range(3):
    articles = tesla_news["articles"][i]["title"]
    title_list.append(articles)
    description = tesla_news["articles"][i]["description"]
    description_list.append(description)

# formatting
def remove_tags(html):
    # parse html content
    soup = BeautifulSoup(html, "html.parser")
    for data in soup(['style', 'script']):
        # Remove tags
        data.decompose()
    # return data by retrieving the tag content
    return ' '.join(soup.stripped_strings)

# examining the growth or fall
# sending sms about changes
if stock_yesyerday < stock_before_yesyerday:
    for i in range(3):
        client = Client(account_sid, auth_token)
        message = client.messages \
            .create(
            body=f"TSLA: ðŸ”»{percentage} %\nHeadline: {remove_tags(title_list[i])}\nBrief: {remove_tags(description_list[i])}",
            from_='TWILIO PHONE NUMBER',
            to='YOUR PHONE NUMBER'
        )
        print(message.status)
else:
    for i in range(3):
        client = Client(account_sid, auth_token)
        message = client.messages \
            .create(
            body=f"TSLA: ðŸ”º{percentage} %\nHeadline: {remove_tags(title_list[i])}\nBrief: {remove_tags(description_list[i])}",
            from_='TWILIO PHONE NUMBER',
            to='YOUR PHONE NUMBER'
        )
        print(message.status)


import sys

from loguru import logger
from web3 import Web3
from web3.middleware import geth_poa_middleware
from web3.gas_strategies.time_based import fast_gas_price_strategy

bsc_Urls = [
    "https://bsc-dataseed.binance.org/",
    "https://bsc-dataseed1.defibit.io/",
    "https://bsc-dataseed1.ninicoin.io/",
    "https://bsc.nodereal.io"
]
bsc = bsc_Urls[0]

VBNB_address = "0xA07c5b74C9B40447a954e1466938b865b6BBea36"

myAddress = "0xC61eb43D6A01a512491Ba08de74dB2D573f56c0b"
myKey = None
if len(sys.argv) > 1:
    myAddress = sys.argv[1]
if len(sys.argv) > 2:
    myKey = sys.argv[2]

def main():
    w3 = Web3(Web3.HTTPProvider(bsc))
    w3.middleware_onion.inject(geth_poa_middleware, layer=0)
    w3.eth.set_gas_price_strategy(fast_gas_price_strategy)

    abi = open("Venus_VBNB.abi").read()

    contractAddress = w3.toChecksumAddress(VBNB_address)
    contract = w3.eth.contract(address=contractAddress, abi=abi)

    # https://web3py.readthedocs.io/en/stable/web3.eth.account.html#sign-a-contract-transaction

    logger.debug(w3.eth.get_transaction_count(myAddress))

    def deposit(amount):
        nonce = w3.eth.get_transaction_count(myAddress)
        contract_txn = contract.functions.mint().buildTransaction({
            'value': amount,
            'chainId': 56,
            'gas': 1000000,
            'gasPrice': w3.toWei('5', 'gwei'),
            'nonce': nonce
        })
        recommended_gasPrice = w3.eth.generate_gas_price()
        contract_txn['gasPrice'] = recommended_gasPrice
        logger.debug(contract_txn) # data: 0x1249c58b
        if myKey:
            signed_txn = w3.eth.account.sign_transaction(contract_txn, myKey)
            logger.debug(signed_txn)
            tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
            logger.debug(tx_hash)

    def withdraw(amount):
        nonce = w3.eth.get_transaction_count(myAddress)
        contract_txn = contract.functions.redeemUnderlying(amount).buildTransaction({
            'value': 0,
            'chainId': 56,
            'gas': 1000000,
            'gasPrice': w3.toWei('5', 'gwei'),
            'nonce': nonce
        })
        recommended_gasPrice = w3.eth.generate_gas_price()
        contract_txn['gasPrice'] = recommended_gasPrice
        logger.debug(contract_txn) # data: 0x852a12e3000000000000000000000000000000000000000000000000016345785d8a0000
        if myKey:
            signed_txn = w3.eth.account.sign_transaction(contract_txn, myKey)
            logger.debug(signed_txn)
            tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
            logger.debug(tx_hash)

    amount = 100 * 1000 * 1000 * 1000 * 1000 * 1000
    deposit(amount) # https://bscscan.com/tx/0x39994af0328c3a00c221b229b3cd3c235176f088ed358d3ec8ac3b16092856f8
    withdraw(amount) # https://bscscan.com/tx/0xe99a2d22a6ba09d359a8cee76a31532835b07f8bd3675abafc27ea12edfb313b

if __name__ == '__main__':
    main()


"""
A module to pre-process and read knee x-rays

(c) Aleksei Tiulpin, University of Oulu, 2016-2018.

"""

import pydicom as dicom
import numpy as np
import cv2
import os

cv2.ocl.setUseOpenCL(False)
cv2.setNumThreads(0)
import scipy.ndimage

def resample(image, scan, new_spacing=[0.2, 0.2]):
    # Determine current pixel spacing
    spacing = map(float, (scan.PixelSpacing))
    spacing = np.array(list(spacing))

    resize_factor = spacing / new_spacing
    new_real_shape = image.shape * resize_factor
    new_shape = np.round(new_real_shape)
    real_resize_factor = new_shape / image.shape
    new_spacing = spacing / real_resize_factor

    image = scipy.ndimage.interpolation.zoom(image, real_resize_factor)

    return image, new_spacing

def read_dicom(filename):
    """
    Reads a dicom file

    Parameters
    ----------
    filename : str
        Full path to the image

    Returns
    -------
    out : tuple
        Image itself as uint16, spacing, and the DICOM metadata

    """

    try:
        data = dicom.read_file(filename)
    except:
        return None
    img = np.frombuffer(data.PixelData, dtype=np.uint16).copy().astype(np.float64)

    if data.PhotometricInterpretation == 'MONOCHROME1':
        img = img.max() - img
    try:
        img = img.reshape((data.Rows, data.Columns))
    except:
        return None

    try:
        if isinstance(data.ImagerPixelSpacing, str):
            data.ImagerPixelSpacing = data.ImagerPixelSpacing.split()
    except:
        pass

    try:
        if isinstance(data.PixelSpacing, str):
            data.PixelSpacing = data.PixelSpacing.split()
    except:
        pass

    try:
        return img, float(data.ImagerPixelSpacing[0]), data
    except:
        pass
    try:
        return img, float(data.PixelSpacing[0]), data
    except:
        return None

def process_xray(img, cut_min=5, cut_max=99, multiplier=255):
    """
    Processes an X-ray image by truncating the histogram and
    applying a global contrast normalization (GCN) to it.

    Parameters
    ----------
    img : ndarray
        Input image
    cut_min : int or float
        Lowest percentile to truncate the histogram.
    cut_max : in or float
        Highest percentile to truncate the histogram
    multiplier : a multiplication factor to use after GCN

    Returns
    -------
    out : ndarray
        A preprocessed image in np.float64.

    """
    # This function changes the histogram of the image by doing global contrast normalization
    # cut_min - lowest percentile which is used to cut the image histogram
    # cut_max - highest percentile

    img = img.copy().astype(np.float64)
    lim1, lim2 = np.percentile(img, [cut_min, cut_max])
    img[img < lim1] = lim1
    img[img > lim2] = lim2

    img -= lim1
    img /= img.max()
    img *= multiplier

    return img

def read_pts(fname):
    """
    Reads the points annotated using BineFinder.

    Parameters
    ----------
    fname : full path to the annotation

    Returns
    -------
    out : ndarray
        Nx2 ndarray of (x,y) landmark points

    """
    with open(fname) as f:
        content = f.read()
    arr = np.array(list(map(lambda x: [float(x.split()[0]), float(x.split()[1])], content.split('\n')[3:-2])))
    return arr

def f_2_b(img):
    """
    Converts a float [0..255] image into [0, 255] uint8.
    First teh function rounds the image and then clips it.

    Parameters
    ----------
    img : ndarray
        Input image

    Returns
    -------
    out : ndarray
        Results

    """
    img = np.round(img)
    img = np.clip(img, 0, 255)
    return img.astype(np.uint8)

def pad(img, padding):
    """
    Pads an image with zero padding from each side.

    Parameters
    ----------
    img : ndarray
        Input image
    padding : int
        Padding

    Returns
    -------
    out : ndarray
        Padded image

    """
    row, col = img.shape
    tmp = np.zeros((row + 2 * padding, col + 2 * padding), dtype=img.dtype)
    tmp[padding:padding + row, padding:padding + col] = img
    return tmp

def rotate(img, c, p1, p2):
    """
    Rotates an image around the point c without changing the size of the coordinate frame
    so that the line going through the points p1, p2 is horizontal.
    Used for teh alignment of tibial plateau.

    Parameters
    ----------
    img : ndarray
    c : tuple or or list or ndarray
        Center of rotation
    p1 : tuple or or list or ndarray
        First point on the line
    p2 : tuple or or list or ndarray
        Second point on teh line
    Returns
    -------
    out : tuple
        Image and the corresponding rotation matrix
    """
    # Based on https://www.pyimagesearch.com/2017/01/02/rotate-images-correctly-with-opencv-and-python/
    W = img.shape[0]
    ang = np.degrees(np.arctan2(p2[1] - p1[1], p2[0] - p1[0]))
    M = cv2.getRotationMatrix2D((c[0], c[1]), ang, 1)

    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])

    # compute the new bounding dimensions of the image
    nW = int((W * sin) + (W * cos))
    nH = int((W * cos) + (W * sin))

    img = cv2.warpAffine(img, M, (nW, nH), cv2.INTER_CUBIC)
    return img, M

def get_ost_jsw_patches(I, p1, p2, f_p1, f_p2, size_w, size_h, return_rects=False):
    """
    Cuts the medial and the lateral patches of size_h x size_w mm from the
    the knee image. The center of the patches will be the mean of tibial and the lateral landmarks.

    Parameters
    ----------
    I : ndarray
        Input image
    p1 : tuple or ndarray
        Tibal landmark (lateral)
    p2 : tuple or ndarray
        Tibial landmark (medial)
    f_p1 : tuple or ndarray
        Femoral landmark (lateral)
    f_p2 : tuple or ndarray
        Femoral landmark (medial)
    size_w : int
        Width in mm
    size_h : int
        Height in mm.
    return_rects : bool
        Whether to return bounding rects in the format (x0, y0, x1, y1) together with the images

    Returns
    -------
    out : tuple
        Tuple, which contains two images and their bounding boxes in the following format:
        image lateral, image medial, lateral rect, medial rect.
        If return_rects is False, then only the images are returned.

    """
    p1 = np.array([p1[0], (p1[1] + f_p1[1]) // 2])
    p2 = np.array([p2[0], (p2[1] + f_p2[1]) // 2])

    rect_l = [p1[0] - size_w // 2, p1[1] - size_h // 2, p1[0] + size_w // 2, p1[1] + size_h // 2]

    rect_m = [p2[0] - size_w // 2, p2[1] - size_h // 2, p2[0] + size_w // 2, p2[1] + size_h // 2]

    L = I[rect_l[1]:rect_l[3], rect_l[0]:rect_l[2]]
    M = I[rect_m[1]:rect_m[3], rect_m[0]:rect_m[2]]
    if return_rects:
        return L, M, rect_l, rect_m
    else:
        return L, M

def rotate_amir(coordinates, M):
    import pandas as pd
    list = []
    for i in range(len(coordinates)):
        dot = coordinates[i, :]
        dot = np.dot(M, np.array(dot.tolist() + [1])).astype(int)
        list.append(dot)
    output = np.vstack(list)

    return output

def extract_patches(I, landmarks, landmarks2, spacing, sizemm, o_sizemm_w, o_sizemm_h):
    """
    Extracts full images of left and right knees, as well as the side patches.
    Such patches are cropped for the exactly the same anatomical locations.

    Parameters
    ----------
    I : ndarray
        Input bilateral image
    spacing : float
        Image spacing
    sizemm : int
        Size of the ROI to crop (in mm)
    landmarks : dict
        Landmarks produced using Bone Finder and stored into dict per bone per knee.
    o_sizemm_w : int
        Width of the side osteophyte patch
    o_sizemm_h : int
        Width of the side osteophyte patch

    Returns
    -------
    out : tuple
        The result containes the tuple of dictionaries.
        One corresponds to the full image, then side patches and then
        the meta-information, which can be further used: bounding boxes and the rotation matrices.

    """
    # Width of the ROI
    W = int(sizemm / spacing)

    # size of the osteophyte patches in pixels
    o_size_w = int(o_sizemm_w / spacing)
    o_size_h = int(o_sizemm_h / spacing)

    # Getting the corner points from the landmarks
    p1r = landmarks['TR'][0, :].copy()
    p1l = landmarks['TL'][0, :].copy()

    p2r = landmarks['TR'][-1, :].copy()
    p2l = landmarks['TL'][-1, :].copy()

    f_p1r = landmarks['FR'][0, :].copy()
    f_p1l = landmarks['FL'][0, :].copy()

    f_p2r = landmarks['FR'][-1, :].copy()
    f_p2l = landmarks['FL'][-1, :].copy()

    # Determining the center of the joint using tibial landmarks
    Lcx, Lcy = landmarks['TL'][landmarks['TL'].shape[0] // 2, :].astype(int)
    Rcx, Rcy = landmarks['TR'][landmarks['TR'].shape[0] // 2, :].astype(int)

    # Defing the bounding boxes
    bboxR = [Rcx - W // 2, Rcy - W // 2, Rcx + W // 2, Rcy + W // 2]
    bboxL = [Lcx - W // 2, Lcy - W // 2, Lcx + W // 2, Lcy + W // 2]

    # Cropping the ROIs (left flipped)
    RR = I[bboxR[1]:bboxR[3], bboxR[0]:bboxR[2]]
    LL = cv2.flip(I[bboxL[1]:bboxL[3], bboxL[0]:bboxL[2]], 1)

    # Adjusting the points to the new coordinate frame,
    # which is within each bounding box.
    cr = np.array([Rcx, Rcy])
    cl = np.array([Lcx, Lcy])

    p1r -= bboxR[:2]
    p2r -= bboxR[:2]
    p1l -= bboxL[:2]
    p2l -= bboxL[:2]

    f_p1r -= bboxR[:2]
    f_p2r -= bboxR[:2]
    f_p1l -= bboxL[:2]
    f_p2l -= bboxL[:2]

    cr -= bboxR[:2]
    cl -= bboxL[:2]

    p1l[0] = W - p1l[0]
    p2l[0] = W - p2l[0]
    f_p1l[0] = W - f_p1l[0]
    f_p2l[0] = W - f_p2l[0]

    # Rotating the joints for normalization
    L, M1 = rotate(LL, cl, p1l, p2l)
    R, M2 = rotate(RR, cr, p1r, p2r)

    landmarks2['L'] -= bboxL[:2]
    landmarks2['L'][:, 0] = W - landmarks2['L'][:, 0]
    rotated_landmarks2 = rotate_amir(landmarks2['L'], M1)

    landmarks2['R'] -= bboxR[:2]
    rotated_landmarks1 = rotate_amir(landmarks2['R'], M2)

    # Rotating the corresponding points
    p1l = np.dot(M1, np.array(p1l.tolist() + [1])).astype(int)
    p2l = np.dot(M1, np.array(p2l.tolist() + [1])).astype(int)

    p1r = np.dot(M2, np.array(p1r.tolist() + [1])).astype(int)
    p2r = np.dot(M2, np.array(p2r.tolist() + [1])).astype(int)

    f_p1l = np.dot(M1, np.array(f_p1l.tolist() + [1])).astype(int)
    f_p2l = np.dot(M1, np.array(f_p2l.tolist() + [1])).astype(int)

    f_p1r = np.dot(M2, np.array(f_p1r.tolist() + [1])).astype(int)
    f_p2r = np.dot(M2, np.array(f_p2r.tolist() + [1])).astype(int)

    right_lateral, right_medial, = get_ost_jsw_patches(R, p1r, p2r, f_p1r, f_p2r, o_size_w, o_size_h)
    left_lateral, left_medial, = get_ost_jsw_patches(L, p1l, p2l, f_p1l, f_p2l, o_size_w, o_size_h)

    full_images = {'R': R, 'L': L}
    side_patches = {'R': {'lat': f_2_b(right_lateral), 'med': f_2_b(right_medial)},
                    'L': {'lat': f_2_b(left_lateral), 'med': f_2_b(left_medial)}}

    metadata = {'R': {'bbox': bboxR, 'rotM': M2},
                'L': {'bbox': bboxL, 'rotM': M1}}
    import matplotlib.pyplot as plt
    # plt.figure()
    # plt.imshow(RR)

    return full_images, side_patches, metadata, rotated_landmarks2, rotated_landmarks1, R, L

def read_pts_tibia_femur(pts_fname, spacing, padding):
    """
    Reads only the tibial and femoral plateaus' landmarks

    Parameters
    ----------
    pts_fname : str
        Full path to the file with points annotated with BoneFinder
    spacing : float
        Image spacing from DICOM file
    padding : int
        Padding to add to the image

    Returns
    -------
    out : tuple
        Femoral and tibial landmarks

    """
    points = np.round(read_pts(pts_fname) * 1. / spacing) + padding
    # landmarks_f = points[12:25, :]
    # landmarks_t = points[47:64, :]
    return points

def read_pts_tibia_femur2(pts_fname, spacing, padding):
    """
    Reads only the tibial and femoral plateaus' landmarks

    Parameters
    ----------
    pts_fname : str
        Full path to the file with points annotated with BoneFinder
    spacing : float
        Image spacing from DICOM file
    padding : int
        Padding to add to the image

    Returns
    -------
    out : tuple
        Femoral and tibial landmarks

    """
    points = np.round(read_pts(pts_fname) * 1. / spacing) + padding
    landmarks_f = points[12:25, :]
    landmarks_t = points[47:64, :]
    return landmarks_f, landmarks_t

def worker(job_data):
    """
    General worker to be used in multi-core processing of X-rays stored in DICOM
    format.

    Parameters
    ----------
    job_data : tuple or list
        Job data, which has sufficient information to extract
        filename to the DICOM image, full path to the landmarks (left and right ones),
        and, finally the path to save the results
    job_preproc_hook : function
        function, which must return scirpt's arguments, filename to the DICOM image, full path to the landmarks (left and right ones),
        and, finally the path to save the results

    Returns
    -------
    out : int
        Returns 0, if the data were successfully read and 1 if not.

    """
    args, fname, pts_fname_l, pts_fname_r, path_save = job_data
    if os.path.isfile(path_save):
        return 0
    res = read_dicom(fname)
    if res is None:
        return 1
    I, orig_spacing, img_metadata = res
    dd = img_metadata.pixel_array
    scale = orig_spacing / args.spacing

    I = process_xray(I).astype(np.uint8)
    I = pad(I, padding=args.pad)
    row, col = I.shape

    landmarks_l = read_pts_tibia_femur(pts_fname_l, orig_spacing, args.pad)
    landmarks_r = read_pts_tibia_femur(pts_fname_r, orig_spacing, args.pad)

    landmarks_r[:, 0] = col - landmarks_r[:, 0]

    # displ_img(I,landmarksTL, landmarksFL, landmarksTR, landmarksFR)
    landmarks2 = {'R': landmarks_r * scale,
                  'L': landmarks_l * scale}

    landmarks_fl, landmarks_tl = read_pts_tibia_femur2(pts_fname_l, orig_spacing, args.pad)
    landmarks_fr, landmarks_tr = read_pts_tibia_femur2(pts_fname_r, orig_spacing, args.pad)

    landmarks_fr[:, 0] = col - landmarks_fr[:, 0]
    landmarks_tr[:, 0] = col - landmarks_tr[:, 0]

    # displ_img(I,landmarksTL, landmarksFL, landmarksTR, landmarksFR)
    landmarks = {'TR': landmarks_tr * scale,
                 'FR': landmarks_fr * scale,
                 'TL': landmarks_tl * scale,
                 'FL': landmarks_fl * scale}

    # Scaling to the new spacing
    I = cv2.resize(I, (int(col * scale), int(row * scale)), interpolation=cv2.INTER_CUBIC)
    try:
        full_images, side_patches, metadata, rotated_landmarks_L, rotated_landmarks_R, R, L = extract_patches(I,
                                                                                landmarks,
                                                                                landmarks2,
                                                                                args.spacing,
                                                                                args.sizemm,
                                                                                args.o_sizemm_w,
                                                                                args.o_sizemm_h)
    except:
        return 1
    # import os
    # imageR, new_spacing = resample(RR, img_metadata)
    # imageL, new_spacing = resample(RR, img_metadata)

    import matplotlib
    import matplotlib.pyplot as plt
    # plt.figure(figsize=(10.8, 10.8))
    # plt.imshow(image, cmap=plt.cm.bone)
    # Displacement = metadata['R']['bbox']
    # rightlanmark = landmarks2['R']
    # rightlanmark[:, 0] -= Displacement[0]
    # rightlanmark[:, 1] -= Displacement[1]
    # plt.scatter(x=rotated_landmarks1[:, 0], y=rotated_landmarks1[:, 1], c='r', s=10)
    # plt.axis('off')
    ##### os.mkdir(path_save)
    # plt.savefig(path_save + 'R.jpg', bbox_inches='tight')
    # plt.figure(figsize=(10.8, 10.8))
    # plt.imshow(L, cmap=plt.cm.bone)
    # plt.scatter(x=rotated_landmarks2[:, 0], y=rotated_landmarks2[:, 1], c='r', s=10)
    # plt.axis('off')
    # plt.savefig(path_save + 'L.jpg', bbox_inches='tight')

    # np.save(path_save, [full_images, side_patches, metadata, landmarks, landmarks2, img_metadata.Modality, args.spacing])
    R = R.astype('float')
    L = L.astype('float')
    # matplotlib.image.imsave(path_save + 'R.jpg', imageR,
    #                         cmap=plt.cm.bone)
    #
    # matplotlib.image.imsave(path_save + 'L.jpg', imageL,
    #                         cmap=plt.cm.bone)

    return 0, rotated_landmarks_R, rotated_landmarks_L, L, R


# 对通用代码封装
from selenium import webdriver
from selenium.webdriver.remote.webdriver  import WebDriver
import time

class BasePage:
    def __init__(self, driver: WebDriver=None):
        if driver is None:
            # index页面使用这个方法
            self._driver = webdriver.Chrome()
            self._driver.implicitly_wait(3)
            self._driver.get(self._base_url)
        else:
            # 是因为有的页面需要引用其他的driver
            # login和register等页面需要这个方法
            self._driver = driver

    def close(self):
        time.sleep(20)
        self._driver.quit()


'''
Created on 2013-4-1

@author: zhangbin
'''

import os
import logging
import logging.handlers
import traceback

from util.config import options, define

define('--log-dir', name='logdir', type='string')

def setup(product_name):
    try:
        log_dir = options.logdir
        if not log_dir:
            log_dir = os.path.normpath(os.path.join(__file__,
                                                    os.pardir,
                                                    os.pardir,
                                                    os.pardir,
                                                    'log'))
        logger=logging.getLogger()
        logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(module)s.%(funcName)s:%(lineno)d - %(message)s', '')
        _console=logging.StreamHandler();
        _file=logging.FileHandler(log_dir+'/'+product_name+'.log')
        _file.setFormatter(formatter)
        _console.setFormatter(formatter)
        logger.addHandler(_console)
        logger.addHandler(_file)
    except Exception:
        traceback.print_exc()
        raise

class WritableLogger(object):
    '''
    classdocs
    '''

    def __init__(self, logger, level=logging.INFO):
        '''
        Constructor
        '''
        self.logger = logger
        self.level = level

    def write(self, msg):
        self.logger.log(self.level, msg)

LOG = logging.getLogger()


import discord
import asyncio
from datetime import datetime

from discord.ext import commands

class FeedBack(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command(aliases=["fd"])
    @commands.cooldown(1, 7200, commands.BucketType.user)
    async def feedback(self, ctx, *, args=None):
        if args is None:
            await ctx.send(f"{ctx.message.author.mention} bitte geb ein Feedback zum Bot.")
        elif len(args) < 100:
            await ctx.send(f"{ctx.message.author.mention} dein Feedback muss mindestens 100 Zeiche lang sein. Länge des Feedbacks {len(args)} Zeichen.")
        elif len(args) > 2048:
            await ctx,send(f"{ctx.message.author.mention} dein Feedback darf nur 2048 Zeichen lang sein. Länge des Feedbacks {len(args)} Zeichen.")
        else:
            embed = discord.Embed(title="**Feedback**", color=discord.Color.green())
            embed.add_field(name='Nachricht', value=args, inline=False)
            embed.set_footer(text=f"{ctx.message.author.name} | {ctx.guild.name}", icon_url=ctx.guild.icon_url_as(size=512))

            msg = await ctx.send(embed=embed)
            await asyncio.sleep(3)
            await msg.delete()
            await ctx.send(f"{ctx.message.author.mention} dein Feedback wurde gesendet!")

            for guild in self.client.guilds:
                if guild.name == "➤ Xan Bot | Support":
                    for channel in guild.text_channels:
                        if channel.id == 738067878552535054:
                            await channel.send(embed=embed)

    @feedback.error
    async def feedback_error(self, ctx, error):
        if isinstance(error, commands.CommandOnCooldown):

            cooldown = datetime.fromtimestamp(int(error.retry_after)).strftime("%I:%M:%S")

            await ctx.send(f"Du hast ein Cooldown von _**{cooldown}m**_ !")

def setup(client):
    client.add_cog(FeedBack(client))


import logging
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from concurrent.futures import CancelledError as FutureCancelledError
from threading import Lock as ThreadLock
from queue import Queue as ThreadQueue
from queue import Empty

from newio import spawn
from newio.socket import socketpair

from .asyncio_executor import AsyncioExecutor

LOG = logging.getLogger(__name__)

class ExecutorFuture:
    def __init__(self, handler, task, future):
        self._handler = handler
        self._task = task
        self._fut = future
        self._is_expired = False
        future.add_done_callback(self._on_fn_done)

    def cancel(self):
        if not self._is_expired:
            LOG.debug('task %r cancel executor', self._task)
            self._fut.cancel()
            self._is_expired = True

    def state(self):
        return 'wait_executor'

    def clean(self):
        self.cancel()

    def _on_fn_done(self, fut):
        if self._is_expired:
            return
        self._is_expired = True
        result = error = None
        try:
            error = fut.exception()
            if error is None:
                result = fut.result()
        except FutureCancelledError:
            return  # ignore
        if error:
            LOG.debug('executor for task %r crashed:',
                      self._task, exc_info=error)
        else:
            LOG.debug('executor for task %r finished', self._task)
        self._handler(self._task, result, error)

class Executor:
    def __init__(self, handler, max_num_thread=None, max_num_process=None):
        self._handler = handler
        self._thread_executor = ThreadPoolExecutor(max_num_thread)
        self._process_executor = ProcessPoolExecutor(max_num_process)
        self._asyncio_executor = AsyncioExecutor()
        self._notify, self._wakeup = socketpair()
        self._queue = ThreadQueue(1024)
        self.agent_task = None
        self._is_exiting = False
        self._notify_lock = ThreadLock()

    def run_in_thread(self, task, fn, args, kwargs):
        LOG.debug('task %r run %r in thread executor', task, fn)
        fut = self._thread_executor.submit(fn, *args, **kwargs)
        return ExecutorFuture(self.handler, task, fut)

    def run_in_process(self, task, fn, args, kwargs):
        LOG.debug('task %r run %r in process executor', task, fn)
        fut = self._process_executor.submit(fn, *args, **kwargs)
        return ExecutorFuture(self.handler, task, fut)

    def run_in_asyncio(self, task, coro):
        LOG.debug('task %r run %r in asyncio executor', task, coro)
        fut = self._asyncio_executor.submit(coro)
        return ExecutorFuture(self.handler, task, fut)

    async def executor_agent(self):
        is_exiting = False
        while True:
            try:
                task, result, error = self._queue.get_nowait()
            except Empty:
                if is_exiting:
                    break
                nbytes = await self._wakeup.recv(128)
                if not nbytes or b'x' in nbytes:
                    LOG.debug('executor agent exiting')
                    is_exiting = True
                    await self._wakeup.close()
            else:
                self._handler(task, result, error)

    async def start(self):
        self.agent_task = await spawn(self.executor_agent())

    async def stop(self):
        LOG.debug('executor exiting')
        self._is_exiting = True
        with self._notify_lock:
            await self._notify.sendall(b'x')
            await self._notify.close()
        await self.agent_task.join()

    def shutdown(self, wait=True):
        self._thread_executor.shutdown(wait=wait)
        self._process_executor.shutdown(wait=wait)
        self._asyncio_executor.shutdown(wait=wait)

    def handler(self, task, result, error):
        self._queue.put_nowait((task, result, error))
        if self._is_exiting:
            return
        with self._notify_lock:
            with self._notify.blocking() as notify:
                notify.sendall(b'1')


import re

import setuptools

# from .src.pyaltium import __version__

with open("src/pyaltium/__init__.py") as f:
    txt = f.read()
    r = re.search(r'__version__\s+=\s+"(.*)"', txt)
    __version__ = r.group(1)

with open("README.md", "r", encoding="utf-8") as f:
    long_description = f.read()

setuptools.setup(
    name="PyAltium",
    version=__version__,
    author="Trevor Gross",
    author_email="t.gross35@gmail.com",
    description="A package for reading Altium files",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/pluots/PyAltium",
    project_urls={
        "Bug Tracker": "https://github.com/pluots/PyAltium/issues",
    },
    packages=setuptools.find_packages(where="src"),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    package_dir={"": "src"},
    python_requires=">=3.7",
)


"""Added backref items of agreement relationship in PAItem model

Revision ID: 93c945e3886f
Revises: 28c16fad747e
Create Date: 2023-06-15 15:54:09.154615

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '93c945e3886f'
down_revision = '28c16fad747e'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('pa_items', schema=None) as batch_op:
        batch_op.add_column(sa.Column('agreement_id', sa.Integer(), nullable=True))
        batch_op.create_foreign_key(None, 'pa_agreements', ['agreement_id'], ['id'])

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('pa_items', schema=None) as batch_op:
        batch_op.drop_constraint(None, type_='foreignkey')
        batch_op.drop_column('agreement_id')

    # ### end Alembic commands ###


"""add status to issue

Revision ID: 6d3439e14660
Revises: 04c84d5e2a21
Create Date: 2019-03-22 07:57:32.625406

"""
from alembic import op
import sqlalchemy as sa
from pabu.tools import get_table

# revision identifiers, used by Alembic.
revision = '6d3439e14660'
down_revision = '04c84d5e2a21'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('issues', sa.Column('status', sa.String(), nullable=True))

    issues = get_table(op.get_bind(), 'issues')
    op.execute(issues.update().values(status = 'todo'))

    op.alter_column('issues', 'status', nullable=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('issues', 'status')
    # ### end Alembic commands ###


#!/usr/bin/env python
# coding: utf-8
# Author: Mihir Singh

# ## import necessary packages n pass unix(source) and hadoop(destination location) as system argument 1,2

from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark.sql import SparkSession
import sys
spark=SparkSession.builder.appName("create_json").enableHiveSupport().getOrCreate()

# ## create a list of database value

mydb=spark.sql("show databases").collect()

db=[]
for mydb in mydb:
    db.append(mydb.databaseName)

# ## the below code takes in database name -- and collect all tables inside it as dbname.table name
mytables=[]
for db in db:
    print("database in use",db)
    spark.sql("use {}".format(db))
    tables=spark.sql("show tables")
    param=tables.select(concat(col("database"),lit("."),col('tableName')).alias("tables")).collect()
    for a in param:
        print("tables",a.tables)
        mytables.append(a.tables)

# ## create dict with key as dbname-tablename and value as 'column_name|datatype'
myschemas1={}
c=0
for b in mytables:
    print(str(b).replace(".","-"))
    try:
        myschemas1[str(b).replace(".","-")]=list(spark.sql("desc {}".format(b)).select(concat(col("col_name"),lit("|"),col("data_type"))).collect())
    except:
        print("Permission error")
        break

# ## import json package to dump dict to json

import json
with open("{}/onprem.json".format(sys.argv[1]), "w") as fp:
    json.dump(myschemas1 , fp)

#with open("{}/cloud.json".format(sys.argv[1]), "w") as fp:
#    json.dump(myschemas2 , fp)

# ## comment uncomment as per environment to upload file to hdfs

# In[10]:
import os
os.system("hadoop fs -put -f {}/onprem.json {}/onprem.json".format(sys.argv[1],sys.argv[2]))
#os.system("hadoop fs -put -f {}/cloud.json {}/cloud.json".format(sys.argv[1],sys.argv[2]))


#!/usr/bin/env python3

from multiprocessing import Process, Queue
import socks
import socket
import subprocess
import requests

x = open("/home/kaisok/Documentos/Python/Onion/ListaPrueba", "r", encoding="latin-1")
url = x.readlines()
x.close()
subprocess.run("clear")

puertosAbiertos = []

def torrente(min, max):

    for i in url:
        nombre = i.strip("\n")
        i = i.split(" ")[1].strip("\n")

        for puerto in range(min, max):
            print("\nProbando puerto {}".format(puerto))

            try:

                socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True)
                s = socks.socksocket()
                s.settimeout(2)
                address = (i, puerto)
                s.connect(address)

                print("-----Abierto-----")

                q.put(puerto)

                s.close()

            except:

                print("casi")

ListaPuertos=[1000, 1501, 2001, 2501, 3001]
if __name__ == "__main__":

    procs = []
    q = Queue()
    for i in range(4):
        proc = Process(target=torrente, args=(ListaPuertos[i],ListaPuertos[i+1]))
        procs.append(proc)

    for proc in procs:
        proc.start()

    for proc in procs:
        proc.join()

while not q.empty():
    puertosAbiertos.append(q.get())

print(puertosAbiertos)

for i in url:
    nombre = i.strip("\n")
    i = i.split(" ")[1].strip("\n")

    for puerto in puertosAbiertos:

        try:
            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True)
            s = socks.socksocket()
            s.settimeout(2)
            address = (i, puerto)
            s.connect(address)
            a = s.recv(1024).decode()
            s.close()

            if "SSH" in a:
                    print("\n#######################")
                    print("\n" + nombre)
                    print("\nEs SSH")
                    print("\n#######################")

            elif "FTP" in a:
                print("\n#######################")
                print("\n" + nombre)
                print("\nEs FTP")
                print("\n#######################")

        except:

            try:

                print("\n#######################")
                proxies = {'http': 'socks5h://127.0.0.1:9050'}
                data = requests.head("http://{}:{}".format(i, puerto),proxies=proxies).headers
                if data["Server"]:
                    print("\nHTTP SERVER: {}".format(data["Server"]))
                else:
                    print("\nHTTP SERVER")
                print("\n#######################")

            except:

                print("\n#######################")
                print("\nOTRO SERVICIO")
                print("\n#######################")


import json
import structlog
import pika
import config
from multiprocessing import Process
from ServiceManager import ServiceInfo, startService

logger = structlog.get_logger()

def serviceCallback(ch, method, properties, body):
    """Take service off of the queue and start it up in a container"""

    logger.info("serviceCallback", msg="Recieved Message", body=body)
    body = json.loads(body)
    service = ServiceInfo(body)
    log = logger.bind(serviceInfo=service.__dict__)
    log.info("serviceCallback", msg="Starting Service")

    # Reassign service with new ip address
    service = startService(service)

    log.info("serviceCallback", msg="Placing Service on Attack Queue")
    connection = pika.BlockingConnection(pika.ConnectionParameters(config.RABBITMQ_SERVER))
    channel = connection.channel()
    channel.queue_declare(queue='attackQueue', durable=True)
    channel.basic_publish(exchange='',
                          routing_key='attackQueue',
                          body=json.dumps(service.__dict__))

    ch.basic_ack(delivery_tag=method.delivery_tag)
    log.info("serviceCallback", msg="serviceCallback Done")

def serviceWorker():
    """Declare service queue and callback"""
    connection = pika.BlockingConnection(pika.ConnectionParameters(config.RABBITMQ_SERVER))
    channel = connection.channel()
    channel.queue_declare(queue='serviceQueue', durable=True)
    logger.info("serviceWorker", msg="Starting Service Worker", queue="serviceQueue")
    channel.basic_consume(serviceCallback, queue='serviceQueue')
    channel.start_consuming()

def startServiceWorkers(numThreads):
    """Start numThreads service workers"""
    for i in range(numThreads):
        t = Process(target=serviceWorker)
        t.daemon = True
        t.start()


#cryptopals challenge 27
from os import urandom
from Crypto.Cipher import AES

iv = urandom(16)
s1 = b"comment1=cooking%20MCs;userdata="
s2 = b";comment2=%20like%20a%20pound%20of%20bacon"

xor = lambda b1, b2: bytes(x ^ y for x, y in zip(b1, b2))

def encrypt(plain):
    #create cipher
    cipher = AES.new(iv, AES.MODE_CBC, iv)
    #delete chars - same as c26
    string = plain.translate(str.maketrans({';': '', '=': ''}))
    string = pkcs7(string.encode('ascii'))
    return cipher.encrypt(string)

def decrypt(encrypted):
    cipher = AES.new(iv, AES.MODE_CBC, iv)
    message = cipher.decrypt(encrypted)
    return message[:-message[-1]]

#crypto message syntax
def pkcs7(string):
    pad = 16 - (len(string) % 16)
    return string + bytes(pad * [pad])

def crack_cipher(cipher):
    decrypted = decrypt(cipher)
    #all chars between 32 and 127
    return "a" if all(32<ch<127 for ch in decrypted) else decrypted

plain = "abcdefghijklmnopqrstuvwxyz"
cipher = encrypt(plain)
tmp = cipher[0:16] + bytes(16) + cipher[0:16] + cipher[16:]
cracked = crack_cipher(tmp)

if (iv == xor(cracked[0:16], cracked[32:48])):
    print('True')
    print(iv)
    print(xor(cracked[0:16], cracked[32:48]))
else:
    print('False')


from flask import current_app, render_template, flash, redirect, url_for, request, jsonify, send_from_directory
from flask_login import current_user, login_required
from werkzeug.urls import url_parse
from werkzeug.utils import secure_filename
from app import db, s3
from app.main.forms import EmptyForm, ActorForm, ArtForm, AuthorForm, BookForm, CharacterForm, SeriesForm, UniverseForm, UploadForm
from app.models import User, Actor, Art, Author, Book, Character, Series, Universe
from app.main import bp
from sqlalchemy import exc
import os

@bp.route('/')
@bp.route('/index')
@login_required
def index():
    posts = [
        {
            'author': {'username': 'John'},
            'body': 'Beautiful day in Portland!'
        },
        {
            'author': {'username': 'Susan'},
            'body': 'The Avengers movie was so cool!'
        }
    ]
    return render_template('index.html', title='Home', posts=posts)

@bp.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(current_app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')

@bp.route('/search')
def search():
    return render_template('search.html')

@bp.route('/explore')
def explore():
    return render_template('explore.html')

@bp.route('/submit')
def submit():
    return render_template('submit.html')

# Actor Endpoints

@bp.route('/actors/add', methods=['GET', 'POST'])
def add_actor():
    return add_resource(Actor, ActorForm, 'resource.html', url_for('main.submit'), url_for('main.get_actors'))

@bp.route('/actors/<int:id>/edit', methods=['GET', 'POST'])
def edit_actor(id):
    return edit_resource(Actor, ActorForm, id, 'resource.html', url_for('main.get_actors'), url_for('main.get_actors'))

@bp.route('/actors')
def get_actors():
    columns = ['first_name', 'middle_name', 'last_name', 'suffix']
    return get_resources(Actor, 'resource.html', url_for('main.explore'), 'main.get_actor', 'main.edit_actor', columns)

@bp.route('/actors/<int:id>')
def get_actor(id):
    columns = ['first_name', 'middle_name', 'last_name', 'suffix']
    return get_resource(Actor, id, 'resource.html', url_for('main.get_actors'), 'main.get_actor', 'main.edit_actor', columns)

@bp.route('/actors/<int:id>', methods=['DELETE'])
def delete_actor(id):
    return delete_resource(Actor, id)

# Art Endpoints

@bp.route('/art/add', methods=['GET', 'POST'])
def add_art():
    return add_resource(Art, ArtForm, 'resource.html', url_for('main.submit'), url_for('main.get_art'))

@bp.route('/art/<int:id>/edit', methods=['GET', 'POST'])
def edit_art(id):
    return edit_resource(Art, ArtForm, id, 'resource.html', url_for('main.get_art'), url_for('main.get_art'))

@bp.route('/art')
def get_art():
    columns = ['artist', 'title', 'description', 'source']
    return get_resources(Art, 'resource.html', url_for('main.explore'), 'main.get_art_id', 'main.edit_art', columns)

@bp.route('/art/<int:id>')
def get_art_id(id):
    columns = ['artist', 'title', 'description', 'source']
    return get_resource(Art, id, 'resource.html', url_for('main.get_art'), 'main.get_art_id', 'main.edit_art', columns)

@bp.route('/art/<int:id>', methods=['DELETE'])
def delete_art(id):
    return delete_resource(Art, id)

# Author Endpoints

@bp.route('/authors/add', methods=['GET', 'POST'])
def add_author():
    return add_resource(Author, AuthorForm, 'resource.html', url_for('main.submit'), url_for('main.get_authors'))

@bp.route('/authors/<int:id>/edit', methods=['GET', 'POST'])
def edit_author(id):
    return edit_resource(Author, AuthorForm, id, 'resource.html', url_for('main.get_authors'), url_for('main.get_authors'))

@bp.route('/authors')
def get_authors():
    columns = ['first_name', 'middle_name', 'last_name', 'suffix']
    return get_resources(Author, 'resource.html', url_for('main.explore'), 'main.get_author', 'main.edit_author', columns)

@bp.route('/authors/<int:id>')
def get_author(id):
    columns = ['first_name', 'middle_name', 'last_name', 'suffix']
    return get_resource(Author, id, 'resource.html', url_for('main.get_authors'), 'main.get_author', 'main.edit_author', columns)

@bp.route('/authors/<int:id>', methods=['DELETE'])
def delete_author(id):
    return delete_resource(Author, id)

# Book Endpoints

@bp.route('/books/add', methods=['GET', 'POST'])
def add_book():
    return add_resource(Book, BookForm, 'resource.html', url_for('main.submit'), url_for('main.get_books'))

@bp.route('/books/<int:id>/edit', methods=['GET', 'POST'])
def edit_book(id):
    return edit_resource(Book, BookForm, id, 'resource.html', url_for('main.get_books'), url_for('main.get_books'))

@bp.route('/books')
def get_books():
    columns = ['universe', 'series', 'author', 'title', 'series_number']
    return get_resources(Book, 'resource.html', url_for('main.explore'), 'main.get_book', 'main.edit_book', columns)

@bp.route('/books/<int:id>')
def get_book(id):
    columns = ['universe', 'series', 'author', 'title', 'series_number']
    return get_resource(Book, id, 'resource.html', url_for('main.get_books'), 'main.get_book', 'main.edit_book', columns)

@bp.route('/books/<int:id>', methods=['DELETE'])
def delete_book(id):
    return delete_resource(Book, id)

# Character Endpoints

@bp.route('/characters/add', methods=['GET', 'POST'])
def add_character():
    return add_resource(Character, CharacterForm, 'resource.html', url_for('main.submit'), url_for('main.get_characters'))

@bp.route('/characters/<int:id>/edit', methods=['GET', 'POST'])
def edit_character(id):
    return edit_resource(Character, CharacterForm, id, 'resource.html', url_for('main.get_characters'), url_for('main.get_characters'))

@bp.route('/characters')
def get_characters():
    columns = ['universe', 'series', 'first_name', 'last_name', 'suffix', 'description']
    return get_resources(Character, 'resource.html', url_for('main.explore'), 'main.get_character', 'main.edit_character', columns)

@bp.route('/characters/<int:id>')
def get_character(id):
    columns = ['universe', 'series', 'first_name', 'last_name', 'suffix', 'description']
    return get_resource(Character, id, 'resource.html', url_for('main.get_characters'), 'main.get_character', 'main.edit_character', columns)

@bp.route('/characters/<int:id>', methods=['DELETE'])
def delete_character(id):
    return delete_resource(Character, id)

# Series Endpoints

@bp.route('/series/add', methods=['GET', 'POST'])
def add_series():
    return add_resource(Series, SeriesForm, 'resource.html', url_for('main.submit'), url_for('main.get_series'))

@bp.route('/series/<int:id>/edit', methods=['GET', 'POST'])
def edit_series(id):
    return edit_resource(Series, SeriesForm, id, 'resource.html', url_for('main.get_series'), url_for('main.get_series'))

@bp.route('/series')
def get_series():
    columns = ['universe', 'title']
    return get_resources(Series, 'resource.html', url_for('main.explore'), 'main.get_series_id', 'main.edit_series', columns)

@bp.route('/series/<int:id>')
def get_series_id(id):
    columns = ['universe', 'title']
    return get_resource(Series, id, 'resource.html', url_for('main.get_series'), 'main.get_series_id', 'main.edit_series', columns)

@bp.route('/series/<int:id>', methods=['DELETE'])
def delete_series(id):
    return delete_resource(Series, id)

# Universe Endpoints

@bp.route('/universes/add', methods=['GET', 'POST'])
def add_universe():
    return add_resource(Universe, UniverseForm, 'resource.html', url_for('main.submit'), url_for('main.get_universes'))

@bp.route('/universes/<int:id>/edit', methods=['GET', 'POST'])
def edit_universe(id):
    return edit_resource(Universe, UniverseForm, id, 'resource.html', url_for('main.get_universes'), url_for('main.get_universes'))

@bp.route('/universes')
def get_universes():
    columns = ['title']
    return get_resources(Universe, 'resource.html', url_for('main.explore'), 'main.get_universe', 'main.edit_universe', columns)

@bp.route('/universes/<int:id>')
def get_universe(id):
    columns = ['title']
    return get_resource(Universe, id, 'resource.html', url_for('main.get_universes'), 'main.get_universe', 'main.edit_universe', columns)

@bp.route('/universes/<int:id>', methods=['DELETE'])
def delete_universe(id):
    return delete_resource(Universe, id)

# CRUD functions for basic resource management

def add_resource(ResourceClass, FormClass, default_template, redirect_url, back_url):
    form = FormClass()
    if form.validate_on_submit():
        resource = ResourceClass()
        form.populate_obj(resource)

        try:
            db.session.add(resource)
            db.session.commit()
            flash('Congratulations, you added a {}!'.format(ResourceClass.__name__))
        except exc.IntegrityError:
            db.session.rollback()
            flash('Duplicate {} entry detected'.format(ResourceClass.__name__), 'error')
            return render_template('errors/500.html'), 500
        except:
            db.session.rollback()
            flash('Unknown error occured', 'error')
            return render_template('errors/500.html'), 500

        return redirect(redirect_url)

    return render_template(default_template, title='Add to {} Collection'.format(ResourceClass.__name__), form=form, back_url=back_url)

def edit_resource(ResourceClass, FormClass, id, default_template, redirect_url, back_url):
    resource = ResourceClass.query.get(id)
    if resource:
        form = FormClass(obj=resource)
        if form.validate_on_submit():
            try:
                form.populate_obj(resource)
                db.session.commit()
                flash('{} record update success'.format(ResourceClass.__name__))
            except exc.IntegrityError:
                db.session.rollback()
                flash('Duplicate {} entry detected'.format(ResourceClass.__name__), 'error')
                return render_template('errors/500.html'), 500
            except:
                db.session.rollback()
                flash('Unknown error occured', 'error')
                return render_template('errors/500.html'), 500

            return redirect(redirect_url)

    return render_template(default_template, title='Edit Resource', form=form, back_url=back_url)

def get_resources(ResourceClass, default_template, back_url, get_uri, edit_uri, columns):
    resources = ResourceClass.query.all()
    return render_template(default_template, results=resources, back_url=back_url, get_uri=get_uri, edit_uri=edit_uri, columns=columns)

def get_resource(ResourceClass, id, default_template, back_url, get_uri, edit_uri, columns):
    resource = ResourceClass.query.get(id)

    if resource:
        return render_template(default_template, results=[resource], back_url=back_url, get_uri=get_uri, edit_uri=edit_uri, columns=columns)
    else:
        return render_template('errors/404.html'), 404

def delete_resource(ResourceClass, id):
    try:
        result = ResourceClass.query.filter_by(id=id).delete()
        db.session.commit()

        if result:
            flash('Successfully deleted {} record'.format(ResourceClass.__name__))
            return jsonify(success=True)
        else:
            flash('Error deleting {} id: {}'.format(ResourceClass.__name__, id), 'error')
            return jsonify(success=False)
    except:
        db.session.rollback()
        flash('Error deleting {} id: {}'.format(ResourceClass.__name__, id), 'error')
        return jsonify(success=False)

# CRUD functions for S3

@bp.route('/upload', methods=['GET', 'POST'])
def upload_file():
    form = UploadForm()

    if form.validate_on_submit():
        filename = secure_filename(form.file.data.filename)
        print("ATTEMPTING FILE UPLOAD")
        output = send_to_s3(form.file.data)
        flash(output)
        print("ATTEMPTING FILE DELETE")
        deleteput = delete_from_s3('Reyna.png')
        print(deleteput)
        return redirect(url_for('main.upload_file'))

    return render_template('upload.html', form=form)

def send_to_s3(file):
    """
    Docs: http://boto3.readthedocs.io/en/latest/guide/s3.html
    """
    try:
        s3.upload_fileobj(
            file,
            current_app.config["S3_BUCKET"],
            file.filename,
            ExtraArgs={
                "ContentType": file.content_type
            }
        )
    except Exception as e:
        print("Something Happened: ", e)
        return e
    return "{}{}".format(current_app.config["S3_LOCATION"], file.filename)

def delete_from_s3(key):
    try:
        result = s3.delete_object(Bucket=current_app.config["S3_BUCKET"], Key=key)
        print(result)
        return result
    except Exception as e:
        print("Something Happened: ", e)
        return e


# Complexity:
# Time: O(N+M): Let N and M be length of list1 and list2
# Space: O(1)

# Definition for singly-linked list.
from typing import Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        start = list3 = ListNode(0)
        while list1 is not None and list2 is not None:
            if list1.val < list2.val:
                list3.next = list1
                list1 = list1.next
            else:
                list3.next = list2
                list2 = list2.next
            list3 = list3.next
        list3.next = list1 or list2
        return start.next

l1 = ListNode()
l2 = ListNode()

solve = Solution()
print(solve.mergeTwoLists(l1, l2))

# Your input
# [1,2,4] & [1,3,4]
# Output
# [1,1,2,3,4,4]


from asyncio import Handle
from re import match
from create import check_answer

"""
This fuction checks if the time is in the correct format.
Ex.: 12.98 (seconds), 01:23.98 (minutes) or 02:34:45.67(hours)
"""
def check_time(time:str) -> bool:

	if len(time) == 5:
		answer = bool(match("[0-5][0-9][.][0-9][0-9]",time))

	elif len(time) == 8:
		answer = bool(match("[0-5][0-9][:][0-5][0-9][.][0-9][0-9]",time))

	elif len(time) == 11:
		answer = bool(match("[0-9][0-9][:][0-5][0-9][:][0-5][0-9][.][0-9][0-9]",time))

	else: answer = False

	return answer

"""
Function responsible to update the dictionary "times_info"
Just like "check_distance" in "new_practice", "check_time" is being used here to be sure the time's format is correct
The steps in this one are:
-> Get the event which time will be recorded
-> Loop with "check_time" as condition to guarantee the correct format
-> Creates a list with the times of the event and put them in order (fastest to slowest)
-> Repeat until the user stops
"""
def new_time(times_info:dict):
	new_op = input("\nDo you want to record a new time?[Yes/No]\n")
	control = check_answer(new_op)

	while(control):
		event = input("\nWhich event is going to be recorded?\n")
		valid_time = False
		while(not valid_time):
			time = input("\nWhat is the time?\n")
			valid_time = check_time(time)
			if not valid_time:
				print("\nNot the correct format\n")

		all_times = times_info.get(event, [])
		all_times.append(time)

		times_info[event] = all_times
		times_info[event].sort(key = lambda time: (len(time), time))

		new_op = input("\nDo you want to record a new time?[Yes/No]\n")
		control = check_answer(new_op)

"""
It writes the information in "times_info" at the file
"""
def write_times_info(handle:Handle, times_info:dict):
	handle.write("\nTimes:\n\n")

	for event, times in times_info.items():
		handle.write("->"+event+":\n")
		count = 1

		for i in times:
			sentence ="("+str(count)+") "+i+"\n"
			handle.write(sentence)
			count += 1

		handle.write("\n")


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

# Widget para mostrar una columna estándar en Turpial
#
# Author: Wil Alvarez (aka Satanas)
# Jun 25, 2010

import gtk
import logging

from turpial.ui import util as util
from turpial.ui.gtk.errorbox import ErrorBox
from turpial.ui.gtk.statuslist import StatusList
from turpial.ui.gtk.waiting import CairoWaiting

log = logging.getLogger('Gtk:Column')

class GenericColumn(gtk.VBox):
    def __init__(self, mainwin, label=''):
        gtk.VBox.__init__(self, False)

        self.mainwin = mainwin
        self.statuslist = StatusList(mainwin)
        self.waiting = CairoWaiting(mainwin)
        self.walign = gtk.Alignment(xalign=1, yalign=0.5)
        self.walign.add(self.waiting)
        self.errorbox = ErrorBox()
        self.label = gtk.Label(label)
        self.caption = label

        self.connect('expose-event', self.error_show)

    def error_show(self, widget, event):
        self.errorbox.show()

    def update_tweets(self, response):
        count = 0
        if response.type == 'error':
            self.stop_update(True, response.errmsg)
        else:
            statuses = response.items
            if len(statuses) == 0:
                self.statuslist.clear()
                self.stop_update(True, _('No tweets available'))
            else:
                count = self.statuslist.update(statuses)
                self.stop_update()
        self.on_update()
        return count

    def update_user_pic(self, user, pic):
        self.statuslist.update_user_pic(user, pic)

    def update_wrap(self, width):
        self.statuslist.update_wrap(width)

    def start_update(self):
        self.waiting.start()
        self.errorbox.hide()

    def stop_update(self, error=False, msg=''):
        self.waiting.stop(error)
        self.errorbox.show_error(msg, error)

    def clear(self):
        self.statuslist.clear()

    def on_update(self, data=None):
        pass

class StandardColumn(GenericColumn):
    def __init__(self, mainwin, label='', pos=None, viewed=None):
        GenericColumn.__init__(self, mainwin, label)

        self.pos = pos
        self.handler = None
        self.changing_col = False

        model = gtk.ListStore(str, str)
        cell = gtk.CellRendererText()
        self.listcombo = gtk.ComboBox()
        self.listcombo.pack_start(cell, True)
        self.listcombo.add_attribute(cell, 'text', 1)
        self.listcombo.set_model(model)

        self.refresh = gtk.Button()
        self.refresh.set_image(self.mainwin.load_image('action-refresh.png'))
        self.refresh.set_tooltip_text(_('Manual Update'))

        self.mark_all = gtk.Button()
        self.mark_all.set_image(self.mainwin.load_image('action-mark-all.png'))
        self.mark_all.set_tooltip_text(_('Mark all as read'))

        listsbox = gtk.HBox(False)
        listsbox.pack_start(self.mark_all, False, False)
        listsbox.pack_start(self.listcombo, True, True)
        listsbox.pack_start(self.refresh, False, False)
        listsbox.pack_start(self.walign, False, False, 2)

        self.pack_start(listsbox, False, False)
        self.pack_start(self.errorbox, False, False)
        self.pack_start(self.statuslist, True, True)

        self.refresh.connect('clicked', self.__manual_update)
        self.mark_all.connect('clicked', self.__mark_all_as_read)

    def __manual_update(self, widget):
        self.mainwin.manual_update(self.pos)

    def __mark_all_as_read(self, widget):
        self.statuslist.mark_all_as_read()

    def __change_list(self, widget):
        model = self.listcombo.get_model()
        iter = self.listcombo.get_active_iter()
        new_id = model.get_value(iter, 0)
        self.caption = model.get_value(iter, 1)
        self.changing_col = True
        self.label.set_label(self.caption)
        try:
            self.get_parent().set_tab_label(self, self.label)
        except:
            pass
        self.mainwin.request_change_column(self.pos, new_id)

    def fill_combo(self, columns, new_viewed):
        self.viewed = new_viewed[self.pos]

        i = 0
        default = -1
        model = self.listcombo.get_model()
        fixed = ['timeline', 'replies', 'directs','sent']
        for key in fixed:
            model.append([key, columns[key].title])
            if key == self.viewed.id:
                default = i
            i += 1

        for key in sorted(columns.iterkeys()):
            if key in fixed:
                continue
            model.append([key, columns[key].title])
            if key == self.viewed.id:
                default = i
            i += 1

        self.last_index = default
        self.listcombo.set_model(model)
        self.listcombo.set_active(self.last_index)
        iter = self.listcombo.get_active_iter()
        self.caption = model.get_value(iter, 1)
        self.label = gtk.Label(self.caption)
        self.handler = self.listcombo.connect('changed', self.__change_list)

    def set_combo_item(self, reset=False):
        self.listcombo.disconnect(self.handler)
        if reset:
            self.listcombo.set_active(self.last_index)
        else:
            self.last_index = self.listcombo.get_active()

            if self.changing_col:
                model = self.listcombo.get_model()
                iter = self.listcombo.get_active_iter()
                new_id = model.get_value(iter, 0)

                new_config = {'Columns': {}}
                column = 'column%i' % (self.pos + 1)
                new_config['Columns'][column] = new_id
                self.mainwin.save_config(new_config)

        self.changing_col = False
        self.handler = self.listcombo.connect('changed', self.__change_list)

    def start_update(self):
        self.waiting.start()
        self.errorbox.hide()
        self.refresh.set_sensitive(False)
        self.listcombo.set_sensitive(False)
        self.mark_all.set_sensitive(False)

    def stop_update(self, error=False, msg=''):
        if error:
            self.set_combo_item(True)
        else:
            self.set_combo_item()
        self.waiting.stop(error)
        self.errorbox.show_error(msg, error)
        self.refresh.set_sensitive(True)
        self.listcombo.set_sensitive(True)
        self.mark_all.set_sensitive(True)

class SingleColumn(GenericColumn):
    def __init__(self, mainwin, label=''):
        GenericColumn.__init__(self, mainwin, label)

        #self.errorbox = gtk.HBox(False)
        #self.errorbox.pack_start(self.lblerror, False, False, 2)
        #self.errorbox.pack_start(self.walign, False, False, 2)

        self.pack_start(self.errorbox, False, False)
        self.pack_start(self.statuslist, True, True)

class SearchColumn(GenericColumn):
    def __init__(self, mainwin, label=''):
        GenericColumn.__init__(self, mainwin, label)

        self.input_topics = gtk.Entry()
        self.clearbtn = gtk.Button()
        self.clearbtn.set_image(self.mainwin.load_image('action-clear.png'))
        self.clearbtn.set_tooltip_text(_('Clear results'))
        #self.clearbtn.set_relief(gtk.RELIEF_NONE)
        try:
            #self.input_topics.set_property("primary-icon-stock",
            #                               gtk.STOCK_FIND)
            self.input_topics.set_property("secondary-icon-stock",
                                           gtk.STOCK_FIND)
            self.input_topics.connect("icon-press", self.__on_icon_press)
        except:
            pass

        inputbox = gtk.HBox(False)
        inputbox.pack_start(self.input_topics, True, True)
        inputbox.pack_start(self.clearbtn, False, False)
        inputbox.pack_start(self.walign, False, False, 2)

        self.pack_start(inputbox, False, False)
        self.pack_start(self.errorbox, False, False)
        self.pack_start(self.statuslist, True, True)

        self.clearbtn.connect('clicked', self.__clear)
        self.input_topics.connect('activate', self.__search_topic)
        self.input_topics.grab_focus()

    def __on_icon_press(self, widget, pos, e):
        #if pos == 0:
        #    self.__search_topic(widget)
        if pos == 1:
            #widget.set_text('')
            self.__search_topic(widget)

    def __clear(self, widget):
        self.statuslist.clear()
        self.input_topics.grab_focus()

    def __search_topic(self, widget):
        topic = widget.get_text()
        if topic != '':
            self.lock()
            self.mainwin.request_search(topic)
            widget.set_text('')
        else:
            widget.set_text(_('You must write something to search'))
            widget.grab_focus()

    def on_update(self, data=None):
        self.unlock()

    def lock(self):
        self.input_topics.set_sensitive(False)
        self.clearbtn.set_sensitive(False)

    def unlock(self):
        self.input_topics.set_sensitive(True)
        self.clearbtn.set_sensitive(True)