from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms

import numpy as np
import torch.utils.data as utils

#for checking summary of model
from torchvision import models
from torchsummary import summary

#for plotting
import matplotlib.pyplot as plt

# The parts that you should complete are designated as TODO
class ConvNet(nn.Module):
    def __init__(self):
        super(ConvNet, self).__init__()
        # TODO: define the layers of the network
        self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, stride=1, padding=0)
        self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=0)
        self.relu = nn.ReLU()
        self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
        self.dropout = nn.Dropout2d(p=0.25)
        self.flatten = nn.Flatten()
        self.linear1 = nn.Linear(9216, 128)
        self.dropout2 = nn.Dropout(p=0.5)
        self.linear2 = nn.Linear(128,10)

    def forward(self, x):
        # TODO: define the forward pass of the network using the layers you defined in constructor
        x = self.conv1(x)
        x = self.relu(x)
        x = self.conv2(x)
        x = self.relu(x)
        x = self.pool1(x)
        x = self.dropout(x)
        x = self.flatten(x)
        x = self.linear1(x)
        x = self.relu(x)
        x = self.dropout2(x)
        x = self.linear2(x)

        return x

def train(model, device, train_loader, optimizer, epoch):
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = F.cross_entropy(output, target)
        loss.backward()
        optimizer.step()
        #accuracy = 100. * batch_idx / len(train_loader)
        if batch_idx % 100 == 0: #Print loss every 100 batch
            print('Train Epoch: {} [{}/{}]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                loss.item()))
    print('-'*20)
    print('Training Accuracy (not test accuracy):')
    accuracy = test(model, device, train_loader)
    print('-'*20)

    return accuracy

def test(model, device, test_loader):
    model.eval()
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()

    accuracy = 100. * correct / len(test_loader.dataset)
    print('\nTest set Accuracy: {}/{} ({:.0f}%)\n'.format(
        correct, len(test_loader.dataset),
        accuracy))
    print('-'*20)

    return accuracy

def main():
    print('-'*20)
    print('Start of CNN Script')
    torch.manual_seed(1)
    np.random.seed(1)
    # Training settings
    use_cuda = False # Switch to False if you only want to use your CPU
    learning_rate = 0.01
    NumEpochs = 10
    batch_size = 32

    device = torch.device("cuda" if use_cuda else "cpu")

    train_X = np.load('../../Data/X_train.npy')
    train_Y = np.load('../../Data/y_train.npy')

    test_X = np.load('../../Data/X_test.npy')
    test_Y = np.load('../../Data/y_test.npy')

    train_X = train_X.reshape([-1,1,28,28]) # the data is flatten so we reshape it here to get to the original dimensions of images
    test_X = test_X.reshape([-1,1,28,28])

    # transform to torch tensors
    tensor_x = torch.tensor(train_X, device=device)
    tensor_y = torch.tensor(train_Y, dtype=torch.long, device=device)

    test_tensor_x = torch.tensor(test_X, device=device)
    test_tensor_y = torch.tensor(test_Y, dtype=torch.long)

    train_dataset = utils.TensorDataset(tensor_x,tensor_y) # create your datset
    train_loader = utils.DataLoader(train_dataset, batch_size=batch_size) # create your dataloader

    test_dataset = utils.TensorDataset(test_tensor_x,test_tensor_y) # create your datset
    test_loader = utils.DataLoader(test_dataset) # create your dataloader if you get a error when loading test data you can set a batch_size here as well like train_dataloader

    model = ConvNet().to(device)
    #print a summary of layer dimensions and parameters
    print('Model Summary:')
    summary(model, input_size=(1,28,28))
    optimizer = optim.Adam(model.parameters(), lr=learning_rate)

    #create lists to store training and testing accuracy for plotting
    training_accuracy = []
    testing_accuracy = []

    for epoch in range(NumEpochs):
        train_acc = train(model, device, train_loader, optimizer, epoch)
        #append training accuracy list
        training_accuracy.append(train_acc)
        test_acc = test(model, device, test_loader)
        #append testing accuracy list
        testing_accuracy.append(test_acc)

    torch.save(model.state_dict(), "mnist_cnn.pt")

    #TODO: Plot train and test accuracy vs epoch
    plt.plot(list(range(1,11)), training_accuracy, label='Training Accuracy')
    plt.plot(list(range(1,11)), testing_accuracy, label='Testing Accuracy')
    plt.title('Training and Testing Accuracy\nfor Each Epoch')
    plt.xlabel('Number of Epochs')
    plt.ylabel('Accuracy (%)')
    plt.legend()
    plt.savefig('../Figures/cnn_accuracy.png')
    plt.show()
    plt.clf()

    print('End of CNN Script')
    print('-'*20)
    print('End of HW5 Scripts')

if __name__ == '__main__':
    main()

#Below was used to generate the predictions for the submission folder
#select all and run selection if you would like to reproduce
#digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#model.eval()
#correct = 0
#predictions_vect = []
#with torch.no_grad():
#    for data, target in test_loader:
#        data, target = data.to(device), target.to(device)
#        output = model(data)
#        pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
#        correct += pred.eq(target.view_as(pred)).sum().item()
#        _, predictions = torch.max(output, 1)
#        predictions_vect.append(digits[predictions])
#np.savetxt('../Predictions/predictions_MNIST.csv', predictions_vect, delimiter=',')


from transformers import MarianMTModel, MarianTokenizer

fp = open("opus.en-sr-test.en")
en_test_split = fp.read().splitlines()

test_sentences = [sentence for sentence in en_test_split]

# loading the model and translating test set again
model_checkpoint = "./Helsinki-NLP/shortXXL-opus-mt-tc-base-en-sh"
tokenizer = MarianTokenizer.from_pretrained(model_checkpoint)
model = MarianMTModel.from_pretrained(model_checkpoint)
padded_test_set = [">>srp_Latn<< " + sentence for sentence in test_sentences]
translated = model.generate(**tokenizer(test_sentences,
                                        return_tensors="pt", padding=True))
trans_file = open("short_XXL_translation.txt", "w")
for t in translated:
    trans_file.write(tokenizer.decode(t, skip_special_tokens=True) + "\n")

trans_file.close()


"""
NERD module querying Shodan.io using its Python API.

Requirements:
- "shodan" package
"""

from core.basemodule import NERDModule
import g

import logging
import threading
import shodan

# *** Global lock disabling parallel querying ***
# Shodan API has a limit on query rate. Normally API response is so slow
# (there is probably an artifically added delay) that the threshold can not be
# exceeded by sequential querying. If we would send queries by more threads in
# parallel, the rate limit would be easily exceeded and API would return errors.
#
# IMPORTANT: The API query takes around 0.7 second (according to my experiments
# at the time of writing), so maximal rate of queries is ~1.4/s.
# THIS LIMITS THE MAXIMAL RATE OF NEW IPs NERD CAN PROCESS and also MAXIMAL
# NUMBER OF IPs IN DATABASE (since Shodan info of IPs is updated every week)
shodan_api_lock = threading.Lock()

class Shodan(NERDModule):
    """
    Module querying IP addresses in Shodan

    Queries newly added IP addresses to Shodan database to get list of open
    ports and other available info.

    Event flow specification:
      !NEW -> getShodanInfo -> shodan.{ports,os,devicetype,linktype,tags}
    """

    def __init__(self):
        self.log = logging.getLogger('Shodan')
        #self.log.setLevel("DEBUG")
        self.errors = 0 # Number of API errors that has occurred
        self.enabled = True

        self.apikey = g.config.get('shodan.apikey', None)
        if not self.apikey:
            self.log.warning("No API key set, Shodan module disabled.")
            return

        try:
            self.client = shodan.Shodan(key=self.apikey)
            self.client.info() # Test connection and validity of the key
        except shodan.exception.APIError as e:
            self.log.error("Cannot initialize Shodan module: {}".format(str(e)))
            self.log.error("Shodan module disabled.")
            return

        g.um.register_handler(
            self.getShodanInfo, # function (or bound method) to call
            'ip', # entity type
            ('!NEW','!every1w'), # tuple/list/set of attributes to watch (their update triggers call of the registered method)
            ('shodan.ports','shodan.os','shodan.devicetype','shodan.linktype','shodan.tags',) # tuple/list/set of attributes the method may change
        )
        self.log.info("Shodan module initialized")

    def getShodanInfo(self, ekey, rec, updates):
        """
        Query Shodan via its API for the IP address. Get basic information -
        list of opened ports, OS, device type, link type and tags.

        Arguments:
        ekey -- two-tuple of entity type and key, e.g. ('ip', '192.0.2.42')
        rec -- record currently assigned to the key
        updates -- list of all attributes whose update triggered this call and
          their new values (or events and their parameters) as a list of
          2-tuples: [(attr, val), (!event, param), ...]

        Returns:
        List of the following update requests (some may not be present):
          ('set', 'shodan.ports', [list_of_numbers])
          ('set', 'shodan.os', 'os_name')
          ('set', 'shodan.devicetype', 'device_type')
          ('set', 'shodan.linktype', 'link_type')
          ('set', 'shodan.tags', 'tags')  # e.g. "vpn" or "tor"
        """
        if not self.enabled:
            return None

        etype, key = ekey
        if etype != 'ip':
            return None

        ip = key

        self.log.debug("Querying Shodan for {}".format(ip))

        try:
            with shodan_api_lock: # This ensures only one thread can process the query at a time
                data = self.client.host(ip, minify=True)
        except shodan.exception.APIError as e:
            if str(e) == "No information available for that IP.":
                self.log.debug("Shodan info for {}: Not found".format(ip))
                # Store empty dict into "shodan" key to mark that the info was queried but the IP is not in Shodan DB
                return [('set', 'shodan', dict())]
            else:
                self.log.error("Error when querying '{}': {}".format(ip, str(e)))
                self.errors += 1
                if self.errors > 10:
                    self.log.critical("More than 10 API errors -> stopping module".format(ip, str(e)))
                    self.enabled = False
            return None

        self.log.debug("Shodan info for {}: {}".format(ip, data))

        update_requests = []

        # Check presence of various fields and check whether they have expected format
        # If it is OK, add its value to our IP record.
        # TODO: remove fields that may be set before but are no longer returned by Shodan
        if 'ports' in data and data['ports']:
            ports = data['ports']
            if isinstance(ports, list) and all(map(lambda x: isinstance(x, int), ports)):
                update_requests.append(('set', 'shodan.ports', ports))
            else:
                self.log.error("Error when querying '{}': Unexpected format of 'ports': {}".format(ip, repr(ports)))

        if 'os' in data and data['os']:
            os = data['os']
            if isinstance(os, str):
                update_requests.append(('set', 'shodan.os', os))
            else:
                self.log.error("Error when querying '{}': Unexpected format of 'os': {}".format(ip, repr(os)))

        if 'devicetype' in data and data['devicetype']:
            devicetype = data['devicetype']
            if isinstance(devicetype, str):
                update_requests.append(('set', 'shodan.devicetype', devicetype))
            else:
                self.log.error("Error when querying '{}': Unexpected format of 'devicetype': {}".format(ip, repr(devicetype)))

        if 'linktype' in data and data['linktype']:
            linktype = data['linktype']
            if isinstance(linktype, str):
                update_requests.append(('set', 'shodan.linktype', linktype))
            else:
                self.log.error("Error when querying '{}': Unexpected format of 'linktype': {}".format(ip, repr(linktype)))

        if 'tags' in data and data['tags']:
            tags = data['tags']
            if isinstance(tags, list) and all(map(lambda x: isinstance(x, str), tags)):
                update_requests.append(('set', 'shodan.tags', tags))
            else:
                self.log.error("Error when querying '{}': Unexpected format of 'tags': {}".format(ip, repr(tags)))

        self.log.debug("Shodan update requests for {}: {}".format(ip, update_requests))

        return update_requests


from flask import Blueprint, render_template

from models.auth.auth_functions import customer_login_required, restricted_customer_error, staff_login_required, \
    restricted_staff_error

user = Blueprint('user', __name__)

@user.route('/CustomerDashboard')
def customer_dashboard():
    if customer_login_required():
        return render_template('user/customer_dashboard.html')
    else:
        return restricted_customer_error()

@user.route('/StaffDashboard')
def staff_dashboard():
    if staff_login_required():
        return render_template('user/staff_dashboard.html')
    else:
        return restricted_staff_error()

@user.route('/customerProfile')
def customer_profile():
    if customer_login_required():
        return render_template('user/customer_profile.html')
    else:
        return restricted_customer_error()

@user.route('/StaffProfile')
def staff_profile():
    if staff_login_required():
        return render_template('user/staff_profile.html')
    else:
        return restricted_staff_error()


from discord.ext.commands import HelpCommand, DefaultHelpCommand, Cog
from . import force_async

argparse_command_registry = {}

def register_argparse_command(coro):
    argparse_command_registry[coro] = True
    return coro

class ArgparseHelpCommand(HelpCommand):
    async def send_command_help(self, command):
        if argparse_command_registry.get(command.callback): # no False default value, None is falsy
            await self.context.invoke(command, args="--help")
        else:
            await super().send_command_help(command)

class ArgparseDefaultHelpCommand(ArgparseHelpCommand, DefaultHelpCommand):
    pass

class Help(Cog):
    def __init__(self, bot):
        self._original_help_command = bot.help_command
        bot.help_command = ArgparseDefaultHelpCommand()
        bot.help_command.cog = self

    def cog_unload(self):
        self.bot.help_command = self._original_help_command

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


from typing import NewType

# Декларация нового типа "UserId"
UserId = NewType('UserId', int)

def odd_or_even(user_id: UserId) -> str:
    return 'odd' if (user_id % 2) == 0 else 'even'

some_id = UserId(5423434)
some_id_wrong = -1
print(odd_or_even(some_id))
print(odd_or_even(some_id_wrong))

# # Сложение двух UserId вернет int
output = UserId(23413) + UserId(54341)
print(output)

# Производный тип данных
ProUserId = NewType('ProUserId', UserId)
some_id_2 = ProUserId(UserId(5))
print(some_id_2)


#!/usr/bin/env python
import logging
import os
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("Starting")
a=os.uname()
logger.debug("uname done")
b=os.getcwd()
logger.info("cwd done")


import sqlite3
from sqlite3 import Error

class banco_db:

    def __init__(self,banco =None):
        self.conn = None
        self.cursor = None

        if banco:
            self.open(banco)

    def open(self,banco):
        try:
            self.conn= sqlite3.connect(banco)
            self.cursor = self.conn.cursor()
            print("Conexão Criada")
        except sqlite3.Error as e:
            print("Conexão nao Estabelecida")

#__________________CRIA O BANCO CASO NAO TENHA NO PROJETO________________#

    def criar_tabela(self):#cria tabela, se ja tiver a tabela ela ignora esse comando
        cur = self.cursor
        cur.execute("""
        CREATE TABLE cadastro (
        nome TEXT NOT NULL,
        login TEXT NOT NULL,
        senha TEXT NOT NULL,
        nivel INTEGER NOT NULL,
        Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT);""")

#__________________FUNÇÃO CRIADA PARA FAZER INSERT INTO NO BANCO_______________#

    def inserir_dados(self,query):
        cur = self.cursor
        cur.execute(query)
        self.conn.commit()

#_____________________FUNÇÃO CRIADA PARA FAZER SELECT NO BANCO____________________#

    def pegar_dados(self,query):
        cur = self.cursor
        cur.execute(query)
        return cur.fetchall

#_______________________FUNÇÃO CRIADA PARA PEGAR APENAS O CAMPO NIVEL DO BANCO____________#

    def pegarNivel(self,query):
        cur = self.cursor
        cur.execute(query)

#___________DESCOMENTE E EXECUTE O COD. PARA GERAR MAIS BANCOS CASO QUEIRA_____________________________#

#db = banco_db("X.db") #SUBISTITUIR O X PELO NOME DO NOVA BANCO.
#db.criar_tabela()


import asyncio
import logging

from asyncua import Client

class HelloClient:
    def __init__(self, endpoint):
        self.client = Client(endpoint)

    async def __aenter__(self):
        await self.client.connect()
        return self.client

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.client.disconnect()

async def main():
    async with HelloClient("opc.tcp://localhost:4840/freeopcua/server/") as client:
        root = client.nodes.root
        print("Root node is: ", root)
        objects = client.nodes.objects
        print("Objects node is: ", objects)

        hellower = await objects.get_child("0:Hellower")
        print("Hellower is: ", hellower)

        resulting_text = await hellower.call_method("0:SayHello", False)
        print(resulting_text)

        resulting_text = await hellower.call_method("1:SayHello2", True)
        print(resulting_text)

        resulting_array = await hellower.call_method("1:SayHelloArray", False)
        print(resulting_array)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())


"""
Serve GraphQL on a socket.
"""

import asyncio
import os
import threading
import urllib.parse
import sys

from fastapi import FastAPI
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.websockets import WebSocket
from ariadne.asgi import GraphQL as AriadneGraphQL
from ariadne.asgi.handlers import GraphQLTransportWSHandler

# Assume RIME is in the directory above this one.
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from rime import Rime
from rime.graphql import schema, QueryContext
from rime.config import Config

class NullBGCall:
    """
    Acts like a BG Executor, but is passed to the background RIME and just runs things immediately.
    """
    def __init__(self):
        super().__init__()
        self._rime = None

    def set_rime(self, rime):
        self._rime = rime

    def __call__(self, fn, *args, **kwargs):
        return fn(self._rime, *args, **kwargs)

class RimeBGCall:
    """
    When invoked, run the given function in the background, passing as a first argument 'rime'
    (which should correspond to the background RIME instance).
    """
    def __init__(self, config):
        super().__init__()

        self._loop = asyncio.new_event_loop()
        self._thread = threading.Thread(target=self._bg_thread, args=(config, self._loop), daemon=True)
        self._thread.start()

    def _bg_thread(self, config, loop):
        # Create an asyncio event loop. This will drive the background thread.
        asyncio.set_event_loop(loop)

        # Create the background RIME.
        self.rime = Rime.create(config, NullBGCall(), loop)

        # Run the event loop.
        loop.run_forever()

    def __call__(self, fn, *args, bg_call_complete_fn=None, **kwargs):
        future = asyncio.run_coroutine_threadsafe(fn(self.rime, *args, **kwargs), self._loop)

        if bg_call_complete_fn:
            future.add_done_callback(bg_call_complete_fn)

        return future

class RimeSingleton:
    """
    Serialise access to RIME so all DB access is done from the same thread.

    We use the current thread for foreground tasks, and create a separate background
    thread for background tasks such as subsetting with anonymisation.
    """
    def __init__(self, config, async_loop):
        super().__init__()

        self._config = config
        self._bg_call = RimeBGCall(config)

        # Create the foreground RIME.
        self._rime = Rime.create(config, self._bg_call, async_loop)

    def get_context_value(self, request, data):
        return QueryContext(self._rime)

    async def get_media(self, media_id):
        return self._rime.get_media(media_id)

    async def startup(self):
        await self._rime.start_background_tasks_async()

    async def shutdown(self):
        await self._rime.stop_background_tasks_async()

def create_app():
    # Read config
    frontend_host, frontend_port = os.environ.get('RIME_FRONTEND', 'localhost:3000').split(':')
    for filename in (os.environ.get('RIME_CONFIG', 'rime_settings.local.yaml'), 'rime_settings.yaml'):
        if os.path.exists(filename):
            print("RIME is using the configuration file", filename)
            rime_config = Config.from_file(filename)
            break
    else:
        print("Configuration file not found. Create rime_settings.local.yaml or set RIME_CONFIG.")
        sys.exit(1)

    rime = RimeSingleton(rime_config, asyncio.get_running_loop())
    app = FastAPI()

    # Add CORS middleware to allow the frontend to communicate with the backend on a different port.
    cors_origins = [
        f"http://{frontend_host}:{frontend_port}",
    ]

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

    @app.on_event("startup")
    async def startup():
        await rime.startup()

    @app.on_event("shutdown")
    async def shutdown():
        await rime.shutdown()

    @app.get("/media/{media_id:path}")
    async def handle_media(media_id: str):
        media_id = urllib.parse.unquote(media_id)
        media_data = await rime.get_media(media_id)

        response = StreamingResponse(media_data.handle, media_type=media_data.mime_type)
        response.headers['Content-Length'] = str(media_data.length)
        return response

    graphql_app = AriadneGraphQL(
        schema,
        websocket_handler=GraphQLTransportWSHandler(),
        context_value=rime.get_context_value
    )

    # For checking that the server is up:
    @app.get("/ping")
    async def ping():
        return JSONResponse({"ping": "pong"})

    # Use a separate endpoint, rather than app.mount, because Starlette doesn't support root mounts not ending in /.
    # See https://github.com/encode/starlette/issues/869 .
    @app.post("/graphql")
    async def handle_graphql_post(request: Request):
        # Queries and mutations.
        return await graphql_app.handle_request(request)

    @app.websocket("/graphql-ws")
    async def handle_graphql_ws(websocket: WebSocket):
        return await graphql_app.handle_websocket(websocket)

    return app


import configparser
import os
import sys
from collections import defaultdict
from pathlib import Path
from subprocess import CalledProcessError, run

import click
import yaml

def get_playbook(path: Path) -> list:
    """Reads the playbook in YAML from path.
    Args:
      pathlib.Path: path to playbook in YAML file
    Returns:
      list: playbook
    """
    plays = []
    with open(path) as infile:
        plays = yaml.safe_load(infile.read())
    # let's validate the playbook
    if not plays:
        raise ValueError("Empty playbook")
    if "hosts" not in plays[0]:
        raise ValueError("Invalid playbook, missing hosts")
    if "tasks" not in plays[0]:
        raise ValueError("Invalid playbook, missing tasks")
    for task in plays[0]["tasks"]:
        if "name" not in task:
            raise ValueError("Invalid playbook, missing description of the task")
        if "bash" not in task:
            raise ValueError("Invalid playbook, missing bash command to run")
    return plays

def get_hosts(path: Path) -> dict:
    """Reads the hosts inventory file in INI format.
    Args:
      pathlib.Path: path to hosts inventory INI file
    Returns:
      dict: hosts grouped by key
    """
    with open(path, "r") as infile:
        # configparser does not allow for ungrouped items
        # but ansible does: https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html
        config_string = "[ungrouped]\n" + infile.read()
    config = configparser.ConfigParser(allow_no_value=True)
    config.read_string(config_string)
    grouped_hosts = defaultdict(list)
    for section in config.sections():
        for item in config[section]:
            grouped_hosts[section].append(item)
    return dict(grouped_hosts)

def run_playbook(playbook: list = None, hosts: dict = None, user: str = None) -> None:
    """Run commands from playbook on all hosts from given group.
    Prints the output of the commands to the standard output.
    Args:
      list: playbook
      dict: hosts
    Returns:
      None
    """

    if playbook is None:
        playbook = []
    if hosts is None:
        hosts = {}
    if user is None:
        try:
            user = os.environ["USER"]
        except KeyError:
            sys.stdout.write("Missing $USER in env\n")
            return

    for hostgroup in playbook:
        for host in hosts.get(hostgroup.get("hosts"), []):
            for task in hostgroup.get("tasks", {}):
                try:
                    sys.stdout.write(
                        f"===> Running {task['bash']} on {host} from {hostgroup['hosts']}\n"
                    )
                    # check if a user can connect to the node without the password
                    cmd = [
                        "ssh",
                        "-o",
                        "PasswordAuthentication=no",
                        "-o",
                        "BatchMode=yes",
                        f"{user}@{host}",
                        "exit",
                    ]
                    if run(cmd).returncode:
                        sys.stdout.write(f"User {user} can not connect to {host}\n")
                        continue
                    cmd = ["ssh", f"{user}@{host}"] + task["bash"].split()
                    try:
                        output = run(cmd, capture_output=True, check=True)
                        sys.stdout.writelines(output.stdout.decode())
                    except CalledProcessError as cpe:
                        sys.stdout.writelines(cpe.stderr.decode())
                except KeyError:
                    # we ignore missing `bash` entry
                    pass

@click.command()
@click.option(
    "--hosts",
    default="/etc/ansible/hosts",
    help="Name of the hosts input file, by default /etc/ansible/hosts",
    type=click.Path(exists=True, dir_okay=False),
)
@click.option(
    "--playbook",
    default="./playbook.yaml",
    help="Name of the YAML input file with the playbook, by default ./playbook.yaml",
    type=click.Path(exists=True, dir_okay=False),
)
@click.option(
    "--user",
    default=os.environ.get("USER"),
    help="Username used to connect to the remote nodes, by default $USER",
    type=click.STRING,
)
def main(user, playbook, hosts):
    """Main script to run the playbook"""
    run_playbook(get_playbook(playbook), get_hosts(hosts), user)


#!/usr/bin/env python3.5
from __future__ import print_function

from seq_funcs import read_multi_fastas
from AASeq import AASeq
from _binding_data import binding_data

import pandas as pd
from collections import OrderedDict
import matplotlib.pyplot as plt
from matplotlib import colors
from numpy import array, arange
# import sys
# import os
# import subprocess

# import numpy as np
from sklearn.tree import DecisionTreeClassifier, export_graphviz

root_path = '/home/labs/fleishman/jonathaw/decision_tree/'
aa2num = OrderedDict([('-', 0), ('A', 1), ('C', 2), ('D', 3), ('E', 4), ('F', 5), ('G', 6), ('H', 7), ('I', 8),
                       ('K', 9), ('L', 10), ('M', 11), ('N', 12), ('P', 13), ('Q', 14), ('R', 15), ('S', 16), ('T', 17),
                       ('V', 18), ('W', 19), ('Y', 20)])
num2aa = OrderedDict({v: k for k, v in aa2num.items()})
types = ['p', 'n', 'o', 'h']
positions = {'core_coh': [11, 12], 'core_doc': [2, 6, 10]}
positions['rim_coh'] = [i for i in range(1, 21, 1) if i not in positions['core_coh']]
positions['rim_doc'] = [i for i in range(1, 11, 1) if i not in positions['core_doc']]

coh_poses_1ohz = [32, 33, 35, 37, 63, 66, 68, 70, 73, 75, 77, 79, 81, 83, 85, 116, 118, 119, 121, 123, 125, 127]
doc_poses_1ohz = [11, 14, 15, 18, 19, 21, 22, 45, 46, 48, 49, 52, 53]

def main():
    print('parsing data')
    df = parse_binding_data()
    # print(df)

    features = list(df.columns[2:-1])

    y = df['binding']
    X = df[features]

    print('fitting tree')
    dt = DecisionTreeClassifier()#min_samples_split=20)#, random_state=99)
    dt.fit(X, y)

    df['prediction'] = dt.predict(X)
    predict = {coh: {doc: int(df.loc[(df.coh == coh) & (df.doc == doc)].prediction) for doc in df['doc']}
               for coh in set(df['coh'])}

    # with open('decision_tree.dot', 'w') as fout:
    #     export_graphviz(dt, out_file=fout, feature_names=features)

    show_predcition_matrix(predict)
    # command = ['dot', '-Tpng', 'decision_tree.dot', '-o', 'decision_tree.png']
    # subprocess.check_call(command)

def show_predcition_matrix(prediction: dict) -> None:
    obs_pre = {0: {0: 0, 1: 2}, 1: {0: 3, 1: 1}}
    binding_ = binding_data()
    df = pd.DataFrame(data=0, index=list(binding_.values())[0].keys(), columns=binding_.keys())
    for coh, doc_ in binding_.items():
        for doc, obs in doc_.items():
            df[coh][doc] = obs_pre[binding_[coh][doc]][prediction[coh][doc]]

    plt.figure()
    axis = plt.gca()
    cmap = colors.ListedColormap(['white', 'cornflowerblue', 'red', 'darkorange'])
    bounds = [-0.5, 0.5, 1.5, 2.5, 3.5]
    norm = colors.BoundaryNorm(bounds, cmap.N)
    heatmap = plt.pcolor(array(df), cmap=cmap, norm=norm, edgecolors='k', linewidth=2)
    for y in range(array(df.shape)[0]):
        for x in range(array(df.shape)[1]):
            if array(df)[y, x] >= 0:
                plt.text(x+0.5, y+0.5, array(df)[y, x], horizontalalignment='center', verticalalignment='center')
    plt.yticks(arange(0.5, len(df.index), 1), df.index)
    plt.xticks(arange(0.5, len(df.columns), 1), df.columns, rotation=70)
    plt.xlabel('Cohesin name', style='oblique')
    plt.ylabel('Dockerin name', style='oblique')
    axis.set_aspect('equal')
    plt.title('Cohesin dockerin cross binding')
    plt.suptitle('0: obs no pred no, 1: obs yes, pred yes\n2: obs no pred yes, 3: obs yes pred no')
    plt.show()

def seq_to_num(seq: str) -> int:
    return int(''.join(str(aa2num[a]) for a in seq))

def parse_binding_data() -> pd.DataFrame:
    # cohs = read_multi_fastas(root_path+'cohs_specific_pos.fasta', suffix_to_remove='/')
    # docs = read_multi_fastas(root_path+'docs_specific_pos.fasta', suffix_to_remove='/')
    cohs, docs = retrive_relevant_poses()
    data = binding_data()

    colums = ['coh', 'doc'] + \
             ['core coh %i %s' % (i, aa) for i in [1, 2] for aa in aa2num.keys()] + \
             ['core doc %i %s' % (i, aa) for i in [1, 2, 3] for aa in aa2num.keys()] + \
             ['rim coh %i %s' % (i, t) for i in range(1, 19, 1) for t in types] + \
             ['rim doc %i %s' % (i, t) for i in range(1, 8, 1) for t in types] + ['binding']
    df = pd.DataFrame(columns=colums)
    i = 1
    for coh, doc_dict in data.items():
        coh_seq = cohs[coh].get_seq
        for doc, res in doc_dict.items():
            doc_seq = docs[doc].get_seq
            df.loc[i] = [coh, doc] + seqs2row(coh_seq, doc_seq) + [1 if res else 0]
            i += 1
    return df

def retrive_relevant_poses() -> (dict, dict):
    """
    :return: seq dicts for cohs and docs, holding only the relevqant positions, determined by 1OHZ
    """
    cohs_old = read_multi_fastas(root_path+'cohesins_from_rachel.fasta_aln', suffix_to_remove='/')
    docs_old = read_multi_fastas(root_path+'dockerins_from_rachel.fasta_aln', suffix_to_remove='/')

    coh_1ohz = cohs_old['1OHZ']
    coh_poses = [coh_1ohz.non_aligned_position_at_aligned(p) for p in coh_poses_1ohz]
    doc_1ohz = docs_old['1OHZ']
    doc_poses = [doc_1ohz.non_aligned_position_at_aligned(p) for p in doc_poses_1ohz]

    cohs_new, docs_new = {}, {}

    for coh, res in cohs_old.items():
        cohs_new[coh] = AASeq(string=''.join(res.get_aligned_positions(coh_poses)), name=coh)
    for doc, res in docs_old.items():
        docs_new[doc] = AASeq(string=''.join(res.get_aligned_positions(doc_poses)), name=doc)
    return cohs_new, docs_new

def aa2rim_type(aa: str) -> str:
    if aa in ['K', 'R', 'H']:
        return 'p'
    elif aa in ['D', 'E']:
        return 'n'
    elif aa in ['N', 'Q', 'T', 'S', 'C']:
        return 'o'
    elif aa in ['L', 'I', 'M', 'V', 'A', 'F', 'W', 'Y', 'P', 'G']:
        return 'h'

def aa2binary_core(aa: str) -> list:
    """
    :param aa: amino acid
    :return: binary for aa
    >>> aa2binary('A')
    [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    >>> aa2binary('W')
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
    """
    res = [0] * len(aa2num.keys())
    res[aa2num[aa]] = 1
    return res

def aa2binary_rim(aa: str) -> list:
    """
    :param aa: an amino acid
    :return: binary for rim type
    >>> aa2binary_rim('A')
    [0, 0, 0, 1]
    >>> aa2binary_rim('E')
    [0, 1, 0, 0]
    """
    t = aa2rim_type(aa)
    res = [0] * len(types)
    for i, ty in enumerate(types):
        if t == ty:
            res[i] = 1
    return res

def seqs2row(coh_seq: str, doc_seq: str) -> list:
    """
    :param coh_seq: cohesin sequence
    :param doc_seq: dockerin sequence
    :return: binary list repersenting the sequences
    >>> seqs2row('SKTRVSSNDYTGLETALGL-', 'SSLSTSNSLA')

    """
    res = []
    for p in positions['core_coh']:
        res += aa2binary_core(coh_seq[p-1])
    for p in positions['core_doc']:
        res += aa2binary_core(doc_seq[p-1])

    for p in positions['rim_coh']:
        res += aa2binary_rim(coh_seq[p-1])
    for p in positions['rim_doc']:
        res += aa2binary_rim(doc_seq[p-1])
    return res

if __name__ == '__main__':
    main()


import argparse
import os
import sys

import numpy as np
from allennlp.commands.train import train_model
from allennlp.common import Params
from allennlp.common.util import import_module_and_submodules
from dotenv import load_dotenv

sys.path.append('src')

load_dotenv()

WANDB_CALLBACKS = ["wandb", "wandb_best"]

def to_string(value):
    if isinstance(value, list):
        return [to_string(x) for x in value]
    elif isinstance(value, bool):
        return "true" if value else "false"
    else:
        return str(value)

def parse_args(argv):
    args = argparse.ArgumentParser()
    args.add_argument('--name', type=str)
    return args.parse_args(argv)

def get_wandb_callback(settings):
    callbacks = [cb for cb in settings['trainer']['callbacks'] if
                 type(cb) is dict and cb.get("type") in WANDB_CALLBACKS]
    return callbacks[0] if callbacks else None

def update_wandb_params(settings):
    wandb_callback = get_wandb_callback(settings)
    if not wandb_callback:
        return

    wandb_callback['wandb_kwargs']['resume'] = 'must'

def main_train(argv):
    args = parse_args(argv)
    import_module_and_submodules('src')

    experiment_dir = f"../runs/{args.name}/{args.name}"

    settings = Params.from_file(f"{experiment_dir}/config.json")
    print(f"Loading experiment from {experiment_dir}")
    print(f"path: {settings['train_data_path']}")

    os.environ["WANDB_RESUME"] = "must"

    train_model(
        params=settings,
        serialization_dir=experiment_dir,
        recover=True
    )

if __name__ == "__main__":
    main_train(sys.argv[1:])


import json
import requests

def get_json(keyword, page_ind=0):
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    u_id = 1   # MOSCOW
    # u_id = 113   # SANKT-PETERSBURG
    # u_id = 1002  # MINSK
    # u_id = 115   # KIEV
    only_with_salary = 'true'
    url = f'https://api.hh.ru/vacancies?&text={keyword}&area={u_id}&only_with_salary={only_with_salary}&page={page_ind}&specialization=1'

    response = requests.get(url, headers=headers)
    json_data = json.loads(response.text)
    return json_data

def test():
    json_data = get_json('Python')
    print(json_data['found'])

if __name__ == '__main__':
    test()


from random import random
from requests_html import HTMLSession
import requests
from bs4 import BeautifulSoup
from lxml import etree
import random
import datetime, pytz
import environ

env = environ.Env()
environ.Env.read_env()
#print(env('NEWS_API_KEY'))

class weather:
    def get_weather(query):
        session = HTMLSession()

        query = query

        url= f'https://www.google.com/search?q=weather+{query}'

        r = session.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.46'})

        soup = BeautifulSoup(r.content, 'html.parser')
        dom = etree.HTML(str(soup))
        try:
            clouds = (dom.xpath('//*[@id="wob_dc"]'))[0].text
            temperature = (dom.xpath('//*[@id="wob_tm"]'))[0].text
        except:
            clouds= "Enter Valid Location"

        print(clouds, temperature+" degrees")
        return clouds

#https://www.google.com/search?q=movies&source=lnms&tbm=nws&sa=X&ved=2ahUKEwjk1MWz1-T2AhUJwzgGHRdRBPQQ_AUoA3oECAIQBQ&biw=1536&bih=754&dpr=1.25
class home_content:

    def gnews_api(query):

        query = query
        session = HTMLSession()
        token= env('GNEWS_TOKEN')
        url= f"https://gnews.io/api/v4/top-headlines?&token={token}&lang=en&country=in"

        r = session.get(url)
        json_data = r.json()["articles"]

        count = len(json_data)

        #index = random.randint(1,count)
        titles = []
        urls = []
        images = []
        times = []
        descs = []
        formatted_times = []

        for items in json_data:
            titles.append(items["title"])
            urls.append(items["url"])
            images.append(items["image"])
            descs.append(items["description"])
            times.append(items["publishedAt"])
        now = str(datetime.datetime.now(pytz.timezone('UTC'))).split('.')[0]
        now = datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
        for tim in times:
            try:
                art_time = str(tim).replace('T', ' ').replace('Z', ' ').strip()
                art_time = datetime.datetime.strptime(art_time, '%Y-%m-%d %H:%M:%S')

                diff = now - art_time
                diff = int(diff.total_seconds())

                if diff>59 and diff<3601:
                    diff = f"{int(diff/60)} mins ago"
                elif diff<61:
                    diff = f"{int(diff)} secs ago"
                elif diff>3599 and diff<86400:
                    diff = f"{int(diff/60/60)} hours ago"
                elif diff>86399:
                    diff = f"{int(diff/24/60/60)} days ago"
                formatted_times.append(diff)

            except:
                formatted_times.append('')
        content = {"title":titles,"link":urls,"time":formatted_times,"desc":descs, "image":images}
        return content

    def news_api(query):
        query = query
        session = HTMLSession()
        api_key = env('NEWS_API_KEY')
        url= f"https://newsapi.org/v2/top-headlines?country={query}&sortBy=publishedAt&apiKey={api_key}&language=en"
        try:
            r = session.get(url)
            json_data = r.json()["articles"]
            count = len(json_data)

            index = random.randint(1,int(count/2))
            titles = []
            urls = []
            images = []
            times = []
            descs = []
            formatted_times = []

            for items in json_data:
                titles.append(items["title"])
                urls.append(items["url"])
                images.append(items["urlToImage"])
                descs.append(items["description"])
                times.append(items["publishedAt"])

            now = str(datetime.datetime.now(pytz.timezone('UTC'))).split('.')[0]
            now = datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:%S')

            for tim in times:
                try:
                    art_time = str(tim).replace('T', ' ').replace('Z', ' ').strip()
                    art_time = datetime.datetime.strptime(art_time, '%Y-%m-%d %H:%M:%S')

                    diff = now - art_time
                    diff = int(diff.total_seconds())

                    if diff>59 and diff<3601:
                        formatted_times.append(f"{int(diff/60)} mins ago")
                    elif diff<61:
                        formatted_times.append(f"{int(diff)} secs ago")
                    elif diff>3599 and diff<86400:
                        formatted_times.append(f"{int(diff/60/60)} hours ago")
                    elif diff>86399:
                        formatted_times.append(f"{int(diff/24/60/60)} days ago")
                except:
                    formatted_times.append("")
            #now_utc = str(now.astimezone(pytz.utc)).split("+")[0]
            content = {"title":titles,"link":urls,"time":formatted_times,"desc":descs, "image":images}
            return content

        except:

            try:
                return home_content.gnews_api(query)
            except:
                return home_content.get_content(query)

    def get_content(query):

        """session = HTMLSession()
        query = query"""

        url= f"https://www.google.com/search?q=news&tbm=nws"
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.46'}
        try:
            req= requests.get(url, headers=headers)
            soup = BeautifulSoup(req.content, 'html.parser')

            blocks = soup.find_all('g-card', class_='ftSUBd')
            titles = []
            descs = []
            links = []
            times = []
            images = []
            for t in blocks:
                titles.append(t.find('div', role='heading').text.replace('\n', '').strip())
                descs.append(t.find('div', class_='GI74Re nDgy9d').text.strip())
                ln = t.find('a').attrs['href']
                links.append(ln)
                times.append(t.find('div', class_='OSrXXb ZE0LJd').find('span').text.strip())
                images.append(home_content.get_image(ln))

            print(len(blocks))
            print(images[0])

            #Getting content using DOM, etree
            """dom = etree.HTML(str(soup))

            count= len((dom.xpath(f'//*[@id="rso"]/div/g-card/div/div/a/div/div[2]/div[2]')))
            index = random.randint(0, count)

            try:
                content_title = (dom.xpath(f'//*[@id="rso"]/div[{index}]/g-card/div/div/a/div/div[2]/div[2]'))[0].text
            except:
                content = {"title":"","link":"","time":"","desc":"", "image":""}
                return content

            try:
                content_link = (dom.xpath(f'//*[@id="rso"]/div[{index}]/g-card/div/div/a'))[0].attrib['href']
            except:
                content_link = "#"

            try:
                content_time = (dom.xpath(f'//*[@id="rso"]/div[{index}]/g-card/div/div/a/div/div[2]/div[4]/span'))[0].text

            except:
                content_time = "####"

            try:
                content_desc = (dom.xpath(f'//*[@id="rso"]/div[{index}]/g-card/div/div/a/div/div[2]/div[3]'))[0].text
            except:
                content_desc = "Something went wrong"

            try:
                content_image = home_content.get_image(content_link)
            except:
                content_image = "No Image Found"

            content = {"title":content_title,"link":content_link,"time":content_time,"desc":content_desc, "image":content_image}
            """

            content = {"title":titles,"link":links,"time":times,"desc":descs, "image":images}
        except:
            content= {}
        return content

    def get_image(link):
        url = link
        session = HTMLSession()
        req= session.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.46'})
        soup = BeautifulSoup(req.content, 'html.parser')
        try:
            meta_image = soup.find('meta', property="og:image").attrs['content']
        except:
            meta_image = ""
        return meta_image


#sound from zapsplat.com
#images from seekpng.com
#start button similarpng.com
import pygame
import random
from pygame.locals import (
    RLEACCEL,
    K_SPACE,
    K_UP,
    K_DOWN,
    K_LEFT,
    K_RIGHT,
    K_ESCAPE,
    KEYDOWN,
    QUIT,
)

pygame.init()

myfont = pygame.font.SysFont("Comic Sans MS", 30)

endGameText = myfont.render("", False, (255,255,0))

score = 0

numLasers = 5

brocolliKilled = 0

pygame.mixer.music.load("BackgroundMusic.mp3")

LaserSound = pygame.mixer.Sound("LaserSound.mp3")
ExplosionSound = pygame.mixer.Sound("ExplosionSound.mp3")
#IceCreamSound = pygame.mixer.Sound("IceCreamSound.mp3")

SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500

screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])

clock = pygame.time.Clock()

all_sprites = pygame.sprite.Group()
enemies_group = pygame.sprite.Group()
friends_group = pygame.sprite.Group()
laser_group = pygame.sprite.Group()
explosion_group = pygame.sprite.Group()

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super(Player, self).__init__()
        self.surf = pygame.image.load("PlayerShip.png").convert()
        self.surf = pygame.transform.scale(self.surf, (40,26))
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect()
        self.rect.center = (460, 250)
    def getPos(self) :
        return self.rect.center

class Enemy(pygame.sprite.Sprite):
    def __init__(self, xPos, yPos):
        super(Enemy, self).__init__()
        self.speed = random.randint(4, 6)
        self.surf = pygame.image.load("EnemyShip.png").convert()
        self.surf = pygame.transform.scale(self.surf, (30,30))
        self.surf.set_colorkey((0,0,0), RLEACCEL)
        self.rect = self.surf.get_rect()
        self.rect.center = (xPos,yPos)

    def update(self):
        self.rect.move_ip(self.speed, 0)

class Laser(pygame.sprite.Sprite):
    def __init__(self, pos):
        super(Laser, self).__init__()
        self.speed = 4
        self.surf = pygame.image.load("BulletPic3.jpg").convert()
        self.surf = pygame.transform.scale(self.surf, (20,10))
        self.surf.set_colorkey((255,255,255), RLEACCEL)
        self.rect = self.surf.get_rect()
        self.rect.center = (pos)

    def update(self):
        self.rect.move_ip(-self.speed, 0)

class Explosion(pygame.sprite.Sprite):
    def __init__(self, pos):
        super(Explosion, self).__init__()
        self.speed = 4
        self.surf = pygame.image.load("ExplosionPic2.jpg").convert()
        self.surf = pygame.transform.scale(self.surf, (40,40))
        self.surf.set_colorkey((255,255,255), RLEACCEL)
        self.rect = self.surf.get_rect()
        self.rect.center = (pos)
        self.length = 40
        self.count = 0
    def update(self):
        self.count += 1

class Star(pygame.sprite.Sprite):
    def __init__(self, pos, color):
        super(Star, self).__init__()
        self.color = color
        self.surf = pygame.Surface((1,1))
        self.surf.fill((255,255,color))
        self.rect = self.surf.get_rect()
        self.rect.center = (pos)

for x in range(1000) :
    w = random.randint(0,SCREEN_WIDTH)
    h = random.randint(0,SCREEN_HEIGHT)
    c = random.randint(150,200)
    star = Star((w,h),c)
    all_sprites.add(star)

player = Player()
player.groups()
all_sprites.add(player)

makeEnemy = pygame.USEREVENT + 1
pygame.time.set_timer(makeEnemy, 500)

getLaser = pygame.USEREVENT + 8
pygame.time.set_timer(getLaser, 3000)

# INTRO CODE HERE
directions = False
welcome = True
while welcome :
    screen.fill((0, 0, 0))
    for x in range(255) :
        pygame.draw.circle(screen, (0, 0, x), (SCREEN_WIDTH/2,SCREEN_HEIGHT/2), 255 - x)
    image_surf = pygame.image.load("PlayerShip.png").convert()
    image_surf = pygame.transform.scale(image_surf, (240,156))
    image_surf.set_colorkey((0, 0, 0), RLEACCEL)
    image_surf = pygame.transform.rotate(image_surf, 30)
    image_rect = image_surf.get_rect()
    image_rect.center = (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)
    bul1_surf = pygame.image.load("BulletPic3.jpg").convert()
    bul1_surf = pygame.transform.scale(bul1_surf, (80,40))
    bul1_surf.set_colorkey((255,255,255), RLEACCEL)
    bul1_surf = pygame.transform.rotate(bul1_surf, -55)
    bul1_rect = bul1_surf.get_rect()
    bul1_rect.center = (400, 350)
    flame_surf = pygame.image.load("FlameTrail.png").convert()
    flame_surf = pygame.transform.scale(flame_surf, (100,200))
    flame_surf.set_colorkey((0,0,0), RLEACCEL)
    flame_surf = pygame.transform.rotate(flame_surf, 35)
    flame_rect = flame_surf.get_rect()
    flame_rect.center = (470, 450)
    start_surf = pygame.image.load("StartButton.png").convert()
    start_surf = pygame.transform.scale(start_surf, (200,80))
    start_surf.set_colorkey((0,0,0), RLEACCEL)
    start_rect = start_surf.get_rect()
    start_rect.center = (250, 410)
    dir_surf = pygame.image.load("howPlay.png").convert()
    dir_surf = pygame.transform.scale(dir_surf, (120,30))
    dir_surf.set_colorkey((0,0,0), RLEACCEL)
    dir_surf.set_colorkey((255,255,255), RLEACCEL)
    dir_rect = dir_surf.get_rect()
    dir_rect.center = (250, 470)
    screen.blit(image_surf, image_rect)
    screen.blit(flame_surf, flame_rect)
    screen.blit(bul1_surf, bul1_rect)
    screen.blit(start_surf, start_rect)
    screen.blit(dir_surf, dir_rect)
    introFont = pygame.font.SysFont("inkfree", 80)
    introText = introFont.render("Space Fight", False, (255,255,0))
    introFont2 = pygame.font.SysFont("inkfree", 200)
    introText2 = introFont2.render("2", False, (255,200,0))
    screen.blit(introText2, (200,0))
    screen.blit(introText, (50,40))
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if start_rect.collidepoint(mouse_pos):
                welcome = False
            if dir_rect.collidepoint(mouse_pos):
                welcome = False
                directions = True
        if event.type == pygame.QUIT:
            pygame.quit()

while directions :
    screen.fill((0, 0, 0))
    for x in range(255) :
        pygame.draw.circle(screen, (0, 0, x), (SCREEN_WIDTH/2,SCREEN_HEIGHT/2), 255 - x)
    start_surf2 = pygame.image.load("StartButton.png").convert()
    start_surf2 = pygame.transform.scale(start_surf2, (200,80))
    start_surf2.set_colorkey((0,0,0), RLEACCEL)
    start_rect2 = start_surf2.get_rect()
    start_rect2.center = (250, 410)
    screen.blit(start_surf2, start_rect2)
    dirFont1 = pygame.font.SysFont("inkfree", 35)
    dirFont2 = pygame.font.SysFont("inkfree", 20)
    dirText1 = dirFont1.render("Goal: ", False, (255,200,0))
    dirText2 = dirFont2.render("Shoot as many red enemy ships as you can (to gain", False, (255,200,0))
    dirText3 = dirFont2.render("points), without getting hit by an enemy ship ", False, (255,200,0))
    dirText4 = dirFont2.render("(which results in death). ", False, (255,200,0))
    dirText5 = dirFont1.render("Directions: ", False, (255,200,0))
    dirText6 = dirFont2.render("Press and release the up/down arrow keys to move.", False, (255,200,0))
    dirText7 = dirFont2.render("Press and release the space bar to shoot.", False, (255,200,0))
    dirText8 = dirFont2.render("Remember: You start with 5 lasers and gain one ", False, (255,200,0))
    dirText9 = dirFont2.render("every 3 seconds. Use them wisely. ", False, (255,200,0))
    screen.blit(dirText1, (40,5))
    screen.blit(dirText2, (40,55))
    screen.blit(dirText3, (40,80))
    screen.blit(dirText4, (40,105))
    screen.blit(dirText5, (40,155))
    screen.blit(dirText6, (40,205))
    screen.blit(dirText7, (40,230))
    screen.blit(dirText8, (40,255))
    screen.blit(dirText9, (40,280))
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if start_rect2.collidepoint(mouse_pos):
                directions = False
        if event.type == pygame.QUIT:
            pygame.quit()

pygame.mixer.music.play(-1)
running = True
dead = False
counter = 0
x1 = 100
y1 = 100 # (used for end graphics)
while running:
    counter += 1

    for event in pygame.event.get():
        if event.type == KEYDOWN and not dead:
            if event.key == K_UP:
                player.rect.move_ip(0, -10)
            elif event.key == K_DOWN:
                player.rect.move_ip(0, 10)
            elif event.key == K_SPACE and numLasers > 0:
                laser = Laser(player.rect.center)
                all_sprites.add(laser)
                laser_group.add(laser)
                pygame.mixer.Sound.play(LaserSound)
                numLasers -= 1

        # note: could also use counter to make enemies
        if event.type == makeEnemy:
            numEnemies = 0
            for num in range(0,score + 1,5) :
                if numEnemies < 6 : # limits the increase after 25
                    x = random.randint(0, 10)
                    y = random.randint(0, SCREEN_HEIGHT)
                    enemy = Enemy(x,y)
                    all_sprites.add(enemy)
                    enemies_group.add(enemy)
                    numEnemies += 1

        if event.type == getLaser :
            numLasers += 1

        if event.type == pygame.QUIT:
            running = False

    for entity in enemies_group:
        if player.rect.colliderect(entity):
            player.kill()
            myfontEnd = pygame.font.SysFont("impact", 50)
            endGameText = myfontEnd.render("Score: " + str(score), False, (255,255,0))
            over_surf = pygame.image.load("GameOver.png").convert()
            over_surf = pygame.transform.scale(over_surf, (200,150))
            over_surf.set_colorkey((0, 0, 0), RLEACCEL)
            if not dead :
                explosion = Explosion((player.rect.centerx - 25,player.rect.centery - 25))
                explosion.surf = pygame.transform.scale(explosion.surf, (90,90))
                all_sprites.add(explosion)
                explosion_group.add(explosion)
                pygame.mixer.Sound.play(ExplosionSound)
            pygame.mixer.music.stop()
            dead = True

    for entity1 in laser_group:
        for entity2 in enemies_group:
            if entity1.rect.colliderect(entity2):
                entity2.kill()
                score = score + 1
                #EXPLOSION
                explosion = Explosion(entity1.rect.center)
                all_sprites.add(explosion)
                explosion_group.add(explosion)
                pygame.mixer.Sound.play(ExplosionSound)

    text_surface = myfont.render("Score: " + str(score), False, (255,255,0))
    text_surface2 = myfont.render("Lasers: " + str(numLasers), False, (255,255,0))

    for explosion in explosion_group :
        explosion.update()
        if explosion.count == explosion.length :
            explosion.kill()

    # red, green, blue
    screen.fill((0, 0, 0))
    for x in range(255) :
        pygame.draw.circle(screen, (0, 0, x), (SCREEN_WIDTH/2,SCREEN_HEIGHT/2), 255 - x)

    for enemy in enemies_group:
        enemy.update()

    for laser in laser_group:
        laser.update()

    for entity in all_sprites:
        screen.blit(entity.surf, entity.rect)

    if not dead :
        screen.blit(text_surface, (325,450))
        screen.blit(text_surface2, (50,450))
    screen.blit(endGameText, (175,225))
    if dead :
        if counter % 50 == 0 :
            x1 = random.randint(0, 300)
            y1 = random.randint(0, 350)
        screen.blit(over_surf, (x1,y1))

    pygame.display.flip()

    clock.tick(60)

pygame.quit()


"""
Catan Board Randomiser - GUI
Stuart Bradley
23/01/2014
"""

import kivy
kivy.require('1.7.2')

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
import kivy.graphics as graphics
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.config import Config
from kivy.adapters.listadapter import ListAdapter
from kivy.uix.listview import ListItemButton, ListView

from math import sin, cos, pi, sqrt
from CatanBackend import CatanBoard, CatanHex
############
#Main Class#
############

class CatanGUI(GridLayout):

	#################
	#Build GUI class#
	#################

	def __init__(self, **kwargs):
		super(CatanGUI, self).__init__(**kwargs)

		self.board = CatanBoard()
		self.mode = 'Thin'
		self.board.grid = self.board.ini_Grid()
		self.hexSize = 40

		self.hexHeight = self.hexSize * 2
		self.hexVert = 0.75 * self.hexHeight

		self.hexWidth = sqrt(3)/2 * self.hexHeight

		self.rows = 2
		self.gridCanvas = Widget()
		self.gridCanvas.bind(pos=self.update_gridCanvas)
		self.gridCanvas.bind(size=self.update_gridCanvas)

		self.UI = GridLayout(cols=2, size_hint_y=0.2)
		self.randomiseButton = Button(text='Randomise')
		self.randomiseButton.bind(on_press=self.randomise_Grid)
		self.list_Adapter = ListAdapter(data=['Coastal', 'Thin Land Mass', 'Large Land Mass', 'Large Islands', 'Small Islands', 'Random'], cls=ListItemButton, selection_mode='single', allow_empty_selection=True)
		self.list_Adapter.bind(on_selection_change=self.item_Selected)
		self.random_Type = ListView(adapter=self.list_Adapter)
		self.UI.add_widget(self.random_Type)
		self.UI.add_widget(self.randomiseButton)

		self.add_widget(self.gridCanvas)
		self.add_widget(self.UI)

		self.startingX = self.gridCanvas.center_x
		self.startingY = self.gridCanvas.center_y + (self.gridCanvas.height * 6)

	def item_Selected(self, *args):
		try:
			self.mode = self.list_Adapter.selection[0].text
		except IndexError:
			pass

	def randomise_Grid(self, *args):
		self.board.grid = self.board.ini_Grid()
		self.board.colour_Grid(self.mode)
		self.update_gridCanvas()

	def update_gridCanvas(self, *args):
		self.gridCanvas.canvas.clear()
		xPos = self.startingX
		yPos = self.startingY
		with self.gridCanvas.canvas:
			for i in range(self.board.gridWidth):
				for j in range(self.board.gridHeight):
					if self.board.grid[i][j] != 'b':
						graphics.Color(self.board.grid[i][j].colour[0],self.board.grid[i][j].colour[1], self.board.grid[i][j].colour[2])
						if j & 1:
							#Why 0.8655? I don't fucking know is why.
							self.build_mesh(self.hexSize, xPos+(self.hexSize*0.8655), yPos)
							self.board.grid[i][j].x = xPos+(self.hexSize*0.8655)
							self.board.grid[i][j].y = yPos
						else:
							self.build_mesh(self.hexSize, xPos, yPos)
							self.board.grid[i][j].x = xPos
							self.board.grid[i][j].y = yPos
					yPos -= self.hexVert
				yPos = self.startingY
				xPos += self.hexWidth

	def build_mesh(self, size, centre_x, centre_y):
		vertices = []
		indices = []
		for i in range(6):
			istep = (pi * 2) / 6 * (i + 0.5)
			x = centre_x + size * cos(istep)
			y = centre_y + size * sin(istep)
			vertices.extend([x, y, 0, 0])
			indices.append(i)
		return graphics.Mesh(vertices=vertices, indices=indices, mode='triangle_fan')

class CatanGUIApp(App):
	title = 'Catan Board Randomiser'
	def build(self):
		Config.set('graphics', 'height', '700')
		Config.set('graphics','resizable',0)
		return CatanGUI()

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


import requests
from json import loads, dumps
from GPT import GPT
from Redis import Redis
from logger import logging
import os
from dotenv import load_dotenv
import json

load_dotenv()
LIMIT = 2

class Worker:

    def process_message(self, db, message_json: str, redisObj: Redis, gptObj: GPT):
        payload = loads(message_json)
        res, status = gptObj.ask_bot(payload['query'])
        if status != 401:
            logging.info(" query process successful ")
            logging.info(res)
            url = "https://server.gallabox.dev/devapi/messages/whatsapp"
            data = {
                "channelId": os.getenv('CHANNEL_ID'),
                "channelType": "whatsapp",
                "recipient": {
                    "name": payload['name'],
                    "phone": payload['phone']
                },
                "whatsapp": {
                    "type": "text",
                    "text": {
                        "body": res['response']
                    }
                }
            }
            headers = {
                'apiKey': os.getenv('API_KEY_GB'),
                'apiSecret': os.getenv('API_SECRET_GB'),
                'Content-Type': 'application/json'
            }
            # payload['res'] = data
            data = json.dumps(data)
            # print(type(data))
            r = requests.post(url, data=data, headers=headers)
            # print(r.reason)
            # print(r.text)
            # print(r.content)
            logging.info(r)
        elif payload['count'] < LIMIT:
            payload['count'] = payload['count']+1
            message_json = dumps(payload)
            redisObj.queue_push(db, message_json)
            logging.warning("Processing failed - requeuing...")
            logging.warning(res)
        else:
            logging.error("Processing failed Attempted requeuing > LIMIT")
            logging.warning(res)

def main():
    redisObj = Redis()
    workerObj = Worker()
    gptObj = GPT()
    db = redisObj.redis_db()
    while True:
        message_json = redisObj.queue_pop(db)
        workerObj.process_message(db, message_json, redisObj, gptObj)

if __name__ == '__main__':
    main()


import streamlit as st
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

def head():
    st.markdown("""

        Kelime Testi Envanteri

    """, unsafe_allow_html=True
                )

    st.caption("""

        Sakarya Üniversitesi Kariyer ve Yetenek Yönetimi Koordinatörlüğü

    """, unsafe_allow_html=True
               )

def body():
    mavi, sari, kirmizi, yesil = 0, 0, 0, 0
    st.markdown("""

            Güçlü Yönler. Her dört seçenekten birini seçiniz.

        """, unsafe_allow_html=True
            )

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose1 = st.radio("------------------------------------- " + "1" + " -------------------------------------",
                            ("Sonuç Odaklı", "Uyum Sağlayan", "Hareketli", "Analitik"),
                            key="choose1",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose2 = st.radio("------------------------------------- " + "2" + " -------------------------------------",
                            ("Mantıklı", "Neşeli", "İkna Edici", "Barışçıl"),
                            key="choose2",
                            horizontal=True)
    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose3 = st.radio("------------------------------------- " + "3" + " -------------------------------------",
                            ("Uysal", "Fedakar", "Sosyal", "İradeli"),
                            key="choose3",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose4 = st.radio("------------------------------------- " + "4" + " -------------------------------------",
                                ("İnsaflı", "Denetimli", "Yarışçıl", "İnandırıcı"),
                                key="choose4",
                                horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose5 = st.radio("------------------------------------- " + "5" + " -------------------------------------",
                                ("Ferahlatıcı", "Saygılı", "İyi dinleyici", "Becerikli"),
                                key="choose5",
                                horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose6 = st.radio("------------------------------------- " + "6" + " -------------------------------------",
                            ("Hoşnut", "Duyarlı", "Kendine güvenen", "Cesur"),
                            key="choose6",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose7 = st.radio("------------------------------------- " + "7" + " -------------------------------------",
                            ("Planlı", "Sabırlı", "Olumlu", "Teşvik edici"),
                            key="choose7",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose8 = st.radio("------------------------------------- " + "8" + " -------------------------------------",
                            ("Emin", "Kendiliğinden", "Programa bağlı", "Utangaç"),
                            key="choose8",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose9 = st.radio("------------------------------------- " + "9" + " -------------------------------------",
                            ("Düzenli", "İyiliksever", "Dobra", "İyimser"),
                            key="choose9",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose10 = st.radio("------------------------------------- " + "10" + "-------------------------------------",
                            ("Arkadaşçıl", "Sadık", "Komik", "Baskıcı"),
                            key="choose10",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose11 = st.radio("------------------------------------- " + "11" + "-------------------------------------",
                            ("Cesaretli", "Hoş", "Diplomatik", "Detaycı"),
                            key="choose11",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose12 = st.radio("------------------------------------- " + "12" + "-------------------------------------",
                            ("Esin Kaynağı", "Tutarlı", "Kültürlü", "Güvenli"),
                            key="choose12",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose13 = st.radio("------------------------------------- " + "13" + "-------------------------------------",
                            ("İdealist", "Bağımsız", "Zararsız", "Heyecanlandırıcı"),
                            key="choose13",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose14 = st.radio("------------------------------------- " + "14" + "-------------------------------------",
                            ("Coşkun", "Kesin", "Kuru esprili", "Derin düşünceli"),
                            key="choose14",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose15 = st.radio("------------------------------------- " + "15" + "-------------------------------------",
                            ("Aracı", "Ahenkli", "Harekete geçiren", "Kolay kaynaşır"),
                            key="choose15",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose16 = st.radio("------------------------------------- " + "16" + "-------------------------------------",
                            ("İnce düşünceli", "İş Bitirici", "Konuşma yanlısı", "Hoşgörülü"),
                            key="choose16",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose17 = st.radio("------------------------------------- " + "17" + "-------------------------------------",
                            ("Destekleyen", "Samimi", "Lider", "Canlı"),
                            key="choose17",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose18 = st.radio("------------------------------------- " + "18" + "-------------------------------------",
                            ("Halinden memnun", "Başkan, Şef", "Araştırmacı", "Şirin"),
                            key="choose18",
                            horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose19 = st.radio("------------------------------------- " + "19" + "-------------------------------------",
                        ("Mükemmeliyetçi", "Cana yakın", "Üretici", "Popüler"),
                        key="choose19",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose20 = st.radio("------------------------------------- " + "20" + "-------------------------------------",
                        ("Cömert", "Atılgan", "Terbiyeli", "Dengeli"),
                        key="choose20",
                        horizontal=True)

    st.markdown("""

            Zayıf Yönler. Her dört seçenekten birini seçiniz.

        """, unsafe_allow_html=True
            )

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose21 = st.radio("------------------------------------- " + "21" + "-------------------------------------",
                        ("İfadesiz", "Çekingen", "Utanması olmayan", "Zorba"),
                        key="choose21",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose22 = st.radio("------------------------------------- " + "22" + "-------------------------------------",
                        ("Disiplinsiz", "Sevimsiz", "Donuk", "Affetmez"),
                        key="choose22",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose23 = st.radio("------------------------------------- " + "23" + "-------------------------------------",
                        ("Ketum", "Kinci", "Dayanıksız", "Tekrarlayan"),
                        key="choose23",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose24 = st.radio("------------------------------------- " + "24" + "-------------------------------------",
                        ("Titiz", "Korkak", "Unutkan", "Açıksözlü"),
                        key="choose24",
                        horizontal=True)
    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose25 = st.radio("------------------------------------- " + "25" + "-------------------------------------",
                        ("Sabırsız", "Güvensiz", "Kararsız", "Laf kesici"),
                        key="choose25",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose26 = st.radio("------------------------------------- " + "26" + "-------------------------------------",
                        ("Sevilmeyen", "İşe karışmayan", "Ne yapacağı belirsiz", "Şefkatsiz"),
                        key="choose26",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose27 = st.radio("------------------------------------- " + "27" + "-------------------------------------",
                        ("Dik kafalı", "Gelişigüzel", "Zor beğenen", "Tereddütlü"),
                        key="choose27",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose28 = st.radio("------------------------------------- " + "28" + "-------------------------------------",
                        ("Sade", "Karamsar", "Kibirli", "Toleranslı"),
                        key="choose28",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose29 = st.radio("------------------------------------- " + "29" + " -------------------------------------",
                        ("Kolay sinirlenir", "Amaçsız", "Tartışmacı", "Soğuk"),
                        key="choose29",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose30 = st.radio("------------------------------------- " + "30" + " -------------------------------------",
                        ("Saf", "Olumsuz tavırlı", "Sinirli", "Kayıtsız"),
                        key="choose30",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose31 = st.radio("------------------------------------- " + "31" + " -------------------------------------",
                        ("Kaygılanan", "İçine Kapanık", "İşkolik", "Tanınmak isteyen"),
                        key="choose31",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose32 = st.radio("------------------------------------- " + "32" + " -------------------------------------",
                        ("Çok hassas", "Kaba", "Ürkek", "Çok konuşan"),
                        key="choose32",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose33 = st.radio("------------------------------------- " + "33" + " -------------------------------------",
                        ("Kuşkulu", "Organize olmamış", "Otoriter", "Kederli"),
                        key="choose33",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose34 = st.radio("------------------------------------- " + "34" + " -------------------------------------",
                        ("Tutarsız", "İçe dönük", "Hoşgörüsüz", "Sıradan"),
                        key="choose34",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose35 = st.radio("------------------------------------- " + "35" + " -------------------------------------",
                        ("Dağınık", "Huysuz", "Ağzında kelimeleri yuvarlayan", "İnsan kullanan"),
                        key="choose35",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose36 = st.radio("------------------------------------- " + "36" + " -------------------------------------",
                        ("Uyuşuk", "İnatçı", "Hava atan", "Kuşkucu"),
                        key="choose36",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose37 = st.radio("------------------------------------- " + "37" + " -------------------------------------",
                        ("Yalnız", "Denetleyici", "Tembel", "Gürültücü"),
                        key="choose37",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose38 = st.radio("------------------------------------- " + "38" + " -------------------------------------",
                        ("Miskin", "Şüpheci", "Çabuk öfkelenen", "Dikkatsiz"),
                        key="choose38",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose39 = st.radio("------------------------------------- " + "39" + " -------------------------------------",
                        ("İntikamcı", "Patavatsız", "İsteksiz", "Kötü dinleyici"),
                        key="choose39",
                        horizontal=True)

    col1, col2, col3 = st.columns([1, 3, 1])
    with col2:
        choose40 = st.radio("------------------------------------- " + "40" + " -------------------------------------",
                        ("Uzlaşmacı", "Eleştirici", "Kurnaz", "Çabuk sıkılan"),
                        key="choose40",
                        horizontal=True)

    if choose1 == "Hareketli":
        sari += 1
    elif choose1 == "Sonuç odaklı":
        kirmizi += 1
    elif choose1 == "Analitik":
        mavi += 1
    else:
        yesil += 1

    if choose2 == "Neşeli":
        sari += 1
    elif choose2 == "İkna Edici":
        kirmizi += 1
    elif choose2 == "Mantıklı":
        mavi += 1
    else:
        yesil += 1

    if choose3 == "Sosyal":
        sari += 1
    elif choose3 == "İradeli":
        kirmizi += 1
    elif choose3 == "Uysal":
        mavi += 1
    else:
        yesil += 1

    if choose4 == "İnandırıcı":
        sari += 1
    elif choose4 == "Yarışçıl":
        kirmizi += 1
    elif choose4 == "İnsaflı":
        mavi += 1
    else:
        yesil += 1

    if choose5 == "Ferahlatıcı":
        sari += 1
    elif choose5 == "Becerikli":
        kirmizi += 1
    elif choose5 == "Saygılı":
        mavi += 1
    else:
        yesil += 1

    if choose6 == "Cesur":
        sari += 1
    elif choose6 == "Kendine güvenen":
        kirmizi += 1
    elif choose6 == "Duyarlı":
        mavi += 1
    else:
        yesil += 1

    if choose7 == "Teşvik edici":
        sari += 1
    elif choose7 == "Olumlu":
        kirmizi += 1
    elif choose7 == "Planlı":
        mavi += 1
    else:
        yesil += 1

    if choose8 == "Kendiliğinden":
        sari += 1
    elif choose8 == "Emin":
        kirmizi += 1
    elif choose8 == "Programa bağlı":
        mavi += 1
    else:
        yesil += 1

    if choose9 == "İyimser":
        sari += 1
    elif choose9 == "Dobra":
        kirmizi += 1
    elif choose9 == "Düzenli":
        mavi += 1
    else:
        yesil += 1

    if choose10 == "Komik":
        sari += 1
    elif choose10 == "Baskıcı":
        kirmizi += 1
    elif choose10 == "Sadık":
        mavi += 1
    else:
        yesil += 1

    if choose11 == "Hoş":
        sari += 1
    elif choose11 == "Cesaretli":
        kirmizi += 1
    elif choose11 == "Detaycı":
        mavi += 1
    else:
        yesil += 1

    if choose12 == "Esin kaynağı":
        sari += 1
    elif choose12 == "Güvenli":
        kirmizi += 1
    elif choose12 == "Kültürlü":
        mavi += 1
    else:
        yesil += 1

    if choose13 == "Heyecanlandırıcı":
        sari += 1
    elif choose13 == "Bağımsız":
        kirmizi += 1
    elif choose13 == "İdealist":
        mavi += 1
    else:
        yesil += 1

    if choose14 == "Coşkun":
        sari += 1
    elif choose14 == "Kesin":
        kirmizi += 1
    elif choose14 == "Derin düşünceli":
        mavi += 1

    if choose15 == "Kolay Kaynaşır":
        sari += 1
    elif choose15 == "Harekete geçiren":
        kirmizi += 1
    elif choose15 == "Ahenkli":
        mavi += 1
    else:
        yesil += 1

    if choose16 == "Konuşma yanlısı":
        sari += 1
    elif choose16 == "İş Bitirici":
        kirmizi += 1
    elif choose16 == "İnce düşünceli":
        mavi += 1
    else:
        yesil += 1

    if choose17 == "Canlı":
        sari += 1
    elif choose17 == "Lider":
        kirmizi += 1
    elif choose17 == "Samimi":
        mavi += 1
    else:
        yesil += 1

    if choose18 == "Şirin":
        sari += 1
    elif choose18 == "Başkan, Şef":
        kirmizi += 1
    elif choose18 == "Araştırmacı":
        mavi += 1
    else:
        yesil += 1

    if choose19 == "Popüler":
        sari += 1
    elif choose19 == "Üretici":
        kirmizi += 1
    elif choose19 == "Mükemmeliyetçi":
        mavi += 1
    else:
        yesil += 1

    if choose20 == "Cömert":
        sari += 1
    elif choose20 == "Atılgan":
        kirmizi += 1
    elif choose20 == "Terbiyeli":
        mavi += 1
    else:
        yesil += 1

    if choose21 == "Utanması olmayan":
        sari += 1
    elif choose21 == "Zorba":
        kirmizi += 1
    elif choose21 == "Çekingen":
        mavi += 1
    else:
        yesil += 1

    if choose22 == "Disiplinsiz":
        sari += 1
    elif choose22 == "Sevimsiz":
        kirmizi += 1
    elif choose22 == "Affetmez":
        mavi += 1
    else:
        yesil += 1

    if choose23 == "Tekrarlayan":
        sari += 1
    elif choose23 == "Dayanıksız":
        kirmizi += 1
    elif choose23 == "Kinci":
        mavi += 1
    else:
        yesil += 1

    if choose24 == "Unutkan":
        sari += 1
    elif choose24 == "Açıksözlü":
        kirmizi += 1
    elif choose24 == "Titiz":
        mavi += 1
    else:
        yesil += 1

    if choose25 == "Laf kesici":
        sari += 1
    elif choose25 == "Sabırsız":
        kirmizi += 1
    elif choose25 == "Güvensiz":
        mavi += 1
    else:
        yesil += 1

    if choose26 == "Ne yapacağı belirsiz":
        sari += 1
    elif choose26 == "Şefkatsiz":
        kirmizi += 1
    elif choose26 == "Sevilmeyen":
        mavi += 1
    else:
        yesil += 1

    if choose27 == "Gelişigüzel":
        sari += 1
    elif choose27 == "Dik kafalı":
        kirmizi += 1
    elif choose27 == "Zor beğenen":
        mavi += 1
    else:
        yesil += 1

    if choose28 == "Toleranslı":
        sari += 1
    elif choose28 == "Kibirli":
        kirmizi += 1
    elif choose28 == "Karamsar":
        mavi += 1
    else:
        yesil += 1

    if choose29 == "Kolay sinirlenir":
        sari += 1
    elif choose29 == "Tartışmacı":
        kirmizi += 1
    elif choose29 == "Soğuk":
        mavi += 1
    else:
        yesil += 1

    if choose30 == "Saf":
        sari += 1
    elif choose30 == "Sinirli":
        kirmizi += 1
    elif choose30 == "Olumsuz tavırlı":
        mavi += 1
    else:
        yesil += 1

    if choose31 == "Tanınmak isteyen":
        sari += 1
    elif choose31 == "İşkolik":
        kirmizi += 1
    elif choose31 == "İçine kapanık":
        mavi += 1
    else:
        yesil += 1

    if choose32 == "Çok konuşan":
        sari += 1
    elif choose32 == "Kaba":
        kirmizi += 1
    elif choose32 == "Çok hassas":
        mavi += 1
    else:
        yesil += 1

    if choose33 == "Organize olmamış":
        sari += 1
    elif choose33 == "Otoriter":
        kirmizi += 1
    elif choose33 == "Kederli":
        mavi += 1
    else:
        yesil += 1

    if choose34 == "Tutarsız":
        sari += 1
    elif choose34 == "Hoşgörüsüz":
        kirmizi += 1
    elif choose34 == "İçe dönük":
        mavi += 1
    else:
        yesil += 1

    if choose35 == "İnsan kullanan":
        sari += 1
    elif choose35 == "Dağınık":
        kirmizi += 1
    elif choose35 == "Huysuz":
        mavi += 1
    else:
        yesil += 1

    if choose36 == "Hava atan":
        sari += 1
    elif choose36 == "İnatçı":
        kirmizi += 1
    elif choose36 == "Kuşkucu":
        mavi += 1
    else:
        yesil += 1

    if choose37 == "Gürültücü":
        sari += 1
    elif choose37 == "Denetleyici":
        kirmizi += 1
    elif choose37 == "Yalnız":
        mavi += 1
    else:
        yesil += 1

    if choose38 == "Dikkatsiz":
        sari += 1
    elif choose38 == "Çabuk öfkelenen":
        kirmizi += 1
    elif choose38 == "Şüpheci":
        mavi += 1
    else:
        yesil += 1

    if choose39 == "Kötü dinleyici":
        sari += 1
    elif choose39 == "Patavatsız":
        kirmizi += 1
    elif choose39 == "İntikamcı":
        mavi += 1
    else:
        yesil += 1

    if choose40 == "Çabuk sıkılan":
        sari += 1
    elif choose40 == "Kurnaz":
        kirmizi += 1
    elif choose40 == "Eleştirici":
        mavi += 1
    else:
        yesil += 1

    return mavi, sari, kirmizi, yesil

def save_file(file_name):
    gauth = GoogleAuth()
    create_cred_file()
    #gauth.LoadCredentialsFile(st.secrets("my_creds"))
    #if gauth.credentials is None:
    #    # Authenticate if they're not there
    #    gauth.LocalWebserverAuth()
    #elif gauth.access_token_expired:
    #    # Refresh them if expired
    #    gauth.Refresh()
    #else:
    #    # Initialize the saved creds
    #    gauth.Authorize()
    # Save the current credentials to a file
    gauth.LoadCredentialsFile('mycreds_test.txt')

    drive = GoogleDrive(gauth)
    folderName = 'Renk Testi'  # Please set the folder name.

    folders = drive.ListFile(
        {
            'q': "title='" + folderName + "' and mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList()
    for folder in folders:
        if folder['title'] == folderName:
            file2 = drive.CreateFile({'parents': [{'id': folder['id']}]})
            file2.SetContentFile(file_name)
            file2.Upload()

def create_cred_file():
    cred_str = '{"access_token": "' + st.secrets["access_token"] +\
               '", "client_id": "' + st.secrets["client_id"] +\
               '", "client_secret": "' + st.secrets["client_secret"] + \
               '", "refresh_token": "' + st.secrets["refresh_token"] + \
               '", "token_expiry": "' + st.secrets["token_expiry"] + \
               '", "token_uri": "' + st.secrets["token_uri"] + \
               '", "user_agent": null' + \
               ', "revoke_uri": "' + st.secrets["revoke_uri"] + \
               '", "id_token": null' + \
               ', "id_token_jwt": null' + \
               ', "token_response": {"access_token": "' + st.secrets["token_response"]["access_token"] + \
               '", "expires_in": ' + str(st.secrets["token_response"]["expires_in"]) + \
               ', "refresh_token": "' + st.secrets["token_response"]["refresh_token"] + \
               '", "scope": "' + st.secrets["token_response"]["scope"] + \
               '", "token_type": "' + st.secrets["token_response"]["token_type"] + \
               '"}, "scopes": ["https://www.googleapis.com/auth/drive"]' + \
               ', "token_info_uri": "' + st.secrets["token_info_uri"] + \
               '", "invalid": false' + \
               ', "_class": "' + st.secrets["_class"] + \
               '", "_module": "' + st.secrets["_module"] + '"}'
    text_file = open("mycreds_test.txt", "w")
    n = text_file.write(cred_str)
    text_file.close()

def version():
    st.caption("""

                ver 1.0.0
build 03052023.2307

            """, unsafe_allow_html=True
               )


from nltk.tag import brill
from nltk.tag.brill_trainer import BrillTaggerTrainer
import utils

class BrillTagger(object):

    def __init__(self):
        # bounds = [(1, end)]
        initial_tagger = get_initial_tagger()
        rules = brill.fntbl37()

        self.trainer = BrillTaggerTrainer(initial_tagger, rules,
                                          deterministic=True, trace=0)
        train_sents, test_sents = utils.training_testing_dataset()
        self.tagger = self.trainer.train(train_sents, max_rules=20)
        print('Brill tagger training completed')

    def tag(self, sent_tokens):
        tagged_sentences = []
        for sent in sent_tokens:
            tags = self.tagger.tag([w for w in sent])
            tagged_sentences.append(tags)
        return tagged_sentences

def get_initial_tagger():
    from TrainedTagger import CustomTrainedTagger
    return CustomTrainedTagger()


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

"""
Flask Application Factory Pattern
http://flask.pocoo.org/docs/0.12/patterns/appfactories/
"""

# Common Python library imports
import os
import sys

# Pip package imports
from flask import Flask as BaseFlask, session, Blueprint, request, g, redirect, url_for, current_app
from flask.helpers import get_debug_flag
from flask_wtf.csrf import generate_csrf
from loguru import logger

# Internal package imports
from .config import (
    BaseConfig,
    DevConfig,
    ProdConfig,
    PROJECT_ROOT,
    TEMPLATE_FOLDER,
    STATIC_FOLDER,
    STATIC_URL_PATH,
    EXTENSIONS,
    DEFERRED_EXTENSIONS,
)

from .magic import (
    is_extension,
    is_blueprint,
    get_bundles,
    get_commands,
    get_extensions,
)

from backend.extensions.babel import babel
from backend.extensions.assets import assets as flask_assets

class Flask(BaseFlask):
    bundles = []
    models = {}
    serializers = {}

def create_app():
    """Creates a pre-configured Flask application.

    Defaults to using :class:`backend.config.ProdConfig`, unless the
    :envvar:`FLASK_DEBUG` environment variable is explicitly set to "true",
    in which case it uses :class:`backend.config.DevConfig`. Also configures
    paths for the templates folder and static files.
    """
    return _create_app(
        DevConfig if get_debug_flag() else ProdConfig,
        template_folder=TEMPLATE_FOLDER,
        static_folder=STATIC_FOLDER,
        static_url_path=STATIC_URL_PATH
    )

def _create_app(config_object: BaseConfig, **kwargs):
    """Creates a Flask application.

    :param object config_object: The config class to use.
    :param dict kwargs: Extra kwargs to pass to the Flask constructor.
    """
    # WARNING: HERE BE DRAGONS!!!
    # DO NOT FUCK WITH THE ORDER OF THESE CALLS or nightmares will ensue
    app = Flask(__name__, **kwargs)
    app.bundles = list(get_bundles())
    configure_app(app, config_object)

    extensions = dict(get_extensions(EXTENSIONS))
    register_extensions(app, extensions)

    register_blueprints(app)
    register_models(app)
    register_serializers(app)
    register_admins(app)
    register_filters(app)
    register_assets(app)
    register_converters(app)

    deferred_extensions = dict(get_extensions(DEFERRED_EXTENSIONS))
    extensions.update(deferred_extensions)
    register_extensions(app, deferred_extensions)

    register_cli_commands(app)
    register_shell_context(app, extensions)

    return app

def configure_app(app, config_object):
    """General application configuration:

    - register the app's config
    - register Jinja extensions
    - register functions to run on before/after request
    """
    # automatically configure a migrations folder for each bundle
    config_object.ALEMBIC['version_locations'] = [
        (bundle._name, os.path.join(PROJECT_ROOT,
                                    bundle.module_name.replace('.', os.sep),
                                    'migrations'))
        for bundle in app.bundles if bundle.has_models
    ]
    app.config.from_object(config_object)

    app.jinja_env.add_extension('jinja2.ext.do')
    app.jinja_env.add_extension('jinja2_time.TimeExtension')
    app.jinja_env.add_extension('jinja2.ext.i18n')

    @app.before_request
    def enable_session_timeout():
        session.permanent = True  # set session to use PERMANENT_SESSION_LIFETIME
        session.modified = True   # reset the session timer on every request

    @app.after_request
    def set_csrf_cookie(response):
        if response:
            response.set_cookie('csrf_token', generate_csrf())
        return response

    @babel.localeselector
    def get_locale():
        try:
            language = session.get('language')
            print('Getting lang from session: ', language, flush=True)
        except KeyError:
            language = None
        if language is None:
            language = request.accept_languages.best_match(current_app.config.get('LANGUAGES').keys())
            print('Getting lang from browser: ', language, flush=True)
        return language

    @app.context_processor
    def inject_conf_var():
        return dict(
            lurl_for=lambda ep, **kwargs: url_for('/' + session.get('language', current_app.config.get('BABEL_DEFAULT_LOCALE')) +ep, **kwargs  ),
            languages=current_app.config.get('LANGUAGES'),
            language=session.get('language',
                                         request.accept_languages.best_match(current_app.config['LANGUAGES'].keys())))

    # Configure the bundles
    for bundle in app.bundles:
        for config_name, config in bundle.configs:
            app.config.from_object(config)

def register_extensions(app, extensions):
    """Register and initialize extensions."""
    for extension in extensions.values():
            extension.init_app(app)

def register_filters(app):
    """Register bundle filters."""
    # register filters
    for bundle in app.bundles:
        # To prevent name collosion, the filter calling name is made like:
        # <bundle_name>.<filter_name>
        for name, filter in bundle.filters:
            app.jinja_env.filters[name] = filter

    # TODO: This is quick and ugly
    from backend.utils.template_helpers import ClassList
    app.jinja_env.globals['classlist'] = ClassList

def register_assets(app):
    """Register bundle assets."""
    for bundle in app.bundles:
        for asset_key, asset in bundle.assets:
            flask_assets.register(asset_key, asset)

def register_converters(app):
    """Register url converters."""
    from backend.utils.url_helpers import DateConverter
    app.url_map.converters['date'] = DateConverter

def register_blueprints(app):
    """Register bundle views."""
    # disable strict_slashes on all routes by default
    if not app.config.get('STRICT_SLASHES', False):
        app.url_map.strict_slashes = False

    # register blueprints
    for bundle in app.bundles:
        for blueprint in bundle.blueprints:
            # rstrip '/' off url_prefix because views should be declaring their
            # routes beginning with '/', and if url_prefix ends with '/', routes
            # will end up looking like '/prefix//endpoint', which is no good
            url_prefix = (blueprint.url_prefix or '').rstrip('/')
            if is_blueprint(blueprint):
                #app.register_blueprint(blueprint, url_prefix=url_prefix, static_folder='static', static_url_path='/static/' + blueprint.name)
                app.register_blueprint(blueprint, url_prefix=url_prefix)

def register_models(app):
    """Register bundle models."""
    models = {}
    for bundle in app.bundles:
        for model_name, model_class in bundle.models:
            models[model_name] = model_class
    app.models = models

def register_admins(app):
    """Register bundle admins."""
    try:
        from backend.extensions import db
        from backend.extensions.admin import admin
    except ImportError as err:
        logger.warning("Admin and database bundles are not present")
    else:
        for bundle in app.bundles:
            if bundle.admin_icon_class:
                admin.category_icon_classes[bundle.admin_category_name] = bundle.admin_icon_class

            for ModelAdmin in bundle.model_admins:
                model_admin = ModelAdmin(ModelAdmin.model,
                                         db.session,
                                         category=bundle.admin_category_name,
                                         name=ModelAdmin.model.__plural_label__)

                # workaround upstream bug where certain values set as
                # class attributes get overridden by the constructor
                model_admin.menu_icon_value = getattr(ModelAdmin, 'menu_icon_value', None)
                if model_admin.menu_icon_value:
                    model_admin.menu_icon_type = getattr(ModelAdmin, 'menu_icon_type', None)

                admin.add_view(model_admin)

            for FileAdmin in bundle.file_admins:
                file_admin = FileAdmin(base_path=FileAdmin.path,
                                       category=bundle.admin_category_name,
                                       name=FileAdmin.name)

                # workaround upstream bug where certain values set as
                # class attributes get overridden by the constructor
                file_admin.menu_icon_value = getattr(FileAdmin, 'menu_icon_value', None)
                if file_admin.menu_icon_value:
                    file_admin.menu_icon_type = getattr(FileAdmin, 'menu_icon_type', None)

                admin.add_view(file_admin)

def register_serializers(app):
    """Register bundle serializers."""
    serializers = {}
    for bundle in app.bundles:
        for name, serializer_class in bundle.serializers:
            serializers[name] = serializer_class
    app.serializers = serializers

def register_cli_commands(app):
    """Register all the Click commands declared in :file:`backend/commands` and
    each bundle's commands"""
    commands = list(get_commands())
    for bundle in app.bundles:
        commands += list(bundle.command_groups)
    for name, command in commands:
        if name in app.cli.commands:
            logger.error(f'Command name conflict: "{name}" is taken.')
            sys.exit(1)
        app.cli.add_command(command)

def register_shell_context(app, extensions):
    """Register variables to automatically import when running `python manage.py shell`."""
    def shell_context():
        ctx = {}
        ctx.update(extensions)
        ctx.update(app.models)
        ctx.update(app.serializers)
        return ctx
    app.shell_context_processor(shell_context)


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

import pewpew
import pytest
import time

def test_span():
    span = pewpew.Beam("big_loop")
    with span:
        time.sleep(0.01)

    timings = span.timings
    assert len(timings) == 1, timings

def test_span_concurrent_access_err():
    span = pewpew.Beam("big_loop")
    with span, pytest.raises(RuntimeError):
        _ = span.timings