print("Suggested usage: python BTSpred.py -in INFILE")
print("make sure predisi.txt and predsl.txt files are ready")

import argparse
import os
import sys
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC

#os.system('source ~/.bash_profile')

parser = argparse.ArgumentParser(description='How to use argparse')
parser.add_argument('-in', '--infile', help='fasta to be processed', default="chromera.fasta")

args = parser.parse_args()

filename = args.infile.split(".")[0]

def query_yes_no(question, default="yes"):
	"""Ask a yes/no question via raw_input() and return their answer.

	"question" is a string that is presented to the user.
	"default" is the presumed answer if the user just hits <Enter>.
		It must be "yes" (the default), "no" or None (meaning
		an answer is required of the user).

	The "answer" return value is True for "yes" or False for "no".
	"""
	valid = {"yes": True, "y": True, "ye": True,
			 "no": False, "n": False}
	if default is None:
		prompt = " [y/n] "
	elif default == "yes":
		prompt = " [Y/n] "
	elif default == "no":
		prompt = " [y/N] "
	else:
		raise ValueError("invalid default answer: '%s'" % default)

	while True:
		sys.stdout.write(question + prompt)
		if sys.platform in ["darwin", "win32"]:
			choice = input().lower()
		elif sys.platform.startswith("linux"):
			choice = raw_input().lower()
		else:
			quit("unrecognized OS, check how to use raw input")

		if default is not None and choice == '':
			return valid[default]
		elif choice in valid:
			return valid[choice]
		else:
			sys.stdout.write("Please respond with 'yes' or 'no' "
							 "(or 'y' or 'n').\n")

monstr_dic = {}
###########################################################################
#		read in seq names to extract nt/aa models of interest:		   #
###########################################################################
inproteins = SeqIO.parse(args.infile, 'fasta')
names = []
for sequence in inproteins:
	annotation = " ".join(sequence.description.split(" ")[1:])
	name = sequence.name
	if "-reversed" in name:
		name = name.replace("-reversed", "")
	if name not in names:
		names.append(name)
	seq = sequence.seq
	monstr_dic[name] = 	{"Annotation": annotation, "Name": name, "Seq": seq}

#print("Now printing control table, number of items per dictionary key...")
#for sequence in monstr_dic.keys():
#	print(sequence, len(monstr_dic[sequence]))

###########################################################################
#		  read in predictions from PrediSi, PredSL, TMHMM:			   #
###########################################################################
predisi = open("predisi.txt").readlines()
predsl = open("predsl.txt").readlines()

print("parsing PrediSi and PredSL predictions and sequences into data dictionary")
for line in predisi:
	line = line.split("\t")
	#FASTA-ID	Cleavage Position	Signal Peptide ?	Score
	#[0]		[1]					[2]					[3]
	if line[0] in names:
		name = line[0]
		if line[2] == "Y" and int(line[1]) < 101: #sometimes we see signal very far in the protein
			monstr_dic[name].update({"PrediSi site": line[1], "PrediSi SPscore": float(line[3])})
		else:
			monstr_dic[name].update({"PrediSi site": "-", "PrediSi SPscore": float(line[3])})

for line in predsl:
	line = line.split()
	#sequence id	mTP score	SP score	prediction	cleavage site
	#[0]			[1]			[2]			[3]			[4]
	if line[0] in names:
		name = line[0]
		#line[3] for nonplant prediction - complex algae
		if line[3] == "secreted":
			monstr_dic[name].update({"PredSL site": line[4], "PredSL SPscore": float(line[2])})
		else:
			monstr_dic[name].update({"PredSL site": "-", "PredSL SPscore": float(line[2])})

###########################################################################
#					  transit peptide detection:						 #
###########################################################################

print("preparing output for MultiLoc2")

with open('cleaved-' + args.infile, 'a') as result:
	for protein in monstr_dic.keys():
		#print(protein, monstr_dic[protein])
		try:
			print(protein)
			SP_si = monstr_dic[protein]["PrediSi site"]
			SP_sl = monstr_dic[protein]["PredSL site"]
			if SP_si == "-":
				if SP_sl != "-":
					SP_sl = int(SP_sl)
					SP_cleaved_sl = '>{}\n{}\n'.format(protein, monstr_dic[protein]["Seq"][SP_sl:])
					#SP_cleaved_sl = '>{}@PredSL\n{}\n'.format(protein, monstr_dic[protein]["Seq"][SP_sl:])
					result.write(SP_cleaved_sl)
			elif SP_sl == "-":
				SP_si = int(SP_si)
				SP_cleaved_si = '>{}\n{}\n'.format(protein, monstr_dic[protein]["Seq"][SP_si:])
				#SP_cleaved_si = '>{}@PrediSi\n{}\n'.format(protein, monstr_dic[protein]["Seq"][SP_si:])
				result.write(SP_cleaved_si)
			elif int(SP_si) == int(SP_sl):
				SP_si = int(SP_si)
				SP_sl = int(SP_sl)
				SP_cleaved = '>{}\n{}\n'.format(protein, monstr_dic[protein]["Seq"][SP_si:])
				result.write(SP_cleaved)
			else:
				SP_si = int(SP_si)
				SP_sl = int(SP_sl)
				SP_cleaved_si = '>{}\n{}\n'.format(protein, monstr_dic[protein]["Seq"][SP_si:])
				SP_cleaved_sl = '>{}@PredSL\n{}\n'.format(protein, monstr_dic[protein]["Seq"][SP_sl:])
				result.write(SP_cleaved_si)
				result.write(SP_cleaved_sl)
		except ValueError as VE:
			with open('result_errors.txt', 'a') as errors:
				errors.write('SP cleavage error: {}\n{}\n\n'.format(monstr_dic[protein][5], str(VE)))

print("cleaved proteins written to {}... now running MultiLoc2 plant option to determine transit peptide probabilities.".format("cleaved-" + args.infile))

if query_yes_no("Do you wish to perform MultiLoc2 on cleaved sequences?") is True:
	os.system('python /home/manager/MultiLoc2/src/multiloc2_prediction.py -fasta={} -predictor=LowRes -origin=plant -result=pred-ML2-cleave.txt -output=simple'.format("cleaved-" + args.infile))
#use the following if your script failed, but you have made the new MultiLoc2 predictions
#if os.path.isfile("pred-ML2-cleave.txt") == False:
#	os.system('python /home/manager/MultiLoc2/src/multiloc2_prediction.py -fasta={} -predictor=LowRes -origin=plant -result=pred-ML2-cleave.txt -output=simple'.format("cleaved-" + args.infile))

print("MultiLoc2 finished, now adding predictions to data dictionary")

with open("pred-ML2-cleave.txt") as infileML2:
	ML2C = infileML2.read().split('\n')

alternativecleavage = open("alternativecleavage-" + filename + ".txt", "w")
alternativecleavage_dict = {}

for line in ML2C:
	if len(line.split('\t')) != 1:
		line = line.split('\t')
		preds = sorted(line[1:])
		name = line[0]
		#['chloroplast: ', 'cytoplasmic: ', 'mitochondrial: ', 'nuclear: ', 'secretory pathway: ']
		if "@PredSL" in name or "@PrediSi" in name:
			alternativecleavage.write("alternative cleavage for: {}\n".format("\t".join(line)))
			name = name.split("@")[0]
			try:
				cTP = preds[0].split()[1]
				mTP = preds[2].split()[1]
				combinedMLpred = float(cTP) + float(mTP)
				if combinedMLpred > 0.3:
					ourguess = "BIPARTITE, plastid"
				else:
					ourguess = "secretory"
				#print(cTP, mTP)
				if name in alternativecleavage_dict:
					if combinedMLpred > alternativecleavage_dict[name]: #here we choose the "better prediction"
						monstr_dic[name].update({"ML2post-cleavage": "pt: {} (mt: {})".format(cTP, mTP), "ourguess": ourguess, "ourscore": combinedMLpred})
				else:
					alternativecleavage_dict[name] = combinedMLpred
					monstr_dic[name].update({"ML2post-cleavage": "pt: {} (mt: {})".format(cTP, mTP), "ourguess": ourguess, "ourscore": combinedMLpred})

			except ValueError as VE:
				with open('result_errors.txt', 'a') as errors:
					errors.write('ML2 processing error: {}\n{}\n\n'.format(line, str(VE)))

		else:
			try:
				cTP = preds[0].split()[1]
				mTP = preds[2].split()[1]
				combinedMLpred = float(cTP) + float(mTP)
				if combinedMLpred > 0.3:
					ourguess = "BIPARTITE, plastid"
				else:
					ourguess = "secretory"
				#print(cTP, mTP)
				monstr_dic[name].update({"ML2post-cleavage": "pt: {} (mt: {})".format(cTP, mTP), "ourguess": ourguess, "ourscore": combinedMLpred})
			except ValueError as VE:
				with open('result_errors.txt', 'a') as errors:
					errors.write('ML2 processing error: {}\n{}\n\n'.format(line, str(VE)))
print("Transit peptide predictions made, check alternativecleavage" + filename + ".txt for ambiguous predictions.")
alternativecleavage.close()

print("Now writing results...")
outtable = 'FINALTABLE-' + filename + '.txt'

#solution without pandas
with open('FINALTABLE-' + filename, 'w') as outtable, open('FINALPREDS-' + filename, 'w') as outpreds:
	for name in monstr_dic:
		item = monstr_dic[name]
		ML2pred = item.get("ML2post-cleavage", "-")
		ourplastidpred = item.get("ourguess", "non-plastid")
		ourplastidscore = "%.3f" % ((max(item["PrediSi SPscore"], item["PredSL SPscore"]) + 3*item.get("ourscore", 0))/4)
		outtable.write("{}\t{}\t{}\t{}\n".format(item["Name"],item["PrediSi site"],item["PredSL site"],ML2pred))
		outpreds.write("{}\t{}\t{}\n".format(item["Name"],ourplastidpred, ourplastidscore))
		print(item["Name"], item["PrediSi SPscore"], item["PredSL SPscore"], item.get("ourscore", 0))

print("Writing done. Hooray.")


import os
import base64
import json
import uuid
import functions_framework
from google.api_core.client_options import ClientOptions
from google.cloud import language_v1
from google.cloud import pubsub_v1

@functions_framework.cloud_event
# receive new text events from pub sub
def new_text(cloud_event):
    debugx = False
    if os.environ.get('DEBUGX') == "1":
        debugx = True

    msg_content = base64.b64decode(cloud_event.data["message"]["data"]).decode()
    json_data = json.loads(msg_content)

    if "eid" in json_data:
        eid = json_data['eid']
    else:
        eid = uuid.uuid4().hex

    if debugx:
        print(f"DEBUGX:" + eid + ":" + msg_content)

    extract_syntax(msg_content, eid)

# extract word tokens and filter by parts of speech
def extract_syntax(msg_content, eid):
    debugx = False
    if os.environ.get('DEBUGX') == "1":
        debugx = True

    client = language_v1.LanguageServiceClient()
    type_ = language_v1.Document.Type.PLAIN_TEXT

    if debugx:
        print(f"DEBUGX:{eid}:pubsub data {msg_content}")

    json_data = json.loads(msg_content)

    language = "en"
    document = {"content": json_data['extracted_text'], "type_": type_, "language": language}

    encoding_type = language_v1.EncodingType.UTF8

    response = client.analyze_syntax(
        request={"document": document, "encoding_type": encoding_type}
    )

    # Extract the categories we want
    useful_parts_of_speech = ["NOUN", "ADJ", "VERB"]

    # An optional filter of words can also be implemented here
    extracted_words = ""
    for token in response.tokens:
        text = token.text
        part_of_speech = token.part_of_speech
        if language_v1.PartOfSpeech.Tag(part_of_speech.tag).name in useful_parts_of_speech:
            if extracted_words == "":
                extracted_words = extracted_words + text.content
            else:
                extracted_words = extracted_words + " " + text.content

    if debugx:
        print(f"DEBUGX:{eid}: Extracted words: {extracted_words}")

    publish_text(json_data['bucket'], json_data['file_name'], extracted_words, eid)

# Publish the extracted words to pub sub
def publish_text(bucket_name: str, file_name: str, syntax_data, eid):
    debugx = False
    if os.environ.get('DEBUGX') == "1":
        debugx = True

    project_id = os.environ.get('PROJECT_ID')
    topic_id = os.environ.get('TOPIC_ID')

    publisher = pubsub_v1.PublisherClient()
    topic_path = publisher.topic_path(project_id, topic_id)

    if debugx:
        print(f"Debug:{eid}: Topic path: {topic_path}")
    data = {}
    data['bucket'] = bucket_name
    data['file_name'] = file_name
    data['syntax_data'] = syntax_data
    data['eid'] = eid

    json_data = json.dumps(data)
    data = json_data.encode("utf-8")
    if debugx:
        print(f"DEBUGX:" + eid + ":" + "Data sent:" + json_data)

    future = publisher.publish(topic_path, data)
    if debugx:
        print(f"DEBUGX::{eid}: {future.result()}")


from tkinter import *
from PIL import Image, ImageTk

root = Tk()
root.title("Daniel")
root.iconbitmap('c:/users/gusta/star.ico')

photo = ImageTk.PhotoImage(Image.open("c:/users/gusta/icon.png"))

root.mainloop()


import sys
sys.setrecursionlimit(10 ** 6)

input = sys.stdin.readline

N, M = map(int, input().split())

def check(idx):
    if idx >= N:
        return 0

    if dp[idx] < 1000:
        return dp[idx]

    val = M - names[idx]

    for i in range(idx+1, N+1):
        if val < 0:
            break

        if i == N:
            dp[idx] = 0
            break

        dp[idx] = min(dp[idx], val * val + check(i))
        val -= names[i] + 1

    return dp[idx]

names = [int(input()) for _ in range(N)]
dp = [1000 for _ in range(N)]
dp[-1] = 0

print(check(0))


from functools import lru_cache

import logzero
import numpy as np
import pandas as pd
import pmdarima as pm
from logzero import logger
from pmdarima import arima, model_selection, pipeline
from pmdarima import preprocessing as ppc

# Connect to logzero log file
log_path = "logs/"
log_file = "dashboard_app.log"
logzero.logfile(
    log_path + log_file,
    maxBytes=1e5,
    backupCount=1,
    disableStderrLogger=True,
)
logger.info(f"pmd_tools logger initialized")

@lru_cache(maxsize=64)
def get_train_test(df, feature, test_size):
    """Produce and return time-series friendly train and test dataframes"""

    columns = df.columns.tolist()

    train, test = model_selection.train_test_split(df, test_size=test_periods)

    train = pd.DataFrame(train, index=df[: len(train)].index, columns=columns)
    test = pd.DataFrame(test, index=df[len(train) :].index, columns=columns)

    return train, test

def get_arima_fft_model(train, fc_periods):

    autoarima = arima.AutoARIMA(
        stepwise=True,
        trace=1,
        seasonal=False,  # because we use Fourier
        intercept="auto",
        suppress_warnings=True,
        error_action="ignore",
        random_state=42,
        m=1,
        start_p=1,
        start_q=1,
        max_p=3,
        max_q=4,
    )

    pipe = pipeline.Pipeline(
        [
            ("fourier", ppc.FourierFeaturizer(m=12, k=2)),
            ("arima", autoarima),
        ]
    )

    pipe.fit(train)

    return pipe

def get_arima_auto_model(train, fc_periods):

    model = pm.AutoARIMA(
        stepwise=True,
        trace=1,
        seasonal=True,
        intercept="auto",
        suppress_warnings=True,
        error_action="ignore",
        random_state=42,
        m=12,
        start_p=1,
        start_q=1,
        max_p=3,
        max_q=3,
        start_P=1,
        start_Q=1,
        max_P=2,
        max_Q=2,
        # start_D=0,
        # max_D=2,
    )

    model.fit(train)

    return model


def new_game():
    guesses = []
    correct_guesses = 0
    question_no = 1
    for i in questions:
        print('-----------------------')
        print(i)
        for j in answers[question_no-1]:
            print(j)
        question_no += 1
        guess = input('Enter A/B/C/D: ').upper()
        guesses.append(guess)
        correct_guesses += check_answer(questions.get(i), guess)

    display_score(correct_guesses, guesses)

def check_answer(answer, guess):
    if answer == guess:
        print('Correct!')
        return 1
    else:
        print('Wrong!')
        return 0

def display_score(correct_guesses, guesses):
    print('-----------------------')
    print('Result:')
    print('-----------------------')
    print('Answers: ', end='')
    for i in questions:
        print(questions.get(i), end=' ')
    print()
    print('Guesses: ', end='')
    for i in guesses:
        print(i, end=' ')
    print()
    print(f'You have got {correct_guesses} points!')

def play_again():
    response = input('Do you Want to play again ? (y/n): ')
    response = response.upper()
    if response == 'Y':
        return True
    else:
        return False

questions = {
    'Who created Python?: ': 'A',
    'What year was Python created: ': 'B',
    'Python is tributed to which dance company!': 'C',
    'Is the earth round?: ': 'A'
}

answers =  [['A. Guido van rossum', 'B. Bill gates', 'C. Elon Musk', 'D. Mark Zach'], ['A. 1989', 'B. 2016', 'C. 2000', 'D. 2001'],
['A. Lonely Island', 'B. B Smosh', 'C. Monty Python', 'D. SNL'], ['A. False', 'B. True', 'C. Sometimes', 'D. What is this!']]

new_game()
while play_again():
    new_game()


import time
import config
import threading
import datetime
import queue
import json
import os

import board as brd
from sgf import make_sgf, parse_sgf
from client import ClientSocketError
from utils import check_and_mkdir, get_html_code

def color_to_char(c):
    if c == brd.BLACK:
        return 'b'
    return 'w'

def get_opp_color(c):
    if c == brd.BLACK:
        return brd.WHITE
    return brd.BLACK

def move_to_vertex(board, move, support_analysis):
    move = move.strip()
    analysis = None
    if support_analysis:
        # Parse and validate analyze info.
        tokens = move.split(None, 1)
        move = tokens[0]
        if len(tokens) > 1:
            try:
                info = json.loads(tokens[1])
                analysis = json.dumps(info, indent=None, separators=(",", ":"))
            except:
                pass
    vertex = brd.NULL_VERTEX
    move = move.lower()

    if move == "pass":
        vertex = brd.PASS
    elif move == "resign":
        vertex = brd.RESIGN
    else:
        x = ord(move[0]) - (ord('A') if ord(move[0]) < ord('a') else ord('a'))
        y = int(move[1:]) - 1
        if x >= 8:
            x -= 1
        vertex = board.get_vertex(x,y)
    return move, vertex, analysis

def write_sgf_and_html(
    setting,
    names,
    date,
    move_history,
    result,
    base_name
):
    black_name, white_name = names
    sgf_store_path = os.path.join(
        *config.DATA_DIR_ROOT, "sgf", setting["store"])

    if os.path.isdir(sgf_store_path):
        # Save the SGF file.
        sgf_name = "{}.sgf".format(base_name)
        sgf = make_sgf(
                  setting["board_size"],
                  setting["komi"],
                  black_name,
                  white_name,
                  setting["main_time"],
                  date,
                  move_history,
                  result
              )
        sgf_full_name = os.path.join(sgf_store_path, sgf_name)
        with open(sgf_full_name, 'w') as f:
            f.write(sgf)

        html_store_path = os.path.join(
            *config.DATA_DIR_ROOT, "html", setting["store"])
        if os.path.isdir(html_store_path) and config.WGO_PATH is not None:
            html_name = "{}.html".format(base_name)

            back_count = 0
            for v in setting["store"].split(os.sep):
                # Assume there is no ".." symbol.
                if v != ".":
                    back_count += 1

            back_path = "."
            for _ in range(back_count+1):
                # Back to data directory root.
                back_path = os.path.join(back_path, "..")

            # Rewrite the WGO and SGF path in the HTML file.
            sgf_name_in_html = os.path.join(
                back_path, "sgf", setting["store"], sgf_name)
            wgo_path_in_html = os.path.join(back_path, config.WGO_PATH)

            html_full_name = os.path.join(html_store_path, html_name)
            if not os.path.isfile(html_full_name):
                # Only wrtie the HTML file once.
                with open(html_full_name, 'w') as f:
                    f.write(get_html_code(wgo_path_in_html, sgf_name_in_html))
        return True
    return False

def play_match_game(game_id, black, white, setting):
    # Play a match game and save the SGF file. The client may
    # crash here. We detect it and guarantee that the client can
    # return back safely. The socket is not closed here when
    # crashing. The master will close it later.

    # Initialize some basic data.
    time_lefts = {
        brd.BLACK : setting["main_time"],
        brd.WHITE : setting["main_time"]
    }
    players = {
        brd.BLACK : black,
        brd.WHITE : white
    }

    # TODO: Add support for Chinese rule and Japanese rule.
    rule = setting["rule"]
    should_superko = rule == "chinese-like"

    # We only record the starting time in order to fix
    # the output file name.
    date = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M:%S")

    #
    sgf_clock_time = time.time()

    # The store path and SGF name.
    base_name = "{}-{}(B)-{}(W)-g{}".format(date, black.name, white.name, game_id)

    move_history = list() # It contains (move, time_left and analysis).

    # Try to read the SGF file. Should start the game from
    # it if the source is not None.
    sgf_source = setting.get("sgf", None)
    if (sgf_source is not None) and (os.path.isfile(sgf_source)):
        with open(sgf_source, 'r') as f:
            sgf = f.read().strip()
            board_size, komi, move_history = parse_sgf(sgf)
            # Rewrite the game setting.
            setting["board_size"] = board_size
            setting["komi"] = komi

    board = brd.Board(setting["board_size"], setting["komi"])
    result_status = dict()

    try:
        for player in players.values():
            # Request each clients to initialize the game also
            # create new socket file.
            player.create_sockfile()
            player.request_setup(
                setting["board_size"],
                setting["komi"],
                setting["main_time"] * 1000,
                players[brd.WHITE].name,
                players[brd.BLACK].name
            )

        while len(move_history) > board.move_num:
            # Play the moves from SGF file.
            side_to_move = board.to_move
            to_move_player = players[side_to_move]
            move, time_left, _ = move_history[board.move_num]

            move, vertex, _ = move_to_vertex(
                                  board, move, False
                              )

            # Always assuem the move is legel.
            board.play(vertex)

            # Both clients should play the move.
            for player in players.values():
                player.request_play(
                    color_to_char(side_to_move),
                    board.vertex_to_text(vertex),
                    int(time_left * 1000)
                )

        while True:
            side_to_move = board.to_move
            opp_to_move = get_opp_color(board.to_move)
            to_move_player = players[side_to_move]

            # Request the engine to genmove the next move.
            clock_time = time.time()
            time_left = time_lefts[side_to_move]
            rep = to_move_player.request_genmove(
                      color_to_char(side_to_move),
                      int(time_left * 1000)
                  )
            time_left -= (time.time() - clock_time)

            if time_left < 0:
                # Game ended by time out.
                winner = opp_to_move
                result_status["winner"] = winner
                result_status["type"] = "time out"
                result_status["info"] = "{}+Time".format(
                                            color_to_char(winner).upper()
                                        )
                break

            # Parse the move and analysis string.
            time_lefts[side_to_move] = time_left
            move, vertex, analysis = move_to_vertex(
                                         board,
                                         rep,
                                         to_move_player.support_analysis
                                     )

            if vertex == brd.RESIGN:
                # Game ended by resign move.
                winner = opp_to_move
                result_status["winner"] = winner
                result_status["type"] = "resign"
                result_status["info"] = "{}+Resign".format(
                                            color_to_char(winner).upper()
                                        )
                break

            is_legal = board.play(vertex)

            if not is_legal or \
                (vertex != brd.PASS and \
                     not should_superko and board.superko()):
                # Game ended by illegal move.
                winner = opp_to_move
                result_status["winner"] = winner
                result_status["type"] = "illegal move"
                result_status["info"] = "{}+Illegal".format(
                                            color_to_char(winner).upper()
                                        )
                break

            move_history.append((move, int(time_left), analysis))

            # Try to save game result into SGF file after updating
            # the move_history. Failed to save it if the client play
            # the move too quick.
            if time.time() - sgf_clock_time > 5:
                if write_sgf_and_html(
                       setting,
                       (black.name, white.name),
                       date,
                       move_history,
                       None,
                       base_name):
                    sgf_clock_time = time.time()

            # Request the opponent to play the move.
            time_left = time_lefts[opp_to_move]
            opp_player = players[opp_to_move]
            opp_player.request_play(
                color_to_char(side_to_move),
                board.vertex_to_text(vertex),
                int(time_left * 1000)
            )

            if board.num_passes >= 2:
                # Game ended by double pass. Now score
                # the final position.

                if rule == "chinese-like":
                    result_status["type"] = "double pass"
                    black_score = board.final_score()
                elif rule == "null":
                    result_status["type"] = "no rule"
                    black_score = 0
                else:
                    # Invalid rules.
                    result_status["type"] = "invalid rule"
                    black_score = 0

                if black_score > 0.001:
                    winner = brd.BLACK
                elif black_score < -0.001:
                    winner = brd.WHITE
                else:
                    winner = brd.EMPTY
                result_status["winner"] = winner

                if winner == brd.EMPTY:
                    result_status["info"] = "0"
                else:
                    result_status["info"] = "{}+{}".format(
                                                color_to_char(winner).upper(),
                                                abs(black_score)
                                            )
                break
    except:
        # TODO: Catch the error and write it into the SGF file.
        result_status["winner"] = brd.EMPTY
        result_status["type"] = "socket error"
        result_status["info"] = "0"

    result = result_status["info"]
    err = str()

    for player in players.values():
        try:
           # Send the last request to server here in order
           # to check whether the socket is still connected.
           player.request_poll()
        except ClientSocketError as e:
            pass

    # Close the socket file because the we can not push socket file
    # onto process queue.
    for player in players.values():
        try:
           player.close_sockfile()
        except ClientSocketError as e:
            pass

    # Always save the SGF file before leaving.
    write_sgf_and_html(
        setting,
        (black.name, white.name),
        date,
        move_history,
        result,
        base_name)

def match_loop(process_id, ready_queue, finished_queue):
    match_threads = dict()

    while True:
        finished_ids = list()
        for k, v in match_threads.items():
            # Collect all finished match games.
            t, _, _, _ = v
            if not t.is_alive():
                finished_ids.append(k)

        for i in finished_ids:
            # The match game is game over. Push the play
            # back to main pooling.
            v = match_threads.pop(i)
            t, i, b, w = v
            t.join()

            task = {
                "black" : b,
                "white" : w,
                "gid"   : i,
                "pid"   : process_id
            }
            finished_queue.put(task)

        try:
            task = ready_queue.get(block=True, timeout=0.1)
            if task["pid"] != process_id:
                # Not correct process id. Reture it to finished
                # queue.
                finished_queue.put(task)
            black = task["black"] # black player
            white = task["white"] # white player
            game_id = task["gid"] # game id
        except queue.Empty:
            continue

        # TODO: Add support for more task type.

        setting = {
            "main_time"  : task.get("main_time", config.DEFAULT_MAIN_SECOND),
            "board_size" : task.get("board_size", config.DEFAULT_BOARD_SIZE),
            "komi"       : task.get("komi", config.DEFAULT_KOMI),
            "sgf"        : task.get("sgf", None),
            "store"      : task.get("store", config.DEFAULT_STORE_DIR),
            "rule"       : task.get("rule", "chinese-like")
        }

        # New game is starting. Each threads hold one game. The threads
        # will be released after the gameover.
        t = threading.Thread(
                target=play_match_game,
                args=(game_id, black, white, setting, ),
                daemon=True
            )
        t.start()
        match_threads[t.ident] = (t, game_id, black, white)


import os
import time
import warnings
warnings.filterwarnings('ignore')

import torch
import cv2
from tqdm import tqdm

from openpose.body.estimator import BodyPoseEstimator
from openpose.utils import draw_body_connections, draw_keypoints

def get_img_paths(img_folder):
    image_names = [x for x in os.listdir(img_folder) if x.endswith('.jpg') or x.endswith('.jpeg')]
    image_paths = [
        os.path.join(img_folder, image)
        for image in image_names
        if image.endswith('.jpg') or image.endswith('.jpeg')
    ]
    return image_paths, image_names

def load_img(path):
    return cv2.imread(path)

def save_img(img, path):
    cv2.imwrite(path, img)

def main(input_folder, output_folder, use_cuda=False):

    io_time = 0
    compute_time = 0
    other_time = 0

    model_download_time = time.time()
    estimator = BodyPoseEstimator(pretrained=True, use_cuda=use_cuda)
    model_download_time = time.time() - model_download_time

    other_t = time.time()
    image_paths, image_names = get_img_paths(input_folder)
    other_time += time.time() - other_t

    print(f'Processing {len(image_names)} images using {"GPU" if use_cuda else "CPU"} ...')
    for image_path, image_name in tqdm(zip(image_paths, image_names)):
        io_t = time.time()
        img_input = load_img(image_path)
        io_time += time.time() - io_t

        compute_t = time.time()
        keypoints = estimator(img_input)
        img_output = draw_body_connections(img_input, keypoints, thickness=4, alpha=0.7)
        img_output = draw_keypoints(img_output, keypoints, radius=5, alpha=0.8)
        compute_time += time.time() - compute_t

        io_t = time.time()
        save_path = os.path.join(output_folder, image_name)
        save_img(img_output, save_path)
        io_time += time.time() - io_t

    return other_time, io_time, compute_time

if __name__ == "__main__":
    input_folder = r"C:\Users\Mobin\Desktop\Mobin\eca-dl\data\image\batch32"
    use_cuda = False

    other_time = time.time()
    path, folder = os.path.split(input_folder)
    output_folder = os.path.join(path, folder+'_pose')
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    other_ti = other_time + time.time()
    # print(f'-- other time is: {other_time} seconds')

    other_time, io_time, compute_time = main(input_folder, output_folder, use_cuda)
    print(f'-- other time is: {other_time+other_ti} seconds')
    print(f'-- io time is: {io_time} seconds')
    print(f'-- compute time is: {compute_time} seconds')


import string
import math
import numpy as np
import matplotlib.pyplot as plt

data=open('../results/Test1_2.txt')

for line in data:
    if line=="\n":
        break

data.readline()

index=[]
X1=[]
X2=[]
F=[]
fitVal=[]

for line in data:
    (i,x1,x2,f,fit)=line.split()
    index.append(int(i))
    X1.append(float(x1))
    X2.append(float(x2))
    F.append(math.log10(float(f)))
    fitVal.append(float(fit))

plt.plot(index,X1,label="X1")
plt.plot(index,X2,label="X2")
plt.xlabel("Iteration Step")
plt.ylabel("X")
plt.legend()
plt.plot()
plt.savefig('../pic/T1-2_res_x1_x2.png')
plt.close()

plt.plot(index,F)
plt.xlabel("Iteration Step")
plt.ylabel("log(F(x1,x2))")
plt.plot()
plt.savefig('../pic/T1-2_res_f.png')
plt.close()

Multi-objective Optimization in Fluid Mechanics/script/t1-2_draw_res.py


from langchain.document_loaders import PyPDFDirectoryLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import Chroma

def process_and_save_vectors():
    # Load PDF documents from a directory
    #PyPDFDirectoryLoader load and split the pdf present in documents into pages

    loader = PyPDFDirectoryLoader("documents")
    pages = loader.load_and_split()
    print(len(pages))
    #RecursiveCharacterTextSplitter split pages into smaller chunks
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1024, chunk_overlap=20)
    documents = text_splitter.split_documents(pages)
    print(len(documents))

    # Initialize HuggingFaceEmbeddings for sentence embeddings
    embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

    # Create and persist a Chroma vector database from the documents
    vectordb = Chroma.from_documents(
        documents,
        embeddings,
        persist_directory='./data'
    )
    vectordb.persist()

if __name__ == "__main__":
    process_and_save_vectors()


def main():
    grid = [ [] for i in range(9)]
    with open("input.txt","r") as fp:
        lines = fp.read().splitlines()
        length = len(lines[0])
        grid = [ [] for i in range(length)]
        for x in range(len(lines)):
            #print(lines[x])
            for i in lines[x]:
                grid[x].append(int(i))
        forest = trees(grid)
        #for i in forest.getGrid():
        #    print(i)
        #print(forest.checkVisible(1,3))
        #exit()
        for i in range(1,length-1):
            for j in range(1,length-1):
                forest.checkVisible(i,j)
        vis = forest.getVisible()
        max = 0
        for i in vis:
            if vis[i] > max:
                max = vis[i]
        print(max)

class trees:
    grid = []
    length = 0
    visible = {}
    def __init__(self, grid):
        self.grid = grid
        self.visible = {}
        self.length = len(grid[0])
    def getGrid(self):
        return self.grid
    def getVisible(self):
        return self.visible
    def checkVisible(self, x,y):
        #print(x,y)
        #if (x,y) in self.visible:
        #    return self.visible[(x,y)]
        left = self.checkLeft(x,y)

        right = self.checkRight(x,y)
        up = self.checkUp(x,y)
        down = self.checkDown(x,y)
        self.visible[(x,y)] = up * down * left * right
        return
    def checkLeft(self, x,y):
        val = self.grid[y][x]
        #print('check left val',val)
        cnt = 0
        x-=1
        while x >= 0:
            cnt+=1
            if self.grid[y][x] >= val:
                #print('cant see',x,y,'val',self.grid[y][x])
                return cnt
            x-=1
        return cnt
    def checkRight(self, x,y):
        val = self.grid[y][x]
        #print('check right val',val)
        cnt=0
        x+=1
        while x < self.length:
            cnt+=1
            if self.grid[y][x] >= val:
                #print('cant see',x,y,'val',self.grid[y][x])
                return cnt
            x+=1
        return cnt
    def checkUp(self, x,y):
        val = self.grid[y][x]
        #print('check up val',val)
        cnt=0
        y-=1
        while y >= 0:
            cnt+=1
            if self.grid[y][x] >= val:
                #print('cant see',x,y,'val',self.grid[y][x])
                return cnt
            y-=1
        return cnt
    def checkDown(self, x,y):
        val = self.grid[y][x]
        #print('check down val',val)
        cnt=0
        y+=1
        while y < self.length:
            cnt+=1
            if self.grid[y][x] >= val:
                #print('cant see',x,y,'val',self.grid[y][x])
                return cnt
            y+=1
        return cnt

if __name__=="__main__":
    main()


# Require individual inference queries of the form P(q|e):

# Number of columns occupied by each attribute
list_of_lengths=[4,10,5,10,10,5,5,4,1,3,4,4,10,3,3,4,4,2,1,1,1]

# Get column indices for where each attribute begins and ends
cumulative=[0]
for i,j in enumerate(list_of_lengths):
    cumulative.append(cumulative[i]+j)
print(cumulative)

total_number = sum(list_of_lengths) # 94
template=["*" for j in range(total_number)] # * indicates loop over variable

queries=[]
evidence_male=[]
evidence_female=[]

""" For every attribute component, set up a blank template, and then specify the configuration of the query we want to make for ONE ATTRIBUTE (e.g. [1,0,0,0,*,*,*,*,...])"""

for inference_instance in range(total_number):
    # Template
    temporary=["*" for j in range(total_number)]
    for position,threshold in enumerate(cumulative):
        # Only perform procedure if the inference_instance is in the range of the attribute we're currently considering
        if (inference_instance<threshold) and (inference_instance>=cumulative[position-1]):

            # Procedure for binary variables (must do [*,*,*,0,*] and [*,*,*,1,*]).
            if (threshold-cumulative[position-1])==1:
                # Set up two queries, one with a 0 in the relevant position and the other with a one.
                temporary_1=["*" for j in range(total_number)]
                temporary_2=["*" for j in range(total_number)]
                temporary_1[inference_instance]=0
                temporary_2[inference_instance]=1

                # Append to list of queries
                queries.append(temporary_1)
                queries.append(temporary_2)

                # Now allocate an evidence query (1 or 0 in protected attribute column
                temporary_evidence_1=["*" for j in range(total_number)]
                temporary_evidence_F1=["*" for j in range(total_number)]
                temporary_evidence_1[53]=0
                temporary_evidence_F1[53]=1

                # Append to evidence
                evidence_male.append(temporary_evidence_1)
                evidence_male.append(temporary_evidence_1)
                evidence_female.append(temporary_evidence_F1)
                evidence_female.append(temporary_evidence_F1)

            # Procedure for one-hot encoded variables (e.g. [*,*,0,0,1,0,*,*]
            else:
                temp_range=range(cumulative[position-1],threshold)

                # Specify all zeros in range of attribute.
                for index in temp_range:
                    temporary[index]=0

                # Set one specific column of these zeros to be 1
                temporary[inference_instance]=1

                # Append to queries
                queries.append(temporary)

                # Generate corresponding evidence input and append
                temporary_evidence_1=["*" for j in range(total_number)]
                temporary_evidence_F1=["*" for j in range(total_number)]
                temporary_evidence_1[53]=0
                temporary_evidence_F1[53]=1
                evidence_male.append(temporary_evidence_1)
                evidence_female.append(temporary_evidence_F1)

#print(queries)

import csv

csvfile="single_attribute_query.q"
male_evidencefile="protected_attribute_evidence_male.ev"
female_evidencefile="protected_attribute_evidence_female.ev"

# Write queries and evidence to CSV files for input to SPN Inference task.
with open(csvfile,"w") as output:
    writer=csv.writer(output,lineterminator='\n')
    writer.writerows(queries)

with open(male_evidencefile,"w") as output:
    writer=csv.writer(output,lineterminator='\n')
    writer.writerows(evidence_male)

with open(female_evidencefile,"w") as output:
    writer=csv.writer(output,lineterminator='\n')
    writer.writerows(evidence_female)

# Pseudocode for inference.

# Ascertain set {v_i,...,v_j} \in s such that v_i || protected attribute a.

# Write separate python script to clean out all statistically INDEPENDENT variables, so we just train a vanilla SPN with data subdivision in first step on just the dependent variables.

# Write to array P(q|ev) for all q.

# Calculate (again using python script) \mathbb{E}(q|ev) for all continuous variables.

# Back out P(q|ev) for all categoricals.

# Train (on all variables, including the modified ones) a model for predicting some attribute on the basis of the existing set.

# I've had another idea: what if you TRAIN on unadjusted variables, but then perform TESTING on adjusted counterparts??

MSc Code/MSc Python Code/Inference_query_generator.py


"""Given a list of n numbers, determine if it contains any duplicate numbers."""
# Restate Question
# So I am given a list of numbers and I should determine if dupliactes are in this list?

# Clarifying Question
# For example, if I had nums = [5,6,3,8,2], I'll return no since it has none
# And = [3,6,2,7,4,7] return Yes, 7.
# Should I return the new list?

# Assumptions
# We have room for memory

# Brainstorm Solution
# We could sort the list and add duplicates to another list
# We could compare every value in the list
# We could create a dictionary and count the frequency of each number and return key value pairs
# We Could use Binary search to find duplicates

# Explain Rational
# We can sort, loop. For each duplicate we will add to a new list. This is a o(1) runtime.
# Discuss Tradeoffs
# We trade memory for speed because we create a new list
# Suggest Improvements
# For speed I would say use a hash map to find duplicate.

def find_duplicate(nums):
    # Create an empty array
    new_nums = []
    # loop through nums
    for num in nums:
        # if num not in nums
        if num in new_nums:
            # return num
            return num
        new_nums.append(num)
    return new_nums

nums = [3,6,2,7,4,7]
print(find_duplicate(nums))


import PyPluMA

class BetaInAndOutPlugin:
    def input(self, inputfile):
       self.parameters = dict()
       paramfile = open(inputfile, 'r')
       for line in paramfile:
           contents = line.strip().split('\t')
           self.parameters[contents[0]] = contents[1]

    def run(self):
        csvfile = open(PyPluMA.prefix()+"/"+self.parameters['csvfile'], 'r')
        metafile = open(PyPluMA.prefix()+"/"+self.parameters['metadata'], 'r')
        header = metafile.readline()
        headercontents = header.strip().split(',')
        sample_idx = headercontents.index("\"Sample\"")
        group_idx = headercontents.index("\"Group\"")

        groups = dict()
        group_list = []
        for line in metafile:
           contents = line.strip().split(',')
           sample = contents[sample_idx]
           group = contents[group_idx]
           if (group in groups):
               groups[group].append(sample)
           else:
               group_list.append(group)
               groups[group] = [sample]

        csvfile.readline()
        self.values = dict()
        # Assume: Sample1, Sample2, Value
        for i in range(len(group_list)):
            self.values[group_list[i]] = []
        self.values["\"out\""] = []

        for line in csvfile:
            contents = line.strip().split(',')
            sample1 = contents[0]
            sample2 = contents[1]
            value = contents[2]
            group_idx1 = -1
            group_idx2 = -1
            for i in range(len(group_list)):
                if (sample1 in groups[group_list[i]]):
                   group_idx1 = i
                if (sample2 in groups[group_list[i]]):
                   group_idx2 = i
            if (group_idx1 == group_idx2):
               self.values[group_list[group_idx1]].append(value)
            else:
               self.values["\"out\""].append(value)

    def output(self, filename):
       outfile = open(filename, 'w')
       for group1 in self.values:
          outfile.write(group1+',')
          for i in range(len(self.values[group1])):
              outfile.write(self.values[group1][i])
              if (i == len(self.values[group1])-1):
                  outfile.write('\n')
              else:
                  outfile.write(',')


from http import HTTPStatus

from src.app import jwt
from src.common.response import BaseResponse
from src.db.redis import redis_client

@jwt.token_in_blocklist_loader
def check_if_token_is_revoked(jwt_header, jwt_payload: dict):
    jti = jwt_payload["jti"]
    token_in_redis = redis_client.get(jti)
    return token_in_redis is not None

@jwt.revoked_token_loader
def revoked_token_callback(jwt_header, jwt_payload: dict):
    return (
        BaseResponse(
            success=False, error={"msg": "The token has been revoked."}
        ).dict(),
        HTTPStatus.NOT_FOUND,
    )

@jwt.needs_fresh_token_loader
def token_not_fresh_callback(jwt_header, jwt_payload):
    return (
        BaseResponse(
            success=False, error={"msg": "The token is not fresh."}
        ).dict(),
        HTTPStatus.UNAUTHORIZED,
    )


def accum(inputStr):
    outputList = []
    count = 0
    for v in inputStr:
        initialValue = v
        listLen = count +1
        tempList = [initialValue]*listLen
        # print (tempList)
        tempString= ''.join(tempList)
        tempString= tempString.capitalize()
        # print (tempString)
        outputList.append(tempString)
        count = count+1
        # print (outputList)
    outputString = '-'.join(outputList)
    return outputString

# 利用enumerate()简化代码

def accum(inputStr):
    outputList = []
    for i,v in enumerate(inputStr,1):
        tempList = [v]*i
        tempString= ''.join(tempList)
        tempString= tempString.capitalize()
        outputList.append(tempString)
    outputString = '-'.join(outputList)
    return outputString

# 考虑直接字符处理不用list

#未完成

def accum(inputStr):
    outputList = []
    # count = 0
    for i,v in enumerate(inputStr,1):
        tempString = v*i
        print (tempString)
        tempString= tempString.capitalize()
        print (tempString)
        outputString = '-'.join(tempString)
    return outputString

# Best One

def accum(s):
    return '-'.join(c.upper() + c.lower() * i for i, c in enumerate(s))


import cx_Freeze
import os

os.environ['TCL_LIBRARY'] = r'C:\Users\igrok\AppData\Local\Programs\Python\Python37-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\igrok\AppData\Local\Programs\Python\Python37-32\tcl\tk8.6'

base = 'Win32GUI'

tcl = "C:/Users/igrok/AppData/Local/Programs/Python/Python37-32/DLLs/tcl86t.dll"
tk = "C:/Users/igrok/AppData/Local/Programs/Python/Python37-32/DLLs/tk86t.dll"

vcruntime140 = "vcruntime140-32.dll"

packages = ["pygame", "random", "math", "sys", "time"]
include_files = ["img/earth.png", "img/jupiter.png", "img/mars.png", "img/mercury.png",
"img/neptune.png", "img/saturn.png", "img/sun.png", "img/uranus.png", "img/venus.png",
"img/meteor.png", tcl, tk, vcruntime140, "python37-32.dll",
"music/music.mp3", "img/question.png","img/settings_ico.png",
"text/all_text_eng.txt", "text/all_text_ru.txt", "text/hint_hole_eng.txt",
"text/hint_hole_ru.txt", "text/hint_solar_eng.txt", "text/hint_solar_ru.txt",
"text/text_planets_eng.txt", "text/text_planets_ru.txt", "font/font.ttf"]
includes = ["dots", "dot_hole", "functions", "planets", "settings"]

# executables = []

cx_Freeze.setup(
    name = "Black Hole",
    options = {"build_exe": {"packages": packages,
                            "include_files": include_files,
                            "includes" : includes,
                            'include_msvcr': True
                            }},
    executables = [cx_Freeze.Executable("main.py",
                                        base = base,
                                        icon = "ico.ico",
                                        targetName = "Space.exe")],
    version='1.5.0'
)


raw_minutes = int(input('Hur många minuter? '))

minutes = raw_minutes % 60
hours = (raw_minutes / 60) - (minutes / 60)

hours, minutes = int(hours), int(minutes)

hour_form = 'timmar'
minute_form = 'minuter'

if hours == 1:
	hour_form = 'timme'

if minutes == 1:
	minute_form = 'minut'

message = f'Det är {hours} {hour_form}'
if minutes:
	message += f' och {minutes} {minute_form}'
message += '.'

print(message)


#!/usr/bin/env python

# System.
import os

# Arguments.
import argparse

# Parser.
from syntaxic import parser

# Helper.
from helper import Helper

class Assembler:
	"""
	Assembles programs.
	"""

	@staticmethod
	def __parse_arguments():
		"""
		Parses the arguments.

		:return: The parsed arguments.
		"""

		# Parse the arguments.
		argument_parser = argparse.ArgumentParser()
		argument_parser.add_argument("file", help="select the input assembly file")
		argument_parser.add_argument("-o", "--output", help="select the output logisim file")
		return vars(argument_parser.parse_args())

	@staticmethod
	def assemble(input_path: str, output_path: str):
		"""
		Assembles a program.

		:param input_path: The input assembly file.
		:param output_path: The output logisim file.
		"""

		# Check the input file.
		if os.path.exists(input_path):

			# Read the assembly file.
			input_file = open(input_path, "r")
			data = input_file.read()
			input_file.close()

			# Write the logisim file.
			output_file = open(output_path, "w")
			output = parser.parse(data)
			output_file.write(output)
			output_file.close()

			# Check the output file.
			if not os.path.exists(output_path):
				print("Assembler error: Error while assembling the program.")

		else:
			print("Assembler error: No such file '{}'.".format(input_path))

	@staticmethod
	def run():
		"""
		Runs the assembler.
		"""

		# Parse the arguments.
		options = Assembler.__parse_arguments()

		# Set the default output path.
		if options["output"] is None:
			options["output"] = Helper.replace_extension(options["file"], "out")

		# Assemble the program.
		Assembler.assemble(options["file"], options["output"])

# Run the assembler.
if __name__ == "__main__":
	Assembler.run()


emp_list = [['rita','singh',25,30],['tim','cruse',24,35]]
class Employee ():
  def __init__(self,employee=[]):
    self.fname = employee[0]
    self.lname = employee[1]
    self.hrate = employee[2]
    self.hrs_worked = employee[3]

  def calc_wages(self):
    wages = self.hrate * self.hrs_worked
    name = self.fname+""+self.lname
    print(name,wages)

for employees in emp_list:
  emp = Employee(employee)
  emp.calc_wages()


import sys
sys.path.append('.')
sys.path.append('..')
sys.path.append('../../')
sys.path.append('../../../')
import numpy as np
import pandas as pd
import csv
from config import corpus, model_label as model, model_stats, label_stats
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
from textstat import fernandez_huerta
from sentiment_analysis_spanish import sentiment_analysis
from subprocess import call
import os.path

sentiment = sentiment_analysis.SentimentAnalysisSpanish()
def sentimiento(text):
    return sentiment.sentiment(text)

df = pd.read_csv('./corpus/preprocessed/preprocess_%s'%corpus, delimiter='\t', header=None, names=['index', 'label', 'text'], quoting=csv.QUOTE_NONE, error_bad_lines=False)
df['label'] = df['label'].str.strip()
df['char'] = df['text'].str.len()
df['words'] = df['text'].str.split().apply(len)
df['readability'] = df['text'].apply(lambda x : fernandez_huerta(x))
df['sentiment'] = df['text'].apply(lambda x : sentimiento(x))

if label_stats:
    if not os.path.exists('./corpus/stats'):
        call('mkdir ./corpus/stats', shell=True)
    call('mkdir ./corpus/stats/%s'%corpus.replace('.txt', ''), shell=True)

    label_set = list(dict.fromkeys(df['label'].str.strip()))

    for label in label_set:
        label_df = df[df.label.str.contains(label,case=True)]
        fig, axes = plt.subplots(4, 1, sharex=False, figsize=(20, 25))
        fig.suptitle('Stats for label %s'%label)

        # ROW 1
        sns.histplot(data=label_df['char'], ax = axes[0], stat='count', palette = sns.color_palette('hls'))
        axes[0].axvline(x=label_df['char'].mean(), color="red", linestyle="--", label='mean')
        axes[0].set_xlim([0, 300])
        axes[0].set_title('Number of characters in samples')
        axes[0].set_xlabel('MEAN: %s'%label_df['char'].mean())

        # ROW 2
        sns.histplot(data=label_df['words'], ax = axes[1], stat='count', palette = sns.color_palette('hls'))
        axes[1].axvline(x=label_df['words'].mean(), color="red", linestyle="--", label='mean')
        axes[1].set_title('Number of words in samples')
        axes[1].set_xlim([0, 50])
        axes[1].set_xlabel('MEAN: %s'%label_df['words'].mean())

        # ROW 3
        sns.histplot(data=label_df['readability'], ax = axes[2], stat='count')
        axes[2].axvline(x=label_df['readability'].mean(), color='red', linestyle='--', label='mean')
        axes[2].set_title('Readability of samples')
        axes[2].set_xlim([-130, 130])
        axes[2].set_xlabel('MEAN: %s'%label_df['readability'].mean())

        # ROW 4
        sns.histplot(data=label_df['sentiment'], ax = axes[3], stat = 'count')
        axes[3].axvline(x = label_df['sentiment'].mean(),  color="red", linestyle="--", label='mean')
        axes[3].set_title('Sentiment of samples')
        axes[3].set_xlim([0, 1])
        axes[3].set_xlabel('MEAN: %s'%label_df['sentiment'].mean())

        plt.tight_layout()

        plt.savefig('./corpus/stats/%s/%s.png'%(corpus.replace('.txt', ''), label))

    # BOXPLOTS

    fig, axes = plt.subplots(4, 1, sharex=False, figsize=(16,20))
    fig.suptitle('BoxPlots for Corpus %s'%corpus.replace('txt', ''))
    sns.boxplot(x = 'char', y = 'label', data=df, ax = axes[0], orient = 'h', palette='Set2')
    sns.boxplot(x = 'words', y = 'label', data=df, ax = axes[1], orient = 'h', palette='Set2')
    sns.boxplot(x = 'readability', y = 'label', data=df, ax = axes[2], orient = 'h', palette='Set2')
    sns.boxplot(x = 'sentiment', y = 'label', data=df, ax = axes[3], orient = 'h', palette='Set2')

    plt.savefig('./corpus/stats/%s/boxplots.png'%corpus.replace('.txt', ''))

if model_stats:
    df['cluster'] = pd.read_csv('./results/%s/topics.txt'%model, header=None, names=['cluster'], quoting=csv.QUOTE_NONE, error_bad_lines=False)

    discards = df[df['cluster'] == -1]
    classified = df[df['cluster'] != -1]

    fig, axes = plt.subplots(4, 2, sharex=False, figsize=(28, 20))
    fig.suptitle('Stats for model %s'%model)

    # FIRST ROW: NUM CHARACTERS
    sns.histplot(data=classified['char'], ax = axes[0,0], stat='count', palette = sns.color_palette('hls'))
    axes[0, 0].axvline(x=classified['char'].mean(), color="red", linestyle="--", label='mean')
    axes[0, 0].set_title('Number of char classified')
    axes[0, 0].set_xlim([0, 300])
    axes[0, 0].set_xlabel('MEAN: %s'%classified['char'].mean())

    sns.histplot(data=discards['char'], ax = axes[0,1], stat='count', palette = sns.color_palette('hls'))
    axes[0, 1].axvline(x=discards['char'].mean(), color="red", linestyle="--", label='mean')
    axes[0, 1].set_title('Number of char discards')
    axes[0, 1].set_xlim([0, 300])
    axes[0, 1].set_xlabel('MEAN: %s'%discards['char'].mean())

    # SECOND ROW: NUM WORDS
    sns.histplot(data=classified['words'], ax = axes[1, 0], stat='count', palette = sns.color_palette('hls'))
    axes[1, 0].axvline(x=classified['words'].mean(), color="red", linestyle="--", label='mean')
    axes[1, 0].set_title('Number of words classified')
    axes[1, 0].set_xlim([0, 50])
    axes[1, 0].set_xlabel('MEAN: %s'%classified['words'].mean())

    sns.histplot(data=discards['words'], ax = axes[1, 1], stat='count', palette = sns.color_palette('hls'))
    axes[1, 1].axvline(x=discards['words'].mean(), color="red", linestyle="--", label='mean')
    axes[1, 1].set_title('Number of words discards')
    axes[1, 1].set_xlim([0, 50])
    axes[1, 1].set_xlabel('MEAN: %s'%discards['words'].mean())

    # THIRD ROW: READABILITY
    sns.histplot(data=classified['readability'], ax = axes[2,0], stat='count')
    axes[2, 0].axvline(x=classified['readability'].mean(), color='red', linestyle='--', label='mean')
    axes[2, 0].set_title('Readability of classified')
    axes[2, 0].set_xlim([-130, 130])
    axes[2, 0].set_xlabel('MEAN: %s'%classified['readability'].mean())

    sns.histplot(data=discards['readability'], ax = axes[2,1], stat='count')
    axes[2, 1].axvline(x=discards['readability'].mean(), color='red', linestyle='--', label='mean')
    axes[2, 1].set_title('Readability of discards')
    axes[2, 1].set_xlim([-130, 130])
    axes[2, 1].set_xlabel('MEAN: %s'%discards['readability'].mean())

    # FOURTH ROW: POLARITY
    sns.histplot(data=classified['sentiment'], ax = axes[3, 0], stat = 'count')
    axes[3, 0].axvline(x = classified['sentiment'].mean(),  color="red", linestyle="--", label='mean')
    axes[3, 0].set_title('Sentiment of classified')
    axes[3, 0].set_xlim([0, 1])
    axes[3, 0].set_xlabel('MEAN: %s'%classified['sentiment'].mean())

    sns.histplot(data=discards['sentiment'], ax = axes[3, 1], stat = 'count')
    axes[3, 1].axvline(x = discards['sentiment'].mean(),  color="red", linestyle="--", label='mean')
    axes[3, 1].set_title('Sentiment of discards')
    axes[3, 1].set_xlim([0, 1])
    axes[3, 1].set_xlabel('MEAN: %s'%discards['sentiment'].mean())

    plt.tight_layout()

    plt.savefig('./results/%s/stats.png'%model)


import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD) #Pin dizilimi secildi

GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP) #12.Pin giris olarak ayarlandi

GPIO.setup(11,GPIO.OUT) #11.Pin cikis olarak ayarlandi

while True:
    input_state = GPIO.input(12)
    if input_state == False:
        print('Butana basildi! Elazig Makerspace')
        GPIO.output(11,1) #GPIO.HIGH = 1
        time.sleep(0.2)	#0.2sn bekle
        GPIO.output(11,0) #GPIO.LOW = 0


from app import db
from app.models.base import Base

class Predios(db.Model, Base):
	__tablename__ = 'predios'

	id = 	db.Column(db.Integer, primary_key=True)
	nome =	db.Column(db.String(255))
	ativo =	db.Column(db.Boolean)

	@classmethod
	def get(cls, ativo=False):
		predios =	cls.query.order_by(cls.ativo.desc(), cls.nome)

		if ativo:
			return predios.filter(cls.ativo==True).all()
		else:
			return predios.all()

class Quartos(db.Model, Base):
	__tablename__ = 'quartos'

	id =			db.Column(db.Integer, primary_key=True)
	numero =		db.Column(db.String(255))
	predio_id =		db.Column(db.ForeignKey(Predios.id))
	qt_banheiros =	db.Column(db.Integer)
	lotacao =		db.Column(db.Integer)
	cozinha =		db.Column(db.Boolean)
	custo =			db.Column(db.Float)
	compartilhado =	db.Column(db.Boolean)
	ativo =			db.Column(db.Boolean)
	predio_ref = 	db.relationship('Predios', backref='quartos_ref')

	@classmethod
	def get(cls, ativo=False, compartilhado=False):
		quartos =	cls.query.join(Predios, Predios.id==cls.predio_id).order_by(cls.ativo.desc(), Predios.nome,
			cls.numero).filter(Predios.ativo==True)

		if compartilhado:
			quartos =	quartos.filter(cls.compartilhado==True)
		else:
			quartos =	quartos.filter(cls.compartilhado==False)

		if ativo:
			return quartos.filter(cls.ativo==True).all()
		else:
			return quartos.all()


import sys
from math import floor

def single(A, min, max):
    mid = floor((max + min) / 2)
    mod2 = mid % 2
    if min == max:
        return A[min]
    elif A[mid] == A[mid - 1] and mod2 == 0:
        return single(A, min, mid - 2)
    elif A[mid] == A[mid - 1] and mod2 == 1:
        return single(A, mid + 1, max)
    elif A[mid] == A[mid + 1] and mod2 == 0:
        return single(A, mid + 2, max)
    elif A[mid] == A[mid + 1] and mod2 == 1:
        return single(A, min, mid - 1)
    else:
        return A[mid]

def main(argv):
    input = open(argv[1], "r")
    ls = input.readline().split(', ')
    print(single(ls, 0, len(ls) - 1))
    input.close()

if __name__ == "__main__":
    main(sys.argv)


from datetime import date

from sqlalchemy import and_
from sqlalchemy.orm import Session

from src.database.models import Contact, User
from src.schemas import ContactModel

async def get_contacts(skip: int, limit: int, first_name: str, last_name: str, email: str, user: User, db: Session):
    """
    The get_contacts function returns a list of contacts that match the search criteria.
        If no search criteria is provided, it will return all contacts for the user.

    :param skip: int: Skip the first n number of contacts in the database
    :param limit: int: Limit the number of results returned
    :param first_name: str: Filter the contacts by first name
    :param last_name: str: Filter the contacts by last name
    :param email: str: Filter the contacts by email
    :param user: User: Get the user id of the logged in user
    :param db: Session: Access the database
    :return: A list of contacts
    :doc-author: Trelent
    """
    first_name_query = db.query(Contact).filter(and_(Contact.first_name == first_name, Contact.user_id == user.id))
    last_name_query = db.query(Contact).filter(and_(Contact.last_name == last_name, Contact.user_id == user.id))
    email_query = db.query(Contact).filter(and_(Contact.email == email, Contact.user_id == user.id))
    if first_name and last_name and email:
        return first_name_query.union(last_name_query).union(email_query).all()
    if first_name and last_name:
        return first_name_query.union(last_name_query).all()
    if first_name and email:
        return first_name_query.union(email_query).all()
    if last_name and email:
        return last_name_query.union(email_query).all()
    if first_name:
        return first_name_query.all()
    if last_name:
        return last_name_query.all()
    if email:
        return email_query.all()
    return db.query(Contact).filter(Contact.user_id == user.id).offset(skip).limit(limit).all()

async def get_contacts_birthdays(skip: int, limit: int, user: User, db: Session):
    """
    The get_contacts_birthdays function returns a list of contacts with birthdays in the next 7 days.
        Args:
            skip (int): The number of contacts to skip.
            limit (int): The maximum number of contacts to return.
            user (User): A User object containing information about the current user, including their id and email address.
            db (Session): An SQLAlchemy Session object used for querying the database.

    :param skip: int: Skip a number of contacts in the database
    :param limit: int: Limit the number of contacts returned
    :param user: User: Get the user id from the database
    :param db: Session: Pass the database session to the function
    :return: A list of contacts that have their birthdays in the next 7 days
    :doc-author: Trelent
    """
    contacts_with_birthdays = []
    today = date.today()
    current_year = today.year
    contacts = db.query(Contact).filter(Contact.user_id == user.id).offset(skip).limit(limit).all()
    for contact in contacts:
        td = contact.date_of_birth.replace(year=current_year) - today
        if 0 <= td.days <= 7:
            contacts_with_birthdays.append(contact)
        else:
            continue
    return contacts_with_birthdays

async def get_contact_by_id(contact_id: int, user: User, db: Session):
    """
    The get_contact_by_id function returns a contact by its id.
        Args:
            contact_id (int): The id of the contact to be returned.
            user (User): The user who is requesting the return of this specific contact.
            db (Session): A database session object that will be used to query for contacts in our database.
        Returns:
            Contact: A single Contact object from our database, or None if no such Contact exists.

    :param contact_id: int: Get the contact by its id
    :param user: User: Get the user id from the database
    :param db: Session: Pass a database session to the function
    :return: A contact object with the given id if it exists
    :doc-author: Trelent
    """
    return db.query(Contact).filter(and_(Contact.id == contact_id, Contact.user_id == user.id)).first()

async def create_contact(body: ContactModel, user: User, db: Session):
    """
    The create_contact function creates a new contact in the database.

    :param body: ContactModel: Pass the request body to the function
    :param user: User: Get the user id from the database
    :param db: Session: Access the database
    :return: A contact object
    :doc-author: Trelent
    """
    contact = Contact(**body.dict(), user_id=user.id)
    db.add(contact)
    db.commit()
    db.refresh(contact)
    return contact

async def update_contact(contact_id: int, body: ContactModel, user: User, db: Session):
    """
    The update_contact function updates a contact in the database.
        Args:
            contact_id (int): The id of the contact to update.
            body (ContactModel): The updated information for the specified user's contact.
            user (User): The current logged-in user, used to verify that they are updating their own contacts and not someone else's.
            db (Session): A connection to our database, used for querying and committing changes.

    :param contact_id: int: Identify the contact that is being updated
    :param body: ContactModel: Pass the contact object to the function
    :param user: User: Get the user id from the token
    :param db: Session: Access the database, and the user: user parameter is used to get information about the current user
    :return: The contact object
    :doc-author: Trelent
    """
    contact = db.query(Contact).filter(and_(Contact.id == contact_id, Contact.user_id == user.id)).first()
    if contact:
        contact.first_name = body.first_name
        contact.last_name = body.last_name
        contact.email = body.email
        contact.phone = body.phone
        contact.date_of_birth = body.date_of_birth
        db.commit()
    return contact

async def remove_contact(contact_id: int, user: User, db: Session):
    """
    The remove_contact function removes a contact from the database.
        Args:
            contact_id (int): The id of the contact to be removed.
            user (User): The user who owns the contacts list.
            db (Session): A session object for interacting with the database.
        Returns:
            Contact: The deleted Contact object.

    :param contact_id: int: Specify the id of the contact to be removed
    :param user: User: Get the user_id from the user object
    :param db: Session: Pass the database session to the function
    :return: The contact that was removed
    :doc-author: Trelent
    """
    contact = db.query(Contact).filter(and_(Contact.id == contact_id, Contact.user_id == user.id)).first()
    if contact:
        db.delete(contact)
        db.commit()
    return contact


#By Hossein Kamkar

nameList = ['']
name = ''
i = 0
while i < 10:
    name = input()
    name = name.lower()
    name = name.capitalize()
    nameList.append(name)
    i += 1

i = 1
while i < len(nameList):
    print(nameList[i])
    i += 1


DEFINITIONS = {
    'error': 'because value not valid',
    # app
    'BILIBILI': 'com.typcn.Bilibili',
    # replacement
    '可以是中文': ('比如', 'hello', 'Xee³'),
    # device
    'CHERRY_3494': ['0x046a', '0x0011'],
    'UIElementRole::自定义UI组件': '用作 filter',
    # modifierdef
    'Modifier::KEYLOCK': '',
}

MAPS = [
    ['cmd', 'alt'],
    ['_double_', 'shift', '#! osascript -e \'display notification "test1"\''],
    ['alt mouse_left', 'mouse_left "#! osascript -e \'display notification \\"test2\\"\'"'],
    ['alt E', 'Finder', ['UIElementRole::自定义UI组件']],
    ['alt X', 'Xee³.app', ['Finder', 'cmd']],
    ['__FlipScrollWheel__', 'flipscrollwheel_vertical', ['Xee³.app', 'built_in_keyboard_and_trackpad']],
    ['ctrl cmd F', 'cmd F', ['VIRTUALMACHINE']],
    ['alt', 'none', ['KEYLOCK']],
    ['cmd', 'none', ['Modifier::KEYLOCK']],
]


ans = 1e9
a, b, c = map(int, input().split())
for op1 in ('+', '-', '*', '//'):
    if op1 == '//' and a % b:
        continue
    num = eval(f'{a}{op1}{b}')
    for op2 in ('+', '-', '*', '//'):
        if op2 == '//' and num % c:
            continue
        res = eval(f'{num}{op2}{c}')
        ans = ans if res < 0 else min(ans, res)
print(ans)


from tkinter import *

class Kalkulator():
    def __init__(self):
        self.window = Tk()
        self.window.title("Kalkulator Cinta")
        label = Label(self.window, text = "Kalkulator Cinta", fg = "Blue", bg = "Yellow")
        label2 = Label(self.window, text = "Masukan Nama 1:", fg = "Green", bg = "Red")
        label3 = Label(self.window, text = "Masukan Nama 2:", fg = "Green", bg = "Red")
        self.label4 = Label(self.window)
        self.entry1 = Entry(self.window)
        self.entry2 = Entry(self.window)
        button1 = Button(self.window, text = "Calculate", bg = "Pink", fg = "White", command = self.pressed)
        button2 = Button(self.window, text = "Exit", bg = "Pink", fg = "White", command = self.quitz)

        label["font"] = "Times 40 bold"
        label2["font"] = "Times 20 bold"
        label3["font"] = "Times 20 bold"

        label.grid(row=0, column=0)
        label2.grid(row=1, column=0)
        label3.grid(row=2, column=0)
        self.label4.grid(row=3, column=0)
        self.entry1.grid(row=1, column=1)
        self.entry2.grid(row=2, column=1)
        button1.grid(row=4, column=0)
        button2.grid(row=4, column=1)
        self.window.mainloop()

    def pressed(self):
        Nama1 = (self.entry1.get())
        Nama2 = (self.entry2.get())
        a = 0
        b = 0
        total1 = 0
        total2 = 0

        while a < len(Nama1):
                ordnama1 = ord(Nama1[a])
                total1+=ordnama1
                a+=1
        while b < len(Nama2):
                ordnama2 = ord(Nama2[b])
                total2+= ordnama2
                b+=1

        x = ((total1) + (total2)) % 101
        if (x>=85) and (x<=100):
                self.label4["text"] = "{} dan {} Memiliki Skor {} dengan Kategori Sangat Cocok".format(Nama1, Nama2, x)
        elif (x>=70) and (x<=84):
                self.label4["text"] = "{} dan {} Memilki Skor {} dengan Kategori Sangat Biasa".format(Nama1, Nama2, x)
        elif (x>=50) and (x<=69):
                self.label4["text"] = "{} dan {} Memiliki Skor {} dengan Kategori Biasa".format(Nama1, Nama2, x)
        elif (x>=30) and (x<=49):
                self.label4["text"] = "{} dan {} Memiliki Skor {} dengan Kategori Tidak Cocok".format(Nama1, Nama2, x)
        elif (x>=0) and (x<=29):
                self.label4["text"] = "{} dan {} Memiliki Skor {} dengan Kategori  Sangat Tidak Cocok".format(Nama1, Nama2, x)

    def quitz(self):
        messagebox.showinfo(message = "Terima Kasih Telah Memakai Applikasi Ini. Semoga Harimu Menyenangkan")
        self.window.destroy()

coba = Kalkulator()

Lab Tutorial/Lab 8/Lab08_Ahmad Dzaki Naufal_1606889093_A_Adrianus Saga Ekakristi.py


import numpy as np
import cv2

net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
# net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')

# layerNames = net.getLayerNames()
# layerNames = [layerNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]
layerNames = ['yolo_82', 'yolo_94', 'yolo_106']

labels = open('coco.names').read().strip().split('\n')
colors = np.random.randint(0, 255, size=(len(labels), 3), dtype='uint8')

cap = cv2.VideoCapture(0)

while True:
    _, frame = cap.read()
    h, w = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(frame, 1/255, (416, 416), swapRB=True, crop=False)
    net.setInput(blob)
    layerOutputs = net.forward(layerNames)
    print(layerOutputs)

    boxes = []
    confidences = []
    classIds = []

    for output in layerOutputs:
        for detection in output:
            scores = detection[5:]
            classId = np.argmax(scores)
            confidence = scores[classId]

            if confidence > 0.5:
                box = detection[0:4] * np.array([w, h, w, h])
                centerX, centerY, width, height = box.astype('int')
                x = int(centerX - width // 2)
                y = int(centerY - height // 2)

                boxes.append([x, y, int(width), int(height)])
                confidences.append(float(confidence))
                classIds.append(classId)

    indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
    print(indices)

    if len(indices) > 0:
        for i in indices.flatten():
            x, y = (boxes[i][0], boxes[i][1])
            w, h = (boxes[i][2], boxes[i][3])

            color = [int(c) for c in colors[classIds[i]]]
            cv2.rectangle(frame, (x, y), (x+w, y+h), color, 2)
            text = '{}: {:.2f}'.format(labels[classIds[i]], confidences[i])
            cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

    cv2.imshow('Yolo', frame)
    if cv2.waitKey(50) == 27:
        break

cap.release()
cv2.destroyAllWindows()


__author__ = 'R.Azh'

# Convert the interface of a class into another interface clients expect.
#  Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

# Target: defines the domain-specific interface that Client uses.
class Compound:
    _chemical = None
    _boiling_point = None
    _melting_point = None
    _molecular_weight = None
    _molecular_formula = None

    def __init__(self, chemical):
        self._chemical = chemical

    def display(self):
        print("\nCompound: {} ------ ".format(self._chemical))

# Adaptee: defines an existing interface that needs adapting
class ChemicalDataBank(object):
    def get_critical_point(self, compound, point):
        melting_point_switcher = {"water": 0.0,
                                  "benzene": 5.5,
                                  "ethanol": -114.1}

        boiling_point_switcher = {"water": 100.0,
                                  "benzene": 80.1,
                                  "ethanol": 78.3}

        if point == "M":
            if compound.lower() in melting_point_switcher:
                return melting_point_switcher[compound.lower()]
            else:
                return 0
        else:
            if compound.lower() in boiling_point_switcher:
                return boiling_point_switcher[compound.lower()]
            else:
                return 0

    def get_molecular_structure(self, compound):
        molecular_structure_switcher = {"water": "H20",
                                        "benzene": "C6H6",
                                        "ethanol": "C2H50H"}
        if compound.lower() in molecular_structure_switcher:
            return molecular_structure_switcher[compound.lower()]
        else:
            return ""

    def get_molecular_weight(self, compound):
        molecular_weight_switcher = {"water": 18.015,
                                     "benzene": 78.1134,
                                     "ethanol": 46.0688}
        if compound.lower() in molecular_weight_switcher:
            return molecular_weight_switcher[compound.lower()]
        else:
            return 0

# Adapter: adapts the interface Adaptee to the Target interface
class RichCompound(Compound):
    _bank = None

    def __init__(self, name):
        super().__init__(name)

    def display(self):
        self._bank = ChemicalDataBank()
        self._boiling_point = self._bank.get_critical_point(self._chemical, "B")
        self._melting_point = self._bank.get_critical_point(self._chemical, "M")
        self._molecular_formula = self._bank.get_molecular_structure(self._chemical)
        self._molecular_weight = self._bank.get_molecular_weight(self._chemical)

        super().display()
        print('Formula: {}'.format(self._molecular_formula))
        print('weight: {}'.format(self._molecular_weight))
        print('Melting pt: {}'.format(self._melting_point))
        print('Boinling pt: {}'.format(self._boiling_point))

# client: collaborates with objects conforming to the Target interface

unknown_compound = RichCompound("unknown")
unknown_compound.display()

water_compound = RichCompound("water")
water_compound.display()

benzene_compound = RichCompound("benzene")
benzene_compound.display()

ethanol_compound = RichCompound("ethanol")
ethanol_compound.display()


"""Gets port info from DSDA

Pulls port info from main page and can pull port info from all wads for
cross-comparison.
"""

import operator
import re

from collections import defaultdict

import dsda_parser_scripts.helper_functions.helper_functions as hf

__author__ = '4shockblast'

MAIN_PAGE = 'http://doomedsda.us/index.html'
WAD_URL_TEMPLATE = 'http://doomedsda.us/wad{}.html'
OUTPUT_TEMPLATE = """family: {family}
version: {version}"""

HARDCODED_PORT_INFO = {
    'MBF': ['v2.03'],
    'TASDoom': [''],
    'TASMBF': ['']
}

# Regexes matching executables used by players on DSDA mapped
# to their respective compatibilities
EXECUTABLE_REGEXES = {
    # Original Boom port versions
    re.compile(r'^Boom.*$'): 'Boom',

    # Initially a modified doom2.exe, eventually based on MBF with extra
    # features. Currently only recordings by port author for vanilla
    # mapsets.
    re.compile(r'^CDooM.*$'): 'limit-removing',

    # Designed to emulate vanilla Doom as closely as possible, mapped to
    # limit-removing to be safe
    re.compile(r'^Chocolate DooM.*$'): 'limit-removing',

    # Modified Chocolate with extra speedrun-oriented features, only
    # vanilla compatible demos supported
    re.compile(r'^CNDoom.*$'): 'limit-removing',

    # Modified Chocolate with limits removed
    re.compile(r'^Crispy Doom.*$'): 'limit-removing',

    # Vanilla Doom, Doom 2, or Final Doom exes all map to limit-removing
    # to be safe
    re.compile(r'^DooM2? v1.\d+\.?\d*f?$'): 'limit-removing',

    # Doom 95 exes map to limit-removing to be safe
    re.compile(r'^DooM2? v95f?$'): 'limit-removing',

    # Doom 64 port to PC, maps to its own compatibility
    re.compile(r'^Doom64 EX.*$'): 'Doom 64',

    # Advanced source port, features mostly limited to hi-res textures and
    # fancy effects, but still does not correspond easily to any
    # obvious compatibility
    re.compile(r'^Doomsday.*$'): 'Unknown',

    # Earliest source port, mostly equivalent to vanilla
    re.compile(r'^DosDooM.*$'): 'limit-removing',

    # Version of DosDoom designed for TAS, also should be mostly equivalent
    # to vanilla
    re.compile(r'^TasDooM.*$'): 'limit-removing',

    # Advanced source port, impossible to map to anything, as its features
    # are in between PrBoom and (G)ZDoom
    re.compile(r'^Eternity.*$'): 'Unknown',

    # Advanced source port
    re.compile(r'^GZDoom.*$'): 'GZDoom',

    # Initially very similar to DOSDoom, later added many advanced features
    re.compile(r'^Legacy.*$'): 'Unknown',

    # Modified version of (G)ZDoom with some extra features and difficulty
    # settings, maps to GZDoom compatibility I guess
    re.compile(r'^ManDoom.*$'): 'GZDoom',

    # Modified Boom with extra features, maps to MBF compatibility
    re.compile(r'^MBF.*$'): 'MBF',

    # Version of MBF supporting TAS, it doesn't look like any demos are
    # marked with this even though there are MBF TAS demos on DSDA
    re.compile(r'^TASMBF.*$'): 'MBF',

    # Encompasses both the original PrBoom and PrBoom+, if a compatiblity
    # level is specified, then that gives the wad compat mapping, otherwise
    # doesn't map to anything
    re.compile(r'^PRBoom.*$'): 'PrBoom',

    # Modified version of Chocolate with some limits removed
    re.compile(r'^Strawberry DooM.*$'): 'limit-removing',

    # Old multiplayer port of ZDoom, with limited exceptions commonly
    # used for rocket jump maps, so it maps to its own compatibility,
    # some exceptions are that recordings for ZDoom maps and
    # co-op demos that are not too common
    re.compile(r'^ZDaemon.*$'): 'ZDaemon',

    # Advanced source port, maps to GZDoom compatibility as there
    # is no clear distinction that can be made between the
    # two based on the version of (G)ZDoom used
    re.compile(r'^ZDoom.*$'): 'GZDoom'
}
VERSIONED_PORT_RE = re.compile(r'^.*((r\d+)|(v\d\.?(\d\.)*)).*$')
VERSION_RE = re.compile(r'^.*((r\d+)|(v\d\.?(\d\.)*)).*$')
SOURCE_PORTS_RE = re.compile(r'^\s*source\s*ports\s*$', re.IGNORECASE)

def get_demo_rows_for_wad_url(wad_url):
    """Gets demo rows for a wad URL"""
    tree = hf.get_web_page_html(wad_url)
    # Demos for wads on DSDA are placed in a table, and there are at
    # most two tables on a particular page (demo and page navigation
    # tables), so the first one is needed to parse the demos
    tables = tree.xpath('//table')
    # All demo rows on DSDA have these classes
    rows = tables[0].xpath('.//tr[@class="row1" or @class="row2" or'
                           ' @class="row1top" or @class="row2top"]')
    return rows

def get_ports_for_wad_url(wad_url):
    """Gets ports for wad URL list"""
    ports = defaultdict(list)
    rows = get_demo_rows_for_wad_url(wad_url)
    for row in rows[1:]:
        if len(row) > 2:
            port = row[-2].text
            if re.match(VERSIONED_PORT_RE, port):
                port_split = port.rsplit(' ', 1)
                port_family = port_split[0]
                if len(port_split) > 1:
                    if port_family == 'PRBoom':
                        port_version = port_split[1].split('cl')[0]
                    else:
                        port_version = port_split[1]
                    if port_family in ports:
                        if port_version not in ports[port_family]:
                            ports[port_family].append(port_version)
                    else:
                        ports[port_family].append(port_version)
                else:
                    port_version = ''
                    if port_family in ports:
                        if port_version not in ports[port_family]:
                            ports[port_family].append(port_version)
                    else:
                        ports[port_family].append(port_version)
            else:
                port_sanitized = port.strip()
                port_version = ''
                if port_sanitized in ports:
                    if port_version not in ports[port_sanitized]:
                        ports[port_sanitized].append(port_version)
                else:
                    ports[port_sanitized].append(port_version)

    return ports

def get_wad_port_info(wad_id):
    return get_ports_for_wad_url(WAD_URL_TEMPLATE.format(wad_id))

def get_main_port_info():
    tree = hf.get_web_page_html(MAIN_PAGE)
    info_lists = tree.xpath('//li')
    source_ports_elem = None
    for info_list in info_lists:
        if len(info_list):
            if re.match(SOURCE_PORTS_RE, info_list[0].text_content()):
                source_ports_elem = info_list
    if source_ports_elem is None or not len(source_ports_elem):
        return None

    ports = defaultdict(list)
    cur_port_family = None
    for elem in source_ports_elem:
        if elem.tag == 'span':
            cur_port_family = elem.text
        if elem.tag == 'a':
            if cur_port_family is not None:
                ports[cur_port_family].append(elem.text)

    return ports

def main():
    """Main function"""
    main_ports = get_main_port_info()
    if main_ports is not None:
        main_ports.update(HARDCODED_PORT_INFO)
        for family, versions in main_ports.items():
            for version in versions:
                print(OUTPUT_TEMPLATE.format(
                    family=family,
                    version=version
                ))

    print()
    wad_ports = get_wad_port_info('586')
    if wad_ports is not None:
        for family, versions in wad_ports.items():
            for version in versions:
                print(OUTPUT_TEMPLATE.format(
                    family=family,
                    version=version
                ))

if (__name__ == '__main__' or
        __name__ == 'get_port_info__main__'):
    main()


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('details_chapter/<int:id_capitulo>/', views.details_chapter, name='details_chapter'),
    path('details_character/<int:id_character>/', views.details_character, name='details_character'),
    path('details_location/<int:id_location>/', views.details_location, name='details_location'),
    path('search/', views.search, name='search'),

]


# -*- coding: utf-8 -*-
#Adapted by Amit Rana from: https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/config.py
from detectron2.config import CfgNode as CN

def add_maskformer2_config(cfg):
    """
    Add config for MASK_FORMER.
    """
    # NOTE: configs from original maskformer
    # data config
    # select the dataset mapper
    cfg.SEED = 2091831170
    cfg.INPUT.DATASET_MAPPER_NAME = "mask_former_semantic"
    cfg.INPUT.MIN_AREA_FOR_OBJECT = 500.0
    cfg.INPUT.MIN_AREA_FOR_MASK = 1000.0

    cfg.INPUT.DISTRACTOR_BG  = False
    cfg.INPUT.DISTRACTOR_OBJECTS = False
    # Color augmentation
    cfg.INPUT.COLOR_AUG_SSD = False
    # We retry random cropping until no single category in semantic segmentation GT occupies more
    # than `SINGLE_CATEGORY_MAX_AREA` part of the crop.
    cfg.INPUT.CROP.SINGLE_CATEGORY_MAX_AREA = 1.0
    # Pad image and segmentation GT in dataset mapper.
    cfg.INPUT.SIZE_DIVISIBILITY = -1

    # solver config
    # weight decay on embedding
    cfg.SOLVER.WEIGHT_DECAY_EMBED = 0.0
    # optimizer
    cfg.SOLVER.OPTIMIZER = "ADAMW"
    cfg.SOLVER.BACKBONE_MULTIPLIER = 0.1
    # cfg.SOLVER.NUM_DECAYS =  3
    # cfg.SOLVER.RESCALE_INTERVAL = False

    # mask_former model config
    cfg.MODEL.MASK_FORMER = CN()

    cfg.MODEL.MIT_BACKBONE = CN()

    cfg.MODEL.MIT_BACKBONE.NAME = "b0"
    # loss
    cfg.MODEL.MASK_FORMER.DEEP_SUPERVISION = True
    cfg.MODEL.MASK_FORMER.NO_OBJECT_WEIGHT = 0.1
    cfg.MODEL.MASK_FORMER.CLASS_WEIGHT = 1.0
    cfg.MODEL.MASK_FORMER.DICE_WEIGHT = 1.0
    cfg.MODEL.MASK_FORMER.MASK_WEIGHT = 20.0

    # interactive transformer
    cfg.MODEL.MASK_FORMER.INTERACTIVE_TRANSFORMER_NAME = "DynamiteInteractiveTransformer"
    cfg.MODEL.MASK_FORMER.DECODER = CN()
    cfg.MODEL.MASK_FORMER.DECODER.USE_DECODER = True
    cfg.MODEL.MASK_FORMER.DECODER.DEC_LAYERS = 5
    cfg.MODEL.MASK_FORMER.DECODER.DEC_SCALE_FACTOR = 1.0
    # transformer config
    cfg.MODEL.MASK_FORMER.NHEADS = 8
    cfg.MODEL.MASK_FORMER.DROPOUT = 0.1
    cfg.MODEL.MASK_FORMER.DIM_FEEDFORWARD = 2048
    cfg.MODEL.MASK_FORMER.ENC_LAYERS = 6
    cfg.MODEL.MASK_FORMER.PRE_NORM = False

    cfg.MODEL.MASK_FORMER.HIDDEN_DIM = 256

    cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE = "res5"
    cfg.MODEL.MASK_FORMER.ENFORCE_INPUT_PROJ = False

    # Sometimes `backbone.size_divisibility` is set to 0 for some backbone (e.g. ResNet)
    # you can use this config to override
    cfg.MODEL.MASK_FORMER.SIZE_DIVISIBILITY = 32

    # pixel decoder config
    cfg.MODEL.SEM_SEG_HEAD.MASK_DIM = 256
    # adding transformer in pixel decoder
    cfg.MODEL.SEM_SEG_HEAD.TRANSFORMER_ENC_LAYERS = 0
    # pixel decoder
    cfg.MODEL.SEM_SEG_HEAD.PIXEL_DECODER_NAME = "BasePixelDecoder"
    cfg.MODEL.SEM_SEG_HEAD.REFINE_MASK_FEATURES = False

    cfg.MODEL.SEM_SEG_HEAD.IN_CHANNELS_SEGFORMER = [32, 64, 160, 256]
    cfg.MODEL.SEM_SEG_HEAD.FEATURES_STRIDES_SEGFORMER = [4, 8, 16, 32]
    cfg.MODEL.SEM_SEG_HEAD.IN_INDEXES_SEGFORMER = [0, 1, 2, 3]
    cfg.MODEL.SEM_SEG_HEAD.DROPOUT_RATIO_SEGFORMER = 0.1
    cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES_SEGFORMER = 1

    # swin transformer backbone
    cfg.MODEL.SWIN = CN()
    cfg.MODEL.SWIN.PRETRAIN_IMG_SIZE = 224
    cfg.MODEL.SWIN.PATCH_SIZE = 4
    cfg.MODEL.SWIN.EMBED_DIM = 96
    cfg.MODEL.SWIN.DEPTHS = [2, 2, 6, 2]
    cfg.MODEL.SWIN.NUM_HEADS = [3, 6, 12, 24]
    cfg.MODEL.SWIN.WINDOW_SIZE = 7
    cfg.MODEL.SWIN.MLP_RATIO = 4.0
    cfg.MODEL.SWIN.QKV_BIAS = True
    cfg.MODEL.SWIN.QK_SCALE = None
    cfg.MODEL.SWIN.DROP_RATE = 0.0
    cfg.MODEL.SWIN.ATTN_DROP_RATE = 0.0
    cfg.MODEL.SWIN.DROP_PATH_RATE = 0.3
    cfg.MODEL.SWIN.APE = False
    cfg.MODEL.SWIN.PATCH_NORM = True
    cfg.MODEL.SWIN.OUT_FEATURES = ["res2", "res3", "res4", "res5"]
    cfg.MODEL.SWIN.USE_CHECKPOINT = False

    # NOTE: maskformer2 extra configs
    # transformer module
    cfg.MODEL.MASK_FORMER.TRANSFORMER_DECODER_NAME = "MultiScaleMaskedTransformerDecoder"

    # LSJ aug
    cfg.INPUT.IMAGE_SIZE = 1024
    cfg.INPUT.MIN_SCALE = 0.1
    cfg.INPUT.MAX_SCALE = 2.0

    # MSDeformAttn encoder configs
    cfg.MODEL.SEM_SEG_HEAD.DEFORMABLE_TRANSFORMER_ENCODER_IN_FEATURES = ["res3", "res4", "res5"]
    cfg.MODEL.SEM_SEG_HEAD.DEFORMABLE_TRANSFORMER_ENCODER_N_POINTS = 4
    cfg.MODEL.SEM_SEG_HEAD.DEFORMABLE_TRANSFORMER_ENCODER_N_HEADS = 8

    # point loss configs
    # Number of points sampled during training for a mask point head.
    cfg.MODEL.MASK_FORMER.TRAIN_NUM_POINTS = 112 * 112
    # Oversampling parameter for PointRend point sampling during training. Parameter `k` in the
    # original paper.
    cfg.MODEL.MASK_FORMER.OVERSAMPLE_RATIO = 3.0
    # Importance sampling parameter for PointRend point sampling during training. Parametr `beta` in
    # the original paper.
    cfg.MODEL.MASK_FORMER.IMPORTANCE_SAMPLE_RATIO = 0.75

    #__________________Iterative_training________________

    cfg.ITERATIVE = CN()
    cfg.ITERATIVE.TRAIN = CN()
    cfg.ITERATIVE.TEST = CN()
    cfg.ITERATIVE.TRAIN.MAX_NUM_INTERACTIONS = 10
    cfg.ITERATIVE.TRAIN.STUFF_PROB = 0.15

    cfg.ITERATIVE.TRAIN.USE_STATIC_BG_QUERIES = True
    cfg.ITERATIVE.TRAIN.NUM_STATIC_BG_QUERIES = 9

    cfg.ITERATIVE.TRAIN.POSITIONAL_EMBED = None

    cfg.ITERATIVE.TEST.INTERACTIVE_EVALAUTION = False
    cfg.ITERATIVE.TEST.MAX_NUM_INTERACTIONS = 20
    cfg.ITERATIVE.TEST.IOU_THRESHOLD = 0.85

def add_hrnet_config(cfg):

    cfg.MODEL.HRNET = CN()
    cfg.MODEL.HRNET.STEM_INPLANES = 64
    cfg.MODEL.HRNET.STAGE2 = CN()
    cfg.MODEL.HRNET.STAGE2.NUM_MODULES = 1
    cfg.MODEL.HRNET.STAGE2.NUM_BRANCHES = 2
    cfg.MODEL.HRNET.STAGE2.BLOCK = "BASIC"
    cfg.MODEL.HRNET.STAGE2.NUM_BLOCKS = [4, 4]
    cfg.MODEL.HRNET.STAGE2.NUM_CHANNELS = [32, 64]
    cfg.MODEL.HRNET.STAGE2.FUSE_METHOD = "SUM"
    cfg.MODEL.HRNET.STAGE3 = CN()
    cfg.MODEL.HRNET.STAGE3.NUM_MODULES = 4
    cfg.MODEL.HRNET.STAGE3.NUM_BRANCHES = 3
    cfg.MODEL.HRNET.STAGE3.BLOCK = "BASIC"
    cfg.MODEL.HRNET.STAGE3.NUM_BLOCKS = [4, 4, 4]
    cfg.MODEL.HRNET.STAGE3.NUM_CHANNELS = [32, 64, 128]
    cfg.MODEL.HRNET.STAGE3.FUSE_METHOD = "SUM"
    cfg.MODEL.HRNET.STAGE4 = CN()
    cfg.MODEL.HRNET.STAGE4.NUM_MODULES = 3
    cfg.MODEL.HRNET.STAGE4.NUM_BRANCHES = 4
    cfg.MODEL.HRNET.STAGE4.BLOCK = "BASIC"
    cfg.MODEL.HRNET.STAGE4.NUM_BLOCKS = [4, 4, 4, 4]
    cfg.MODEL.HRNET.STAGE4.NUM_CHANNELS = [32, 64, 128, 256]
    cfg.MODEL.HRNET.STAGE4.FUSE_METHOD = "SUM"
    cfg.MODEL.HRNET.HRFPN = CN()
    cfg.MODEL.HRNET.HRFPN.OUT_CHANNELS = 256


teiler_von_16 = {1, 2, 4, 8, 16}
teiler_von_18 = {1, 2, 3, 6, 9, 18}

if __name__ == '__main__':
    # Gemeinsame Elemente: durch Schnittmenge
    gemeinsame_teiler = teiler_von_16 & teiler_von_18

    # Nicht gemeinsame Elemente: durch Symmetrische Differenz
    nicht_gemeinsame_teiler = teiler_von_16 ^ teiler_von_18

    # Teilbarkeit: durch Teilmengenbeziehung der Teiler
    teilbar_durch_16 = bool(teiler_von_16 <= teiler_von_18)

    print('Gemeinsame Teiler: {}'.format(gemeinsame_teiler))
    print('Nicht gemeinsame Teiler: {}'.format(nicht_gemeinsame_teiler))
    print('18 ist durch 16 teilbar: {}'.format(teilbar_durch_16))