from core.data_loader import load_data

data = load_data("strategy_guide.txt")

parsed_data = [i.split(" ") for i in data.split("\n") if i != ""]

####################  PART 1  #########################
score = 0

own_score_map = {"X": 1, "Y": 2, "Z": 3}

equiv_map = {"A": "X", "B": "Y", "C": "Z"}

mapped_data = list(map(lambda x: [equiv_map[x[0]], x[1]], parsed_data))

for r in mapped_data:
    score += own_score_map[r[1]]
    if r[0] == r[1]:
        score += 3
    elif r[0] == "X" and r[1] == "Z":
        score += 0
    elif (r[0] == "Z" and r[1] == "X") or r[0] < r[1]:
        score += 6

print(score)

####################  PART 2  ########################

score = 0

own_score_map = {"X": 0, "Y": 3, "Z": 6}

result_map = {"A": {"X": 3, "Y": 1, "Z": 2},
              "B": {"X": 1, "Y": 2, "Z": 3},
              "C": {"X": 2, "Y": 3, "Z": 1}}

for r in parsed_data:
    score += own_score_map[r[1]]
    score += result_map[r[0]][r[1]]

print(score)


import re
from typing import List, Tuple

def part1(inp: List[str]) -> int:
    x, y = 0, 0
    orientation = "E"
    directions = ["N", "E", "S", "W"]
    for n, line in enumerate(inp, 1):
        instruction, magnitude = line[0], int(line[1:])
        if instruction == "N":
            y += magnitude
        elif instruction == "S":
            y -= magnitude
        elif instruction == "E":
            x += magnitude
        elif instruction == "W":
            x -= magnitude
        elif instruction == "F":
            delta = {
                "N": [0, 1],
                "E": [1, 0],
                "S": [0, -1],
                "W": [-1, 0],
            }[orientation]
            x += delta[0] * magnitude
            y += delta[1] * magnitude
        elif instruction == "L":
            assert magnitude in (90, 180, 270), f"Unknown value for turn: {line}"
            orientation = directions[int(directions.index(orientation) - (magnitude / 90))]
        elif instruction == "R":
            assert magnitude in (90, 180, 270), f"Unknown value for turn: {line}"
            orientation = directions[(int(directions.index(orientation) + (magnitude / 90))) % 4]
    return abs(x) + abs(y)

def load_input_file(filename: str):
    with open(filename, "r") as inp:
        return [line.strip() for line in inp.readlines()]

def test_part1():
    inp1 = load_input_file("sample.txt")
    assert part1(inp1) == 25

    inp = load_input_file("input.txt")
    assert part1(inp) == 562

def part2(inp: List[str]) -> int:
    w_x, w_y = 10, 1
    x, y = 0, 0
    for n, line in enumerate(inp, 1):
        instruction, magnitude = line[0], int(line[1:])
        if instruction == "N":
            w_y += magnitude
        elif instruction == "S":
            w_y -= magnitude
        elif instruction == "E":
            w_x += magnitude
        elif instruction == "W":
            w_x -= magnitude
        elif instruction == "F":
            x += w_x * magnitude
            y += w_y * magnitude
        elif instruction == "L":
            assert magnitude in (90, 180, 270), f"Unknown value for turn: {line}"
            turns = int(magnitude / 90)
            if turns == 1:
                w_x, w_y = -w_y, w_x
            elif turns == 2:
                w_x, w_y = -w_x, -w_y
            elif turns == 3:
                w_x, w_y = w_y, -w_x
        elif instruction == "R":
            assert magnitude in (90, 180, 270), f"Unknown value for turn: {line}"
            turns = int(magnitude / 90)
            if turns == 1:
                w_x, w_y = w_y, -w_x
            elif turns == 2:
                w_x, w_y = -w_x, -w_y
            elif turns == 3:
                w_x, w_y = -w_y, w_x
    return abs(x) + abs(y)

def test_part2():
    inp1 = load_input_file("sample.txt")
    assert part2(inp1) == 286

    inp = load_input_file("input.txt")
    assert part2(inp) == 101860


# vim:set fileencoding=utf-8:
from django.db import models
from .. import settings

class RusManager(models.Manager):
    use_for_related_fields = True

    def get_queryset(self):
        return super(RusManager, self).get_queryset().select_related('profile', 'rusclass', 'initial_rusclass', 'profile__user')

class TutorProfileManager(models.Manager):
    use_for_related_fields = True

    def get_queryset(self):
        return super(TutorProfileManager, self).get_queryset()

class TutorManager(models.Manager):
    use_for_related_fields = True

    def get_queryset(self):
        return super(TutorManager, self).get_queryset().select_related('profile', 'profile__user')

class VisibleTutorGroups(models.Manager):
    def get_queryset(self):
        qs = super(VisibleTutorGroups, self).get_queryset()
        return qs.filter(visible=True, tutor__year__in=[settings.YEAR]).distinct()

class RusClassManager(models.Manager):
    def create_from_official(self, year, official_name):
        """Translate (2015, "MA1") into a fresh RusClass object."""
        official_study = official_name[:2]
        number = official_name[2:]
        handle, internal_name = next(
            (handle, internal)
            for official, handle, internal in settings.RUSCLASS_BASE
            if official == official_study
        )
        handle = '%s%s' % (handle, number)
        internal_name = '%s %s' % (internal_name, number)
        return self.model(year=year, official_name=official_name,
                          handle=handle, internal_name=internal_name)

    def create_from_handle(self, year, handle):
        """Translate (2015, "mat1") into a fresh RusClass object."""
        study = handle.rstrip('0123456789')
        number = handle[len(study):]
        try:
            official_name, internal_name = next(
                (official, internal)
                for official, handle_, internal in settings.RUSCLASS_BASE
                if handle_ == study
            )
        except StopIteration:
            raise ValueError("Invalid study %r" % study)
        official = '%s%s' % (official_name, number)
        internal = '%s %s' % (internal_name, number)
        return self.model(year=year, official_name=official,
                          handle=handle, internal_name=internal)


# -*- coding: utf-8 -*-
"""
Created on Thu Apr  4 13:53:49 2019

@author: ncelik34
"""
from tensorflow.keras import backend as K
import numpy as np
import pandas as pd
import os
import sys

# Importing the Keras libraries and packages
import tensorflow as tf
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Dropout
from tensorflow.keras.utils import to_categorical
from sklearn import preprocessing
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import RobustScaler
from sklearn.metrics import confusion_matrix, roc_auc_score, classification_report
import math

batch_size = 256

def mcor(y_true, y_pred):
    # matthews_correlation
    y_pred_pos = K.round(K.clip(y_pred, 0, 1))
    y_pred_neg = 1 - y_pred_pos

    y_pos = K.round(K.clip(y_true, 0, 1))
    y_neg = 1 - y_pos

    tp = K.sum(y_pos * y_pred_pos)
    tn = K.sum(y_neg * y_pred_neg)

    fp = K.sum(y_neg * y_pred_pos)
    fn = K.sum(y_pos * y_pred_neg)

    numerator = (tp * tn - fp * fn)
    denominator = K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))

    return numerator / (denominator + K.epsilon())

def precision(y_true, y_pred):
    """Precision metric.

    Only computes a batch-wise average of precision.

    Computes the precision, a metric for multi-label classification of
    how many selected items are relevant.
    """
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
    precision = true_positives / (predicted_positives + K.epsilon())
    return precision

def recall(y_true, y_pred):
    """Recall metric.

    Only computes a batch-wise average of recall.

    Computes the recall, a metric for multi-label classification of
    how many relevant items are selected.
    """
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
    recall = true_positives / (possible_positives + K.epsilon())
    return recall

def f1(y_true, y_pred):
    def recall(y_true, y_pred):
        """Recall metric.

        Only computes a batch-wise average of recall.

        Computes the recall, a metric for multi-label classification of
        how many relevant items are selected.
        """
        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
        possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
        recall = true_positives / (possible_positives + K.epsilon())
        return recall

    def precision(y_true, y_pred):
        """Precision metric.

        Only computes a batch-wise average of precision.

        Computes the precision, a metric for multi-label classification of
        how many selected items are relevant.
        """
        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
        predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
        precision = true_positives / (predicted_positives + K.epsilon())
        return precision
    precision = precision(y_true, y_pred)
    recall = recall(y_true, y_pred)
    return 2*((precision*recall)/(precision+recall+K.epsilon()))

def auc(y_true, y_pred):
    auc = tf.metrics.auc(y_true, y_pred)[1]
    K.get_session().run(tf.local_variables_initializer())
    return auc

def main(filename, mymodel):
	print(filename)
	df30= pd.read_csv(filename, header=None)
	dataset = df30.values
	dataset = dataset.astype('float64')
	timep = dataset[:, 0]
	maxer = np.amax(dataset[:, 2])
	print(maxer)
	maxeri = maxer.astype('int')
	maxchannels = maxeri
	idataset = dataset[:, 2]
	idataset = idataset.astype(int)

	scaler = MinMaxScaler(feature_range=(0, 1))
	dataset = scaler.fit_transform(dataset)

	train_size = int(len(dataset))

	in_train = dataset[:, 1]
	target_train = idataset
	in_train = in_train.reshape(len(in_train), 1, 1, 1)

	loaded_model = load_model(mymodel, custom_objects={
							  'mcor': mcor, 'precision': precision, 'recall': recall, 'f1': f1, 'auc': auc})

	c = loaded_model.predict(in_train, batch_size=batch_size, verbose=True)
	c=np.argmax(c, axis=-1)
	print (f"dataset shape = {dataset.shape}")
	print (f"c shape = {c.shape}")
	output=np.concatenate((dataset[:,0:2],c.reshape(-1,1)),axis=1)
	lenny = 2000
	ulenny = 5000

	return output

if __name__ == "__main__":
	c=main(filename, mymodel)


x = "awesome"

def myfunc():
        global x
        x = "fantastic"

myfunc()

print("Python is " + x)

value = "Hello"
indexValue = value [0]
print(indexValue)

user_input = input('Enter the numbers')

new_list = user_input.split(',')


import re
import requests as req
import bs4
from bs4 import BeautifulSoup as bs

def HtmlGet(url,code='utf-8'):
    try:
        request=req.get(url)
        request.raise_for_status()
        request.encoding=code
        return request.text
    except:
        return ""

def HtmlAss(li,url):
    html=HtmlGet(url,'GB2312')
    soup=bs4.BeautifulSoup(html,"html.parser")
    l=soup.find_all('a')
    for i in l:
        try:
            href=i.attrs['href']
            st=re.findall(r"[s][hz]\d{6}",href)[0]
            li.append(st)
        except:
            continue
    return li

def HtmlPri(li,fileurl,url):
    count=0
    for i in li:
        url2=url+i+".html"
        html=HtmlGet(url2)
        try:
            if html=="":
                continue
            dic = {}
            list=[]
            soup=bs4.BeautifulSoup(html,"html.parser")
            info=soup.find('div',attrs={'class':'stock-bets'})
            name=info.find_all(attrs={'class':'bets-name'})[0]
            price=info.find_all('strong',attrs={'class':'_close'})[0]
            list.append(name.text.strip().split()[0])
            list.append(price.text)
            dic.update({'股票名称：':str(list)})
            with open(fileurl,'a') as f:
                f.write(str(dic)+'\n')
                count=count+1
                print('\r当前进度：{:.2f}%'.format(count/len(li)),end='')
                f.close()
        except:
            f.close()
            #traceback.print_exc()
def main():
    li=[]
    url="http://quote.eastmoney.com/stocklist.html"
    url2="https://gupiao.baidu.com/stock/"
    fileurl="F:\\t.txt"
    #url2=""
    li=HtmlAss(li,url)
    HtmlPri(li,fileurl,url2)

main()


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

import re
import execjs
import requests

lang_url = 'https://fanyi.baidu.com/langdetect'
index_url = 'https://fanyi.baidu.com/?aldtype=16047'
translate_api = 'https://fanyi.baidu.com/v2transapi'
sess = requests.session()

sess.headers = {
    'Accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh,zh-CN;q=0.9,en-US;q=0.8,en;q=0.7',
    'Connection': 'keep-alive',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Host': 'fanyi.baidu.com',
    'Origin': 'https://fanyi.baidu.com',
    'Referer': 'https://fanyi.baidu.com/',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
    'sec-ch-ua-mobile': '?0',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest'
}

def get_token():
    while 1:
        response = sess.get(url=index_url).text
        print(sess.cookies)

        token = re.findall(r"token: '([0-9a-z]+)", response)
        if token:
            token = token[0]
            break
    return token

def get_sign(query):
    with open('baidu_encrypt.js', 'r', encoding='utf-8') as f:
        baidu_js = f.read()
    sign = execjs.compile(baidu_js).call('e', query)
    print(sign)
    return sign

def get_result(lang, query, sign, token):
    data = {
        'from': lang,
        'to': 'en',
        'query': query,
        'transtype': 'realtime',
        'simple_means_flag': '3',
        'sign': sign,
        'token': token,
    }
    response = sess.post(url=translate_api,data=data)
    print(sess.cookies)

    result = response.json()

    if result.get('errmsg'):
        return '访问出现异常，请重试！'
    dst = result['trans_result']['data'][0]['dst']
    return dst

def trans(query):
    response = sess.post(url=lang_url,data={'query': query})
    try:
        lang = response.json()['lan']
    except:
        print(response.text)
        return
    token = get_token()
    sign = get_sign(query)
    result = get_result(lang, query, sign, token)
    print(result)

if __name__ == '__main__':
    # 百度请求频率高会异常，重试即可
    while 1:
        trans('我早上起床，去河边跑步')
        #trans('I get up in the morning and go running by the river')


import pytz
from django.http import HttpResponse
from django.utils.datetime_safe import datetime
from django.views.decorators.csrf import ensure_csrf_cookie
from gatherer.models import Log
from model_builder.bought_together_builder import recalculate_bought_together_db
from model_builder.user_ratings_builder import update_ratings_for_user

@ensure_csrf_cookie
def log_event(request):
    if request.method == 'POST':
        date = datetime.now(pytz.utc)
        event_type = request.POST['event_type']
        content_id = request.POST['content_id']
        session_id = request.POST['session_id']

        log = Log(
            created=date,
            event_type=event_type,
            content_id=content_id,
            session_id=session_id,
            user_id=request.user.id)\
            .save()

        if request.user.id is not None:
            update_ratings_for_user(request.user.id)

        if event_type == "purchase_event":
            recalculate_bought_together_db()

    else:
        return HttpResponse('Log only possible with a POST request!')

    return HttpResponse('ok')


from django.conf import settings
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView,DetailView, View
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import TemplateView
from django.http.response import JsonResponse
from django.utils import timezone
from django.contrib import messages
import string, random
import stripe
from core.api.CRUD_products import crud_products

from .models import Item, OrderItem, Order, BillingAddress, Payment, Coupon, Refund
from .forms import CheckoutForm, CouponForm, RefundForm

def create_ref_code():
	return ''.join(random.choices(string.ascii_lowercase + string.digits, k=20))

def product(request):
	context = {
		'items': Item.objects.all()
	}
	return render(request, "product.html", context)

def is_valid_form(values):
    valid = True
    for field in values:
        if field == '':
            valid = False
    return valid

class CheckoutView(LoginRequiredMixin, View):
	def get(self, *args, **kwargs):
		# part for the coupon
		try:
			order = Order.objects.get(user=self.request.user, ordered=False)
			# form
			form = CheckoutForm()

			context = {
				'form': form,
				'couponform': CouponForm(), # перевірка купону формою
				'order': order,
				'DISPLAY_COUPON_FORM': True,
			}
			return render(self.request, 'checkout.html', context)

		except ObjectDoesNotExist:
			messages.warning(self.request, "You do not have an active order")
			return redirect('/')
		# end part for the coupon

	def post(self, *args, **kwargs):
		form = CheckoutForm(self.request.POST or NONE)
		try:
			order = Order.objects.get(user=self.request.user, ordered=False)
			# print(self.request.POST)  # в консолі показується вся інфа після підтвердження запиту
			if form.is_valid():
				first_name = form.cleaned_data.get('first_name')
				last_name = form.cleaned_data.get('last_name')
				phone_number = form.cleaned_data.get('phone_number')
				email = form.cleaned_data.get('email')
				city = form.cleaned_data.get('city')
				delivery = form.cleaned_data.get('delivery')
				#TODO: add functionality to this field!!!!!!!!!!!!
				# save_info = form.cleaned_data.get('save_info')
				payment_option = form.cleaned_data.get('payment_option')
				billing_address = BillingAddress(
					user=self.request.user,
					first_name=first_name,
					last_name=last_name,
					phone_number=phone_number,
					email=email,
					city=city,
					delivery=delivery
				)
				billing_address.save()

				order.billing_address = billing_address
				# order.save()
				order.save(update_fields=["billing_address"])

				if payment_option == 'Stripe':
					return redirect('core:payment', payment_option='stripe')
				elif payment_option == 'IPay':
					# !!!!!!!!!!!!!!!!!!!!!!!!!!!! TODO IPay !!!!!!!!!!!!!!!!!!
					return redirect('core:checkout-ipay')

			messages.warning(self.request, "Failed checkout")
			return redirect('core:checkout')

		except ObjectDoesNotExist:
			messages.warning(self.request, "You do not have an active order")
			return redirect('core:order-summary')

# stripe part
class PaymentView(View):
	def get(self, *args, **kwargs):
		order = Order.objects.get(user=self.request.user, ordered=False)
		if order.billing_address:
			context = {
				'order': order,
				'DISPLAY_COUPON_FORM': False,
			}
			return render(self.request, "payment.html", context)
		else:
			messages.warning(
				self.request, "You have not added a billing address")
			return redirect("core:checkout")

	# # should be post? maybe not
	def post(self, *args, **kwargs):
			domain_url = 'https://eshop-django-react.herokuapp.com/payment/stripe/'
			stripe.api_key = settings.STRIPE_SECRET_KEY
			order = Order.objects.get(user=self.request.user, ordered=False)
			amount = int((order.get_total()) * 100)

			try:
				stripe_checkout_session = stripe.checkout.Session.create(
					success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
					cancel_url=domain_url + 'cancelled/',
					payment_method_types=['card'],
					mode='payment',
					line_items=[
						{
							'name': 'Your Order',
							'quantity': 1,
							'currency': 'usd',
							'amount': amount,     # 200 = $2.00
						}
					]
				)

				# create the payment
				payment = Payment()
				payment.stripe_charge_id = stripe_checkout_session['id']
				payment.user = self.request.user
				payment.amount = order.get_total()
				payment.save()

				# assign thee payment to the order

				order_items = order.items.all()
				order_items.update(ordered=True)
				for item in order_items:
					item.save()

				order.ordered = True
				order.payment = payment
				order.ref_code = create_ref_code()
				order.save()

				# remove all from cart

				if order.billing_address:
					context = {
						'order': order,
						'DISPLAY_COUPON_FORM': False,
						'STRIPE_PUBLISHABLE_KEY' : settings.STRIPE_PUBLISHABLE_KEY
					}

				messages.success(self.request, "Your order was successful!")
				return redirect("/")

			except stripe.error.CardError as e:
				body = e.json_body
				err = body.get('error', {})
				messages.warning(self.request, f"{err.get('message')}")
				return redirect("/")

			except stripe.error.RateLimitError as e:
				# Too many requests made to the API too quickly
				messages.warning(self.request, "Rate limit error")
				return redirect("/")

			except stripe.error.InvalidRequestError as e:
				# Invalid parameters were supplied to Stripe's API
				print(e)
				messages.warning(self.request, "Invalid parameters")
				return redirect("/")

			except stripe.error.AuthenticationError as e:
				# Authentication with Stripe's API failed
				# (maybe you changed API keys recently)
				messages.warning(self.request, "Not authenticated")
				return redirect("/")

			except stripe.error.APIConnectionError as e:
				# Network communication with Stripe failed
				messages.warning(self.request, "Network error")
				return redirect("/")

			except stripe.error.StripeError as e:
				# Display a very generic error to the user, and maybe send
				# yourself an email
				messages.warning(
				self.request, "Something went wrong. You were not charged. Please try again.")
				return redirect("/")

			except Exception as e:
				# send an email to ourselves
				messages.warning(
				self.request, "A serious error occurred. We have been notifed.")
				return redirect("/")
			messages.warning(self.request, "Invalid data received")
			return redirect('/payment/stripe/')
# end stripe

def home(request):
	context = {
		'items': Item.objects.all()
	}
	return render(request, "home.html", context)

class HomeView(ListView):
	model = Item
	paginate_by = 10
	template_name = "home.html"

class OrderSummaryView(LoginRequiredMixin, View):   # LoginRequiredMixin перекидає на сторінку входу/реєстрації
	def get(self, *args, **kwargs):
		try:
			order = Order.objects.get(user=self.request.user, ordered=False)
			context = {
				'object': order
			}
			return render(self.request, 'order_summary.html', context)
		except ObjectDoesNotExist:
			messages.warning(self.request, "You do not have an active order")
			return redirect('/')

class ItemDetailView(DetailView):
	model = Item
	template_name = "product.html"

@login_required
def add_to_cart(request, slug):
	item = get_object_or_404(Item, slug=slug)
	order_item, created = OrderItem.objects.get_or_create(
		item=item,
		user=request.user,
		ordered=False,
		)
	order_qs = Order.objects.filter(user=request.user, ordered=False)
	if order_qs.exists():
		order = order_qs[0]
		# check if the order item is in the order
		if order.items.filter(item__slug=item.slug).exists():
			order_item.quantity += 1
			order_item.save()
			messages.info(request, "This item quantity was updated.")
			return redirect("core:order-summary")
		else:
			order_item.quantity == 0
			messages.info(request, "This item was added to your cart.")
			order.items.add(order_item)
			return redirect("core:order-summary")
	else:
		ordered_date = timezone.now()
		order = Order.objects.create(user=request.user, ordered_date=ordered_date)
		order.items.add(order_item)
		messages.info(request, "This item was added to your cart.")
	return redirect("core:order-summary")

@login_required
def remove_from_cart(request, slug):
	item = get_object_or_404(Item, slug=slug)
	order_qs = Order.objects.filter(
		user=request.user,
		ordered=False
	)
	if order_qs.exists():
		order = order_qs[0]
		# check if the order item is in the order
		if order.items.filter(item__slug=item.slug).exists():
			order_item = OrderItem.objects.filter(
				item=item,
				user=request.user,
				ordered=False
			)[0]
			order.items.remove(order_item)
			order_item.delete()
			messages.info(request, "This item was removed from your cart.")
			return redirect("core:order-summary")
		else:
			messages.info(request, "This item was not in your cart")
			return redirect("core:product", slug=slug)
	else:
		messages.info(request, "You do not have an active order")
		return redirect("core:product", slug=slug)

@login_required
def remove_single_item_from_cart(request, slug):
	item = get_object_or_404(Item, slug=slug)
	order_qs = Order.objects.filter(
		user=request.user,
		ordered=False
	)
	if order_qs.exists():
		order = order_qs[0]
		# check if the order item is in the order
		if order.items.filter(item__slug=item.slug).exists():
			order_item = OrderItem.objects.filter(
				item=item,
				user=request.user,
				ordered=False
			)[0]
			if order_item.quantity > 1:
				order_item.quantity -= 1
				order_item.save()
			else:
				order.items.remove(order_item)
			messages.info(request, "This item quantity was updated.")
			return redirect("core:order-summary")
		else:
			messages.info(request, "This item was not in your cart")
			return redirect("core:product", slug=slug)
	else:
		messages.info(request, "You do not have an active order")
		return redirect("core:product", slug=slug)

def get_coupon(request, code):
	try:
		coupon = Coupon.objects.get(code=code)
		return coupon

	except ObjectDoesNotExist:
		messages.info(request, "This coupon does not exists")
		return redirect('code:checkout')

class AddCupounView(View):
	def post(self, *args, **qwargs):
		form = CouponForm(self.request.POST or None)
		if form.is_valid():
			try:
				code = form.cleaned_data.get('code')
				order = Order.objects.get(user=self.request.user, ordered=False)
				order.coupon = get_coupon(self.request, code)
				order.save()
				messages.success(self.request, "Successfully added coupon")
				return redirect("core:checkout")

			except ObjectDoesNotExist:
				messages.info(self.request, "You do not have an active order")
				return redirect('code:checkout')

class RequestRefundView(View):
	def get(self, *args, **qwargs):
		form = RefundForm()
		context = {
			'form': form
		}

		return render(self.request, "request_refund.html", context)

	def post(self, *args, **qwargs):
		form = RefundForm(self.request.POST)
		if form.is_valid():
			ref_code = form.cleaned_data.get('ref_code')
			message = form.cleaned_data.get('message')
			email = form.cleaned_data.get('email')
			# edit the order
			try:
				order = Order.objects.get(ref_code=ref_code)
				order.refund_requested = True   # перевірка чи збігається введений код товару з якимось у базі
				order.save()

				# store the refund
				refund = Refund()
				refund.order = order
				refund.reason = message
				refund.email = email
				refund.save()

				messages.info(self.request, "Your request is received")
				return redirect('core:request-refund')

			except ObjectDoesNotExist:
				messages.info(self.request, "This order does not exist")
				return redirect('core:request-refund')
		else:
			messages.info(self.request, "The form is invalid")
			return redirect('core:request-refund')


# Used Python 3 as for Google Colab
import os
from PIL import ImageOps
from PIL import Image
import numpy as np
from keras import backend
from tensorflow.keras.optimizers import RMSprop
from keras.models import Sequential
from keras.layers import Reshape, Dense, Flatten, Conv2D, Conv2DTranspose
from keras.layers import BatchNormalization, Dropout, LeakyReLU
from keras.constraints import Constraint
from matplotlib import pyplot as plt

"""
This is the Weight Clipping class that is used
in the WGAN layers for Weight Clipping.

@author Preslav Kisyov, influenced by Jason Brownlee
-> https://machinelearningmastery.com/how-to-code-a-wasserstein-generative-adversarial-network-wgan-from-scratch/
"""
class WeightClip(Constraint):

    # The main class method
    #
    # @param c_value The clipping value
    def __init__(self, c_value): self.c_value = c_value

    # The method that is called when clipping
    #
    # @param clipped_weights The weights of the layer
    # @return The newly clipped weights
    def __call__(self, clipped_weights): return backend.clip(clipped_weights, -self.c_value, self.c_value)

    # The config method that defines
    # the name and clipping value name
    def get_config(self):
        return {'name': self.__class__.__name__,
                'c_value': self.c_value}

"""
This is the main model WGAN class
that loads data, defines models and trains them.

Note: The method that saves the model has been removed, so
it does not interfere with any already saved models. This
is only for recreational purposes.

@author Preslav Kisyov, influenced by Jason Brownlee
-> https://machinelearningmastery.com/how-to-code-a-wasserstein-generative-adversarial-network-wgan-from-scratch/
"""
class WGAN:

    # This is the main class method
    # that defines all models and image shape
    def __init__(self):
        self.latent_dim = 100
        self.img_shape = (64, 64, 1) # Define image shape
        self.generator = self.create_generator()
        self.critic = self.create_critic()
        self.model = self.create_model()

    # This methid defines the Generator
    #
    # @return generator The generator model
    def create_generator(self):
        generator = Sequential([
            Dense(128*8*8, input_dim=self.latent_dim),
            Reshape((8, 8, 128)),
            # Upsample from 8x8 to 64x64
            Conv2DTranspose(128, kernel_size=4, strides=2, padding="same"),
            BatchNormalization(),
            LeakyReLU(alpha=0.2),
            Conv2DTranspose(128, kernel_size=4, strides=2, padding="same"),
            BatchNormalization(),
            LeakyReLU(alpha=0.2),
            Dropout(0.2),
            Conv2DTranspose(128, kernel_size=4, strides=2, padding="same"),
            BatchNormalization(),
            LeakyReLU(alpha=0.2),
            Dropout(0.2),
            # Get Output Image
            Conv2D(self.img_shape[-1], kernel_size=5, activation='tanh', padding='same')])
        generator.summary()
        return generator

    # This method defines the Critic/Descriminator
    #
    # @return critic The critic/descriminator model
    def create_critic(self):
        const = WeightClip(0.01)
        critic = Sequential([
            # Downsample from 64x64 to 8x8
            Conv2D(128, kernel_size=4, strides=2, padding='same', kernel_constraint=const, input_shape=self.img_shape),
            BatchNormalization(),
            LeakyReLU(alpha=0.2),
            Dropout(0.25),
            Conv2D(128, kernel_size=4, strides=2, padding='same', kernel_constraint=const, input_shape=self.img_shape),
            BatchNormalization(),
            LeakyReLU(alpha=0.2),
            Dropout(0.25),
            Conv2D(128, kernel_size=4, strides=2, padding='same', kernel_constraint=const, input_shape=self.img_shape),
            BatchNormalization(),
            LeakyReLU(alpha=0.2),
            Dropout(0.25),
            # Get Output
            Flatten(),
            Dense(1)])
        # Compile and return the Critic
        critic.compile(loss = self.wasserstein_loss, optimizer = RMSprop(learning_rate=0.00005))
        critic.summary()
        return critic

    # This method freezes all model layers,
    # except for Batchnormalization
    #
    # @param model The model that has its layers frozen
    def freeze_layers(self, model):
        for l in model.layers:
          if not isinstance(l, BatchNormalization): l.trainable = False

    # This method defines the overall model
    #
    # @return model The overall keras model
    def create_model(self):
        self.freeze_layers(self.critic)
        model = Sequential([
            self.generator,
            self.critic])
        model.compile(loss = self.wasserstein_loss, optimizer=RMSprop(learning_rate=0.00005))
        return model

    # This is the main Train method that trains the Critic/Descriminator
    # and the generator. At the end, it plots the losses.
    #
    # @param path The path to the dataset to be loaded
    # @param critic_steps The amount of iterations for training the Critic every epoch
    # @param training_epochs The amount of training epochs/iterations
    # @param batch The batch size
    def train(self, path, critic_steps = 5, training_epochs = 15000, batch = 64):
        final_critic_loss, final_generator_loss = list(), list()
        data = self.load_data(path)
        batch_samples = int(batch/2)

        # Train the Network
        for epoch in range(training_epochs):
            critic_loss = 0
            # Train the Critic/Descriminator
            for _ in range(critic_steps):
                # Pick random Real Sample and Noise
                real_image = data[np.random.randint(0, data.shape[0], batch_samples)]
                fake_labels = np.ones((batch_samples, 1))
                real_labels = -np.ones((batch_samples, 1))
                # Pick random Fake Smaple and Noise
                noise = np.random.randn(batch_samples * self.latent_dim).reshape(batch_samples, self.latent_dim)
                fake_image = self.generator.predict(noise)  # generator predict
                # Update Critic on Real Image
                real_loss = self.critic.train_on_batch(real_image, real_labels)  # train on real
                fake_lose = self.critic.train_on_batch(fake_image, fake_labels)  # train on fake
                critic_loss = np.add(real_loss, fake_lose) / 2
            # Train the Generator
            noise = np.random.randn(batch * self.latent_dim).reshape(batch, self.latent_dim)
            generator_loss = self.model.train_on_batch(noise, -np.ones((batch, 1)))  # generator train
            final_generator_loss.append(generator_loss)
            final_critic_loss.append(critic_loss)
            print('Epochs: %d/%d, Critic_Loss=%.3f Generator_Loss=%.3f' % (epoch+1, training_epochs, critic_loss, generator_loss))

        self.plot_loss(final_critic_loss, final_generator_loss, training_epochs)
        self.generator.save("trained_model.h5")

    # This method plots the history of losses
    #
    # @param final_critic_loss, final_generator_loss All Generator and Critic losses
    # @param epoch All epochs
    def plot_loss(self, final_critic_loss, final_generator_loss, epoch):
        plt.plot(final_critic_loss, label='Critic Loss')
        plt.plot(final_generator_loss, label='Generator Loss')
        plt.legend()
        plt.savefig('WGAN Loss Plot_%d.png' % (epoch))
        plt.close()

    # This method defines the Wasserstein Loss for the model
    #
    # @param real, fake The real and fake labels
    def wasserstein_loss(self, real, fake): return backend.mean(real * fake)

    # This method loads a dataset of images and prepares
    # them for training
    #
    # @param path The path to the image folder
    # @return X_train The Training vector
    def load_data(self, path):
        X_train = list()
        # Loading from directory
        for im_path in os.listdir(path):
            img = ImageOps.grayscale(Image.open(path+im_path)).resize((self.img_shape[0], self.img_shape[1]), Image.BILINEAR)
            img = Image.fromarray(np.uint8(np.where(np.array(img) > 0, 1, 0)*255))
            X_train.append(np.array(img))
        # Normalizing the data
        X_train = (np.array(X_train).astype(np.float32) - 127.5) / 127.5
        X_train = np.expand_dims(X_train, axis=-1)
        print("Data Shape: "+str(X_train.shape))
        return X_train

# Train WGAN
model = WGAN()
model.train("train/")  # Change the parameter depending on the path


import argparse
import csv
import json
import os
from itertools import chain
from six import string_types

from .work_modules import get_words_by_type, clone_repo_from_github, get_funcs_and_vars_names, get_top_names

def load_outsource_base_from_json():
    with open('outsource.json') as outsource_base:
        return json.load(outsource_base)

def choose_outsource(user_argument, outsource_base):
    url = user_argument[0]
    code_source = None
    for key, value in outsource_base.items():
        if key in url:
            code_source = value
            break
    if code_source == 'github':
        code_source = clone_repo_from_github
    return code_source

def get_existing_projects(all_projects):
    existing_projects = []
    for project in all_projects:
        if os.path.exists(project):
            existing_projects.append(project)
    return set(existing_projects)

def output_to_json_file(content, filepath):
    with open(filepath, 'w') as outfile:
        json.dump(content, outfile, ensure_ascii=False)

def create_parser_for_user_arguments():
    parser = argparse.ArgumentParser(description='Work with funcs names.')
    parser.add_argument('--all_names', action='store_true',
                        required=False, help='Get all vars and funcs names')
    parser.add_argument('--by_type', action='store_true',
                        required=False, help='Get all info by word type.')
    parser.add_argument('--top_names', action='store_true',
                        required=False, help='Get top names ')
    parser.add_argument('-t', '--type', nargs='+',
                        required=False, help='Add word type for search.'
                                             'Avaliable: NN, NNS, VB')
    parser.add_argument('-p', '--projects', nargs='+', required=False,
                        type=str, help='Add projects.')
    parser.add_argument('-d', '--download', nargs='+', required=False,
                        type=str, help='Clone code from outsource')
    parser.add_argument('--data_type', nargs='?', required=False,
                        type=str, help='Funcs or vars search')
    parser.add_argument('--cli', action='store_true',
                        required=False, help='Output to cli')
    parser.add_argument('--json', nargs='?', required=False,
                        type=str, help='Save to json file')
    parser.add_argument('--csv', nargs='?', required=False,
                        type=str, help='Save to csv file')
    return parser.parse_args()

def print_all_names(projects):
    for project in projects:
        print('\nproject: {prj}'.format(prj=project['project']))
        print('funcs names:')
        for func in project['funcs']:
            print('\t', func)
        print('vars names:')
        for var in project['vars']:
            print('\t', var)

def print_top_names(words):
    for word in words:
        print('"{word}" count: {count}'.format(
            word=word, count=words[word]))

def print_by_type(projects):
    for project in projects:
        print('\nproject: {prj}'.format(prj=project['project']))
        print('words in funcs:')
        for func in project['words_in_func']:
            print('\t"{word}" count: {count}'.format(
                word=func, count=project['words_in_func'][func]))
        print('words in vars:')
        for var in project['words_in_vars']:
            print('\t"{word}" count: {count}'.format(
                word=var, count=project['words_in_vars'][var]))

def output_to_csv(content, pathfile):
    # getting by https://github.com/vladikk/JSON2CSV
    with open(pathfile, "w") as pathfile:
        def build_row(dict_obj, keys):
            return [dict_obj.get(k, "") for k in keys]

        keys = sorted(set(chain.from_iterable([o.keys() for o in content])))
        rows = [build_row(d, keys) for d in content]
        cw = csv.writer(pathfile)
        cw.writerow(keys)
        for row in rows:
            cw.writerow([c if isinstance(c, string_types) else c for c in row])

def output_to_cli(content_for_output, content_type):
    if content_type == 'all_names':
        print_all_names(content_for_output)
    if content_type == 'top_names':
        print_top_names(content_for_output)
    if content_type == 'words_counter':
        print_by_type(content_for_output)

def main():
    user_argument = create_parser_for_user_arguments()
    if user_argument.download:
        outsource_base = load_outsource_base_from_json()
        outsource_choice = choose_outsource(user_argument.download,
                                            outsource_base)
        outsource_choice(user_argument.download)
    if user_argument.type:
        word_type = [word.upper() for word in user_argument.type]
        existing_projects = get_existing_projects(user_argument.projects)
        output_choice = user_argument.data_type
        projects_funcs_vars_names = get_funcs_and_vars_names(existing_projects)
        words_counter = get_words_by_type(projects_funcs_vars_names, word_type)
        top_names = get_top_names(projects_funcs_vars_names, output_choice)
        if user_argument.all_names:
            content_to_output = projects_funcs_vars_names
            content_type = 'all_names'
        if user_argument.top_names:
            content_to_output = top_names
            content_type = 'top_names'
        if user_argument.by_type:
            content_to_output = words_counter
            content_type = 'words_counter'
        if user_argument.cli:
            output_to_cli(content_to_output, content_type)
        if user_argument.json:
            output_to_json_file(content_to_output, user_argument.json)
        if user_argument.csv:
            output_to_csv(content_to_output, user_argument.csv)
    else:
        print('No arguments(verb_counter --help)')

if __name__ == '__main__':
    main()


'''9. Γράψτε μια συνάρτηση η οποία να ονομάζεται maxSequence η οποία να παίρνει σαν είσοδο μία λίστα και να επιστρέφει την υπολίστα (συνεχόμενα στοιχεία μέσα στη λίστα) που έχει το μέγιστο άθροισμα.
Παράδειγμα: maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) επιστρέφει 6: [4, -1, 2, 1] '''

def maxSequence(ls):
    if len(ls) == 0:
       raise Exception("Array empty") # should be non-empty

    runSum = maxSum = ls[0]
    i = 0
    start = finish = 0

    for j in range(1, len(ls)):
        if ls[j] > (runSum + ls[j]):
            runSum = ls[j]
            i = j
        else:
            runSum += ls[j]

        if runSum > maxSum:
            maxSum = runSum
            start = i
            finish = j
            global start1
            global finish1
            start1=start
            finish1=finish

    maxsequencenumbs=[]
    for p in range(start, finish+1):
       maxsequencenumbs.append(ls[p])
    print ("Τhe maxSequence total is", maxSum)
    print ("the maxSequence numbers",maxsequencenumbs)

maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])


import sys
import pygame
import time

BLACK = 0,0,0

######
#
#   Sprite Classes
#
######

class Player(pygame.sprite.Sprite):
    def __init__(self, xCoord, yCoord):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("/assets/player.jpg")
        self.rect = self.image.get_rect()
        self.rect.x = xCoord
        self.rect.y = yCoord
        self.dx = 0
        self.lives = 5

    def update(self):
        self.rect.x += self.dx

        if self.rect.left < 0 or self.rect.right > width:
            self.stop()

    def get_rect(self):
        return self.rect

    def go_left(self):
        self.dx = -5

    def go_right(self):
        self.dx = 5

    def stop(self):
        self.dx = 0

class Laser(pygame.sprite.Sprite):
    def __init__(self, start_X, start_y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("/assets/laser.jpg")
        self.rect = self.image.get_rect()
        self.rect.x = start_X
        self.rect.y = start_y
        self.dy = -20
        self.damage = 10

    def update(self):
        self.rect.y += self.dy

        if self.rect.top < 0 or self.rect.bottom > height + 50:
           self.kill()

class Minion(pygame.sprite.Sprite):
    def __init__(self, start_X, start_Y):
        super().__init__()

        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("/assets/minion.jpg")
        self.rect = self.image.get_rect()
        self.rect.x = start_X
        self.rect.y = start_Y
        self.dx = 0
        self.dy = 0
        self.health = 25

    def check_alive(self):
        if self.health > 0:
            return True
        else:
            return False

######
#
#   Main game loop
#
######

def spawn_minions(amount):
    count = 0
    row_count = 0
    column_count = 0

    while count < amount:
        if column_count > 5:
            column_count = 0
            row_count += 1

        xCoord = (25 + (75 * column_count))  # spaces each minion out by 75 pixels into 5 columns
        yCoord = (100 * row_count)

        new_minion = Minion(xCoord, yCoord)
        all_sprite_list.add(new_minion)
        enemy_sprite_list.add(new_minion)
        count += 1
        column_count += 1

def player_fire_laser(curtime, all_sprites, player_lasers, placement):
    shot_time = pygame.time.get_ticks()
    #   Checks to see if 500 ms has passed between shots
    if shot_time - cur_time > 500:
        #   shoots laser from other side of ship
        if placement == 1:
            new_laser = Laser((player.rect.x + 15), player.rect.y)
            all_sprites.add(new_laser)
            player_lasers.add(new_laser)
            placement *= -1

        else:
            new_laser = Laser((player.rect.x + 35), player.rect.y)
            all_sprite_list.add(new_laser)
            player_laser_list.add(new_laser)
            placement *= -1

pygame.init()

#   Sprite groups
all_sprite_list = pygame.sprite.Group()
enemy_sprite_list = pygame.sprite.Group()
player_laser_list = pygame.sprite.Group()
enemy_laser_list = pygame.sprite.Group()

#   Sprites
player = Player(220, 600)
all_sprite_list.add(player)

size = width, height = 500, 750
screen = pygame.display.set_mode(size)
cur_time = pygame.time.get_ticks()
shot_placement = 1

spawn_minions(18)

# Animation loop
while True:
    clock = pygame.time.Clock()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

#   Checks key presses
        if event.type == pygame.KEYDOWN:

# -------------- Player presses shoot --------------
            if event.key == pygame.K_SPACE:
                player_fire_laser(cur_time, all_sprite_list, player_laser_list, shot_placement)
                #   Switches side of the ship laser is fired from
                shot_placement *= -1
# -------------- End shooting loop ---------------------

            if event.key == pygame.K_RIGHT:
                player.go_right()
            if event.key == pygame.K_LEFT:
                player.go_left()

        #   Checks for key release
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                player.stop()

#   Animate everything on screen
    all_sprite_list.update()

#   Checks collision between player lasers and enemy sprites
    for laser in player_laser_list:
        block_hit_list = pygame.sprite.spritecollide(laser, enemy_sprite_list, True)

        for each in block_hit_list:
            each.health -= laser.damage

#   Checks if the enemy minion's health is low enough to remove it from the screen and the game
            if each.health <= 0:
                all_sprite_list.remove(each)
                player_laser_list.remove(laser)
                all_sprite_list.remove(laser)

            all_sprite_list.remove(laser)
            player_laser_list.remove(laser)

        if laser.rect.y < -50:
            player_laser_list.remove(laser)
            all_sprite_list.remove(laser)

    screen.fill(BLACK)
    all_sprite_list.draw(screen)
    clock.tick(120)
    pygame.display.flip()


#!/usr/bin/env python

import rospy

from pygraph.classes.graph import graph
from pygraph.classes.exceptions import NodeUnreachable
from pygraph.algorithms.heuristics.euclidean import euclidean
from pygraph.algorithms.minmax import heuristic_search

from math import sqrt
from random import uniform

#=============================== YOUR CODE HERE ===============================
# Instructions: complete the currently empty RandomizedRoadmapPlanner class.
#               An instance of this class will be created by the path_planner
#               node. It should maintain a graph of points and the connections
#               between them.
#               The 'plan()' function should find a path between the requested
#               points, inserting new nodes and edges if necessary. Make sure
#               that it stops at some point in time if no path between the
#               points exists.
#
# Remark: it will be necessary to test points and line segments for emptiness.
#         The class is (as usual) ROS-independent, so the actual mechanism of
#         performing these tests is abstracted by two callback functions, which
#         the object receives during the construction. In order to test whether
#         e.g. the point (1, 4) is free you should do:
#
#             free = self.point_free_cb((1, 4))
#
# Hint: use the standard function 'math.uniform()' to generate the coordinates
#       for random points.
#
# Hint: if you decided to use 'pygraph' library for graph and search
#       implementations, make sure that the graph object is stored in a member
#       field called 'graph'. If this is the case, the nodes and edges of the
#       graph will be automatically visualized by the path_planner node after
#       each planning request.

class RandomizedRoadmapPlanner:

    def __init__(self, point_free_cb, line_free_cb, dimensions):
        """
        Construct a randomized roadmap planner.

        'point_free_cb' is a function that accepts a point (two-tuple) and
        outputs a boolean value indicating whether the point is in free space.

        'line_free_cb' is a function that accepts two points (the start and the
        end of a line segment) and outputs a boolen value indicating whether
        the line segment is free from obstacles.

        'dimensions' is a tuple of tuples that define the x and y dimensions of
        the world, e.g. ((-8, 8), (-8, 8)). It should be used when generating
        random points.
        """
        self.point_free_cb = point_free_cb
        self.line_free_cb = line_free_cb
        self.dimensions = dimensions

        self.search_algorithm = euclidean()
        self.number_of_trials = 500
        self.search_result = False
        self.output_path = None
        self.id_generator = 10000
        self.graph = graph()

    def next_id(self):
        self.id_generator=self.id_generator+1
        return self.id_generator

    def is_valid_points(self, point1, point2):
        return self.point_free_cb(point1) and self.point_free_cb(point2)

    def plan(self, point1, point2):
        """
        Plan a path which connects the two given 2D points.

        The points are represented by tuples of two numbers (x, y).

        Return a list of tuples where each tuple represents a point in the
        planned path, the first point is the start point, and the last point is
        the end point. If the planning algorithm failed the returned list
        should be empty.
        """
        #reset number of trials
        self.number_of_trials = 50

        self.search_result = False
        self.output_path = list()
        start_node_id = self.next_id()
        end_node_id = self.next_id()

        if not self.is_valid_points(point1, point2):
            rospy.logwarn(self.__class__.__name__ + ": invalid points")
            return self.output_path #return empty list
        else:
            # add point1, point2 to the graph
            self.graph.add_node(start_node_id, attrs=[('position', point1)])
            self.graph.add_node(end_node_id, attrs=[('position', point2)])

            # connect point1, point2
            if self.line_free_cb(point1, point2):
                edge_weight = sqrt(pow(point1[0] - point2[0], 2) + pow(point1[1] - point2[1], 2))
                self.graph.add_edge((start_node_id, end_node_id), wt = edge_weight)

            # add more edges between point1, point2 and the rest of graph
            for temp_id, attr in self.graph.node_attr.iteritems():
                # 'temp_id' contains node temp_id, 'attr' contains array of attributes
                temp_position = attr[0][1]
                if point1 != temp_position and self.line_free_cb(point1, temp_position):
                    edge_weight = sqrt(pow(point1[0] - temp_position[0], 2) + pow(point1[1] - temp_position[1], 2))
                    self.graph.add_edge((start_node_id, temp_id), wt = edge_weight)

                if point2 != temp_position and self.line_free_cb(point2, temp_position):
                    edge_weight = sqrt(pow(point2[0] - temp_position[0], 2) + pow(point2[1] - temp_position[1], 2))
                    self.graph.add_edge((end_node_id, temp_id), wt = edge_weight)

        while not self.search_result and self.number_of_trials > 0:
            try:
                #find a path (sequence of node ids) between start and end
                self.search_algorithm.optimize(self.graph)
                node_ids = heuristic_search(self.graph, start_node_id, end_node_id, self.search_algorithm)

                for temp_id in node_ids:
                    node_position = self.graph.node_attributes(temp_id)
                    self.output_path.append(node_position[0][1])

                self.search_result = True

            except NodeUnreachable:
                # create a random point if there is no path
                x = uniform(self.dimensions[0][0] , self.dimensions[0][1])
                y = uniform(self.dimensions[1][0] , self.dimensions[1][1])
                new_point_position = (x , y)
                # add the new point to graph
                if self.point_free_cb(new_point_position):
                    new_point_id = self.next_id()
                    self.graph.add_node(new_point_id, attrs=[('position', new_point_position)])
                    # connect the new_point with older nodes
                    for temp_id, attr in self.graph.node_attr.iteritems():
                        temp_position = attr[0][1]
                        if new_point_position != temp_position and self.line_free_cb(new_point_position, temp_position):
                            edge_weight = sqrt(pow(new_point_position[0] - temp_position[0], 2) + pow(new_point_position[1] - temp_position[1], 2))
                            self.graph.add_edge((new_point_id, temp_id), wt = edge_weight)

            # decrease number of trials
            self.number_of_trials = self.number_of_trials-1

        return self.output_path

    def remove_edge(self, point1, point2):
        """
        Remove the edge of the graph that connects the two given 2D points.

        The points are represented by tuples of two numbers (x, y).

        Has an effect only if both points have a corresponding node in the
        graph and if those nodes are connected by an edge.
        """
        found_node1=False
        found_node2=False
        # search for nodes in graph
        for temp_node_id, attr in self.graph.node_attr.iteritems():
            temp_position = attr[0][1]
            if(point1 == temp_position):
                node1 = temp_node_id;
                found_node1=True
            elif(point2 == temp_position):
                node2 = temp_node_id;
                found_node2=True
            if(found_node1 and found_node2):
                break
        #delete edge if there is an edge that connects the 2 nodes
        if(found_node1 and found_node2 and self.graph.has_edge((node1,node2))):
            self.graph.del_edge((node1,node2));


def getProbability(x, y):
    if x in range(l,r+1) and y in range(u,d+1):
        return 0
    if (x, y) in dp:
        return dp[x,y]
    else:
        if x == w and y == h:
            return 1
        if x == w:
            dp[x,y] = getProbability(x,y+1)
            return dp[x,y]
        if y == h:
            dp[x,y] = getProbability(x+1,y)
            return dp[x,y]
        dp[x,y] = (getProbability(x,y+1) + getProbability(x+1,y))/2
        return dp[x,y]

tests = int(input())
for t in range(tests):
    aux = list(map(int, input().split()))
    dp, w, h, l, u, r, d = {}, aux[0], aux[1], aux[2], aux[3], aux[4], aux[5]
    if (l == 1 and r == w) or (u == 1 and d == h):
        print('Case #', t+1, ': 0.0', sep='')
        continue
    ans = getProbability(1, 1)
    print('Case #', t+1, ': ', float(ans), sep='')


st=input().strip()
n=int(st.split(' ')[0])
l=[int(i) for i in input().strip().split(' ')]
k=int(st.split(' ')[1])
x=count=0
for i in l:
    x+=1
    for j in range(x,len(l),1):
        if (i+l[j])%k ==0:
            count+=1

print(count)


import pandas as pd
import os
import numpy as np
import warnings
import math
warnings.filterwarnings("ignore")
import logging
import sys
# setup logging
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger('Processing CCLE Multiomics data')
file_path = os.path.dirname(os.path.realpath(__file__))
# Load DepMap mapping file
map = pd.read_csv(str(file_path+'/CCLE_Multiomics_Data/sample_info.csv')) # Mapping file downloaded from DepMap
map_imp_id = pd.read_csv(str(file_path+ '/samples.csv')) # Mapping file from Sara Gosline's git repo
map_imp_id = map_imp_id[map_imp_id['id_source'] == 'DepMap'].reset_index(drop=True) # filtering id source as DepMap
ind_imp_id = np.where(pd.isna(map['RRID'])==True)[0] # Indices where RRID = NaN
#Assign improve ids to map file with missing RRID
for ind in ind_imp_id:
    ind2 = np.where(map_imp_id['other_id']==map['DepMap_ID'][ind])[0]
    if len(ind2)!=0:
        map['RRID'][ind] = map_imp_id['improve_sample_id'][ind2].values[0]
map = map.dropna(subset = ['RRID']).reset_index(drop=True) # Remove rows where RRID/Improve_id == NaN
# Some DepMap IDs in this mapping file is mapped to the same RRIDs. Manual changes to address this issue:
cl_rm = ['ACH-001189','ACH-001024', 'ACH-002222', 'ACH-002260'] #cell-lines to be removed
for cl in cl_rm:
    map = map[map.DepMap_ID != cl].reset_index(drop=True)

# Load entrz id-gene symbol mapping file for copy number and gene expression files
path = file_path+'/Maps/eg_gs_map_cn_ge.csv'
eg_gs = pd.read_csv(path).drop(columns={'Unnamed: 0'})
eg_gs = eg_gs.astype({'old_entrez_id': str})
eg_gs_map = dict(zip(eg_gs.old_entrez_id, eg_gs.en2gs_GS )) # Mapping dictionary
eg_ens_map = dict(zip(eg_gs.old_entrez_id, eg_gs.ens_id )) # Mapping dictionary

#########Copy number data - WES#############
logger.info('Processing Copy number WES data')
path = str(file_path +'/CCLE_Multiomics_Data/CCLE_wes_gene_cn.csv')
cn_file = pd.read_csv(path)
cn_file=cn_file.rename(columns={'Unnamed: 0':'DepMap_ID'})
# Map Entrenz gene id to new gene symbols and replace old gene symbols
genes = list(cn_file.columns[1:])
gs = []
es = []
col_ind = []
for gene in genes: #Separating column header into gene symbols and entrenz ids
    es.append(gene.split('(', 1)[1].split(')')[0])
    gs.append(gene.split(' ', 1)[0])
    col_ind.append(cn_file.columns.get_loc(gene))
es_gs = pd.DataFrame({'gene_symbol':gs, 'entrenz_id':es, 'col_ind':col_ind})
ind = np.where(es_gs['entrenz_id']=='nan')[0]
cn_file = cn_file.drop(cn_file.columns[ind+1], axis=1) # Drop columns where entrenz_id = nan
genes = list(cn_file.columns[1:])
gs = []
es = []
col_ind = []
for gene in genes: #Separating column header into gene symbols and entrenz ids
    es.append(gene.split('(', 1)[1].split(')')[0])
    gs.append(gene.split(' ', 1)[0])
    col_ind.append(cn_file.columns.get_loc(gene))
es_gs2 = pd.DataFrame({'gene_symbol':gs, 'entrenz_id':es, 'col_ind':col_ind})
#es_gs2 = es_gs[es_gs.entrenz_id!='nan'].reset_index(drop=True)

# Several Entrenz gene ids are repeating. So we need to remove columns corresponding to wrong entrenz id
dup_ind = np.where(es_gs2.duplicated(subset = ['entrenz_id'], keep=False)==True)[0]
es_gs_dup = es_gs2.iloc[dup_ind].reset_index(drop=True)
es_gs_dup['gs_map'] = es_gs_dup['entrenz_id'].map(eg_gs_map)
ind_drop = np.where((es_gs_dup['gene_symbol'] == es_gs_dup['gs_map'])==False)[0]
col_drop = es_gs_dup['col_ind'][ind_drop]
cn_file = cn_file.drop(cn_file.columns[col_drop], axis=1)
es_gs2 = es_gs2.drop(np.where(es_gs2['col_ind'].isin(col_drop)==True)[0]).reset_index(drop=True)

#mapping eg to gs and eg to ens_id
new_gs = es_gs2['entrenz_id'].map(eg_gs_map)
new_ens_id = es_gs2['entrenz_id'].map(eg_ens_map)
es_gs2['New_gene_symbol'] = new_gs
es_gs2['New_ensembl_id'] = new_ens_id
ind = np.where(pd.isna(new_gs)==True)[0] #index to drop columns
cn_file = cn_file.drop(cn_file.columns[ind+1], axis=1) # Drop columns where entrenz_id cannot be mapped to a gene symbol
es_gs2 = es_gs2.dropna(subset=['New_gene_symbol'])
# Add the new gene symbols to the data file
cn_file.columns = ['DepMap_ID']+list(es_gs2['entrenz_id'])
new_row1 = pd.DataFrame([['']+list(es_gs2['New_gene_symbol'])],columns = cn_file.columns )
new_row2 = pd.DataFrame([['']+list(es_gs2['New_ensembl_id'])],columns = cn_file.columns )
cn_file = pd.concat([new_row1, new_row2, cn_file]).reset_index(drop = True)
#Map DepMap ID with RRID
cn_file.insert(loc=0, column='RRID', value=['' for i in range(cn_file.shape[0])])
col = cn_file.columns
rows = [cn_file.iloc[0].values]
rows.append(list(cn_file.iloc[1].values))
for i in range(len(map)):
    id = np.where(cn_file['DepMap_ID']==map['DepMap_ID'][i])
    if len(id[0])!=0:
        row_append = cn_file.iloc[id[0][0]]
        row_append['RRID'] = map['RRID'][i]
        rows.append(list(row_append.values))
cn_file_new = pd.DataFrame(rows, columns = col)
cn_file_new = cn_file_new.drop(columns = ['DepMap_ID'])
cn_file_new = cn_file_new.drop_duplicates().reset_index(drop=True) # Remove duplicate rows
cn_file_new.to_csv(str(file_path+'/Curated_CCLE_Multiomics_files/CCLE_AID_wes_gene_cn.csv'),index=False)
# Binary copy number
# deep del < 0.5210507 < het loss < 0.7311832 < diploid < 1.214125 < gain < 1.422233 < amp
cn_file_new_b = cn_file_new.drop(columns = ['RRID'])
cn_file_new_b = cn_file_new_b.drop([0,1])
cn_file_new_b[cn_file_new_b <= 0.5210507] = -2
cn_file_new_b[(cn_file_new_b > 0.5210507) &  (cn_file_new_b <= 0.7311832)] = -1
cn_file_new_b[(cn_file_new_b > 0.7311832) &  (cn_file_new_b <= 1.214125)] = 0
cn_file_new_b[(cn_file_new_b > 1.214125) &  (cn_file_new_b <= 1.422233)] = 1
cn_file_new_b[cn_file_new_b > 1.422233] = 2
cn_file_new_b.insert(column = 'RRID', loc=0, value = cn_file_new['RRID'][2:])
cn_file_new_b = pd.concat([cn_file_new[0:2], cn_file_new_b])
cn_file_new_b.to_csv(str(file_path+'/Curated_CCLE_Multiomics_files/CCLE_AID_wes_gene_cn_discretized.csv'),index=False)

#########Copy number data - gene#############
logger.info('Processing Copy number gene data')
path = str(file_path +'/CCLE_Multiomics_Data/CCLE_gene_cn.csv')
cn_file = pd.read_csv(path)
cn_file=cn_file.rename(columns={'Unnamed: 0':'DepMap_ID'})
# Map Entrenz gene id to new gene symbols and replace old gene symbols
genes = list(cn_file.columns[1:])
gs = []
es = []
col_ind = []
for gene in genes: #Separating column header into gene symbols and entrenz ids
    es.append(gene.split('(', 1)[1].split(')')[0])
    gs.append(gene.split(' ', 1)[0])
    col_ind.append(cn_file.columns.get_loc(gene))
es_gs = pd.DataFrame({'gene_symbol':gs, 'entrenz_id':es, 'col_ind':col_ind})
ind = np.where(es_gs['entrenz_id']=='nan')[0]
cn_file = cn_file.drop(cn_file.columns[ind+1], axis=1) # Drop columns where entrenz_id = nan
genes = list(cn_file.columns[1:])
gs = []
es = []
col_ind = []
for gene in genes: #Separating column header into gene symbols and entrenz ids
    es.append(gene.split('(', 1)[1].split(')')[0])
    gs.append(gene.split(' ', 1)[0])
    col_ind.append(cn_file.columns.get_loc(gene))
es_gs2 = pd.DataFrame({'gene_symbol':gs, 'entrenz_id':es, 'col_ind':col_ind})
#es_gs2 = es_gs[es_gs.entrenz_id!='nan'].reset_index(drop=True)

# Several Entrenz gene ids are repeating. So we need to remove columns corresponding to wrong entrenz id
dup_ind = np.where(es_gs2.duplicated(subset = ['entrenz_id'], keep=False)==True)[0]
es_gs_dup = es_gs2.iloc[dup_ind].reset_index(drop=True)
es_gs_dup['gs_map'] = es_gs_dup['entrenz_id'].map(eg_gs_map)
ind_drop = np.where((es_gs_dup['gene_symbol'] == es_gs_dup['gs_map'])==False)[0]
col_drop = es_gs_dup['col_ind'][ind_drop]
cn_file = cn_file.drop(cn_file.columns[col_drop], axis=1)
es_gs2 = es_gs2.drop(np.where(es_gs2['col_ind'].isin(col_drop)==True)[0]).reset_index(drop=True)

#mapping eg to gs
new_gs = es_gs2['entrenz_id'].map(eg_gs_map)
new_ens_id = es_gs2['entrenz_id'].map(eg_ens_map)
es_gs2['New_gene_symbol'] = new_gs
es_gs2['New_ensembl_id'] = new_ens_id
ind = np.where(pd.isna(new_gs)==True)[0] #index to drop columns
cn_file = cn_file.drop(cn_file.columns[ind+1], axis=1) # Drop columns where entrenz_id cannot be mapped to a gene symbol
es_gs2 = es_gs2.dropna(subset=['New_gene_symbol'])
# Add the new gene symbols to the data file
cn_file.columns = ['DepMap_ID']+list(es_gs2['entrenz_id'])
new_row1 = pd.DataFrame([['']+list(es_gs2['New_gene_symbol'])],columns = cn_file.columns )
new_row2 = pd.DataFrame([['']+list(es_gs2['New_ensembl_id'])],columns = cn_file.columns )
cn_file = pd.concat([new_row1, new_row2, cn_file]).reset_index(drop = True)
#Map DepMap ID with RRID/Improve ID
cn_file.insert(loc=0, column='RRID', value=['' for i in range(cn_file.shape[0])])
col = cn_file.columns
rows = [cn_file.iloc[0].values]
rows.append(list(cn_file.iloc[1].values))
for i in range(len(map)):
    id = np.where(cn_file['DepMap_ID']==map['DepMap_ID'][i])
    if len(id[0])!=0:
        row_append = cn_file.iloc[id[0][0]]
        row_append['RRID'] = map['RRID'][i]
        rows.append(list(row_append.values))
cn_file_new = pd.DataFrame(rows, columns = col)
cn_file_new = cn_file_new.drop(columns = ['DepMap_ID'])
cn_file_new = cn_file_new.drop_duplicates().reset_index(drop=True) # Remove duplicate rows
cn_file_new.to_csv(str(file_path+'/Curated_CCLE_Multiomics_files/CCLE_AID_gene_cn.csv'),index=False)
# Binary copy number
# deep del < 0.5210507 < het loss < 0.7311832 < diploid < 1.214125 < gain < 1.422233 < amp
cn_file_new_b = cn_file_new.drop(columns = ['RRID'])
cn_file_new_b = cn_file_new_b.drop([0,1])
cn_file_new_b[cn_file_new_b <= 0.5210507] = -2
cn_file_new_b[(cn_file_new_b > 0.5210507) &  (cn_file_new_b <= 0.7311832)] = -1
cn_file_new_b[(cn_file_new_b > 0.7311832) &  (cn_file_new_b <= 1.214125)] = 0
cn_file_new_b[(cn_file_new_b > 1.214125) &  (cn_file_new_b <= 1.422233)] = 1
cn_file_new_b[cn_file_new_b > 1.422233] = 2
cn_file_new_b.insert(column = 'RRID', loc=0, value = cn_file_new['RRID'][2:])
cn_file_new_b = pd.concat([cn_file_new[0:2], cn_file_new_b])
cn_file_new_b.to_csv(str(file_path+'/Curated_CCLE_Multiomics_files/CCLE_AID_gene_cn_discretized.csv'),index=False)

######### Gene expression #############
logger.info('Processing gene expression data V1')
path = str(file_path +'/CCLE_Multiomics_Data/CCLE_expression.csv')
ge_file = pd.read_csv(path)
ge_file=ge_file.rename(columns={'Unnamed: 0':'DepMap_ID'})
# Map Entrenz gene id to new gene symbols and replace old gene symbols
genes = list(ge_file.columns[1:])
gs = []
es = []
col_ind = []
for gene in genes: #Separating column header into gene symbols and entrenz ids
    es.append(gene.split('(', 1)[1].split(')')[0])
    gs.append(gene.split(' ', 1)[0])
    col_ind.append(ge_file.columns.get_loc(gene))
es_gs = pd.DataFrame({'gene_symbol':gs, 'entrenz_id':es, 'col_ind':col_ind})
ind = np.where(es_gs['entrenz_id']=='nan')[0]
ge_file = ge_file.drop(ge_file.columns[ind+1], axis=1) # Drop columns where entrenz_id = nan
es_gs2 = es_gs[es_gs.entrenz_id!='nan'].reset_index(drop=True)

# Several Entrenz gene ids are repeating. So we need to remove columns corresponding to wrong entrenz id
dup_ind = np.where(es_gs2.duplicated(subset = ['entrenz_id'], keep=False)==True)[0]
es_gs_dup = es_gs2.iloc[dup_ind].reset_index(drop=True)
es_gs_dup['gs_map'] = es_gs_dup['entrenz_id'].map(eg_gs_map)
ind_drop = np.where((es_gs_dup['gene_symbol'] == es_gs_dup['gs_map'])==False)[0]
col_drop = es_gs_dup['col_ind'][ind_drop]
ge_file = ge_file.drop(ge_file.columns[col_drop], axis=1)
es_gs2 = es_gs2.drop(np.where(es_gs2['col_ind'].isin(col_drop)==True)[0]).reset_index(drop=True)

#mapping eg to gs
new_gs = es_gs2['entrenz_id'].map(eg_gs_map)
new_ens_id = es_gs2['entrenz_id'].map(eg_ens_map)
es_gs2['New_gene_symbol'] = new_gs
es_gs2['New_ensembl_id'] = new_ens_id
ind = np.where(pd.isna(new_gs)==True)[0] #index to drop columns
ge_file = ge_file.drop(ge_file.columns[ind+1], axis=1) # Drop columns where entrenz_id cannot be mapped to a gene symbol
es_gs2 = es_gs2.dropna(subset=['New_gene_symbol'])
# Add the new gene symbols to the data file
ge_file.columns = ['DepMap_ID']+list(es_gs2['entrenz_id'])
new_row1 = pd.DataFrame([['']+list(es_gs2['New_gene_symbol'])],columns = ge_file.columns )
new_row2 = pd.DataFrame([['']+list(es_gs2['New_ensembl_id'])],columns = ge_file.columns )
ge_file = pd.concat([new_row1, new_row2, ge_file]).reset_index(drop = True)
#Map DepMap ID with RRID
ge_file.insert(loc=0, column='RRID', value=['' for i in range(ge_file.shape[0])])
col = ge_file.columns
rows = [ge_file.iloc[0].values]
rows.append(list(ge_file.iloc[1].values))
for i in range(len(map)):
    id = np.where(ge_file['DepMap_ID']==map['DepMap_ID'][i])
    if len(id[0])!=0:
        row_append = ge_file.iloc[id[0][0]]
        row_append['RRID'] = map['RRID'][i]
        rows.append(list(row_append.values))
ge_file_new = pd.DataFrame(rows, columns = col)
ge_file_new = ge_file_new.drop(columns = ['DepMap_ID'])
ge_file_new = ge_file_new.drop_duplicates().reset_index(drop=True) # Remove duplicate rows
ge_file_new.to_csv(str(file_path+'/Curated_CCLE_Multiomics_files/CCLE_AID_expression.csv'),index=False)

############ Gene expression - scaled rows ############
#Since several cell lines have total TPM values significantly less than 1 million,
#we need to generate another version of gene expression data such that each row/cell-line is scaled by a factor
#that makes the total TPM for the cell-line to be 1 million.
#Check Gene TPM
logger.info('Processing gene expression scaled data')
ge_copy = ge_file_new.copy()
ge_copy.drop(columns = ['RRID'], inplace = True)
ge_copy = ge_copy.drop([0,1]).reset_index(drop=True)
tpm = ge_copy.apply(lambda a:(2**a)-1, axis = 1 )
tpm_sum = tpm.sum(axis = 1)
factor = 1000000/tpm_sum
tpm_factor = tpm.mul(factor, axis=0)
new_ge = tpm_factor.apply(lambda a:np.log2(a+1), axis = 1 )
new_tpm = new_ge.apply(lambda a:(2**a)-1, axis = 1 )
new_tpm_sum = new_tpm.sum(axis = 1)
new_ge.insert(loc = 0, column = 'RRID', value =ge_file_new['RRID'][1:].reset_index(drop=True))
new_row1 = pd.DataFrame([ge_file_new.iloc[0].values],columns = new_ge.columns )
new_row2 = pd.DataFrame([ge_file_new.iloc[1].values],columns = new_ge.columns )
new_ge = pd.concat([new_row1,new_row2, new_ge]).reset_index(drop = True)
new_ge.to_csv(str(file_path+'/Curated_CCLE_Multiomics_files/CCLE_AID_expression_scaled.csv'),index=False)

######### Gene Expression full ############# This gene expression file has the sum of TPM ~1 million
logger.info('Processing gene expression full data')
path = str(file_path +'/CCLE_Multiomics_Data/CCLE_expression_full.csv')
gef_file = pd.read_csv(path)
gef_file=gef_file.rename(columns={'Unnamed: 0':'DepMap_ID'})
# Map Ensembl gene id to new gene symbols and replace old gene symbols
genes = list(gef_file.columns[1:])
gs = []
ens = []
col_ind = []
for gene in genes: #Separating column header into gene symbols and entrenz ids
    if '(' in gene:
        ens.append(gene.split('(', 1)[1].split(')')[0])
        gs.append(gene.split(' ', 1)[0])
    else:
        ens.append(gene)
        gs.append(np.nan)
    col_ind.append(gef_file.columns.get_loc(gene))
es_gs = pd.DataFrame({'gene_symbol':gs, 'ensembl_id':ens, 'col_ind':col_ind})
ind = np.where(es_gs['ensembl_id']=='nan')[0]
gef_file = gef_file.drop(gef_file.columns[ind+1], axis=1) # Drop columns where entrenz_id = nan
es_gs2 = es_gs[es_gs.ensembl_id!='nan'].reset_index(drop=True)
# Check if Ensembl Ids are repeating
dup_ind = np.where(es_gs2.duplicated(subset = ['ensembl_id'], keep=False)==True)[0] #len(dup_ind) = 0, so there are no duplicate ensembl ids
#mapping ens to gs
# Load Ensembl_ID-Entrz id-Gene symbol mapping file - Gene expression full file
path = file_path+'/Maps/ens_eg_gs_map_gef.csv'
ens_eg_gs = pd.read_csv(path).drop(columns={'Unnamed: 0'})
col_drop = ens_eg_gs['orig_ensembl_id'][np.where(pd.isna(ens_eg_gs.entrenzID)==True)[0]]
ens_eg_gs = ens_eg_gs.dropna(subset = ['entrenzID']).reset_index(drop=True)
ens_eg_gs = ens_eg_gs.astype({'entrenzID': int})
ens_eg_gs = ens_eg_gs.astype({'entrenzID': str})
ens_gs_map = dict(zip(ens_eg_gs.orig_ensembl_id, ens_eg_gs.new_GS )) # Mapping dictionary EnsemblID to new gene symbol
ens_eg_map = dict(zip(ens_eg_gs.orig_ensembl_id, ens_eg_gs.entrenzID )) # Mapping dictionary Ensembl ID to Entrenz ID
new_eg = es_gs2['ensembl_id'].map(ens_eg_map)
new_gs = es_gs2['ensembl_id'].map(ens_gs_map)
es_gs2['New_gene_symbol'] = new_gs
es_gs2['New_entrenzID'] = new_eg
ind = np.where(pd.isna(new_gs)==True)[0] #index to drop columns
gef_file = gef_file.drop(gef_file.columns[ind+1], axis=1) # Drop columns where entrenz_id cannot be mapped to a gene symbol
es_gs2 = es_gs2.dropna(subset = ['New_gene_symbol']).reset_index(drop=True)
### Check for duplicate gene symbols in the mapping file
dup_ind = np.where(es_gs2.duplicated(subset = ['New_gene_symbol'], keep=False)==True)[0]
es_gs_dup = es_gs2.iloc[dup_ind].reset_index(drop=True)
es_gs_dup = es_gs_dup.sort_values(by = ['New_entrenzID']).reset_index(drop=True)
en = []
c_drop = []
special_case = pd.DataFrame(columns = es_gs_dup.columns)
for i in range(len(es_gs_dup)):
    if es_gs_dup['New_entrenzID'][i] in en:
        continue
    en.append(es_gs_dup['New_entrenzID'][i])
    sub = es_gs_dup.iloc[np.where(es_gs_dup['New_entrenzID']==es_gs_dup['New_entrenzID'][i])[0]].reset_index(drop=True)
    id = np.where(sub['gene_symbol'] == es_gs_dup['New_gene_symbol'][i])[0]
    if len(id) == 0 or len(id)>1:
        special_case = pd.concat([special_case, sub]).reset_index(drop = True)
        continue
    id_no = [k for k in range(len(sub)) if k !=id ]
    #c_drop.extend(np.where(es_gs2['col_ind'].values==sub['col_ind'][id_no].values)[0]+1)
    c_drop.extend(np.where(es_gs2['col_ind'].isin(sub['col_ind'][id_no].values)==True)[0]+1)
    #es_gs2 = es_gs2.drop(index = np.where(es_gs2['col_ind'].values==sub['col_ind'][id_no].values)[0])
    #sub = sub.drop(index = id_no)

# Manually editing special cases
c_drop.extend(np.where(es_gs2.ensembl_id == 'ENSG00000277526')[0]+1)
c_drop.extend(np.where(es_gs2.ensembl_id == 'ENSG00000248991')[0]+1)
c_drop.extend(np.where(es_gs2.ensembl_id == 'ENSG00000258325')[0]+1)
c_drop.extend(np.where(es_gs2.ensembl_id == 'ENSG00000234394')[0]+1)

gef_file = gef_file.drop(gef_file.columns[c_drop], axis=1)
es_gs2 = es_gs2.drop(index = [x - 1 for x in c_drop]).reset_index(drop = True)

###
# Add the new gene symbols to the data file
gef_file.columns = ['DepMap_ID']+list(es_gs2['ensembl_id'])
new_row1 = pd.DataFrame([['']+list(es_gs2['New_entrenzID'])],columns = gef_file.columns )
new_row2 = pd.DataFrame([['']+list(es_gs2['New_gene_symbol'])],columns = gef_file.columns )
gef_file = pd.concat([new_row2, gef_file]).reset_index(drop = True)
gef_file = pd.concat([new_row1, gef_file]).reset_index(drop = True)
#Map DepMap ID with RRID
gef_file.insert(loc=0, column='RRID', value=['' for i in range(gef_file.shape[0])])
col = gef_file.columns
rows = [gef_file.iloc[0].values]
rows.append(list(gef_file.iloc[1].values))
for i in range(len(map)):
    id = np.where(gef_file['DepMap_ID']==map['DepMap_ID'][i])
    if len(id[0])!=0:
        row_append = gef_file.iloc[id[0][0]]
        row_append['RRID'] = map['RRID'][i]
        rows.append(list(row_append.values))
gef_file_new = pd.DataFrame(rows, columns = col)
gef_file_new = gef_file_new.drop(columns = ['DepMap_ID'])
gef_file_new = gef_file_new.drop_duplicates().reset_index(drop=True) # Remove duplicate rows
gef_file_new.to_csv(str(file_path+'/Curated_CCLE_Multiomics_files/CCLE_AID_expression_full.csv'),index=False)

######## Reverse Phase Protein Array (RPPA) ##########
logger.info('Processing RPPA data')
path = str(file_path +'/CCLE_Multiomics_Data/CCLE_RPPA_20180123.csv')
rppa_file = pd.read_csv(path)
rppa_file= rppa_file.rename(columns={'Unnamed: 0':'CCLE_Name'})
rppa_file.insert(loc=0, column='RRID', value=['' for i in range(rppa_file.shape[0])])
col = rppa_file.columns
rows = []
for i in range(len(map)):
    id = np.where(rppa_file['CCLE_Name']==map['CCLE_Name'][i])
    if len(id[0])!=0:
        row_append = rppa_file.iloc[id[0][0]]
        row_append['RRID'] = map['RRID'][i]
        rows.append(list(row_append.values))
rppa_file_new = pd.DataFrame(rows, columns = col)
rppa_file_new = rppa_file_new.drop(columns = ['CCLE_Name'])
rppa_file_new = rppa_file_new.drop_duplicates().reset_index(drop=True) # Remove duplicate rows
rppa_file_new.to_csv(str(file_path+'/Curated_CCLE_Multiomics_files/CCLE_AID_RPPA_20180123.csv'),index=False)

########### DNA Methylation - Reduced Representation Bisulfite Sequencing (RRBS) ##########
logger.info('Processing RRBS data')
path = str(file_path +'/CCLE_Multiomics_Data/CCLE_RRBS_TSS_1kb_20180614.txt')
rrbs_file = pd.read_table(path)
#rrbs_file = pd.read_table(path,index_col=0)
#Loading Gene symbol - Entrz id map file
gs_eg_rrbs_map = pd.read_csv(file_path +'/Maps/gs_eg_gs_map_rrbs.csv').drop(columns={'Unnamed: 0'})
# Some of the genes in the mapping file contains aliases of genes already present in the feature set.
# This created some duplicate TSS_ids
# We need to remove those genes from the mapping file as well as the original file
dup_genes = ['C9orf47', 'ERICH1-AS1', 'ZASP', 'NARR', 'PALM2', 'AKAP2']
rrbs_file = rrbs_file[~rrbs_file['gene'].isin(dup_genes)].reset_index(drop=True)
gs_eg_rrbs_map = gs_eg_rrbs_map[~gs_eg_rrbs_map['orig_GS'].isin(dup_genes)].reset_index(drop=True)

ind_equal = np.where(rrbs_file['gene']==gs_eg_rrbs_map['new_GS'])[0]
ind_diff = np.setdiff1d(list(range(len(rrbs_file))), ind_equal)
gene = rrbs_file['gene']
e_id = gs_eg_rrbs_map['new_entrenz_id']
ens_id = gs_eg_rrbs_map['ens_id']
tss_id = rrbs_file['TSS_id']
drop_ind = []
for ind in ind_diff:
    if not pd.isna(gs_eg_rrbs_map['new_GS'][ind]):
        gene[ind] = gs_eg_rrbs_map['new_GS'][ind]
        tss_id[ind] = gs_eg_rrbs_map['new_GS'][ind]+'_'+tss_id[ind].split('_', 1)[1]
    else:
        gene = gene.drop(ind)
        e_id = e_id.drop(ind)
        ens_id = ens_id.drop(ind)
        tss_id = tss_id.drop(ind)
        drop_ind.append(ind)
rrbs_file=rrbs_file.drop(index=drop_ind).reset_index(drop=True)
rrbs_file['TSS_id'] = tss_id.values
rrbs_file['gene'] = gene.values

rrbs_file.drop(rrbs_file.columns[[0,1, 2,3, 4, 5,6]], axis = 1, inplace = True)
cell_lines = rrbs_file.columns
rrbs_file = rrbs_file.transpose().reset_index(drop=True)
rrbs_file.columns = tss_id.values
rrbs_file.insert(loc = 0, column = 'CCLE_Name', value = cell_lines)
new_row = pd.DataFrame([['']+list(gene)],columns = rrbs_file.columns )
rrbs_file = pd.concat([new_row, rrbs_file]).reset_index(drop=True)
new_row1 = pd.DataFrame([['']+list(e_id.astype('int64'))],columns = rrbs_file.columns )
new_row2 = pd.DataFrame([['']+list(ens_id)],columns = rrbs_file.columns )
rrbs_file = pd.concat([new_row1,new_row2, rrbs_file]).reset_index(drop=True)
rrbs_file.insert(loc=0, column='RRID', value=['' for i in range(rrbs_file.shape[0])])
col = rrbs_file.columns
rows = [rrbs_file.iloc[0].values, rrbs_file.iloc[1].values]
for i in range(len(map)):
    id = np.where(rrbs_file['CCLE_Name']==map['CCLE_Name'][i])
    if len(id[0])!=0:
        row_append = rrbs_file.iloc[id[0][0]]
        row_append['RRID'] = map['RRID'][i]
        rows.append(list(row_append.values))
rrbs_file_new = pd.DataFrame(rows, columns = col)
rrbs_file_new = rrbs_file_new.drop(columns = ['CCLE_Name'])
rrbs_file_new = rrbs_file_new.drop_duplicates().reset_index(drop=True) # Remove duplicate rows
rrbs_file_new.to_csv(str(file_path+'/Curated_CCLE_Multiomics_files/CCLE_AID_RRBS_TSS_1kb_20180614.csv'),index=False)

########## miRNA #############
logger.info('Processing miRNA data')
path = str(file_path +'/CCLE_Multiomics_Data/CCLE_miRNA_20180525.gct')
mirna_file = pd.read_table(path)
mirna_file.drop(mirna_file.columns[[0]], axis = 1, inplace = True)
mirna_file = mirna_file.set_index('Description')
mirna_file = mirna_file.transpose()
mirna_file.reset_index(inplace=True)
mirna_file=mirna_file.rename(columns={'index':'CCLE_Name'})
mirna_file.insert(loc=0, column='RRID', value=['' for i in range(mirna_file.shape[0])])
col = mirna_file.columns
rows = []
for i in range(len(map)):
    id = np.where(mirna_file['CCLE_Name']==map['CCLE_Name'][i])
    if len(id[0])!=0:
        row_append = mirna_file.iloc[id[0][0]]
        row_append['RRID'] = map['RRID'][i]
        rows.append(list(row_append.values))
mirna_file_new = pd.DataFrame(rows, columns = col)
mirna_file_new = mirna_file_new.drop(columns = ['CCLE_Name'])
mirna_file_new = mirna_file_new.drop_duplicates().reset_index(drop=True) # Remove duplicate rows
mirna_file_new.to_csv(str(file_path+'/Curated_CCLE_Multiomics_files/CCLE_AID_miRNA_20180525.csv'),index=False)

logger.info('Data curation completed!')

''''
### duplicate rrids in map
ind = np.where(map.duplicated(subset = ['RRID']) == True)[0] # duplicate rows
map_dup = pd.DataFrame(columns=map.columns)
for i in ind:
    ind_all = np.where(map['RRID']==map['RRID'][i])[0]
    map_dup = pd.concat([map_dup, map.iloc[ind_all]])

map_dup = map_dup.sort_values(by = 'RRID')

##

cl_check = ['ACH-000833', 'ACH-001189', 'ACH-001024', 'ACH-001041', 'ACH-001737', 'ACH-002222', 'ACH-001543', 'ACH-002260']
cl_check_d = {}
for cl in cl_check:
    cl_check_d[cl] = 0

files = ['CCLE_wes_gene_cn.csv', 'CCLE_gene_cn.csv', 'CCLE_expression.csv', 'CCLE_expression_full.csv']
for file in files:
    path = str(file_path +'/CCLE_Multiomics_Data/'+file)
    data_file = pd.read_csv(path)
    data_file=data_file.rename(columns={'Unnamed: 0':'DepMap_ID'})
    for cl in cl_check:
        if cl in data_file.DepMap_ID.values:
            cl_check_d[cl] = cl_check_d[cl]+1

path = file_path+'/CCLE_Multiomics_Data/CCLE_mutations.csv'
mut = pd.read_csv(path)
mut = mut[mut['Entrez_Gene_Id']!=0].reset_index(drop=True) # Remove rows with entrenz id = 0
mut = mut.drop_duplicates().reset_index(drop=True) # Remove duplicate rows
for cl in cl_check:
    if cl in mut.DepMap_ID.values:
        cl_check_d[cl] = cl_check_d[cl]+1
'''


def PhanTu(n):
    if (n == 0):
        return a0
    return PhanTu(n-1)*q

a0, q, n = list(map(int, input().split(" ")))

print("Phan tu thu %d la %d" % (n,PhanTu(n)))

s = 0
for i in range(0, n+1):
    s += PhanTu(i)
print("Tong: %d" %s)


import pandas as pd

# Load dummy data
df = pd.read_excel('../../data/dummy_data.xlsx', 'Data')
demand = df[6:]
demand.reset_index(inplace=True, drop=True)
demand.rename(columns={1: 'product_1', 2: 'product_2', 3: 'product_3', 4: 'product_4'}, inplace=True)
demand = demand[['product_1', 'product_2', 'product_3', 'product_4']]
demand.to_csv('../data/dummy_data.csv', index=False)


'''
<21.02.03>

『목표』
⊙ 파이썬 알고리즘(4)
- 자릿수의 합 알고리즘

『결과』
- 10의 몫과 나머지를 사용하여 합 계산
- str로 변환한 뒤 접근하고 int로 다시 변환하여 합 계산
'''
# 자릿수의 합

n = int(input())
a = list(map(int, input().split()))

def digit_sum(x):
    sum = 0
    while x > 0:
        sum += x % 10
        x = x//10
    return sum

'''
(2) str로 변환
def digit_sum(x):
    sum = 0
    for i in str(x): # 문자열 하나씩 접근
        sum += int(i)
    return sum
'''

max = 0

for i in a:
    total = digit_sum(i)
    if max < total:
        max = total
        res = i
print(res)


from django.shortcuts import render
from AppFamily.models import Familia
from django.http import HttpResponse
from django.template import loader

# Create your views here.

def familia(request):
    padre = Familia(nombre="Pedro",edad=67,nacimiento="1965-3-19")
    madre = Familia(nombre="Rosa",edad=60,nacimiento="1962-3-6")
    hermano = Familia(nombre="Ignacio",edad=23,nacimiento="1999-4-12")
    padre.save()
    madre.save()
    hermano.save()

    dic = { "nombrePadre": padre.nombre,
        "edadPadre": padre.edad,
        "nacimientoPadre": padre.nacimiento,
        "nombreMadre": madre.nombre,
        "edadMadre": madre.edad,
        "nacimientoMadre": madre.nacimiento,
        "nombreHermano": hermano.nombre,
        "edadHermano": hermano.edad,
        "nacimientoHermano": hermano.nacimiento }
       #Diccionario del cual se van a sacar los datos para el HTML (Voy a usar la clave siempre)

    plantilla = loader.get_template("template1.html") #Llamo al template

    doc = plantilla.render(dic)
    return HttpResponse(doc)


from typing import Callable, Tuple

import torch
from torch.nn import functional as F

from src.fwdgrad.activation import softmax
from src.fwdgrad.utils import clamp_probs

def _xent(x: torch.Tensor, t: torch.Tensor, num_classes: int = 10) -> torch.Tensor:
    """Compute cross-entropy loss.

    Args:
        x (torch.Tensor): Output of the model.
        t (torch.Tensor): Targets.
        num_classes (int, optional): Maximum number of classes. Defaults to 10.

    Returns:
        torch.Tensor: Cross-entropy loss.
    """
    y = clamp_probs(softmax(x))
    logy = -torch.log(y)
    loss = torch.mean(torch.sum(logy * F.one_hot(t, num_classes), dim=1))
    return loss

def xent(
    model: torch.nn.Module, x: torch.Tensor, t: torch.Tensor, num_classes: int = 10
) -> torch.Tensor:
    """Cross-entropy loss. Given a pytorch model, it computes the cross-entropy loss.

    Args:
        model (torch.nn.Module): PyTorch model.
        x (torch.Tensor): Input tensor for the PyTorch model.
        t (torch.Tensor): Targets.
        num_classes (int, optional): Maximum number of classes. Defaults to 10.

    Returns:
        torch.Tensor: Cross-entropy loss.
    """
    y = model(x)
    return _xent(y, t, num_classes)

def functional_xent(
    params: Tuple[torch.nn.Parameter, ...],
    model: Callable[[Tuple[torch.nn.Parameter, ...], torch.Tensor], torch.Tensor],
    x: torch.Tensor,
    t: torch.Tensor,
    num_classes: int = 10,
) -> torch.Tensor:
    """Functional cross-entropy loss. Given a functional version of a pytorch model, which can be obtained with
    `fmodel, params = functorch.make_functional(model)`, it computes the cross-entropy loss.

    Args:
        params (Tuple[torch.nn.Parameter, ...]): Model parameters obtained by `fmodel, params = fc.make_functional(model)`.
        model (Callable[[Tuple[torch.nn.Parameter, ...], torch.Tensor], torch.Tensor]): Functional version of a pytorch model,
            obtained by fmodel, `params = fc.make_functional(model)`
        x (torch.Tensor): Input tensor for the PyTorch model.
        t (torch.Tensor): Targets.
        num_classes (int, optional): Maximum number of classes. Defaults to 10.

    Returns:
        torch.Tensor: Cross-entropy loss.
    """
    y = model(params, x)
    return _xent(y, t, num_classes)


import torch.nn as nn
import torch
import math

# Keisuke Fujii, 2021
# modifying the work and code:
#   Interpretable Models for Granger Causality Using Self-explaining Neural Networks
#   Ričards Marcinkevičs, Julia E Volgae, https://openreview.net/forum?id=DEa4JdMWRHp

class SENNGC(nn.Module):
    def __init__(self, num_vars: int, order: int, hidden_layer_size: int, num_hidden_layers: int, device: torch.device,
                 args=None):
        """
        Augmented behavioral model based on self-explaining neural networks.

        @param num_vars: number of variables (p).
        @param order:  model order (maximum lag, K).
        @param hidden_layer_size: number of units in the hidden layer.
        @param num_hidden_layers: number of hidden layers.
        @param device: Torch device.
        @param method: fitting algorithm (currently, only "OLS" is supported).
        """
        super(SENNGC, self).__init__()

        # Networks for amortising generalised coefficient matrices.

        self.num_atoms = args.num_atoms
        self.self_other = args.self_other
        self.percept = args.percept
        self.num_dims = args.num_dims
        out_dims = args.out_dims
        self.experiment = args.experiment
        self.realdata = args.realdata
        self.navigation = args.navigation

        self.d_self = args.d_self
        self.num_vars = num_vars
        if self.navigation:
            if self.self_other:
                self.num_dims += - (num_vars - 1)*2

        elif 'kuramoto' in self.experiment:
            self.d_other = args.d_other
            self.max = args.max

        # Instantiate coefficient networks
        self.coeff_nets = nn.ModuleList()
        if self.self_other: #  and not self.permuted:
            if self.navigation:
                num_dims = self.num_dims-out_dims# (self.num_dims-self.d_self)#//(num_vars - 1)
                # out_dims = 1
                num_dims2 = num_dims# (num_vars-1)
            elif 'kuramoto' in self.experiment:
                num_dims = num_vars # -1
                num_dims2 = num_dims -1
            else:
                num_dims = self.num_dims-out_dims # if not args.percept else self.num_dims - (num_vars-1)
                num_dims2 = num_dims
            for k in range(order):
                self.coeff_nets_ = nn.ModuleList()
                for i in range(num_vars):
                    modules = [nn.Sequential(nn.Linear(num_dims, hidden_layer_size), nn.ReLU())]
                    if num_hidden_layers > 1:
                        for j in range(num_hidden_layers - 1):
                            modules.extend(nn.Sequential(nn.Linear(hidden_layer_size, hidden_layer_size), nn.ReLU()))
                    if 'kuramoto' in self.experiment:
                        modules.extend(nn.Sequential(nn.Linear(hidden_layer_size, num_dims2*out_dims,nn.Sigmoid()))) #
                    else:
                        modules.extend(nn.Sequential(nn.Linear(hidden_layer_size, num_dims2*out_dims)))
                    self.coeff_nets_.append(nn.Sequential(*modules))
                self.coeff_nets.append(self.coeff_nets_)
        else:
            num_dims = self.num_dims #  if not args.percept else self.num_dims - 1
            for k in range(order):
                modules = [nn.Sequential(nn.Linear(num_vars*num_dims, hidden_layer_size), nn.ReLU())]
                if num_hidden_layers > 1:
                    for j in range(num_hidden_layers - 1):
                        modules.extend(nn.Sequential(nn.Linear(hidden_layer_size, hidden_layer_size), nn.ReLU()))
                    if 'kuramoto' in self.experiment:
                        modules.extend(nn.Sequential(nn.Linear(hidden_layer_size, num_vars*num_dims*num_vars*out_dims)))
                    else:
                        modules.extend(nn.Sequential(nn.Linear(hidden_layer_size, num_vars*num_dims*num_vars*out_dims)))
                self.coeff_nets.append(nn.Sequential(*modules))

        if args.percept:
            self.avoid_nets = nn.Linear(1,1)
            self.avoid_nets.apply(self.init_weights_avoid)

        # Some bookkeeping

        self.order = order
        self.hidden_layer_size = hidden_layer_size
        self.num_hidden_layer_size = num_hidden_layers

        self.device = device
        self.out_dims = out_dims
        self.out_dims_final = args.out_dims
        self.num_dims_model = num_dims

    # Initialization
    def init_weights_avoid(self,m):
        if 'bat' in self.experiment:
            nn.init.constant_(m.bias, 0.1)
        elif 'sula' in self.experiment:
            nn.init.constant_(m.bias, 0.001)
        else:
            nn.init.constant_(m.bias, 0.)

    # Forward propagation,
    # returns predictions and generalized coefficients corresponding to each prediction
    def forward(self, inputs: torch.Tensor, CF_pred=False, inds=None, index_none=None):
        coeffs = None

        if index_none is not None:
            index_none = torch.tensor(-(index_none-1)).bool().to(self.device)

        timelength, order, input_dim = inputs.shape
        input_dim //= self.num_vars
        preds = torch.zeros((timelength, self.num_vars*self.out_dims_final)).to(self.device)

        p = self.num_vars
        d_out = self.out_dims
        dim = self.out_dims_final

        if self.percept:
            indds = torch.zeros(0).long()
            coeffs_FP = torch.zeros((timelength,p, p-1)).to(self.device)
            avoid = self.avoid_nets.bias
            for i in range(p):
                for j in range(p-1):
                    indd = (i+1)*input_dim - (p-1) + j
                    inputs_FP = inputs[:, -1, indd].clone()
                    indd2 = (i+1)*input_dim - (p-1)*2 + j
                    inputs_FP2 = inputs[:, -1, indd2].clone()
                    if index_none is None:
                        if 'bat' in self.experiment:
                            coeffs_FP[:,i,j] = torch.sigmoid(1e2*(inputs_FP - avoid)) * (torch.sigmoid(1e2*inputs_FP2)-1/2)*2
                        else:
                            coeffs_FP[:,i,j] = torch.sigmoid(1e6*(inputs_FP )) * (torch.sigmoid(1e2*inputs_FP2)-1/2)*2
                    else:
                        if index_none.shape[0]-inputs.shape[1]-1 == timelength:
                            tmp_idx = index_none[inputs.shape[1]:-1,i]# .shape
                        else:
                            tmp_idx = index_none[inputs.shape[1]:,i]

                        coeffs_FP[tmp_idx,i,j] = torch.sigmoid(1e2*(inputs_FP[tmp_idx] - avoid)) * (torch.sigmoid(1e2*inputs_FP2[tmp_idx])-1/2)*2

        else:
            coeffs_FP = None

        for k in range(self.order):
            coeff_net_k = self.coeff_nets[k]

            if self.self_other:
                for i in range(p):
                    if self.navigation or 'kuramoto' in self.experiment:
                        if self.navigation:
                            idx = torch.arange(input_dim*i + self.num_dims)
                            idx = torch.cat([idx[input_dim*i:input_dim*i+dim],idx[input_dim*i+2*dim:input_dim*i+(2+p-1)*dim]],dim=0)
                            inputs_ = inputs[:, k, idx].clone()
                        elif 'kuramoto' in self.experiment:
                            inputs_ = torch.cat([inputs[:, k, input_dim*i:input_dim*i+1]-inputs[:, k, input_dim*i+4:input_dim*i+5],inputs[:, k, input_dim*i+2:input_dim*i+self.num_dims]],dim=1)
                        else:
                            inputs_ = inputs[:, k, input_dim*i:input_dim*i + self.num_dims].clone()
                    elif 'lorenz' in self.experiment: # delayed processing: same as not self_other???
                        inputs_ = inputs[:, k, :].clone()
                    coeffs_ki = coeff_net_k[i](inputs_)

                    if self.navigation:
                        if self.percept:
                            coeffs_ki = torch.reshape(coeffs_ki**2, (timelength, self.out_dims, self.num_dims_model))
                        else:
                            coeffs_ki = torch.reshape(coeffs_ki, (timelength, self.out_dims, self.num_dims_model))
                    else:
                        if 'kuramoto' in self.experiment:
                            coeffs_ki = torch.reshape(coeffs_ki**2, (timelength, p-1, self.out_dims))
                        else:
                            coeffs_ki = torch.reshape(coeffs_ki, (timelength, p-1, self.out_dims))

                    coeffs_ki2 = coeffs_ki.clone()
                    if self.percept:
                        coeffs_ki2[:,:,-(p-1)*dim:] = coeffs_ki[:,:,-(p-1)*dim:] * coeffs_FP[:,i,:].unsqueeze(2).unsqueeze(2).expand(timelength, p-1, self.out_dims, self.out_dims).reshape((timelength,(p-1)*self.out_dims,self.out_dims)).permute((0,2,1))

                    if 'kuramoto' in self.experiment:
                        inputs__ = inputs[:, k, input_dim*i:input_dim*i + self.num_dims].clone()
                    else:
                        inputs__ = inputs_.clone()

                    if 'kuramoto' in self.experiment:
                        preds__ = inputs__[:,1:2]/self.order + torch.sum(coeffs_ki2*inputs__[:,2:].unsqueeze(dim=2),dim=1)
                        coeffs_ki2 = coeffs_ki2.permute((0,2,1))
                    else:
                        preds__ = torch.matmul(coeffs_ki2, inputs__.unsqueeze(dim=2)).squeeze(2)

                    preds_ = torch.cat([preds_,preds__],1) if i > 0 else preds__
                    coeffs_k = torch.cat([coeffs_k,coeffs_ki2],1) if i > 0 else coeffs_ki2
                    if torch.sum(torch.isnan(preds_))>0:
                        import pdb; pdb.set_trace()
                preds += preds_

            else:
                coeffs_k = coeff_net_k(inputs[:, k, :])
                coeffs_k = torch.reshape(coeffs_k, (timelength, self.num_vars*self.out_dims, self.num_vars*self.num_dims_model))
                preds += torch.matmul(coeffs_k, inputs[:, k, :].unsqueeze(dim=2)).squeeze(2)

            coeffs = torch.cat((coeffs, torch.unsqueeze(coeffs_k, 1)), 1) if coeffs is not None else torch.unsqueeze(coeffs_k, 1)

        return preds, coeffs, coeffs_FP