from mesa.visualization.modules import CanvasGrid
from mesa.visualization.ModularVisualization import ModularServer
from mesa.visualization.modules import ChartModule
from mesa.visualization.UserParam import UserSettableParameter

from .utils import *
from .ball import *
from .model import *

def agent_portrayal(agent):

    fill_colors = {
        STATE_FRUSTRATED: "#000000",
        STATE_GRATIFIED: "#00aa00",
        STATE_NEED: "#ff0000",
    }

    fill_colors_encounter = {
        STATE_FRUSTRATED: "#000000aa",
        STATE_GRATIFIED: "#f00aa00aa",
        STATE_NEED: "#ff0000aa",
    }

    stroke_colors = {
        STATE_FRUSTRATED: "#000000",
        STATE_GRATIFIED: "#00ff00",
        STATE_NEED: "#ff0000",
    }

    def _fill_color(agent):
        if agent.encounter:
            return fill_colors_encounter.get(agent.state)
        else:
            return fill_colors.get(agent.state)

    def _stroke_color(agent):
        return stroke_colors.get(agent.state)

    def _x_offset(agent):
        if agent.encounter:
            if id(agent) < id(agent.encounter):
                return -0.15
            else:
                return 0.15
        else:
            return 0

    def _filled(agent):
        return bool(agent.encounter is None)

    def _text(agent):
        if not agent.encounter:
            return str(agent.state_counter)
        else:
            return ""

    def _text_color(agent):
        return "white"

    portrayal = {
        "ID": agent.unique_id,
        "Shape": "circle",
        "Color": _fill_color(agent),
        "stroke_color": _stroke_color(agent),
        "Filled": _filled(agent),
        "Layer": 0,
        "r": 0.5,
        "x_offset": _x_offset(agent),
        "Need Limit": agent._need_limit,
        "Frustration Limit": agent._frustration_limit,
        "Frustratability": agent._frustration_multiplier,
        "State": agent.state,
        "Steps in State": agent.state_counter,
        "ignoredFeatures": ["Layer", "text", "x_offset"]
        # debug
        # "pos": agent.pos,
        # "unique_id": agent.unique_id,
    }
    if agent.model.show_step_counter:
        portrayal.update(
            {
                "text": _text(agent),
                "text_color": _text_color(agent),
            }
        )

    log.debug(
        f"Agent {agent.unique_id}: ({agent.pos[0]}, {agent.pos[1]}), x_offset: {portrayal.get('x_offset')}"
    )
    return portrayal

grid = CanvasGrid(agent_portrayal, SIZE, SIZE, 600, 600)
server = ModularServer(
    MythematicalModel,
    [grid],
    "Mythematical Social Pool Game",
    {
        "num_balls": UserSettableParameter(
            "slider",
            "Number of balls",
            DEFAULT_NUM_BALLS,
            2,
            40,
            description="Number of balls.",
        ),
        "gratification_limit": UserSettableParameter(
            "slider",
            "Gratification Limit",
            DEFAULT_GRATIFICATION_LIMIT,
            1,
            30,
            description="Calhoun: After a specified period of time elapses. each of the stippled balls will complete its stay in the gratification state and return to the state of needing further contact with other balls.",
        ),
        "gratification_limit_variation": UserSettableParameter(
            "slider",
            "Gratification Limit Variation",
            2,
            0,
            10,
            description="Number of steps the gratification limit can vary more or less.",
        ),
        "need_limit": UserSettableParameter(
            "slider",
            "Need Limit",
            DEFAULT_NEED_LIMIT,
            1,
            30,
            description="Calhoun: Furthermore, each ball from time to time develops a need state for contacting some other ball in an equivalent need state.",
        ),
        "need_limit_variation": UserSettableParameter(
            "slider",
            "Need Limit Variation",
            3,
            0,
            10,
            description="Number of steps the need limit can vary more or less.",
        ),
        "frustration_limit": UserSettableParameter(
            "slider",
            "Frustration Limit",
            5,
            0,
            10,
            description="Steps in before changing from frustrated to to need state.",
        ),
        "frustration_variation": UserSettableParameter(
            "slider",
            "Frustration Variation",
            0,
            0,
            FRUSTRATION_VARIATION_MAX,
            step=FRUSTRATION_VARIATION_STEP,
            description="Range of randomly selected multiplier for how much more frustrated a ball becomes.",
        ),
        "show_step_counter": UserSettableParameter(
            "checkbox", "Show Steps in Current State", value=True
        ),
        "width": SIZE,
        "height": SIZE,
    },
)

if __name__ == "__main__":
    import os

    server.launch()
    os.system(f'open "https://localhost:{server.port}"')


import argparse
from core.text_to_number import TextToNumber
import pandas as pd
import numpy as np

def get_parser():
    """Get parser for command line arguments."""
    parser = argparse.ArgumentParser(description="Tweet Cleaning and Creating Corpus and Dictionary files")
    parser.add_argument("-i",
                        "--input",
                        dest="inputs",
                        help="the path of the csv input file",
                        default='input/arule-text.csv')

    return parser

if __name__ == '__main__':
    parser = get_parser()
    args = parser.parse_args()

    inputFile = args.inputs

    outputFile = inputFile[0:(len(inputFile)-4)] + '.vec.csv'

    textToNumber = TextToNumber()

    texts = []
    with open(inputFile) as f:
        for line in f:
            line = line.replace(',', ' ')
            texts.append(line)

    text_vecs = textToNumber.create_number_vector(texts, output_file=None, append_indicators=None,
                                                        padding_position='post', padding_maxlen=None)

    myMax = np.max(text_vecs)

    with open(outputFile, 'w') as f:
        for vec in text_vecs:
            items = []
            for i in vec:
                if i > 0:
                    items.append(i)
            line = ', '.join(str(x) for x in items)
            f.write(line + '\n')

    print('done, total unique terms:' + str(myMax))


import pickle
import re
import logging
from dateutil.parser import parse as date_parse
import jasmin
from .migration import MAP

LOGGING_HANDLER = 'jcli'

_REGEX_VER = re.compile(r'^(?P<major>(\d+))'
                        r'\.(?P<minor>(\d+))'
                        r'([a-z.]*)'
                        r'(?P<patch>(\d+))$')
_REGEX_HEADER = re.compile(r'^Persisted on (?P<date>(.*)) \[Jasmin (?P<release_version>(.*))\]')

def version_parse(version):
    """Will parse Jasmin release version and return a float, ex: 0.8rc2 will return 0.8002"""
    match = _REGEX_VER.match(version)
    if match is None:
        raise ValueError('%s is not valid Jasmin version string' % version)

    return float("%s.%s%s" % (match.groupdict()['major'],
                              match.groupdict()['minor'], match.groupdict()['patch'].zfill(3)))

def version_is_valid(version, condition):
    """Will compare version with condition, example of condition: <=0.52"""
    version = version_parse(version)

    if condition[:2] in ('>=', '<=', '=='):
        condition_operation = condition[:2]
        condition_value = float(condition[2:])
    elif condition[:1] in ('>', '<'):
        condition_operation = condition[:1]
        condition_value = float(condition[1:])
    else:
        raise ValueError('Invalid condition (%s) while verifying validity with %s' % (condition, version))

    if condition_operation == '>=' and version >= condition_value:
        return True
    elif condition_operation == '<=' and version <= condition_value:
        return True
    elif condition_operation == '==' and version == condition_value:
        return True
    elif condition_operation == '>' and version > condition_value:
        return True
    elif condition_operation == '<' and version < condition_value:
        return True
    else:
        return False

class ConfigurationMigrator:
    """Responsible of migrating old saved configuration to recent definition, if any"""

    def __init__(self, context, header, data):
        """Will contain inputs and parse header to get version and date of persisted data"""
        self.log = logging.getLogger(LOGGING_HANDLER)
        self.context = context
        self.data = pickle.loads(data)
        self.log.debug('Initializing CM with context:%s, header:%s', self.context, header)

        # Parse header and get version & date
        match = _REGEX_HEADER.match(header)
        if match is None:
            raise ValueError('Invalid Jasmin configuration header format:' % header)
        self.date = date_parse(match.groupdict()['date'])
        self.version = match.groupdict()['release_version']
        self.log.debug('[%s] @%s/%s', self.context, self.date, self.version)

    def getMigratedData(self):
        """Return data after executing migration steps"""
        for m in MAP:
            # Context verification
            if self.context not in m['contexts']:
                self.log.debug('%s is not in map conditions: %s', self.context, m['contexts'])
                continue

            # Validate conditions (with AND operator)
            valid = True
            for condition in m['conditions']:
                self.log.debug('Checking condition: %s with version %s', condition, self.version)
                if not version_is_valid(self.version, condition):
                    self.log.debug('Condition failed: %s with version %s', condition, self.version)
                    valid = False
                    break

            # We have matching context and valid conditions
            if valid:
                for operation in m['operations']:
                    self.log.info('Migrating old data [%s] from v%s to v%s by calling %s(data)',
                                  self.context, self.version, jasmin.get_release(), operation.__name__)
                    self.data = operation(self.data, context=self.context)
        return self.data


import torch
import torch.nn as nn
import argparse
import glob
from data import TableDataset
from generator import attribute_deletion, attribute_substitution, word_deletion, word_substitution, numerical_typos,\
    text_typos
import pandas as pd
import random
import numpy as np
from pandas.api.types import is_string_dtype
from pandas.api.types import is_numeric_dtype
from model import AICJNet
import torch.optim as optim
from data import TableDataset
from torch.utils.data import DataLoader
from helper import create_directory

parser = argparse.ArgumentParser()
parser.add_argument('--pos', type = int, default = 6, help = "Number of postive instances")
parser.add_argument('--neg', type = int, default = 20, help = "Number of negative instances")
parser.add_argument('--lr', type = float, default = 1e-6, help = "Learning rate in Adam optimizer")
parser.add_argument('--momentum', type = float, default = 0.9, help = "Momentum in Adam optimizer")
parser.add_argument('--epochs', type = int, default = 30, help = "Number of training epochs")
parser.add_argument('--load', type = int, default = 0, help = "Whether starting training from a checkpoint")
parser.add_argument('--heads', type = int, default = 8, help = "Number of heads in self-attention mechanism")
parser.add_argument('--epsilon', type = float, default = 0.01, help = "constraints of the perturbation vector")
parser.add_argument('--adv', type = int, default = 0, help = "whether using adversarial examples")
parser.add_argument('--cuda', type = int, default = 1, help = "whether using GPU to accelerate model training" )
parser.add_argument('--hidden_size', type = int, default = 256, help = "Hidden size of self-attention" )

args = parser.parse_args()

def finding_adversarial_examples(data, epsilon, gradient):
    sign_gradient = gradient.sign()
    perturbed_data = data + epsilon * sign_gradient
    perturbed_data = torch.clamp(perturbed_data, 0, 1)
    return perturbed_data

training_data_path = '../data/'
augmented_data_path = '../augmented_data/'
create_directory(augmented_data_path)
path_of_tables = glob.glob(training_data_path+'*')

for i, table_path in enumerate(path_of_tables):
    table_name = table_path.replace('\\','/').split('/')[-1]
    augmented_table_path = augmented_data_path + table_name

    table = pd.read_csv(table_path, encoding = 'utf-8', warn_bad_lines=True, error_bad_lines=False)

    columns = table.columns
    IsNum = dict()

    for i, column in enumerate(columns):
        if is_numeric_dtype(table[column]):
            IsNum[column] = 1
        else:
            IsNum[column] = 0

    augmented_table = pd.DataFrame(columns = columns)

    for idx in range(len(table)):
        for i in range(args.pos):
            t = table.iloc[idx]
            attr = random.choice(columns)
            while pd.isna(t[attr]):
                attr = random.choice(columns)
            if IsNum[attr]:
                op = np.random.randint(0, 2)
                if op == 0:
                    augmented_t = attribute_deletion(t, attr)
                else:
                    augmented_t = numerical_typos(t, attr)
            else:
                op = np.random.randint(0, 5)
                if op == 0:
                    augmented_t = attribute_deletion(t, attr)
                elif op == 1:
                    augmented_t = attribute_substitution(t, attr)
                elif op == 2:
                    augmented_t = word_substitution(t, attr)
                elif op == 3:
                    augmented_t = word_deletion(t, attr)
                else:
                    augmented_t = text_typos(t, attr)
            augmented_table = augmented_table.append(augmented_t)

    augmented_table.to_csv(augmented_table_path, index = False)

device = torch.device("cuda:0" if args.cuda else "cpu")

model_name = 'bert-base-uncased'

model = AICJNet(model_name, 768, args.heads, device, args.hidden_size).to(device)

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=args.lr)

checkpoint_path = '../checkpoints/ckp.pth'

if args.load:
    checkpoint = torch.load(checkpoint_path)
    model.load_state_dict(checkpoint['model_state_dict'])

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr = args.lr, momentum = args.momentum)

for epoch in range(args.epochs):
    #model.train()

    for idx, table_path in enumerate(path_of_tables):
        table_name = table_path.replace('\\','/').split('/')[-1]
        augmented_table_path = augmented_data_path + table_name

        train_dataset = TableDataset(table_path, augmented_table_path, args.pos, args.neg, model_name)
        train_loader = DataLoader(train_dataset, batch_size=1, shuffle = True)

        for inputs, labels, masks in train_loader:
            inputs, labels, masks = inputs.to(device), labels.to(device).squeeze(), masks.to(device)
            optimizer.zero_grad()
            outputs, last = model(inputs, masks)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            if args.adv:
                gradient = last.retain_grad().data
                perturbed_data = finding_adversarial_examples(last, args.epsilon, gradient)

                optimizer.zero_grad()
                perturbed_outputs = model(perturbed_data)
                adv_loss = criterion(perturbed_outputs, labels)
                total_loss = (loss + adv_loss)/2

                total_loss.backward()
                optimizer.step()

    print(f"Epoch [{epoch+1}/{args.epochs}], Loss: {loss.item():.4f}")
    torch.save(model.state_dict(), checkpoint_path)


import threading

from chats.console.base_chat import BaseChat, INDENT, BreakLoopException, lock
from chats.console.base_chat import print_information

from opt.appearance import cprint
from opt.strings import *

class UserChat(BaseChat):
    def __init__(self, username, client):
        super().__init__(client)
        self.create_cmd_handlers()

        self.username = username
        self.user_id = self.db_helper.get_user_id(username)

        if self.user_id == self.client.user_id:
            self.self_chat = True

        self.print_mode_help('private message')
        self.init_print_messages()

    def create_cmd_handlers(self):
        self.handlers = {
            (self.R_BACK,      self.back2main),
            (self.R_HELP,      self.help),
        }

    def handle_command(self, command):
        for pattern, handler in self.handlers:
            match = pattern.match(command)
            if match:
                handler(match)
                return True
        send_file = self.R_SEND_FILE.match(command)
        if send_file:
            self.parse_sending_file(send_file, username=self.username)
        else:
            if not self.send_message(username=self.username, text=command):
                cprint(ERROR_WHILE_SENDING)

    def open(self):
        self.print_last_messages(self.user_id)

        while True:
            try:
                try:
                    input()
                    with lock:
                        message = self.user_input('Private', self.username)
                    self.handle_command(message)
                except KeyboardInterrupt:
                    self.back2main()
            except BreakLoopException:
                self.self_chat = False
                break

    def help(self, *args):
        cprint((
            '\n'
            '   <white,bold>* help</>:            Show this help\n'
            '   <white,bold>* back, Ctrl+C</>:    Back to the main menu.\n'
            '   <white,bold>* file [filepath]</>: Send a file.\n'
        ))


class atm :

    def __init__( self , card_number , pin_number ) :

        self.card_number = card_number
        self.pin_number = pin_number

    def balanceEnquiry( self ) :

        print("Your balance is: $1000")

    def cashWithdrawal( self , amount ) :

        new_amount = 1000 - amount
        print("Your remaining balance is " + str(new_amount))
        print("Money withdrawed: " + str(amount))

def main() :

    name = input("Hello ! What is your name ?")
    print("Hello " + name)

    card_number = input("Enter your card number: ")
    pin = input("Enter pin: ")

    new_user = atm( card_number , pin )

    print("What would you like to do today ?")
    print("Press 1 for balance enquiry")
    print("Press 2 for cash withdrawal")

    activity = int(input("Enter your choice: "))

    if activity == 1 :
        new_user.balanceEnquiry()
    else :
        amount = int(input("Enter amount you want to withdraw :"))
        new_user.cashWithdrawal(amount)

main()


from aws_cdk import (
    core,
    aws_codepipeline_actions)
from aws_cdk.aws_codepipeline import Pipeline
from aws_cdk.aws_iam import PolicyStatement, AccountPrincipal
from aws_cdk.core import Stack

from repo_factory_locator import RepoFactoryLocator
from stages.generic_stage_codebuild import GenericStageCodeBuild

class CIPipelineConstruct(Pipeline):

    def __init__(self, scope: core.Construct, id: str, repo_type: str, buildspec: str, build_image: str) -> None:
        super().__init__(scope, id,
                         restart_execution_on_update=True)

        # Source
        repo_factory_locator = RepoFactoryLocator()
        repo_action = repo_factory_locator.get(repo_type, self)
        self.add_stage(stage_name="Source", actions=[repo_action])

        # Build Test
        build_test_actions, _ = GenericStageCodeBuild().get_stage_actions(scope, "BuildTest",
                                                                          repo_action.action_properties.outputs,
                                                                          buildspec_file=buildspec,
                                                                          build_image=build_image)
        self.add_stage(stage_name="BuildTest", actions=build_test_actions)

        # Publish artifacts
        outputs = []
        for build_action in build_test_actions:
            outputs.extend(build_action.action_properties.outputs)
        publish_action = aws_codepipeline_actions.S3DeployAction(bucket=self.artifact_bucket,
                                                                 object_key="BuildArtifacts",
                                                                 action_name="PublishArtifacts", input=outputs[0],
                                                                 extract=True

                                                                 )

        self.add_stage(stage_name="PublishArtifacts", actions=[publish_action])

        # Add decrypt permissions
        self.artifact_bucket.encryption_key.add_to_resource_policy(
            PolicyStatement(principals=[AccountPrincipal(Stack.of(self).account)],
                            actions=["kms:Decrypt"]
                            , resources=["*"]
                            )
        )


def loki_log(message):
	import mrequests
	import config
	import ujson
	import utime
	import gc

	gc.enable()
	gc.collect()
	data = {"streams": [{"stream": {"esp_id":"1"}, "values": [[str(utime.time() + 946684800) + "000000000", message]]}]}
	res = mrequests.post(
		config.LOKI_BACKEND,
		auth=(config.LOKI_USERNAME, config.LOKI_API_KEY),
		headers={'content-type': 'Application/JSON'},
		data=ujson.dumps(data),
		)
	gc.collect()

class Metric:
	def __init__(self, name, val):
		self.name = name
		self.val = val

def send_to_graphite(metrics_list):
	import mrequests
	import config
	import ujson
	import utime
	import gc

	gc.enable()
	gc.collect()
	data = [
		{"name": m.name, "interval": 10, "value": m.val, "mtype": "gauge", "time": utime.time() + 946684800}
		for m in metrics_list
	]
	res = mrequests.post(
		config.GRAPHITE_BACKEND,
		headers={'content-type': 'Application/JSON', "Authorization": "Bearer " + config.GRAPHITE_USERNAME + ":" + config.GRAPHITE_API_KEY},
		data=ujson.dumps(data),
	)
	gc.collect()

def free(full=False):
	import gc

	F = gc.mem_free()
	A = gc.mem_alloc()
	T = F+A
	P = '{0:.2f}%'.format(F/T*100)
	if not full:
		send_to_graphite([Metric('memtotal', T), Metric('memfree', F)])
		return P
	else :
		return ('Total:{0} Free:{1} ({2})'.format(T,F,P))


def str_to_int_time(time:str)->int:
    time = time.split(":")
    return int(time[0]) * 60 + int(time[1])

def remove_sharp(melody:str)->str:
    melody = melody.replace("C#", "c").replace("D#", "d").replace("F#", "f")
    return melody.replace("G#", "g").replace("A#", "a")

def solution(m, musicinfos):
    answer, max_length = '(None)', 0
    m = remove_sharp(m)
    for musicinfo in musicinfos:
        musicinfo = musicinfo.split(",")
        time_beg, time_end, title, melody = musicinfo[:]

        time_length = str_to_int_time(time_end) - str_to_int_time(time_beg)
        melody = remove_sharp(melody)

        melody = (time_length // len(melody)) * melody + melody[0:time_length % len(melody)]

        if m in melody:
            if time_length > max_length:
                max_length = time_length
                answer = title

    return answer

daily/may/week1/0502/p  - previous song.py


import filter

print("[Transport 3] LRT Train / MRT Train:\n")
print("Converting website to text version...\n")

wordstring = ' Delays at Kelana Jaya LRT due to signalling issues'
wordstring += ' Nation'
wordstring += ' Monday, 18 Feb 2019'

wordstring += ' 1:22 AM MYT'
wordstring += ' PETALING JAYA: The Kelana Jaya LRT line is experiencing delays on Monday (Feb 18) due to a signalling fault between the Kelana Jaya station and KLCC. '
wordstring += ' "Train within the area moving in manual mode," LRT operator RapidKL said in a tweet. '
wordstring += ' It added that trains within the area were moving slower and stayed longer at the platform. '
wordstring += ' It said that their technical team was on site working to resolve the problem and apologised for the disruption. '
wordstring += ' RapidKL said they would send buses to ferry passengers between Kelana Jaya Station to KL Sentral and between the KLCC Station to KL Sentral. '

txt = wordstring
q = 101 # A prime number

print("Removing stop words and punctuations...\n")
# print("[CHECK] ori text: ", txt)
txt_nopunct = filter.removePunc(txt)
# print("[CHECK] txt no punc: ", txt_nopunct)

# print("\n[REMOVING STOPWORDS..]")
occurrence = filter.search(filter.stopwords, txt_nopunct, q)
txt_new = filter.removeStopwords(txt_nopunct, occurrence)
# print("[CHECK] new txt: ", txt_new)

stopwfreq = len(occurrence)

print("Comparing words with positive, negative and neutral English words...\n")
occurrence = filter.search(filter.poswords, txt_new, q)
poswfreq = len(occurrence)

occurrence = filter.search(filter.negwords, txt_new, q)
negwfreq = len(occurrence)

occurrence = txt_new.split()
wordfreq = len(occurrence)

#wordlist = txt_new.split()
#wordfreq = []

#for w in wordlist:
#    wordfreq.append(wordlist.count(w))

neutralwfreq = wordfreq - poswfreq - negwfreq
# print("[CHECK FREQUENCY] StopW, PosW, NegW, NeutralW: " + str(stopwfreq) + " & " + str(poswfreq) + " & " + str(negwfreq) + " & " + str(neutralwfreq))

print("Filtered text: \n" + txt_new + "\n")
print("Frequency: " + str(wordfreq) + " words\n")
#print("Pairs\n" + str(list(zip(wordlist, wordfreq))))


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

from PIL import Image
from torchvision import transforms, models
import torch.nn as nn

class Rescale(object):
    """Rescale a image to a given size.

    Args:
        output_size (tuple or tuple): Desired output size. If tuple, output is
            matched to output_size. If int, smaller of image edges is matched
            to output_size keeping aspect ratio the same.
    """

    def __init__(self, *output_size):
        self.output_size = output_size

    def __call__(self, image):
        """
        Args:
            image (PIL.Image) : PIL.Image object to rescale
        """
        new_h, new_w = self.output_size
        new_h, new_w = int(new_h), int(new_w)
        img = image.resize((new_w, new_h), resample=Image.BILINEAR)
        return img

class ResNetFeature(nn.Module):
    def __init__(self, feature='resnet101'):
        """
        Args:
            feature (string): resnet101 or resnet152
        """
        super(ResNetFeature, self).__init__()
        if feature == 'resnet101':
            resnet = models.resnet101(pretrained=True)
        else:
            resnet = models.resnet152(pretrained=True)
        resnet.float()
        resnet.cuda()
        resnet.eval()

        module_list = list(resnet.children())
        self.conv5 = nn.Sequential(*module_list[:-2])
        self.pool5 = module_list[-2]

    def forward(self, x):
        res5c = self.conv5(x)
        pool5 = self.pool5(res5c)
        pool5 = pool5.view(pool5.size(0), -1)
        return res5c, pool5

resnet_transform = transforms.Compose([
    Rescale(224, 224),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])


from dataclasses import (
    dataclass,
)
from fa_purity import (
    Cmd,
    Stream,
)
from fa_purity.pure_iter.factory import (
    from_list,
    unsafe_from_cmd,
)
from fa_purity.stream.factory import (
    from_piter,
)
from fa_purity.stream.transform import (
    chain,
)
from mypy_boto3_batch import (
    BatchClient,
)
from mypy_boto3_batch.literals import (
    JobStatusType,
)
from mypy_boto3_batch.type_defs import (
    JobSummaryTypeDef,
)

@dataclass(frozen=True)
class JobsClient:
    _client: BatchClient
    _queue: str

    def list_jobs(self, status: JobStatusType) -> Stream[JobSummaryTypeDef]:
        data = unsafe_from_cmd(
            Cmd.from_cmd(
                lambda: self._client.get_paginator("list_jobs").paginate(
                    jobQueue=self._queue,
                    jobStatus=status,
                )
            )
        ).map(lambda x: Cmd.from_cmd(lambda: from_list(x["jobSummaryList"])))
        return chain(from_piter(data))


import nltk
import re
import numpy as np
from nltk.translate import IBMModel1,AlignedSent
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.corpus import stopwords
# nltk.download('stopwords')
"""
**********EXAMPLE BASED MACHINE TRANSLATION SYSTEM 'EBMT'******************************
Translation in three steps: matching, alignment and recombination
Matching: finds the example or set of examples from the bitext which most closely match the source-language string to be translated.4
Alignment: extracts the source–target translation equivalents from the retrieved examples of the matching step.
Recombination: produces the final translation by combining the target translations of the relevant subsentential fragments.
"""
############################## PREPROCESSING SECTION ###################################
replacement_patterns = [
(r'won\'t', 'will not'),
(r'can\'t', 'can not'),
(r'i\'m', 'i am'),
(r'ain\'t', 'is not'),
(r'(\w+)\'ll', '\g<1> will'),
(r'(\w+)n\'t', '\g<1> not'),
(r'(\w+)\'ve', '\g<1> have'),
(r'(\w+)\'s', '\g<1> is'),
(r'(\w+)\'re', '\g<1> are'),
(r'(\w+)\'d', '\g<1> would')
]
# stop words for each languages
en_Stp_wrd= set(stopwords.words('english'))
tr_Stp_wrd= set(stopwords.words('turkish'))
az_Stp_wrd= set(stopwords.words('azerbaijani'))
stpwrds= en_Stp_wrd | tr_Stp_wrd | az_Stp_wrd #union all to have a big set of all the stop wprds

# for contraction removals
class RegexpReplacer(object):
    def __init__(self, patterns=replacement_patterns):
        self.patterns = [(re.compile(regex), repl) for (regex, repl) in patterns]
    def replace(self, text):
        s = text
        for (pattern, repl) in self.patterns:
            s = re.sub(pattern, repl, s)
        return s

def preprocessing(files):
    replacer = RegexpReplacer()
    for file in files:
        with open(file,'r',encoding='utf-8') as f:
            text= f.read()
        text = re.sub(r'[()\[\]{}.,;!?\\-]', '', text) #remove any punctutaions and unwanted characters
        text= text.replace('[','')
        text= text.replace(']','')
        text=text.replace('.','')
        text=text.replace(',','')
        text = text.strip() # spaces
        text=text.lower() # lower case
        text=replacer.replace(text) # apply the stemming
        with open(file,'w',encoding='utf-8') as f1:
            f1.write(text) # save changes

# to remove duplicates from  a list of strings
def remove_duplicates(string_array):
    unique_strings = []
    duplicates = []
    for string in string_array:
        words = string.split()  # Split the string into words
        unique_words = []
        for word in words:
            if word not in unique_words:
                unique_words.append(word)
            else:
                duplicates.append(word)
        unique_string = ' '.join(unique_words)
        if unique_string not in unique_strings:
            unique_strings.append(unique_string)

    return unique_strings

##############################################################################################################################################################################
# creates a parallel corpus for 2 languages given its files
def make_par_corpus(src_lang):
    with open (src_lang ,'r', encoding='utf-8')as f :
        src= f.readlines()
    with open('Turkish.txt' ,'r' ,encoding='utf-8') as f1:
        tk=f1.readlines()
    src = [s.strip() for s in src]
    tk = [t.strip() for t in tk]
    corpus = list(zip(src,tk))
    return corpus

def matching(input_sentence, src_lang):
    target_lang = 'Turkish.txt'  # fixed
    with open(src_lang, 'r', encoding='utf-8') as f1:
        src_sentences = f1.readlines()
    with open(target_lang, 'r', encoding='utf-8') as f2:
        turkish_sentences = f2.readlines()

    # Use the TF-IDF vectorizer to convert sentences to vectors
    vectorizer = TfidfVectorizer(stop_words='english')
    sentence_vectors = vectorizer.fit_transform(src_sentences + [input_sentence])

    # Calculate the Cosine Similarity between the input sentence and all the other sentences
    input_vector = sentence_vectors[-1]
    similarity_scores = np.dot(sentence_vectors[:-1], input_vector.T).toarray().flatten()

    # Sort the similarity scores and get the indices of the top 4 sentences only
    top_indices = np.argsort(similarity_scores)[-5:]

    # Retrieve the top 4 similar sentences and their Turkish translations
    similar_sentences = [src_sentences[i] for i in top_indices]
    turkish_sentences = [turkish_sentences[i] for i in top_indices]
    turkish_tokens = [nltk.word_tokenize(s) for s in turkish_sentences]
    similar_tokens = [nltk.word_tokenize(s) for s in similar_sentences]
    parallel_sentences = list(zip(similar_tokens, turkish_tokens))

    print("similar sentences in the corpus: \n",parallel_sentences)
    return parallel_sentences  # return the top 4 similar source sentences with their translation equivalents

# IBM model for checking the alignment of words
def ibm1(src):
    with open(src, 'r',encoding='utf-8') as f1:
        src_sentences = f1.readlines()
    with open('Turkish.txt', 'r',encoding='utf-8') as f2:
        turkish_sentences = f2.readlines()
    #extra step step to remove spaces
    src_sentences = [s.strip() for s in src_sentences]
    turkish_sentences = [t.strip() for t in turkish_sentences]
    # word tokenize all sentences
    src_tokenized=[nltk.word_tokenize(s) for s in src_sentences]
    tgt_tokenized =[nltk.word_tokenize(s) for s in turkish_sentences]
    # make a parallel sentences corpus but the sentences are tokenized
    parallel_sentences = list(zip(src_tokenized,tgt_tokenized))
    # Align all sentnences to train the IBM model
    bitext = [(AlignedSent(s,t)) for s,t in parallel_sentences]
    #train the model
    ibm1= IBMModel1(bitext,15)
    return ibm1 # return  the model

#to extracts the source–target translation equivalents from the retrieved examples of the matching step.
def alignment(src,simialr_sentences,input_text):
    ibm=ibm1(src) # create the model
    turkish_translations= [word for sents in (pair[1] for pair in simialr_sentences) for word in sents] # extract all the turkish words from the similar sentences as the input
    # print(turkish_translations)
    text= nltk.word_tokenize(input_text)# tokenize the input
    equivlants=[] # it will hold pairs of the best match in turkish for each word in the input
    for s in text:
        all_probs= [(ibm.translation_table[s][w]) for w in turkish_translations] # find all the probabilites of each word in the input sentence with ALL tuekish words in the similar sentences
        for t in turkish_translations:
            # if s in stpwrds: # if a word is a stop word, ignore it
            #     continue
            prob=(ibm.translation_table[s][t]) #check probabilty of the word and a turkish word
            if prob == max(all_probs): # if its the highest probabilty , put it in pair so it acts like a dictionary
                equivlants.append((s,t))
                # print(f't({s}|{t} = {prob}')
                break
    return equivlants

# this function should produces the final translation by combining the target translations of the relevant subsentential fragments
def combination(equivlants, input):
    combined_translation=''
    text = nltk.word_tokenize(input) #tokenize the input
    for w in text:
        for s,t  in equivlants:# check from the equivlants pairs we got from the alignment function
            if w == s:  # if the word in input exists in the equiv pairs, get the translated word
                combined_translation+=" "
                combined_translation += t
                combined_translation+=" "
    return combined_translation # return the sentence

def translate(input, src_lang): # Combine all 3 steps to produce the translation
    flag=True # to check if the input already exist in the corpus
    corpus= make_par_corpus(src_lang)
    for pair  in corpus:
        if input  == pair[0]: # if input sentence already exists, print its translation directly
            print("\ninput sentence: \n",input)
            print("\ntranslation: \n",pair[1])
            flag=False #set flag to false to disallow rest of code to run
            break
    if flag:
        similar_sentences = matching(input,src_lang)
        align=alignment(src_lang,similar_sentences,input)
        translation = combination(align,input)
        str= remove_duplicates(nltk.word_tokenize(translation))
        translation=" ".join(str)
        print("\ninput sentence: \n",input)
        print("\ntranslation: \n",translation)

########################## MAIN  ################################
files=['English.txt','Turkish.txt','Azeri.txt']
preprocessing(files) # preprocess all the files
translation= input('enter translation option:\n1)English-Turkish\n2)Azerbjiani-Turkish\n')

while(not(translation == '2' or translation == '1')):
    translation=input("input 1 or 2 only\n\nenter translation option:\n1)English-Turkish\n2)Azerbjiani-Turkish\n")
text = input('Enter a sentence to translate: \n')
while( len(text.split()) < 10): # <10
    text=input("Enter a sentence of atleast 10 words:\n")

if translation == '1':#For English-Turkish
    translate(text, files[0])
if translation =='2':
    translate(text,files[2])#For Azerbjiani-Turkish


import csv

from tourManager import TourManager
from city import City
from population import Population
from GA import GA

if __name__ == '__main__':
    n_cities = 1000
    population_size = 10
    n_generations = 10

    city_location_file = open('TSP.csv', 'r', encoding='utf-8')
    city_location_information = csv.reader(city_location_file)

    # Setup cities and tour
    tourmanager = TourManager()

    for index, [x, y] in enumerate(list(city_location_information)):
        tourmanager.addCity(City(index=index, x=float(x), y=float(y)))

    # Initialize population
    pop = Population(tourmanager, populationSize=population_size, initialise=True)
    print("Initial distance: " + str(pop.getFittest().getDistance()))

    # Evolve population
    ga = GA(tourmanager)

    for i in range(n_generations):
        pop = ga.evolvePopulation(pop)

        fittest = pop.getFittest()

    # Print final results
    print("Finished")
    print(" distance: " + str(pop.getFittest().getDistance()))
    print("Solution:")
    print(pop.getFittest())


#https://www.acmicpc.net/board/view/28285
#부분점수, 준비 다 되고 시간 남으면 풀어보기

key=input()
inc=input()

row=len(inc)//len(key)
lkey=sorted(key)

f=[]
cnt=0
num=row
for i in lkey:
    x=i
    for j in range(cnt,num):
        x+=inc[j]
    cnt=j+1
    num+=row
    f.append(x)

fin=[]
for i in key:
    for j in f:
        if i==j[0]:
            fin.append(j)
            break

# result=''
# for i in range(1,row+1):
#     for j in range(len(fin)):
#         result+=fin[j][i]
# print(result)

print(fin)


# -*- coding: utf-8 -*-
"""
Spyder Editor Spyder 3.2.3

# MAP5725 - Roma, 01-02/2020.

# General, Explicit One-Step Methods for
              d^2/dt^2 x(t) = - x(t)
              x(0)=1; d/dt x(0)=0

"""

import matplotlib.pyplot as plt
import numpy as np
#############################################################################
def phi(t,y,dt,f):
    # define discretization function

    k1 = f(t, y)
    k2 = f(t+dt/2, y + dt/2*k1)
    k3 = f(t+dt/2, y + dt/2*k2)
    k4 = f(t+dt, y + dt*k3)

    #return 1/6*(k1 + 2*k2 + 2*k3 + k4)     # classical RK-44
    return k1    # euler method
############################################################################
############################################################################
def f(t, y):
    # input n-dim ode system right hand side: f=(f0,f1,...,fn-1)
    # ATTENTION: Python arrays and lists start at index "0" !!!!

    f0 =  y[1]
    f1 = -y[0]

    return np.array([f0,f1])
############################################################################
############################################################################
# other relevant data
t_n = [0]; T = 50;        # time interval: t in [t0,T]
y_n = [np.array([1,0])]   # initial condition

n = 10000                  # time interval partition (discretization)
dt = (T-t_n[-1])/n
while t_n[-1] < T:
    y_n.append(y_n[-1] + dt*phi(t_n[-1],y_n[-1],dt,f))
    t_n.append(t_n[-1] + dt)

    dt = min(dt, T-t_n[-1])

y_n = np.array(y_n)

# appropriate/adequate plots... look for information in
# https://matplotlib.org/gallery/index.html

#plt.figure(figsize=(15,5))
plt.plot(t_n, y_n[:,0], color='black', linestyle=(0,(1,1,3,1)),
             label = 'y_1(t)  (in y_1 units)')
#plt.plot(t_n, y_n[:,1], c = 'k', label = 'y_2(t)  (in y_2 units)')
plt.xlabel('time t   (in units)')
plt.ylabel('y  state variables')
plt.title('Numerical Approximation of State Variables')
plt.legend()
plt.show()

plt.plot(t_n, y_n[:,1], c = 'k', label = 'y_2(t)  (in y_2 units)')
plt.xlabel('time t   (in units)')
plt.ylabel('y  state variables')
plt.title('Numerical Approximation of State Variables')
plt.legend()
plt.show()


#This module searches for new files to download, adds the filename to the files table of the
#database, attempts to download the file, and updates the files table if successful.

import psycopg2
import logging
import configparser
from ftplib import FTP
from datetime import datetime

logging.basicConfig(level='DEBUG')

config = configparser.ConfigParser()
config.read('munilyzer.ini')

ftp_address = config['ftp']['ftp_address']
ftp_directory = config['ftp']['ftp_directory']
database_string = config['database']['database_string']
download_directory = config['ftp']['download_directory']

def identify_new_files():
    """Check the ftp server for new files."""
    with psycopg2.connect(database_string) as conn:
        #Retrieve a list of which files we already have.
        logging.debug("Connected to database")
        with conn.cursor() as cur:
            local_files_list = []
            cur.execute('SELECT file_name FROM files')
            for row in cur:
                local_files_list.append(row[0])
            #Download raw gps data as .csv files from ftp server.
            #Connect to ftp server.
            logging.debug("Address of ftp server: " + ftp_address)
            with FTP(ftp_address) as ftp:
                ftp.login()
                ftp.cwd(ftp_directory)
                logging.debug("Logged into ftp server at:" + ftp_address)
                #Retrieve a list of files on the server.
                ftp_files_list = ftp.nlst()
                #For each file on the server, compare to the list of local files.
                for file_name in ftp_files_list:
                    #If the file isn't known about locally add it to files table.
                    if file_name not in local_files_list:
                        #Add filename to database.
                        cur.execute('INSERT INTO files VALUES (%s,%s,%s,%s)',
                                    (file_name,None,None,None))

def download_files():
    """Download files from the ftp server."""
    with psycopg2.connect(database_string) as conn:
        logging.debug("Connected to database")
        with FTP(ftp_address) as ftp:
            ftp.login()
            logging.debug("Logged into ftp server at: " + ftp_address)
            ftp.cwd(ftp_directory)
            with conn.cursor() as cur:
                #Get list of files that aren't yet downloaded.
                cur.execute('SELECT file_name FROM files WHERE downloaded IS NULL')
                files_to_download_list = cur.fetchall()
                for file_name in files_to_download_list:
                    #file_path is the full path that the new file is going to be downloaded to.
                    file_path = download_directory + file_name[0]
                    logging.debug("Attempting to download: " + file_name[0])
                    ftp.retrbinary("RETR " + file_name[0] , open(file_path, 'wb').write)
                    logging.debug("Successfully downloaded: " + file_name[0])
                    #If our download was successfull, update downloaded field
                    logging.debug(cur.mogrify('UPDATE files SET downloaded = %s '
                                              'WHERE file_name = %s',
                                              (datetime.utcnow(),file_name[0]))
                                  )
                    cur.execute('UPDATE files SET downloaded = %s WHERE file_name = %s',
                                (datetime.utcnow(),file_name[0]))
                    conn.commit()

def clean_file(file_name):
    file_path = download_directory + file_name
    #line_list is a list of lines that are going to go in the cleaned .csv file.
    line_list = []
    #The first 30 characters of any line SHOULD be usable as unique keys, but some sometimes they
    #aren't. key_set is used to throw out the duplicates, of which there are ~1 per 20,000 lines.
    key_set = set()
    with open(file_path, 'r+') as f:
        for line in f:
            #if the key isn't in the key set and the line is not blank, keep it.
            if (line[:29] not in key_set) and (line != '\n'):
                #Skip the first 5 characters, as they aren't needed.
                line_list.append(line[:5])
                key_set.add(line[:29])
        #Remove the header data. The header data in these files is only half
        #of the first line; the rest is data.
        line_list[0] = line_list[0][89:]
        #Write clean data to file
        f.writelines(line_list)

def file_name_check(file_name):
    """Ensure that the file we are cleaning is one we should clean."""
    if (file_name[:15] == "sfmtaAVLRawData" and
        file_name[-4:] == ".csv"):
        return True
    else:
        return False

def get_files_to_clean():
    with psycopg2.connect(database_string) as conn:
        logging.debug("Connected to database")
        with conn.cursor() as cur:
            cur.execute('SELECT file_name FROM files WHERE cleaned IS NULL '
                        ' AND downloaded IS NOT NULL ')
            files_to_clean_list = cur.fetchall()
            for file_name in files_to_clean_list:
                if file_name_check(file_name[0]):
                    clean_file(file_name[0])
                    logging.debug("Cleaned file: " + file_name[0])
                    cur.execute('UPDATE files SET cleaned = %s WHERE file_name = %s',
                                (datetime.now(),file_name[0]))
                    conn.commit()

if __name__ == "__main__":
    #identify_new_files()
    #download_files()
    get_files_to_clean()


class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        # optimization
        if len(nums) < 3:
            return
        nums.sort()
        answer = nums[0] + nums[1] + nums[2]
        for i in range(len(nums) - 2):
            # !!!optimization!!!
            if i > 0 and nums[i] == nums[i-1]:
                continue
            j, k = i+1, len(nums)-1
            while j < k:
                total = nums[i] + nums[j] + nums[k]
                if total == target:
                    return total
                if abs(total-target) < abs(answer-target):
                    answer = total
                if total < target:
                    j += 1
                else:
                    k -= 1

        return answer


import sys
import app
import json
import pandas as pd
from sklearn.externals import joblib
reload(sys)
sys.setdefaultencoding('utf8')
from predictiveModelBuilding import PredictiveModelBuilding
import predictiveModelBuilding
from flask import request, abort, jsonify, url_for, render_template,redirect
from . import predictions

@predictions.route('/predictions/predict_form/', methods=['GET'])
def predict_form():
    """ this is the main route to handle the predict form"""
    return render_template('predictions/forms.html')

@predictions.route('/predictions/predict/', methods=['GET', 'POST'])
def predict():
    """

    the main method use to predict

    """
    if request.method == 'GET':
        abort(403)
    else :
        predictives_models = []
        predicted_grades = {}
        model_names = ['FM', 'FSTA', 'FD', 'FSDC', 'FSEG', 'FPSE', 'FT']
        app_floder = predictions.root_path.replace('predictions', 'static/')
        for filename in model_names:
            model = joblib.load(app_floder+'/classes/'+filename+'.pkl')
            predictives_models.append(model)

        new_student = request.data
        new_student_data = pd.DataFrame(new_student, columns=new_student.keys(), index=range(1))
        for dept, name in zip(predictives_models, model_names):
            predicted_grade = dept.predict_new(new_student_data)
            final_grade = predicted_grade[0]
            predicted_grades[name] = final_grade*100
        response = jsonify(predicted_grades)
        response.status_code = 200
        return response

@predictions.route('/predictions/results/<results>', methods=['GET'])
def view_results(results):
    """ display the predicted results """
    results = json.loads(results)
    return render_template('predictions/results.html', results=results)


#========================================================================
#심술쟁이 수는 2,3,5의 곱으로 만들 수 있는 수이다. 다음과 같은 순서의 수가 11개의 심술쟁이 수이다.
#1,2,3,4,5,6,8,9,10,12,15,....
#처음 수는 1로 시작하도록 한다. 입력은 받지 않고, <number> 에 1500번째 심술쟁이 수가 출력되게 한다.

#Sample Output
#The 1500'th ugly number is <number>.

#답
#859963392
#(1550번째는 1093500000, 십만번째는 290142196707511001929482240000000000000)
#========================================================================
#과제1. 숫자 2,3,5의 곱으로 만들 수 있는 수 작은 순서대로 11개를 출력하시오.
#      - 출력 : 1,2,3,4,5,6,8,9,10,12,15

#과제 1 풀이
ugly_list = [1] #심술쟁이 수 리스트, 처음엔 1로 시작
while len(ugly_list) != 11 :  #요소가 11개가 될 때까지 반복
      num_list = []  #2,3,5로 곱한 수 넣을 리스트
      for num in ugly_list: #요소 꺼냄
            for multi in num * 2, num * 3, num * 5:  #2,3,5로 곱한 수를 차례대로 대입
                  if multi > ugly_list[-1]: #곱한 수가 심술쟁이 수 리스트의 마지막 요소보다 클 때만
                        num_list.append(multi) #리스트에 추가
      ugly_list.append(min(num_list)) #가장 작은 수를 심술쟁이 수 리스트에 추가
print(*ugly_list, sep = ',')  #압축 풀고 모든 요소를 콤마로 분리하여 반환
#========================================================================
#과제2. 숫자 2,3,5의 곱으로 만들 수 있는 수를 오름차순으로 정렬할 경우 1550번째 값을 구하시오.
#      - 출력 : 1,093,500,000

#과제 2 풀이
ugly_list2 = [1]                                      #ugly_list2에 리스트에 1을 할당하여 생성
while len(ugly_list2) != 1550:                        #while문을 이용해 ugly_list2의 길이가 1550개 될 때까지 반복
      num_list = []                                   #num_list명의 빈 리스트 생성
      for num in ugly_list2:                          #for문을 이용해 num을 ugly_list2만큼 반복
            for multi in num * 2, num * 3, num * 5 :  #for문을 이용해 multi를 num * 2, num * 3, num * 5값까지 반복
                  if multi > ugly_list2[-1]:          #if문을 이용해 multi > ugly_list2dp -1를 대입한 값이라면
                        num_list.append(multi)        #ugly_list2에 num_list의 최솟값을 ㅜ가
      ugly_list2.append(min(num_list))

print(format(ugly_list2[-1],','))                     #리스트를 천단위로 ','로 구분하여 출력
#========================================================================


import cv2
import numpy as np
from PIL import Image
import os,json

yol = 'C:/Users/DEMET/Desktop/Verikoy/'
tani = cv2.face.LBPHFaceRecognizer_create() #LBP yöntemi
detector = cv2.CascadeClassifier('C:/Users/DEMET/PycharmProjects/yuztanima/haarcascade_frontalface_default.xml')

def getImagesAndLabels(yol):
    faceSamples=[]
    ids = []
    labels = []
    klasorler = os.listdir(yol)
    dictionary = {}

    for i, k1 in enumerate(klasorler):
        dictionary[k1] = int(i)

    f = open("ids.json", "w")#id'lerin tutlacağı yer
    a = json.dump(dictionary,f)
    f.close()

    for k1 in klasorler:
        for res in os.listdir(os.path.join(yol,k1)):
            PIL_img = Image.open(os.path.join(yol,k1,res)).convert('L')
            img_numpy = np.array(PIL_img, 'uint8')
            id = int(dictionary[k1])
            faces = detector.detectMultiScale(img_numpy)
            for (x, y, w, h) in faces:
                faceSamples.append(img_numpy[y:y+h, x:x+w])
                ids.append(id)
    return faceSamples, ids

faces,ids = getImagesAndLabels(yol)

tani.train(faces, np.array(ids))
tani.write('trainer.yml')


def main(data, part, log):
    data = [int(x) for x in data.read().strip().split(',')]
    data.sort()
    if part == 1:
        median = data[len(data) // 2]
        cost = 0
        for d in data:
            cost += abs(median - d)
        print(f'Cost is {cost}')
    else:
        mean = sum(data) // len(data)
        cost = 0
        for d in data:
            diff = abs(d - mean)
            cost += diff * (diff + 1) // 2
        print(f'Cost is {cost}')
        # realmean = sum(data) / len(data)
        # i = 0
        # while data[i] < realmean:
        #     i += 1
        # print(f'{i} numbers below mean of {realmean}, {len(data) - i} higher')


from flask import Flask, jsonify
import requests

app = Flask(__name__)

@app.route('/user/<int:user_id>', methods=['GET'])
def get_user(user_id):
    #this gets user details from another device
    response = request.get(f'http://localhost:5001/user/{user_id}')
    user_data = response.json()

    #return the user details
    return jsonify(user_data)


import os
import re
from logging import info, warning
from pathlib import Path
from shutil import copytree, rmtree
from tempfile import TemporaryDirectory
from typing import Any, Dict, ForwardRef, List, Union

from enchant.tokenize import Filter
from git import Repo
from sphinx_gallery.directives import MiniGallery

HERE = Path(__file__).parent

def _fetch_notebooks(repo_url: str) -> None:
    def copy_files(repo_path: Union[str, Path]) -> None:
        repo_path = Path(repo_path)

        for dirname in ["tutorials", "auto_examples", "gen_modules"]:
            rmtree(dirname, ignore_errors=True)  # locally re-cloning
            copytree(repo_path / "docs" / "source" / dirname, dirname)

    def fetch_remote(repo_url: str) -> None:
        info(f"Fetching notebooks from repo `{repo_url}`")
        with TemporaryDirectory() as repo_dir:
            ref = "main"
            repo = Repo.clone_from(repo_url, repo_dir, depth=1, branch=ref)
            repo.git.checkout(ref, force=True)

            copy_files(repo_dir)

    def fetch_local(repo_path: Union[str, Path]) -> None:
        info(f"Fetching notebooks from local path `{repo_path}`")
        repo_path = Path(repo_path)
        if not repo_path.is_dir():
            raise OSError(f"Path `{repo_path}` is not a directory.")

        copy_files(repo_path)

    notebooks_local_path = Path(
        os.environ.get("SQUIDPY_NOTEBOOKS_PATH", HERE.absolute().parent.parent.parent / "squidpy_notebooks")
    )
    try:
        fetch_local(notebooks_local_path)
    except Exception as e:  # noqa: BLE001
        warning(f"Unable to fetch notebooks locally from `{notebooks_local_path}`, reason: `{e}`. Trying remote")
        download = int(os.environ.get("SQUIDPY_DOWNLOAD_NOTEBOOKS", 1))
        if not download:
            # use possibly old files, otherwise, bunch of warnings will be shown
            info(f"Not fetching notebooks from remove because `SQUIDPY_DOWNLOAD_NOTEBOOKS={download}`")
            return

        fetch_remote(repo_url)

class MaybeMiniGallery(MiniGallery):
    def run(self) -> list[str]:
        config = self.state.document.settings.env.config
        backreferences_dir = config.sphinx_gallery_conf["backreferences_dir"]
        obj_list = self.arguments[0].split()

        new_list = []
        for obj in obj_list:
            path = os.path.join("/", backreferences_dir, f"{obj}.examples")  # Sphinx treats this as the source dir

            if (HERE / path[1:]).exists():
                new_list.append(obj)

        self.arguments[0] = " ".join(new_list)
        try:
            return super().run()  # type: ignore[no-any-return]
        except UnboundLocalError:
            # no gallery files
            return []

def _get_thumbnails(root: Union[str, Path]) -> dict[str, str]:
    res = {}
    root = Path(root)
    thumb_path = Path(__file__).parent.parent.parent / "docs" / "source"

    for fname in root.glob("**/*.py"):
        path, name = os.path.split(str(fname)[:-3])
        thumb_fname = f"sphx_glr_{name}_thumb.png"
        if (thumb_path / path / "images" / "thumb" / thumb_fname).is_file():
            res[str(fname)[:-3]] = f"_images/{thumb_fname}"

    res["**"] = "_static/img/squidpy_vertical.png"

    return res

class ModnameFilter(Filter):
    """Ignore module names."""

    _pat = re.compile(r"squidpy\.(im|gr|pl|read|datasets|ImageContainer).+")

    def _skip(self, word: str) -> bool:
        return self._pat.match(word) is not None

class SignatureFilter(Filter):
    """Ignore function signature artifacts."""

    def _skip(self, word: str) -> bool:
        # TODO(michalk8): find a better way
        return word in ("img[", "imgs[", "img", "img_key", "func[", "func", "combine_attrs", "**kwargs", "n_iter")

# allow `<type_1> | <type_2> | ... | <type_n>` expression for sphinx-autodoc-typehints
def _fwd_ref_init(
    self: ForwardRef,
    arg: str,
    is_argument: bool = True,
    module: Any = None,
    *,
    is_class: bool = False,
) -> None:
    if not isinstance(arg, str):
        raise TypeError(f"Forward reference must be a string -- got {arg!r}")
    if " | " in arg:
        arg = "Union[" + ", ".join(arg.split(" | ")) + "]"
    try:
        code = compile(arg, "<string>", "eval")
    except SyntaxError:
        raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
    self.__forward_arg__ = arg
    self.__forward_code__ = code
    self.__forward_evaluated__ = False
    self.__forward_value__ = None
    self.__forward_is_argument__ = is_argument
    try:
        self.__forward_is_class__ = is_class
    except AttributeError:
        pass
    try:
        self.__forward_module__ = module
    except AttributeError:
        pass

ForwardRef.__init__ = _fwd_ref_init  # type: ignore[method-assign]


import os
from datetime import timedelta
from azure.communication.identity import CommunicationIdentityClient, CommunicationUserIdentifier

try:
   print("Azure Communication Services - Access Tokens Quickstart")
   # Quickstart code goes here
except Exception as ex:
   print("Exception:")
   print(ex)

# This code demonstrates how to retrieve your connection string
# from an environment variable.
connection_string = os.environ["COMMUNICATION_SERVICES_CONNECTION_STRING"]

# Instantiate the identity client
client = CommunicationIdentityClient.from_connection_string(connection_string)

endpoint = os.environ["COMMUNICATION_SERVICES_ENDPOINT"]
client = CommunicationIdentityClient(endpoint, DefaultAzureCredential())

identity = client.create_user()
print("\nCreated an identity with ID: " + identity.properties['id'])

# Issue an access token with a validity of 24 hours and the "voip" scope for an identity
token_result = client.get_token(identity, ["voip"])
print("\nIssued an access token with 'voip' scope that expires at " + token_result.expires_on + ":")
print(token_result.token)

# Issue an access token with a validity of an hour and the "voip" scope for an identity
token_expires_in = timedelta(hours=1)
token_result = client.get_token(identity, ["voip"], token_expires_in=token_expires_in)

# Issue an identity and an access token with a validity of 24 hours and the "voip" scope for the new identity
identity_token_result = client.create_user_and_token(["voip"])

# Get the token details from the response
identity = identity_token_result[0]
token = identity_token_result[1].token
expires_on = identity_token_result[1].expires_on
print("\nCreated an identity with ID: " + identity.properties['id'])
print("\nIssued an access token with 'voip' scope that expires at " + expires_on + ":")
print(token)

# The existingIdentity value represents the Communication Services identity that's stored during identity creation
identity = CommunicationUserIdentifier(existingIdentity)
token_result = client.get_token(identity, ["voip"])

client.revoke_tokens(identity)
print("\nSuccessfully revoked all access tokens for identity with ID: " + identity.properties['id'])

client.delete_user(identity)
print("\nDeleted the identity with ID: " + identity.properties['id'])


#!../venv/bin/python
import sys
import re
from sot.Project import Project

def run():
    project = Project()
    infile = sys.argv[1]
    indata = ''

    with open(infile) as _file:
        indata = _file.read()
    _file.close()

    requires = re.findall(r'(require\((\'|\")(.*?)(\'|\")\))', indata)

    for req in requires:
        contents = ''

        with open(req[2]) as _file:
            contents = _file.read()
        _file.close()

        indata = indata.replace(req[0] + ';', project.transpile(
            out=contents, ext=req[2].split('.')[1]))

    print(indata)

run()


import requests
import config

XYANDEXAPIKEYWEATHER = config.XYANDEXAPIKEYWEATHER
XYANDEXAPIKEYDIR = config.XYANDEXAPIKEYDIR
URLWEATHER = config.URLWEATHER
URLDIR = config.URLDIR
WEATHER = {
    "clear": "ясно",
    "partly-cloudy": "малооблачно",
    "cloudy": "облачно с прояснениями",
    "overcast": "пасмурно",
    "drizzle": "морось",
    "light-rain": "небольшой дождь",
    "rain": "дождь",
    "moderate-rain": "умеренно сильный дождь",
    "heavy-rain": "сильный дождь",
    "continuous-heavy-rain": "длительный сильный дождь",
    "showers": "ливень",
    "wet-snow": "дождь со снегом",
    "light-snow": "небольшой снег",
    "snow": "снег",
    "snow-showers": "снегопад",
    "hail": "град",
    "thunderstorm": "гроза",
    "thunderstorm-with-rain": "дождь с грозой",
    "thunderstorm-with-hail": "гроза с градом"
}
WIND_DIR = {'nw': 'северо-западное',
            'n': 'северное',
            'ne': 'северо-восточное',
            'e': 'восточное',
            'se': 'юго-восточное',
            's': 'южное',
            'sw': 'юго-западное',
            'w': 'западное',
            'с': 'штиль'}

class YandexApi():
    def createHead(self, XYandexAPIKey):
        return {"X-Yandex-API-Key": XYandexAPIKey}

    def getResp(self, XYandexAPIKey: str, URL: str):
        response = requests.get(URL,
                                headers=self.createHead(XYandexAPIKey))
        return response.json()

# @lru_cache(maxsize=128)
class LocCorr():
    def __init__(self):
        self.core = ''
        self.fee = ''

    def parsResp(self, dt):
        try:
            for i in dt:
                try:
                    if not dt['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos']:
                        self.fee = dt['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point'][
                            'pos']
                except Exception as err:
                    print(err)
                    pass
                if i == 'upperCorner':
                    return dt[i]
                elif type(dt[i]) == dict:
                    self.core = self.parsResp(dt[i])
                elif type(dt[i]) == list:
                    for j in dt[i]:
                        self.core = self.parsResp(j)
            if self.fee:
                self.core = self.fee
            return self.core
        except Exception as err:
            print(err)
            return 'error'

    def get_corr(self, city: str):
        resp = YandexApi().getResp(XYandexAPIKey=XYANDEXAPIKEYDIR,
                                   URL=URLDIR.replace('@APIKEY', XYANDEXAPIKEYDIR) + city)
        return [cor for cor in self.parsResp(resp).split(' ')]

class Weather():

    def createURL(self, lon: str, lat: str):
        return URLWEATHER.replace("@LAT", str(lat)).replace("@LON", str(lon))

    def getWeather(self, lon, lat):
        json_response = YandexApi().getResp(XYANDEXAPIKEYWEATHER, self.createURL(lat=lat, lon=lon))
        resp = {
            "Температура": str(json_response['fact']['temp']) + " °C",
            "Погода": WEATHER[json_response['fact']['condition']],
            "Скорость ветра": str(json_response['fact']['wind_speed']) + " м/с",
            # "Скорость ветра": json_response['fact'],
            "Направление ветра": WIND_DIR[json_response['fact']['wind_dir']],
            "Карта: ": json_response['info']['url'],

        }
        return resp


# 여행 가자
# https://www.acmicpc.net/problem/1976
# https://github.com/yhs3434/Algorithms

from heapq import heappush, heappop

def isGo(N, adj, u, v):
    pq = []
    dist = [float('inf')] * N
    dist[u] = 0
    heappush(pq, (0, u))
    while pq:
        cur = heappop(pq)
        cost = cur[0]
        here = cur[1]

        for there in range(N):
            if adj[here][there] == 1:
                nextDist = cost + 1
                if nextDist < dist[there]:
                    dist[there] = nextDist
                    heappush(pq, (nextDist, there))
    if dist[v] == float('inf'):
        return False
    else:
        return True

N = int(input())
M = int(input())
adj = []
for _ in range(N):
    adj.append(list(map(int, input().split(' '))))
arr = list(map(int, input().split(' ')))

flag = True
for i in range(1, len(arr)):
    if not isGo(N, adj, arr[i-1]-1, arr[i]-1):
        flag = False
        break
if flag:
    print("YES")
else:
    print("NO")


"""ResNet (V1 and V2) implementation written with PyTorch

Reference papers:
    - 'Original' (V1): 'Deep Residual Learning for Image Recognition'
        https://arxiv.org/abs/1512.03385
    - 'Pre-Activation' (V2): 'Identity Mappings in Deep Residual Networks'
        https://arxiv.org/abs/1603.05027

Main Reference Implementations:
    - 'Original' (V1): https://github.com/KaimingHe/deep-residual-networks/blob
        /master/prototxt/ResNet-50-deploy.prototxt
    - 'Pre-Activation' (V2): https://github.com/KaimingHe/resnet-1k-layers/blob
        /master/resnet-pre-act.lua

Other Reference Implementations:

    - 'Original' (V1) and 'Pre-Activation' (V2):
        - https://github.com/taehoonlee/tensornets/blob/master/tensornets
            /resnets.py
    - 'Original' (V2):
        - https://github.com/keras-team/keras-applications/blob/master
            /keras_applications/resnet50.py
    - 'Pre-Activation' (V2):
        - https://github.com/keras-team/keras-applications/blob/master
            /keras_applications/resnet_common.py

This implementation follows the "Main Reference Implementation" as closely as
possible. The "Other Reference Implementations" were used as a reference, and
sometimes appear to have slight differences from the main implementation
(although the `tensornets` implementations look extremely close).
"""

import torch
from torch.nn import (
    AvgPool2d, BatchNorm2d, Conv2d, Linear, MaxPool2d, Module, ModuleList, ReLU
)
from torch.nn.init import kaiming_normal_, constant_

from trainet.utils.generic_utils import validate_config

class BottleneckBlockV1(Module):
    """Bottleneck Residual Block

    As implemented in 'Deep Learning for Image Recognition', the original
    ResNet paper (https://arxiv.org/abs/1512.03385).
    """

    def __init__(self, n_in_channels, n_out_channels):
        """Init

        :param n_in_channels: number of channels in the inputs passed to the
         `forward` method
        :type n_in_channels: int
        :param n_out_channels: number of output channels (convolutional
         filters) to use in the convolutions applied to the inputs passed to
         the `forward` method
        :type n_out_channels: int
        """

        super().__init__()

        self.conv1 = Conv2d(
            in_channels=n_in_channels, out_channels=n_out_channels,
            kernel_size=(1, 1), stride=(1, 1), bias=False
        )
        self.bn1 = BatchNorm2d(num_features=n_out_channels)

        self.conv2 = Conv2d(
            in_channels=n_out_channels, out_channels=n_out_channels,
            kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
        )
        self.bn2 = BatchNorm2d(num_features=n_out_channels)

        self.conv3 = Conv2d(
            in_channels=n_out_channels, out_channels=(n_out_channels * 4),
            kernel_size=(1, 1), bias=False
        )
        self.bn3 = BatchNorm2d(num_features=(n_out_channels * 4))

        self.relu = ReLU()

    def forward(self, inputs):
        """Return the output of a forward pass of a BottleneckBlockV1

        :param inputs: batch of inputs, of shape
         (batch_size, n_in_channels, height, width)
        :type inputs: torch.Tensor
        :return: outputs of a BottleneckBlock, of shape
         (batch_size, n_out_channels * 4, height, width)
        :rtype: torch.Tensor
        """

        layer = self.conv1(inputs)
        layer = self.bn1(layer)
        layer = self.relu(layer)

        layer = self.conv2(layer)
        layer = self.bn2(layer)
        layer = self.relu(layer)

        layer = self.conv3(layer)
        layer = self.bn3(layer)

        layer = torch.add(layer, inputs)
        outputs = self.relu(layer)

        return outputs

class BottleneckBlockV2(Module):
    """Bottleneck Residual Block

    As implemented in 'Identity Mappings in Deep Residual Networks', often
    referred to as ResNetV2 (https://arxiv.org/abs/1603.05027).
    """

    def __init__(self, n_in_channels, n_out_channels):
        """Init

        :param n_in_channels: number of channels in the inputs passed to the
         `forward` method
        :type n_in_channels: int
        :param n_out_channels: number of output channels (convolutional
         filters) to use in the convolutions applied to the inputs passed to
         the `forward` method
        :type n_out_channels: int
        """

        super().__init__()

        self.bn1 = BatchNorm2d(num_features=n_in_channels)
        self.conv1 = Conv2d(
            in_channels=n_in_channels, out_channels=n_out_channels,
            kernel_size=(1, 1), stride=(1, 1), bias=False
        )

        self.bn2 = BatchNorm2d(num_features=n_out_channels)
        self.conv2 = Conv2d(
            in_channels=n_out_channels, out_channels=n_out_channels,
            kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
        )

        self.bn3 = BatchNorm2d(num_features=(n_out_channels))
        self.conv3 = Conv2d(
            in_channels=n_out_channels, out_channels=(n_out_channels * 4),
            kernel_size=(1, 1), bias=False
        )

        self.relu = ReLU()

    def forward(self, inputs):
        """Return the output of a forward pass of a BottleneckBlockV2

        :param inputs: batch of inputs, of shape
         (batch_size, n_in_channels, height, width)
        :type inputs: torch.Tensor
        :return: outputs of a BottleneckBlock, of shape
         (batch_size, n_out_channels * 4, height, width)
        :rtype: torch.Tensor
        """

        layer = self.bn1(inputs)
        layer = self.relu(layer)
        layer = self.conv1(layer)

        layer = self.bn2(layer)
        layer = self.relu(layer)
        layer = self.conv2(layer)

        layer = self.bn3(layer)
        layer = self.relu(layer)
        layer = self.conv3(layer)

        outputs = torch.add(layer, inputs)

        return outputs

class ProjectionShortcutV1(Module):
    """ProjectionShortcutV1 module

    As implemented in 'Deep Learning for Image Recognition', the original
    ResNet paper (https://arxiv.org/abs/1512.03385).

    This module is inserted at the beginning of each residual stage, and
    downsamples the input 2x using a convolution with stride 2 (except for the
    first residual stage, in which there is no downsampling).
    """

    def __init__(self, n_in_channels, n_out_channels, stride):
        """Init

        :param n_in_channels: number of channels in the inputs passed to the
         `forward` method
        :type n_in_channels: int
        :param n_out_channels: number of output channels (convolutional
         filters) to use in the convolutions applied to the inputs passed to
         the `forward` method
        :type n_out_channels: int
        :param stride: holds the stride to use in the first convolution of the
         block (i.e. for downsampling)
        :type stride: tuple(int)
        """

        super().__init__()

        self.conv1 = Conv2d(
            in_channels=n_in_channels, out_channels=n_out_channels,
            kernel_size=(1, 1), stride=stride, bias=False
        )
        self.bn1 = BatchNorm2d(num_features=n_out_channels)

        self.conv2 = Conv2d(
            in_channels=n_out_channels, out_channels=n_out_channels,
            kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
        )
        self.bn2 = BatchNorm2d(num_features=n_out_channels)

        self.conv3 = Conv2d(
            in_channels=n_out_channels, out_channels=(n_out_channels * 4),
            kernel_size=(1, 1), bias=False
        )
        self.bn3 = BatchNorm2d(num_features=(n_out_channels * 4))

        self.projection_conv = Conv2d(
            in_channels=n_in_channels, out_channels=(n_out_channels * 4),
            kernel_size=(1, 1), stride=stride, bias=False
        )
        self.projection_bn = BatchNorm2d(num_features=(n_out_channels * 4))

        self.relu = ReLU()

    def forward(self, inputs):
        """Return the output of a forward pass of a ProjectionShortcutV1

        :param inputs: batch of inputs, of shape
         (batch_size, n_in_channels, height, width)
        :type inputs: torch.Tensor
        :return: outputs of a BottleneckBlock, of shape
         (batch_size, n_out_channels * 4, height / 2, width / 2)
        :rtype: torch.Tensor
        """

        layer = self.conv1(inputs)
        layer = self.bn1(layer)
        layer = self.relu(layer)

        layer = self.conv2(layer)
        layer = self.bn2(layer)
        layer = self.relu(layer)

        layer = self.conv3(layer)
        layer = self.bn3(layer)

        shortcut = self.projection_conv(inputs)
        shortcut = self.projection_bn(shortcut)

        layer = torch.add(layer, shortcut)
        outputs = self.relu(layer)

        return outputs

class ProjectionShortcutV2(Module):
    """ProjectionShortcutV2 module

    As implemented in 'Identity Mappings in Deep Residual Networks', often
    referred to as ResNetV2 (https://arxiv.org/abs/1603.05027).

    This module is inserted at the beginning of each residual stage, and
    downsamples the input 2x using a convolution with stride 2 (except for the
    first residual stage, in which there is no downsampling).
    """

    def __init__(self, n_in_channels, n_out_channels, stride):
        """Init

        :param n_in_channels: number of channels in the inputs passed to the
         `forward` method
        :type n_in_channels: int
        :param n_out_channels: number of output channels (convolutional
         filters) to use in the convolutions applied to the inputs passed to
         the `forward` method
        :type n_out_channels: int
        :param stride: holds the stride to use in the first convolution of the
         block (i.e. for downsampling)
        :type stride: tuple(int)
        """

        super().__init__()

        self.bn_preact = BatchNorm2d(num_features=n_in_channels)

        self.conv1 = Conv2d(
            in_channels=n_in_channels, out_channels=n_out_channels,
            kernel_size=(1, 1), stride=stride, bias=False
        )
        self.bn1 = BatchNorm2d(num_features=n_out_channels)

        self.conv2 = Conv2d(
            in_channels=n_out_channels, out_channels=n_out_channels,
            kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
        )
        self.bn2 = BatchNorm2d(num_features=n_out_channels)

        self.conv3 = Conv2d(
            in_channels=n_out_channels, out_channels=(n_out_channels * 4),
            kernel_size=(1, 1), bias=False
        )

        self.projection_conv = Conv2d(
            in_channels=n_in_channels, out_channels=(n_out_channels * 4),
            kernel_size=(1, 1), stride=stride, bias=False
        )

        self.relu = ReLU()

    def forward(self, inputs):
        """Return the output of a forward pass of a ProjectionShortcutV2

        :param inputs: batch of inputs, of shape
         (batch_size, n_in_channels, height, width)
        :type inputs: torch.Tensor
        :return: outputs of a BottleneckBlock, of shape
         (batch_size, n_out_channels * 4, height / 2, width / 2)
        :rtype: torch.Tensor
        """

        preactivation = self.bn_preact(inputs)
        preactivation = self.relu(preactivation)

        layer = self.conv1(preactivation)

        layer = self.bn1(layer)
        layer = self.relu(layer)
        layer = self.conv2(layer)

        layer = self.bn2(layer)
        layer = self.relu(layer)
        layer = self.conv3(layer)

        shortcut = self.projection_conv(preactivation)
        outputs = torch.add(layer, shortcut)

        return outputs

class ResNet(Module):
    """ResNet network

    The version key in the `config` passed to the init should specify one of
    the following:
        - 'original': 'Deep Residual Learning for Image Recognition'
            (https://arxiv.org/abs/1512.03385)
        - 'preactivation': 'Identity Mappings in Deep Residual Networks'
            (https://arxiv.org/abs/1603.05027)
    """

    required_config_keys = {
        'n_channels', 'n_classes', 'n_initial_channels', 'n_blocks_per_stage',
        'version'
    }

    def __init__(self, config):
        """Init

        The `config` must contain the following keys:
        - int n_channels: number of channels of the input
        - int n_classes: number of classes in the output layer
        - int n_initial_channels: number of filters in the initial convolution
          as well as the first residual block; subsequent residual blocks will
          have 2x the filters as the previous residual block
        - list[int] n_blocks_per_stage: iterable holding the number of residual
          blocks to use per residual stage; the length of n_blocks_per_stage
          defines the number of residual stages in the network
        - str version: one of 'original' or 'preactivation'

        :param config: specifies the configuration for the network
        :type config: dict
        """

        super().__init__()

        validate_config(config, self.required_config_keys)
        self.config = config

        self.version = config['version']
        assert self.version in {'original', 'preactivation'}

        self._initialize_layers()
        self._initialize_layer_weights()

        self.n_outputs = 1

    def _initialize_layers(self):
        """Initialize the network's layers used in the forward pass

        This sets the following layers in-place:
        - A general relu used throughout the forward pass
        - Initial conv, bn, and max pooling layers
        - Residual stages, each consisting of a ProjectionShortcut module and
          some number of BottleneckBlock modules. The number of residual stages
          depends on the length of the `n_blocks_per_stage` iterable in
          self.config.
        - Global average pooling layer
        - Final linear layer
        """

        n_initial_channels = self.config['n_initial_channels']
        n_blocks_per_stage = self.config['n_blocks_per_stage']
        n_in_channels = self.config['n_channels']
        n_classes = self.config['n_classes']

        if self.version == 'original':
            BottleneckBlock = BottleneckBlockV1
            ProjectionShortcut = ProjectionShortcutV1
        else:
            BottleneckBlock = BottleneckBlockV2
            ProjectionShortcut = ProjectionShortcutV2

        self.conv = Conv2d(
            in_channels=n_in_channels, out_channels=n_initial_channels,
            kernel_size=(7, 7), stride=(2, 2), padding=(3, 3)
        )
        if self.version == 'original':
            self.bn = BatchNorm2d(num_features=n_initial_channels)
        self.max_pooling = MaxPool2d(kernel_size=(3, 3), stride=(2, 2))

        self.residual_stages = ModuleList()
        n_out_channels = n_initial_channels
        for idx_stage, n_blocks in enumerate(n_blocks_per_stage):
            stage_blocks = ModuleList()

            # Each residual block ends with a conv using 4x the number of
            # n_out_channels, which requires us to adjust n_in_channels to
            # account for that. The exception is when we enter the first
            # residual stage, where the number of channels is simply
            # n_out_channels.
            if idx_stage == 0:
                n_in_channels = n_out_channels
                stride = (1, 1)
            else:
                # Multiply by 2 instead of 4 because at the end of the current
                # iteration of the for loop the `n_out_channels` will be
                # multiplied by 2, which accounts for half of the 4x increase
                # in n_in_channels
                n_in_channels = n_out_channels * 2
                stride = (2, 2)

            stage_blocks.append(ProjectionShortcut(
                n_in_channels, n_out_channels, stride
            ))

            for _ in range(n_blocks - 1):
                # n_in_channels passed to BottleneckBlock needs to be 4x
                # n_out_channels because each ProjectionShortcut ends with a
                # conv using 4x the number of n_out_channels
                stage_blocks.append(BottleneckBlock(
                    n_out_channels * 4, n_out_channels
                ))
            self.residual_stages.append(stage_blocks)

            n_out_channels *= 2
        # Divide n_out_channels by 2 to negate the last multiplication in the
        # for loop that builds the residual stages
        n_out_channels = n_out_channels // 2 * 4

        if self.version == 'preactivation':
            self.bn = BatchNorm2d(num_features=n_out_channels)

        self.average_pooling = AvgPool2d(kernel_size=(7, 7))
        self.linear = Linear(
            in_features=n_out_channels, out_features=n_classes
        )

        self.relu = ReLU()

    def _initialize_layer_weights(self):
        """Initialize the weights of the network's layers

        This follows the initialization strategy in the original paper ('V1
        implementation'), which uses Kaiming / He normal initialization. See
        the module docstring for reference details.
        """

        for module in self.modules():
            if isinstance(module, torch.nn.Conv2d):
                kaiming_normal_(
                    module.weight, mode='fan_out', nonlinearity='relu'
                )
                if module.bias is not None:
                    constant_(module.bias, 0)
            elif isinstance(module, (BatchNorm2d)):
                constant_(module.weight, 1)
                constant_(module.bias, 0)

    def forward(self, inputs):
        """Return the output of a forward pass of the specified ResNet

        :param inputs: batch of input images, of shape
         (batch_size, n_in_channels, height, width)
        :type inputs: torch.Tensor
        :return: outputs of a forward pass of ResNet, of shape
         (batch_size, n_classes)
        :rtype: torch.Tensor
        """

        layer = self.conv(inputs)

        if self.version == 'original':
            layer = self.bn(layer)
            layer = self.relu(layer)
        layer = self.max_pooling(layer)

        for residual_stage in self.residual_stages:
            for residual_block in residual_stage:
                layer = residual_block(layer)

        if self.version == 'preactivation':
            layer = self.bn(layer)
            layer = self.relu(layer)

        layer = self.average_pooling(layer)
        layer = layer.view(layer.size(0), -1)
        outputs = self.linear(layer)

        return outputs


import logging, sys
#logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

import random
import getpass

import netsquid as ns
from netsquid.protocols import NodeProtocol
from netsquid.components import QuantumMemory
import netsquid.components.instructions as instr
import netsquid.util.simtools

class TaskMasterProtocol(NodeProtocol):
	def __init__(self, node, memory_size, cport_name0, qport_name0, cport_name1, qport_name1):
		super().__init__(node)
		self.node = node

		self._qport_name0 = qport_name0
		self._cport_name0 = cport_name0
		self._qport_name1 = qport_name1
		self._cport_name1 = cport_name1

		self.size = memory_size
		self.memory = self.node.qmemory
		self.memory.reset()
		qubit = ns.qubits.create_qubits(self.size)

		self.memory.put(qubit)
		logging.debug('tm: put qubits in memory')

		self.index = random.randint(0, self.size-1)

		self.counter = 0

		logging.debug('tm: init complete')

	def run(self):
		while self.counter < (self.size/2):

			self.counter += 1

			qport0 = self.node.ports[self._qport_name0]
			cport0 = self.node.ports[self._cport_name0]
			qport1 = self.node.ports[self._qport_name1]
			cport1 = self.node.ports[self._cport_name1]

			instr.INSTR_INIT(self.memory, num_positions = self.size)

			#Port forwarding for Player Zero
			port_num = "qin" + str(self.index)
			self.node.qmemory.ports["qout"].forward_output(qport0)
			qport0.forward_input(self.node.qmemory.ports[str(port_num)])

			self.memory.pop(positions=self.index)
			logging.debug('tm: pop qubit index')

			logging.debug("Beforep0: ")
			for i in range(self.size):
				try:
					logging.debug(instr.INSTR_MEASURE_X(self.memory, positions=[i]))
				except:
					logging.debug('None')

			#Wait for return qubit
			logging.debug('tm: waiting for return qubit from p0')
			yield self.await_port_input(qport0)
			logging.debug('tm: recieved return qubit from p0')

			logging.debug("Afterp0: ")
			for i in range(self.size):
				try:
					logging.debug(instr.INSTR_MEASURE_X(self.memory, positions=[i]))
				except:
					logging.debug('None')

			#Send acknowledgement
			cport0.tx_output("Recieved qubit")
			logging.debug('tm: sent the ack signal to p0')

			#Wait for next index
			logging.debug('tm: waiting for the next index from p0')
			yield self.await_port_input(cport0)
			logging.debug('tm: recieved the next index from p0')

			self.index = cport0.rx_input().items[0]

			#-------------------------------------------------------
			#Port forwarding for Player One
			port_num = "qin" + str(self.index)
			self.node.qmemory.ports["qout"].forward_output(qport1)
			qport1.forward_input(self.node.qmemory.ports[str(port_num)])

			self.memory.pop(positions=self.index)
			logging.debug('tm: pop qubit index')

			logging.debug("Beforep1: ")
			for i in range(self.size):
				try:
					logging.debug(instr.INSTR_MEASURE_X(self.memory, positions=[i]))
				except:
					logging.debug('None')

			#Wait for return qubit
			logging.debug('tm: waiting for return qubit from p1')
			yield self.await_port_input(qport1)
			logging.debug('tm: recieved return qubit from p1')

			logging.debug("Afterp1: ")
			for i in range(self.size):
				try:
					logging.debug(instr.INSTR_MEASURE_X(self.memory, positions=[i]))
				except:
					logging.debug('None')

			#Send acknowledgement
			cport1.tx_output("Recieved qubit")
			logging.debug('tm: sent the ack signal to p1')

			#Wait for next index
			logging.debug('tm: waiting for the next index from p1')
			yield self.await_port_input(cport1)
			logging.debug('tm: recieved the next index from p1')

			self.index = cport1.rx_input().items[0]

class PlayerProtocol(NodeProtocol):
	def __init__(self, player_index, memory_size, qport_name, cport_name, node=None, name=None):
		super().__init__(node=node, name=name)
		self._qport_name = qport_name
		self._cport_name = cport_name
		self.memory = self.node.qmemory
		self.tag = "p" + str(player_index)
		self.size = memory_size
		logging.debug(self.tag + ': init complete')

	def run(self):
		while True:
			qport = self.node.ports[self._qport_name]
			cport = self.node.ports[self._cport_name]

			logging.debug(self.tag + ': waiting for input')
			yield self.await_port_input(qport)
			logging.debug(self.tag, ' received', self.memory.peek([0]))

			#Operate on qubit here--------------------------------------------------------------------------------
			operation = None
			ops = ['X','Y','Z','H','K','S','T','I']
			#Ask the player what they want to do with the qubit
			while operation not in ops:
				operation = getpass.getpass(self.tag + " Enter the operation you want to perform on qubit: ").upper()
				if operation not in ops:
					print("Invalid operation. Choose from ", ops)

			instr.INSTR_INIT(self.memory, positions=[0])
			#ns.qubits.operate(qubit, getattr(ns, operation))
			str1 = "INSTR_" + operation
			#implement instr.INSTR_x(self.memory, positions=[0]) || x can be any operation on qubit
			getattr(instr, str1)(self.memory, positions=[0])
			logging.debug(self.memory.measure(0))
			#----------------------------------------------------------------------------------------------------

			self.memory.pop(positions=0)
			logging.debug(self.tag + ': sent the qubit')

			#Wait for acknowledgement signal
			logging.debug(self.tag + ': waiting for ack signal')
			yield self.await_port_input(cport)
			logging.debug(self.tag + ': recieved the ack signal')

			#Send the next index
			next_index = None
			while next_index not in range(0, self.size):
				next_index = int(getpass.getpass("Enter the next index: "))
				if next_index not in range(0, self.size):
					print("Invalid index. Choose between 0 and ", self.size-1)
			self.index = next_index

			cport.tx_output(int(self.index))
			logging.debug(self.tag + ': sent the next index')


from season import Season
from PredictionStats import PredictionStats

year_to_predict = 2017
min_mins_played = 10.0
min_games_played = 20

statsToPredict = PredictionStats.statsToPredictLoop.value
statsToUse = PredictionStats.statsToLoop.value

season_predict = Season()
players = season_predict.calcSeason('season/' + str(year_to_predict) + 'Stats.txt', year_to_predict, min_mins_played, min_games_played)

formulae = []
formulae_rvals = []
formulae_f = open('output/formulae.txt', 'r')
for statPredict in statsToPredict:
  formulae_overall = []
  formulae_rv = 0.0
  for statUse in statsToUse:
    slope, intercept, r_val = map(float, formulae_f.readline().split(' '))
    formulae_overall.append((slope, intercept, r_val))
    formulae_rv += r_val
  formulae.append(formulae_overall)
  formulae_rvals.append(formulae_rv)
formulae_f.close()

for player in players:
  predictionVal = player.name
  player_season = player.getSeason(year_to_predict)
  player_stat_pred = []
  for formulas in range(len(formulae)):
    stat = 0.0
    player_stat = player_season.getStatsByLoopVar( formulas )
    for formula in range(len(formulae[formulas])):
      slope, intercept, r_val = formulae[formulas][formula]
      stat += (float(slope) * float(player_stat) + float(intercept)) * float(r_val) / float(formulae_rvals[formulas])
    #player_stat_pred.append(stat / len(formulae[formulas]))
    player_stat_pred.append(stat)
  for i in range(0, 6):
    predictionVal += ' ' + str(player_stat_pred[i])
  predictionVal += ' ' + str(player_stat_pred[-1])
  print(predictionVal)


import requests

res = requests.get('https://jsonplaceholder.typicode.com/posts')
resp = res.json()
new_dicts = []
for dict_in_resp in resp:
    new = {}
    for k, v in dict_in_resp.items():
        if k in ['id', 'title']:
            new[k] = v
    new_dicts.append(new)

    # new_dict.pop('userId')
    # new_dict.pop('body')


from django.urls import path
from . import views
app_name = 'transaksi'
urlpatterns = [
    path('<str:kodeuser>',views.listkeranjang,name='keranjang'),
    path('buat-transaksi/',views.buattransaksi,name='buat-tansaksi'),
    path('pesanansaya/',views.pesanansaya,name='pesanansaya'),
	path('detailpesanan/<str:kodepesan>',views.detailbarang,name='detailpesanan'),
	path('editkeranjang/<str:kodeuser>',views.edit,name='edit'),
	path('hapuskeranjang/<str:kodeuser>',views.hapuskeranjang,name='hapus-keranjang'),
]


import pygame
import random
import os
pygame.mixer.init()
from pygame.constants import KEYDOWN
pygame.init()
white = (255, 255, 255)
red = (255, 0, 0)
black = (0, 0, 0)
screen_width =1200
screen_height = 500
font = pygame.font.SysFont(None ,55)

gameWindow = pygame.display.set_mode((screen_width,screen_height))
bgimg = pygame.image.load('snake.jpg')
bgimg = pygame.transform.scale(bgimg,(screen_width,screen_height)).convert_alpha()
pygame.display.set_caption("sanpon_ki_nagri")
pygame.display.update()
clock = pygame.time.Clock()
def text_score(text,color,x,y):
        screen_text = font.render(text,True,color)
        gameWindow.blit(screen_text,[x,y])
def plot_snake(gameWindow,color,snk_list,snake_size):
        for x,y in snk_list:
            pygame.draw.rect(gameWindow, color ,[
                        x, y, snake_size, snake_size])

def welcome():
    exit_game=False
    while not exit_game:

        gameWindow.fill(white)
        text_score("Sapon ki Nagri mai apka Swagat hai",black,300,200)
        text_score("Press space to continue",red,350,240)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit_game = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    pygame.mixer.music.load('back.mp3')
                    pygame.mixer.music.play()
                    gameloop()
        pygame.display.update()
        clock.tick(60)

def gameloop():
    snake_x = 45
    snake_y = 55
    snake_size = 10
    exit_game = False
    game_over = False
    fps = 60
    velocity_x = 0
    velocity_y = 0
    food_x = random.randint(20, 1200/2)
    food_y = random.randint(20, 500/2)
    clock = pygame.time.Clock()
    score = 0
    init_velocity = 3

    snk_list = []
    snk_length = 1
    if(not os.path.exists("hiscore.txt")):
        with open("hiscore.txt","w") as f:
            f.write("0")
    with open("hiscore.txt","r") as f:
        hiscore = f.read()

    # game loop
    while not exit_game:

        if game_over:
            with open("hiscore.txt","w") as f:
                f.write(str(hiscore))
            gameWindow.fill(white)
            text_score("gameover! Press enter to continue",red,300,200)
            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    exit_game = True
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        welcome()

        else:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit_game = True

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        velocity_x = init_velocity
                        velocity_y = 0
                    if event.key == pygame.K_LEFT:
                        velocity_x = -init_velocity
                        velocity_y = 0
                    if event.key == pygame.K_UP:
                        velocity_y = - init_velocity
                        velocity_x = 0
                    if event.key == pygame.K_DOWN:
                        velocity_y = init_velocity
                        velocity_x = 0

            snake_x += velocity_x
            snake_y += velocity_y

            if abs(snake_x-food_x)<6 and abs(snake_y-food_y)<6:
                score +=10
                # print("score:",score*10)
                food_x = random.randint(20, 1200/2)
                food_y = random.randint(20, 500/2)
                snk_length +=5
                if score>int(hiscore):
                    hiscore = score

            gameWindow.fill(white)
            gameWindow.blit(bgimg,(0,0))

            text_score("score:"+str(score)+"  hiscore:"+str(hiscore),red,5,5)
            pygame.draw.rect(gameWindow ,red,[food_x, food_y, snake_size,snake_size])

            head =[]
            head.append(snake_x)
            head.append(snake_y)
            snk_list.append(head)

            if len(snk_list)>snk_length:
                del snk_list[0]

            if head in snk_list[:-1]:
                game_over = True
                pygame.mixer.music.load('gameover.mp3')
                pygame.mixer.music.play()

            if snake_x<0 or snake_x>screen_width or snake_y<0 or snake_y>screen_height:
                game_over =True
                pygame.mixer.music.load('gameover.mp3')
                pygame.mixer.music.play()
                print("gameover")
            plot_snake(gameWindow,white,snk_list,snake_size)

        pygame.display.update()
        clock.tick(fps)

    pygame.quit()
    quit()

# gameloop()
welcome()