import sqlalchemy
import os

"""
Reset trending_page_views column for each game
"""

# Connect to Database
engine = sqlalchemy.create_engine(os.getenv('SQLALCHEMY_DATABASE_URI'))

# Prepare SQL query
sql = 'UPDATE games SET trending_page_views = 0'

# Execute query
with engine.connect() as con:
    rs = con.execute(sql)
    print("Trending views have been reset")


import itertools
import json
import os
import re

import numpy as np
import pandas
import pandas as pd
import torch
from pytorch_lightning import LightningDataModule
from pytorch_lightning.utilities.types import TRAIN_DATALOADERS, EVAL_DATALOADERS
from torch.utils.data import DataLoader, Dataset, IterableDataset
from datasets import load_dataset
from typing import List, Optional, Dict
from transformers import PreTrainedTokenizer, AutoTokenizer
import os.path
from datasets import load_dataset
from pathlib import Path
import platform
if platform.system() == "Linux":
    num_workers = 40
else:
    num_workers = 1

class DataModules(LightningDataModule):
    def __init__(self, file_path_dir: str, batch_size: int=32, max_len: int=32):
        super().__init__()
        self.file_path_dir = file_path_dir
        self.batch_size = batch_size
        self.max_len = max_len
        self.save_hyperparameters()

    def setup(self, stage: str) -> None:
        if stage == "fit" or stage is None:
            self.train_set = ToutiaoDataset(self.file_path_dir, "train", select_class=["100", "101"], max_len=self.max_len)
            self.eval_set = ToutiaoDataset(self.file_path_dir, "val", select_class=["100", "101"], max_len=self.max_len)
        if stage == "test" or stage is None:
            self.test_set = ToutiaoDataset(self.file_path_dir, "test", select_class=["100", "101"], max_len=self.max_len)
        if stage == "predict" or stage is None:
            self.predict_set = ToutiaoDataset

    def train_dataloader(self) -> TRAIN_DATALOADERS:
        return DataLoader(self.train_set, batch_size=self.batch_size, shuffle=True, num_workers=num_workers)

    def val_dataloader(self) -> EVAL_DATALOADERS:
        return DataLoader(self.eval_set, batch_size=self.batch_size, shuffle=False, num_workers=num_workers)

    def test_dataloader(self) -> EVAL_DATALOADERS:
        return DataLoader(self.test_set, batch_size=self.batch_size, shuffle=False, num_workers=num_workers)

    def predict_dataloader(self) -> EVAL_DATALOADERS:
        return DataLoader(self.predict_set, batch_size=self.batch_size, shuffle=False, num_workers=4)

class ToutiaoDataset(Dataset):
    def __init__(self, file_path_dir: str, mode: str, select_class: List[str],
                 padding: str="max_length", max_len: int=64, truncation: bool=True, label_map: Dict=None):
        self.file_path_dir = file_path_dir
        self.mode = mode
        self.padding = padding
        self.max_len = max_len
        self.truncation = truncation
        self.data = pd.read_csv(os.path.join(file_path_dir, f"{mode}/corpus-model-filtered-{mode}.csv"), sep="\t", header=0)
        self.select_data = self.data
        # self.select_data = pd.DataFrame(columns=self.data.columns)
        # for label_id in select_class:
        #     tmp = self.data[self.data.label_id == int(label_id)]
        #     self.select_data = pd.concat([self.select_data, tmp])
        # self.select_data = self.select_data.reset_index(drop=True)
        # del self.data
        self.tokenizer = AutoTokenizer.from_pretrained('gpt2-xl')
        # print(self.tokenizer.pad_token_id)
        self.tokenizer.pad_token = self.tokenizer.eos_token
        if label_map is None:
            keys = [str(i) for i in range(100, 117)]
            values = range(0, 17)
            self.label_map = dict(zip(keys, values))
            del keys, values

    def compute_label(self, field):
        label = self.label_map[str(field["label_id"])]
        return np.array(label)

    def convert_str_to_id(self, field):
        text = field["text"]
        output = self.tokenizer(text, text_target=text, padding='max_length', truncation=self.truncation,
                               max_length=self.max_len, add_special_tokens=True)
        output["labels"] = output["labels"][1:]
        return output

    def __len__(self):
        return len(self.select_data)

    def __getitem__(self, item):
        field = self.select_data.loc[item]
        field = field.to_dict()
        feature = self.convert_str_to_id(field)
        # print(feature)
        return (
            np.array(feature["input_ids"]),
            np.array(feature["labels"]),
            np.array(feature["attention_mask"])
        )

class HuggingFaceHugeDatasetLoad(IterableDataset):
    def __init__(self, file_path_dir: str, mode: str, max_len):
        file_list = Path(file_path_dir).glob("*.csv")
        file_list = [file_path.name for file_path in file_list]
        total_len = len(file_list)
        tmp = {"train": [os.path.join(file_path_dir, raw) for raw in file_list[:int(total_len * 0.8)]],
               "validation": [os.path.join(file_path_dir, raw) for raw in file_list[int(total_len * 0.8):int(total_len * 0.9)]],
               "test": [os.path.join(file_path_dir, raw) for raw in file_list[int(total_len * 0.9):]]}
        self.data = load_dataset("csv", data_files=tmp, split=mode, streaming=True)
        self.max_len = max_len

    def __iter__(self):
        for field in self.data:
            tmp = field["input_ids"]
            process = list(map(int, re.sub("'|\[|\]", "", tmp).split(", ")))[:self.max_len]
            yield [np.array(process), np.array(process)[1:], np.ones([self.max_len])]

class PTMDataModules(LightningDataModule):
    def __init__(self, file_path_dir: str, batch_size: int=32, max_len: int=32):
        super().__init__()
        self.file_path_dir = file_path_dir
        self.batch_size = batch_size
        self.max_len = max_len
        self.save_hyperparameters()

    def setup(self, stage: str) -> None:
        if stage == "fit" or stage is None:
            self.train_set = HuggingFaceHugeDatasetLoad(self.file_path_dir, "train", max_len=self.max_len)
            self.eval_set = HuggingFaceHugeDatasetLoad(self.file_path_dir, "validation", max_len=self.max_len)
        if stage == "test" or stage is None:
            self.test_set = HuggingFaceHugeDatasetLoad(self.file_path_dir, "test", max_len=self.max_len)

    def train_dataloader(self) -> TRAIN_DATALOADERS:
        return DataLoader(self.train_set, batch_size=self.batch_size)

    def val_dataloader(self) -> EVAL_DATALOADERS:
        return DataLoader(self.eval_set, batch_size=self.batch_size)

    def test_dataloader(self) -> EVAL_DATALOADERS:
        return DataLoader(self.test_set, batch_size=self.batch_size)

    def predict_dataloader(self) -> EVAL_DATALOADERS:
        return DataLoader(self.predict_set, batch_size=self.batch_size)

#
if __name__ == "__main__":
    # dset = HuggingFaceHugeDatasetLoad(file_path_dir=r"d://workspace//Work//merge_corpus_csv", mode='train', max_len=512)
    # for i in dset:
    #     print(i)
    dm = PTMDataModules(file_path_dir=r"d://workspace//Work//merge_corpus_csv", max_len=32, batch_size=64)
    dm.setup("fit")
    train_loader = dm.train_dataloader()
    for batch, _ in enumerate(train_loader):
        print(_)


import struct

print("len: ", struct.calcsize('i'))
print("len: ", struct.calcsize('I'))
print("len: ", struct.calcsize('h'))

test_dict = {1: 'test'}
print(test_dict.pop(1))

import socket, errno

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.bind(("0.0.0.0", 6620))
except socket.error as e:
    if e.errno == errno.EADDRINUSE:
        print("Port is already in use")
    else:
        # something else raised the socket.error exception
        print(e)

s.close()

def is_port_in_use(port):
    import socket
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex(('0.0.0.0', port)) == 0

print(is_port_in_use(9005))

from test_class import testClass
testClass()
print("end")


from flask import Flask
import json

app = Flask(__name__)

@app.route("/<int:number>", methods=["GET"])
def default_range(number):
    result = []
    for n in range(1, number + 1):
        result.append(n)
    return {
        "result" : tuple(result)
    }

@app.route("/<int:number>/odd", methods=["GET"])
def odd_range(number):
    result = []
    for n in range(1, number + 1, 2):
        if(n % 2 == 1):
            result.append(n)
    return {
        "result" : tuple(result)
    }

@app.route("/<int:number>/even", methods=["GET"])
def even_range(number):
    result = []
    for n in range(2, number + 1, 2):
        result.append(n)
    return {
        "result" : tuple(result)
    }

@app.route("/<int:number>/prime", methods=["GET"])
def prime_range(number):
    result = []
    s = [True] * number

    for a in range(2, number):
        if s[a] == True:
            result.append(a)

            for b in range(2, number):
                if (a * b) >= number:
                    break
                s[a * b] = False

    return {
        "result" : tuple(result)
    }


from werkzeug.serving import make_server
from threading import Thread
import base64
import datetime
import collections
from flask import Flask, request
import logging
from requests_oauthlib import OAuth2Session
import requests
from threading import Timer
import time
import webbrowser
import yaml

class FlaskServer:
    def __init__(self, oauth2_server, host="localhost", port=8000):
        self.oauth2_server = oauth2_server
        self.app = Flask(__name__)
        self.srv = make_server(host, port, self.app)
        self.ctx = self.app.app_context()
        self.ctx.push()
        self.setup_routes()

    def setup_routes(self):
        @self.app.route("/callback")
        def callback():
            authorization_code = request.args.get("code")
            response = self.oauth2_server.fetch_token(authorization_code)
            self.oauth2_server.save_token(response)

            shutdown_thread = Thread(target=self.srv.shutdown)
            shutdown_thread.start()
            return "Success!"

    def run(self, authorization_url):
        Timer(1, lambda: webbrowser.open(authorization_url)).start()
        self.srv.serve_forever()

class OAuth2Server:
    def __init__(
        self,
        client_id,
        client_secret,
        authorization_base_url,
        token_url,
        scope,
        redirect_uri="http://localhost:8000/callback",
    ):
        self.server = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope)
        self.client_id = client_id
        self.client_secret = client_secret
        self.authorization_base_url = authorization_base_url
        self.token_url = token_url
        self.flask_server = FlaskServer(self)
        self.response = None

    def fetch_token(self, authorization_code):
        return self.server.fetch_token(
            self.token_url,
            client_id=self.client_id,
            client_secret=self.client_secret,
            code=authorization_code,
            include_client_id=True,
        )

    def save_token(self, response):
        self.response = response

    def run(self):
        authorization_url, _ = self.server.authorization_url(
            self.authorization_base_url
        )
        logging.info(f"Please go to {authorization_url} and authorize access.")
        self.flask_server.run(authorization_url)

class CredsFile:
    def __init__(self, path):
        self.path = path

    def read_file(self) -> dict:
        with open(self.path, "r") as stream:
            return yaml.safe_load(stream)

    def get(self, key) -> dict:
        return self.read_file()[key]

    def write(self, entries):
        with open(self.path, "w") as stream:
            # Careful, this rewrites the entire yaml file
            yaml.safe_dump(entries, stream)

    def update(self, new_entry):
        entries = self.read_file()
        updated_entries = self.deep_update(entries, new_entry)
        self.write(updated_entries)
        entries = self.read_file()

    def deep_update(self, d, u):
        # https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
        for k, v in u.items():
            if isinstance(v, collections.abc.Mapping):
                d[k] = self.deep_update(d.get(k, {}), v)
            else:
                d[k] = v
        return d

class AccessTokenManager:
    def __init__(self, creds_file):
        self.creds_file = creds_file
        self.creds = None

    def refresh(self, creds_key):
        self.load_creds(creds_key)
        if "access_token" not in self.creds:
            response = self.refresh_with_oauth2()
            self.update_token(response, creds_key)
        elif (
            "expires_at" in self.creds
            and self.token_expired()
            and "refresh_token" in self.creds
        ):
            response = self.refresh_with_refresh_token()
            self.update_token(response, creds_key)

    def token_expired(self):
        return datetime.datetime.today().timestamp() > self.creds["expires_at"]

    def refresh_with_oauth2(self):
        logging.info("Fetching access token using OAuth2")
        server = OAuth2Server(
            self.creds["client_id"],
            self.creds["client_secret"],
            self.creds["authorization_uri"],
            self.creds["token_uri"],
            self.creds.get("scope"),  # Splitwise doesn't API access
        )
        server.run()
        return server.response

    def refresh_with_refresh_token(self):
        logging.info("Using refresh token to fetch fresh access token")
        secret = str(self.creds["client_id"]) + ":" + self.creds["client_secret"]
        header = {"Authorization": "Basic " + self.encode_secret(secret)}
        data = {
            "client_id": self.creds["client_id"],
            "client_secret": self.creds["client_secret"],
            "refresh_token": self.creds["refresh_token"],
            "grant_type": "refresh_token",
        }
        response = requests.post(
            url=self.creds["token_uri"],
            headers=header,
            data=data,
        )
        return response.json()

    @staticmethod
    def encode_secret(secret):
        """Standard protocol for passing bytes over a network to avoid misinterpretation of data
        b64 explanation:
        https://stackoverflow.com/questions/201479/what-is-base-64-encoding-used-for
        Fibit request documentation:
        https://dev.fitbit.com/build/reference/web-api/authorization/client-credentials/
        """
        bytes_secret = secret.encode()
        encoded_bytes_secret = base64.b64encode(bytes_secret)
        encoded_string_secret = encoded_bytes_secret.decode()
        return encoded_string_secret

    def update_token(self, response, creds_key):
        if "expires_in" in response:
            response["expires_at"] = time.time() + response["expires_in"]
        keys_to_update = ["access_token", "refresh_token", "expires_at"]
        new_creds = {
            creds_key: {k: response[k] for k in keys_to_update if k in response}
        }
        self.creds_file.update(new_creds)

    def load_creds(self, creds_key):
        self.creds = self.creds_file.get(creds_key)

if __name__ == "__main__":
    # Creds tests
    print("STRAVA")
    CREDS_KEY = "strava"
    CREDS_PATH = "creds.yml"
    creds_file = CredsFile(CREDS_PATH)
    creds = AccessTokenManager(creds_file)
    creds.refresh(CREDS_KEY)

    print("FITBIT")
    CREDS_KEY = "fitbit"
    CREDS_PATH = "creds.yml"
    creds = AccessTokenManager(creds_file)
    creds.refresh(CREDS_KEY)

    print("SPLITWISE")
    CREDS_KEY = "splitwise"
    CREDS_PATH = "creds.yml"
    creds = AccessTokenManager(creds_file)
    creds.refresh(CREDS_KEY)


from Tkinter import *

import rockpaperscissors
import hangman

root = Tk()
root.title("Linux Sruji Xenial Developer Mega Microgames Collection")

mainframe = Frame(root, height = 200, width = 500)
mainframe.pack_propagate(0)
mainframe.pack(padx = 5, pady = 5)

intro = Label(mainframe, text= """Welcome to Linux Sruji Xenial Developer Mega Microgames Collection.
                                Please Select one of the following games to play:
                                """)
intro.pack(side = TOP)

rps_button = Button(mainframe, text = "Rock, Paper, Scissors",command = rockpaperscissors.gui)
rps_button.pack()

hm_button = Button(mainframe, text = "Hangman",command = hangman.gui)
hm_button.pack()

exit_button = Button(mainframe, text = "Quit", command = root.destroy)
exit_button.pack(side = BOTTOM)

root.mainloop()


#The data we need to retrieve:
#1. Total number of votes cast
#2. A complete list of candidates who received votes
#3. Total number of votes each candidate received
#4. Percentage of votes each candidate won
#5. The winner of the election based on popular vote

#from platform import python_branch

# Add our dependencies
import csv
import os

# Assign a variable to load a file from a path.
file_to_load = os.path.join("Resources", "election_results.csv")

# Assign a variable to save the file to a path.
file_to_save = os.path.join("analysis", "election_analysis.txt")

#1a. Initialize a total vote counter
total_votes = 0

#2a. Candidate Options List
candidate_options = []

#3a. candidate Votes Dictionary, declare an empty dictionary
candidate_votes = {}

#5a. Declare a variable that holds an empty string value for the winning candidate.
winning_candidate = " "
#5b. Declare a variable for the "winning count" equal to zero.
winning_count = 0
#5c. Declare a variable for the "winning_percentage" equal to zero.
winning_percentage = 0

# Open the election results and read the file.
with open(file_to_load) as election_data:

    #Read and analyze the data here
    file_reader = csv.reader(election_data)

    # Read the header row.
    headers = next(file_reader)

    # Print each row in the CSV file.
    for row in file_reader:
        #1b. Add to the total vote count.
        #number = number + 1, which can be augmented to number += 1
        total_votes += 1

        #2b. Print the candidate name from each row
        candidate_name = row[2]

        #2c. Add the candidate name to the candidate list.
        # If the candidate does not match any existing candidate...
        if candidate_name not in candidate_options:
            #Add it to the list of candidates
            candidate_options.append(candidate_name)

            #3b. Begin tacking that candidate's name
            #3c. To begin tracking the candidate's vote count, we initialize each candidate's vote equal to zero.
            candidate_votes[candidate_name] = 0
        #3d. Increment the votes by 1 every time a candidate name appears in a row.
        candidate_votes[candidate_name] +=1

#1c. Print the total votes
#print(total_votes)

#2d. Print the candidate list.
#print(candidate_options)

#3e. print the candidates vote dictionary
#print(candidate_votes)

#Save the results to text file
with open(file_to_save, "w") as txt_file:

    # Print the final vote count to the terminal.
    election_results = (
        f"\nElection Results\n"
        f"-------------------------\n"
        f"Total Votes: {total_votes:,}\n"
        f"-------------------------\n")
    print(election_results, end="")
    # Save the final vote count to the text file.
    txt_file.write(election_results)

    #4. Determine the percentage of votes for each candidate by looping through the counts.
    #4a. Loop through the candidate options list
    for candidate_name in candidate_votes:
        #4b. Retrieve vote count of a candidate.
        votes = candidate_votes[candidate_name]
        #4c. Calculate the percentage of votes
        vote_percentage = float(votes) / float(total_votes) * 100
        #4d. Print the candidate name and percentage of votes using f-string formatting..
        #print(f"{candidate_name}: received {vote_percentage:.2f}% of the vote.")

        #4e. Print out each candidate's name, vote count, and percentage of votes to the terminal.
        #commented out to add txt file:
        #print(f"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\n")

        candidate_results = (
            f"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\n")
        # Print each candidate, their voter count, and percentage to the terminal.
        print(candidate_results)
        # Save the candidate results to our text file.
        txt_file.write(candidate_results)

        #5. Winning Candidate and Winning Count Tracker
        #5d. Determine if the votes are greater than the winning count.
        if (votes > winning_count) and (vote_percentage > winning_percentage):
            #5e. If true then set winning_count = votes and winning_percent = vote_percentage.
            winning_count = votes
            winning_percentage = vote_percentage
            #5f. Set the winning_candidate equal to the candidate's name.
            winning_candidate = candidate_name

    #5g. Print out the winning candidate summary.
    winning_candidate_summary = (
        f"-------------------------\n"
        f"Winner: {winning_candidate}\n"
        f"Winning Vote Count: {winning_count:,}\n"
        f"Winning Percentage: {winning_percentage:.1f}%\n"
        f"-------------------------\n")
    print(winning_candidate_summary)

    # Save the winning candidate's name to the text file.
    txt_file.write(winning_candidate_summary)


import sys
sys.path.append('./libsvm-3.22/python')

from itertools import product
import numpy as np
import svmutil
from irusUtil import IrusDataReader, getVfoldCrossValidation
from multiprocessing import Pool
from functools import partial
import warnings
warnings.filterwarnings("ignore")

templateParameter = "-t {0} -d {1} -g {2} -r {3} -c {4} -q"
def getscore(XTrain, yTrain, n, vals):
    pstring = templateParameter.format(*[vals[0],vals[1],2**vals[2],2**vals[3],vals[4]])
    param = svmutil.svm_parameter(pstring)
    return getVfoldCrossValidation(param,XTrain,yTrain,n, splitRatio=0.6, prewnPercentage = 85), vals

#CostValues=[0.1,0.6,1,100]
CostValues=2.0**np.arange(-6,7)
numberOfTrials=50
problems=[('Iris-versicolor', 'Iris-virginica'),('Iris-versicolor','Iris-setosa'),('Iris-virginica', 'Iris-setosa')]
nvalues = [40,5,5]
pcounter=0
total=numberOfTrials*len(problems)
nextsteps1 = [1,1,1,0.25]
nextsteps2 = [1,1,1,0.25]

if __name__ == '__main__':
    IR=IrusDataReader()
    _pool = Pool(40)

    errors=np.empty((3,4,len(CostValues),numberOfTrials))
    Verrors=np.empty((3,4,len(CostValues),numberOfTrials))
    Allpstrings=[[[[None for i in range(50)]
                    for j in range(len(CostValues))]
                    for k in range(4)]
                    for l in range(3)]

    for trial in range(numberOfTrials):
        for probnr, problem in enumerate(problems):
            print(100*pcounter/total)
            pcounter+=1
            XTrain, yTrain, XTest, yTest = IR.GetDataInPositiveNegativeFormat(*problem)
            XTest, XTrain = IR.GetNormalisedData(XTest, XTrain)
            getscorepartial = partial(getscore, XTrain, yTrain, nvalues[probnr])

            for funcnr,costnr in product(range(4),range(len(CostValues))):
                nextstep1 = nextsteps1[funcnr]
                nextstep2 = nextsteps2[funcnr]
                ranges=[[[0],[0],[0]],
                    [np.arange(2,5),np.arange(0,5.0,nextstep1),np.arange(-4.0,10.0,nextstep2)],
                    [[0],np.arange(0,5.0,nextstep1),[0]],
                    [[0],np.arange(-3,3,nextstep1),np.arange(-3,3,nextstep2)]]
                params=[[funcnr]]+ranges[funcnr]+[[CostValues[costnr]]]

                for stepPow in range(12):

                    scores,values = zip(*_pool.map(getscorepartial,product(*params)))

                    bvi=np.argmax(scores)
                    besterrparams=values[bvi]
                    #print(scores[bvi],besterrparams)

                    step1 = nextstep1
                    nextstep1 = step1/2
                    step2 = nextstep2
                    nextstep2 = step2/2
                    params[1]=[besterrparams[1]]
                    params[2]=np.arange(besterrparams[2]-step1,besterrparams[2]+step1+nextstep1,nextstep1)
                    params[3]=np.arange(besterrparams[3]-step2,besterrparams[3]+step2+nextstep2,nextstep2)

                prob = svmutil.svm_problem(yTrain,XTrain.tolist())
                pstring = templateParameter.format(*[besterrparams[0],besterrparams[1],
                                                     2**besterrparams[2],2**besterrparams[3],besterrparams[4]])
                bestparams = svmutil.svm_parameter(pstring)

                m = svmutil.svm_train(prob, bestparams)
                p_label, p_acc, p_val = svmutil.svm_predict(yTest,XTest.tolist(), m, '-q')
                errors[probnr][funcnr][costnr][trial]=p_acc[0]
                Verrors[probnr][funcnr][costnr][trial]=scores[bvi]
                Allpstrings[probnr][funcnr][costnr][trial]=[besterrparams[0],besterrparams[1],
                                                     2**besterrparams[2],2**besterrparams[3],besterrparams[4]]

    medians=np.percentile(errors,50,axis=3)
    UQ=np.percentile(errors,75,axis=3)
    LQ=np.percentile(errors,25,axis=3)
    mean=np.mean(errors,axis=3)

    print("medians", medians)
    print("medians", UQ)
    print("medians", LQ)
    print("medians", mean)

    np.savez_compressed("OutputStats", medians, UQ, LQ, mean, errors, Verrors, Allpstrings)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('logger', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='RestService',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False,
                                        auto_created=True, primary_key=True)),
                ('service_url', models.URLField(verbose_name='Service URL')),
                ('name', models.CharField(
                    max_length=50,
                    choices=[('f2dhis2', 'f2dhis2'),
                             ('generic_json', 'JSON POST'),
                             ('generic_xml', 'XML POST'),
                             ('bamboo', 'bamboo'),
                             ('textit', 'TextIt POST')])),
                ('xform', models.ForeignKey(
                    to='logger.XForm', on_delete=models.CASCADE)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AlterUniqueTogether(
            name='restservice',
            unique_together=set([('service_url', 'xform', 'name')]),
        ),
    ]


""" Numeric manipulation and printing """

from decimal import Decimal

def roundnear(end: float, price: float, roundUp: bool) -> float:
    """Round a float to a multiple of 'end'.

    This is a more adjustable version of just:
        # example for enforcing 0.25 increments:
        return round(round(x * 4) / 4, 2)

    Note: 0.00 is a valid multiple if rounding down from near-zero or rounding
          up from a negative near-zero."""

    # Borrowed from https://stackoverflow.com/questions/13106953/python-round-05up
    p = Decimal(price)
    dend = Decimal(end)
    remainder = p.remainder_near(dend)

    # already ends in the target round increment
    if remainder == 0:
        return price

    # or maybe we want round up, so round to nearest upper breach of increment
    if roundUp:
        p = Decimal(price + (end / 2))
    else:
        # else, smaller
        p = Decimal(price - (end / 2))

    remainder = p.remainder_near(dend)
    return round(float(p - remainder), 2)

def roundnear5(price: float, roundUp: bool) -> float:
    """Round 'price' to end in a multiple of '0.05'"""
    return roundnear(0.05, price, roundUp)

def roundnear10(price: float, roundUp: bool) -> float:
    """Round 'price' to end in a multiple of '0.10'"""
    return roundnear(0.10, price, roundUp)

def fmtPrice(x, decimals=4):
    """Print price with minimum of two digit decimals or maximum
    of 4 decimals.

    Any rounding for the decimal cutoff is done via the .g formatter directly.
    """
    sign, digits, el = Decimal(str(x)).as_tuple()

    # nan, just be yourself...
    if el == "n":
        return x

    # guard the formatting lengths against being 0 because python
    # throws an exception if you try to format with a 0 specifier.
    capLen = max(2, min(decimals, abs(el)))
    finalLen = max(1, capLen + (len(digits) - abs(el)))

    if abs(el) < 3:
        return f"{x:,.2f}"

    return f"{x:,.{finalLen}g}"

def fmtPricePad(n, padding=10, decimals=4):
    """Format price with padding as:
    - two decimal precision if <= 2 decimals
        - i.e. print 120 as 120.00
               print 120.3 as 120.30
    - up to 4 decimal places if more than 2 (as formatted by 'g')

    Rounding is done by round() and Decimal() then printed via .f or .g

    Also has a check to ignore very small values taking up wide space."""

    # python formatting doesn't allow 0 padding
    padding = max(padding, 1)

    # don't show tiny tiny values, and use 'abs' because sometimes
    # we're printing full negative percentages like -20.3242343289%, which is
    # les sthan 0.005, but we want to still print them nicely.
    # also guard against 'n' being None for some reason.
    if (not n) or abs(n) < 0.005:
        if n:
            return f"{n:>{padding},.2f}"

        return f"{' ':>{padding}}"

    # print at most 4 digits, not ending in zeroes...
    dn = Decimal(str(round(n, decimals)))
    sign, digits, exponent = dn.as_tuple()

    # skip formatting nan
    if exponent == "n":
        return f"{dn:>{padding}}"

    # if less than 3 decimals, always use two places.
    if abs(exponent) < 3:
        return f"{dn:>{padding},.2f}"

    # this long G is okay because we already truncated
    # the float value to 4 decimals at most using the triple conversion
    # above of Decimal(str(round(x, 4)))
    return f"{dn:>{padding},.20g}"


from __future__ import print_function
from __future__ import absolute_import
from __future__ import division

from compas.topology import connected_components

def network_disconnected_nodes(network):
    """Get the disconnected node groups in a network.

    Parameters
    ----------
    network : :class:`~compas.datastructures.Network`
        A network.

    Returns
    -------
    list[list[hashable]]
        The list of disconnected node groups.

    """
    return connected_components(network.adjacency)

def network_disconnected_edges(network):
    """Get the disconnected edge groups in a network.

    Parameters
    ----------
    network : :class:`~compas.datastructures.Network`
        A network.

    Returns
    -------
    list[list[tuple[hashable, hashable]]]
        The list of disconnected edge groups.

    """
    components = network_disconnected_nodes(network)
    return [[(u, v) for u in component for v in network.neighbors(u) if u < v] for component in components]

def network_explode(network, cls=None):
    """Explode a network into its connected components.

    Parameters
    ----------
    network : :class:`~compas.datastructures.Network`
        A network.

    Returns
    -------
    list[:class:`~compas.datastructures.Network`]
        The list of exploded network parts.

    """
    if cls is None:
        cls = type(network)

    exploded_networks = []

    parts = network_disconnected_edges(network)

    for part in parts:
        keys = list(set([key for edge in part for key in edge]))
        nodes = [network.node_coordinates(key) for key in keys]
        key_index = {key: index for index, key in enumerate(keys)}
        edges = [(key_index[u], key_index[v]) for u, v in part]
        exploded_networks.append(cls.from_nodes_and_edges(nodes, edges))

    return exploded_networks


import matplotlib.pyplot as plt
import numpy as np

def f(x,y):
    # 计算高度值
    return (1 - x/2 + x**5 + y**3) * np.exp(-x**2 - y**2)

n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)

# 绑定网格的输入值np.meshgrid()
X,Y=np.meshgrid(x,y)

# 使用plt.contourf()把对应颜色放到等高线中
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)

# 使用plt.contour()绘制等高线，分为8+2部分
C = plt.contour(X,Y,f(X,Y),8,colors='black')

# 在等高线中添加标签
plt.clabel(C,inline=True,fontsize=10)

# 隐藏x轴和y轴角标
plt.xticks(())
plt.yticks(())
plt.show()


def saludar2(nombre= 'juan', edad=30):
    print(f" hola soy {nombre} con edad {edad}")

saludar2()
saludar2("antonio")
saludar2("albert", 40)

def suma(num1, num2):
    """_summary_

    Args:
        num1 (number): numero entero positivo mayor que cero
        num2 (number): numero entero positivo mayor que cero
    """

    return num1 + num2

print(suma(5, 5))

saludo = saludar("Mike-, 35")
print(saludo)

suma = lambda num1, num2: num1 + num2

suma = lambda num1, num2: num1 * num2

print(sumar(5, 5))


n, y = map(int, input().split())

def solve():
    for i in range(2001):
        for j in range(2001):
            if i * 10000 + j * 5000 + (n - i - j) * 1000 == y and n - i - j >= 0:
                return i, j, n - i - j
    return -1, -1, -1

print(' '.join(map(str, solve())))


#!/usr/bin/python3

def safe_print_division(a, b):
    """Returns division of a by b"""
    try:
        div = a / b
    except (TypeError, ZeroDivisionError):
        div = None
    finally:
        print("Inside result: {}".format(div))
        return div  # Unindent this line to fix the indentation error


"""
This script is based on flake8-markdown from John Franey.
Link to repository: https://github.com/johnfraney/flake8-markdown
"""

import argparse
import glob
import re
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor

if sys.version_info.major == 3 and sys.version_info.minor >= 7:
    SUBPROCESS_ARGS = dict(
        capture_output=True,
        text=True,
    )
else:
    SUBPROCESS_ARGS = dict(
        encoding="ascii",
        universal_newlines=True,
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE,
    )

def non_matching_lookahead(pattern):
    return r"(?={})".format(pattern)

def matching_group(pattern):
    return r"({})".format(pattern)

def non_matching_group(pattern):
    return r"(?:{})".format(pattern)

def strip_repl_characters(code):
    """Removes the first four characters from each REPL-style line.

    >>> strip_repl_characters('>>> "banana"') == '"banana"'
    True
    >>> strip_repl_characters('... banana') == 'banana'
    True
    """
    stripped_lines = []
    for line in code.splitlines():
        if line.startswith(">>> ") or line.startswith("... "):
            stripped_lines.append(line[4:])
        else:
            stripped_lines.append(line)
    return "\n".join(stripped_lines)

ONE_OR_MORE_LINES_NOT_GREEDY = r"(?:.*\n)+?"

regex_rule = "".join(
    [
        # Use non-matching group instead of a lookbehind because the code
        # block may have line highlighting hints. See:
        # https://python-markdown.github.io/extensions/fenced_code_blocks/#emphasized-lines
        non_matching_group("^```(python|pycon|py).*$"),
        matching_group(ONE_OR_MORE_LINES_NOT_GREEDY),
        non_matching_lookahead("^```"),
    ]
)

regex = re.compile(regex_rule, re.MULTILINE)

def security_check_markdown_file(markdown_file_path):
    markdown_content = open(markdown_file_path, "r").read()
    code_block_start_lines = []
    for line_no, line in enumerate(markdown_content.splitlines(), start=1):
        # Match python and pycon
        if line.startswith("```py"):
            code_block_start_lines.append(line_no)
    code_block_matches = regex.findall(markdown_content)
    for code_block_match in code_block_matches:
        code_block_type = code_block_match[0]
        match_text = code_block_match[1]
        # pycon lines start with ">>> " or "... ", so strip those characters
        if code_block_type == "pycon":
            match_text = strip_repl_characters(match_text)
        match_text = match_text.lstrip()
        bandit_process = subprocess.run(
            ["bandit", "-"],
            input=match_text,
            **SUBPROCESS_ARGS,
        )
        bandit_output = bandit_process.stdout
        bandit_output = bandit_output.strip()

        bandit_output = "".join(bandit_output)
        bandit_output = bandit_output.replace(r"<stdin>", markdown_file_path)
        print(bandit_output)

def security_check_markdown_glob(markdown_glob):
    files = glob.iglob(markdown_glob, recursive=True)
    with ThreadPoolExecutor() as executor:
        executor.map(security_check_markdown_file, files)

def main(argv=None):
    parser = argparse.ArgumentParser(description="Markdown globs")
    parser.add_argument(
        "globs",
        metavar="glob",
        type=str,
        nargs="+",
        help="a glob of Markdown files to check for vulnerabilities",
    )
    args = parser.parse_args(argv)
    markdown_globs = args.globs
    with ThreadPoolExecutor() as executor:
        executor.map(security_check_markdown_glob, markdown_globs)

main()


import os
import sys
import time
import pickle
import subprocess
import numpy as np
from hyperopt import Trials, STATUS_OK, tpe, hp, fmin

nthreads = 16
opath = "experiments"

r_alpha   = np.arange(0.025, 0.525, 0.025)
r_beta    = np.arange(0.500, 1.025, 0.025)
r_critexp = np.arange(    1,    11,     1)
r_tweight = np.arange(    1,    35,     5)

def evalpnr(space):

  # nextpnr args
  args = ' '.join(map(str, sys.argv[1:]))

  # suppress quiet mode
  args = args.replace('-q','')

  # append optimisation parameters
  cmd = ("%s --placer-heap-alpha %f --placer-heap-beta %f --placer-heap-critexp %i --placer-heap-timingweight %i"
          % (space['alpha'], space['beta'], space['critexp'], space['tweight']))

  # launch process
  process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)

  clk = {}
  # parse process log
  while ( process.poll() is None ):
    output = process.stdout.readline().decode()
    if 'Max frequency for clock' in output:
      clkname = output.split()[5].replace('\'','').replace(':','')
      clk['%s' % clkname] = float(output.split()[6])
      continue

  loss = 1000.0 / np.exp( np.sqrt(clk[clkname]))

  print( "space [%s] -> %f(Mhz) loss=%f" % (space, clk[clkname], loss) )

  return{'loss': loss, 'status': STATUS_OK, 'eval_time': time.time(), 'attachments': {'time_module': pickle.dumps(time.time)}}

def main():

  if (sys.argv[1] != "nextpnr-ice40"):
    print("ERROR: only nexpnr-ice40 is supported")
    sys.exit(1)

  space = {
    'alpha'   : hp.quniform ('alpha',     0.010, 0.800, 0.010),
    'beta'    : hp.quniform ('beta',      0.300, 1.000, 0.010),
    'critexp' : hp.randint  ('critexp',   1,     10          ),
    'tweight' : hp.randint  ('tweight',   1,     40          ),
  }

  trials = Trials()

  best = fmin(fn = evalpnr,
              space = space,
              algo = tpe.suggest,
              parallelism = 1,
              max_evals = 100,
              trials = trials)

  print("\n\n")
  print("Best found: ", best)

if __name__ == "__main__":
  main()


from django.contrib import admin

from goodsapp import models
class TypeInfoAdmin(admin.ModelAdmin):
    list_display = ['id', 'ttitle']

class GoodsInfoAdmin(admin.ModelAdmin):
    list_per_page = 15
    list_display = ['id', 'gtitle', 'gprice', 'gunit', 'gclick', 'gstock', 'gcontent', 'gtype']

admin.site.register(models.TypeInfo, TypeInfoAdmin)
admin.site.register(models.GoodsInfo, GoodsInfoAdmin)


def search(data,key,low,high):
    if low >= high:
        return -1
    else:
        mid = (low+high)//2;
        if data[mid] == key:
            return mid;
        elif key < data[mid]:
            return search(data,key,low,mid-1)
        else:
            return search(data,key,mid+1,high)

    return -1;

def main():

    arr = [22,33,44,55,66,77,88,89]
    key = int(input('enter the key to search :'))

    result = search(arr,key,0,len(arr)-1)

    if result == -1:
        print(key,' not found')
    else:
        print('key found at index of', result+1)

main()


try:
    from feature.backends.wrappers import featurize_points_raw
except ImportError as e:
    def featurize_points_raw(*args, **kwargs):
        raise e

from pocketfeature.io import featurefile

def featurize_points(pointslist, featurize_args=None, featurefile_args=None):
    featurize_args = featurize_args or {}
    featurefile_args = featurefile_args or {}
    data = featurize_points_raw(pointslist, **featurize_args)
    ff = featurefile.load(data, **featurefile_args)
    return ff


from itertools import chain

from flask import render_template
from sqlalchemy import func

from tracker import db
from tracker import tracker
from tracker.form import CVEForm
from tracker.form import GroupForm
from tracker.model import CVE
from tracker.model import CVEGroup
from tracker.model import CVEGroupEntry
from tracker.model import CVEGroupPackage
from tracker.model.cve import cve_id_regex
from tracker.model.cvegroup import vulnerability_group_regex
from tracker.model.enum import status_to_affected
from tracker.user import reporter_required
from tracker.view.error import not_found

@tracker.route('/issue/<regex("{}"):issue>/copy'.format(cve_id_regex[1:-1]), methods=['GET'])
@tracker.route('/cve/<regex("{}"):issue>/copy'.format(cve_id_regex[1:-1]), methods=['GET'])
@tracker.route('/<regex("{}"):issue>/copy'.format(cve_id_regex[1:-1]), methods=['GET'])
@reporter_required
def copy_issue(issue):
    cve = db.get(CVE, id=issue)
    if not cve:
        return not_found()

    form = CVEForm()
    form.cve.data = cve.id
    form.description.data = cve.description
    form.issue_type.data = cve.issue_type
    form.notes.data = cve.notes
    form.reference.data = cve.reference
    form.remote.data = cve.remote.name
    form.severity.data = cve.severity.name

    return render_template('form/cve.html',
                           title='Add CVE',
                           form=form,
                           CVE=CVE,
                           action='/cve/add')

@tracker.route('/group/<regex("{}"):avg>/copy'.format(vulnerability_group_regex[1:-1]), methods=['GET'])
@tracker.route('/avg/<regex("{}"):avg>/copy'.format(vulnerability_group_regex[1:-1]), methods=['GET'])
@tracker.route('/<regex("{}"):avg>/copy'.format(vulnerability_group_regex[1:-1]), methods=['GET'])
@reporter_required
def copy_group(avg):
    group_id = avg.replace('AVG-', '')
    group_data = (db.session.query(CVEGroup, CVE, func.group_concat(CVEGroupPackage.pkgname, ' '))
                  .filter(CVEGroup.id == group_id)
                  .join(CVEGroupEntry, CVEGroup.issues)
                  .join(CVE, CVEGroupEntry.cve)
                  .join(CVEGroupPackage, CVEGroup.packages)
                  .group_by(CVEGroup.id).group_by(CVE.id)
                  .order_by(CVE.id)).all()
    if not group_data:
        return not_found()

    group = group_data[0][0]
    issues = [cve for (group, cve, pkg) in group_data]
    issue_ids = [cve.id for cve in issues]
    pkgnames = set(chain.from_iterable([pkg.split(' ') for (group, cve, pkg) in group_data]))

    form = GroupForm()
    form.advisory_qualified.data = group.advisory_qualified
    form.affected.data = group.affected
    form.bug_ticket.data = group.bug_ticket
    form.cve.data = '\n'.join(issue_ids)
    form.fixed.data = group.fixed
    form.notes.data = group.notes
    form.pkgnames.data = '\n'.join(sorted(pkgnames))
    form.reference.data = group.reference
    form.status.data = status_to_affected(group.status).name

    return render_template('form/group.html',
                           title='Add AVG',
                           form=form,
                           CVEGroup=CVEGroup,
                           action='/avg/add')


# -*- coding: utf-8 -*-
"""
Created on Sat May 11 11:50:58 2019

@author: KIIT
"""

for number in range(1,101):
    if number%3==0 and number%5==0:
        print("FizzBuzz")
        continue
    if number%3==0:
        print("fizz")
        continue
    if number %5==0:
        print("buzz")
        continue
    print(number)


def get_names():
    elements = []
    while len(elements) < 5:
        userInput = input('Enter the name of an element: ').strip().lower()
        if not userInput in elements and not userInput == '':
            elements.append(userInput)
    return elements

import urllib.request

# Download the file from `url` and save it locally under `file_name`:
url = 'https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/elements1_20.txt'
file_name = 'elements1_20.txt'
urllib.request.urlretrieve(url, file_name)
userElements = []
correct = []
incorrect = []

elements_file = open(file_name, 'r')
elements = elements_file.readlines()

for i, element in enumerate(elements):
    elements[i] = element.strip().lower()

userElements = get_names()

for element in userElements:
    if element in elements:
        correct.append(element)
    else:
        incorrect.append(element)

percentage = len(correct) / len(userElements) * 100

print('')

print(str(percentage) + '% correct\n')
print('found: ')
for element in correct:
    print(element, ' ')

print('')

print('not found: ')
for element in incorrect:
    print(element, ' ')

print('')

elements_file.close()


from typing import List
class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        wp=0
        while wp<len(nums):
            temp=nums[wp]
            if nums[wp]==wp+1 or nums[temp-1]==temp:
                wp+=1
            else:
                nums[wp]=nums[temp-1]
                nums[temp-1]=temp
        ans=[]
        for idx,val in enumerate(nums):
            if val!=idx+1:
                ans.append(idx+1)
        return ans
s=Solution()
nums = [4,3,2,7,8,2,3,1]
print(s.findDisappearedNumbers(nums))


class Solution:
    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:

        # directions: up, down, left and right
        dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
        # get the number of rows and columns
        rows = len(heights)
        cols = len(heights[0])
        # initilize variables, keep track of the cell which can reach the ocean
        memo_pac = set()
        memo_atl = set()

        def dfs(r, c, memo):
            #get the height of the current cell
            h = heights[r][c]
            # mark the current cell to be visted
            memo.add((r, c))
            # start the recursion
            for dir in dirs:
                r_next = r + dir[0]
                c_next = c + dir[1]
                if r_next < 0 or r_next >= rows or c_next < 0 or c_next >= cols or (r_next, c_next) in memo or heights[r_next][c_next] < h:
                    continue
                dfs(r_next, c_next, memo)

        # iterates throught each cell on the coast and start DFS
        for r in range(rows):
            dfs(r, 0, memo_pac)
            dfs(r, cols - 1, memo_atl)

        for c in range(cols):
            # dfs traversal for the current cell
            dfs(0, c, memo_pac)
            dfs(rows - 1, c, memo_atl)

        return list(memo_pac.intersection(memo_atl))


import math
import numpy as np
import tensorflow as tf
from tensorflow.contrib import slim
from PIL import Image
from functools import reduce
import os, cv2

'''
    Be careful about everything you write here because every model use the code like:
    from utils import *
    Give variable names carefully and strictly to avoid namespace conflict
'''

def conv_out_size_same(size, stride):
  return int(math.ceil(float(size) / float(stride)))

# arr should be 4 dimensional
def save_image(arr, name, idx, scale=True, path='./generated/'):
    if scale:
        arr = arr * (255.0 / np.max(arr))
    try:
        for i in range(arr.shape[0]):
            img_to_save = arr[i, :, :, :].astype(np.uint8)
            cv2.imwrite(path + str(idx) + '_' + str(i) + '_' + name, img_to_save)
    except:
        print('Error encountered when saving generated images!')
        return
    print('SAVING GENERATED IMAGES TO: ' + path + name)

def show_all_variables():
    all_variables = tf.trainable_variables()
    slim.model_analyzer.analyze_vars(all_variables, print_info=True)

def get_inception_score(images, sess):
    inps = list(map(lambda img: np.expand_dims(img.astype(np.float32), axis=0), images))
    bs = 100
    preds = list()
    n_batches = int(math.ceil(float(len(inps)) / float(bs)))
    for i in range(n_batches):
        inp = inps[(i * bs):min((i + 1) * bs, len(inps))]
        inp = np.concatenate(inp, 0)
        pred = sess.run(softmax, {'ExpandDims:0': inp})
        preds.append(pred)

# The anime portrait dataset
class animeReader(object):
    def __init__(self, path, low=0, high=5000):
        self.low, self.high = low, high
        fs = os.listdir(path)
        self.files = list(map(lambda x: path + x, fs))
        arrs = list(map(lambda x: cv2.imread(x).astype(np.float32), self.files[low: high]))
        arrs = list(map(lambda x: x.flatten()[None, :], arrs))
        self.data = np.concatenate(arrs, axis=0)
        print('Data successfully loaded --sample number: %d' % (high - low))
        self.counter = 0

    # Randomized output
    def next_batch(self, num):
        index = np.random.randint(low=self.low, high=self.high, size=(1, num))
        x_batch = self.data[index]
        return x_batch[0]

    # Ordinal output
    def ordinal_batch(self, num):
        if self.counter + num < len(self.files):
            end_idx = self.counter + num
            return self.data[self.counter: end_idx, :]
        else:
            start_idx = (self.counter + num) % len(self.files)
            sub1 = self.data[: start_idx, :]
            sub2 = self.data[self.counter:, :]
            return np.concatenate([sub1, sub2], axis=0)

class cifar10Reader(object):
    dataset_dir = 'E:\\datasets\\cifar-10-batches-py\\'

    def __init__(self):
        import pickle
        file_names = ['data_batch_%d' % i for i in range(1, 6)]
        file_names = list(map(lambda x: self.dataset_dir + x, file_names))
        self.dictionaries = list(map(lambda x: pickle.load(open(x, 'rb'), encoding='bytes'), file_names))
        for item in self.dictionaries:
            # The valid value is supposed to be between 0 and 1!!!
            item[b'labels'] = np.array(item[b'labels'])
            item[b'data'] = item[b'data'].astype(np.float32) / 255.0

    def test(self):
        x, y = self.next_batch(64)
        res = x.reshape((64,32,32,3))
        cv2.imwrite('test.png', res[0, :, :, :]*255.0)

    def next_batch(self, num):
        batch_idx = np.random.randint(0, 5)
        image_idx = np.random.randint(0, 10000, size=(num))
        samples = self.dictionaries[batch_idx][b'data'][image_idx]
        labels = self.dictionaries[batch_idx][b'labels'][image_idx]
        # Fucking bloody cifar-10 orders
        for i in range(num):
            res = samples[i, :].reshape((3,32,32)).transpose([1,2,0])
            samples[i, :] = res.reshape((1, 3072))
        return samples, labels

if __name__ == '__main__':
    # Just for tests

    reader = cifar10Reader()
    reader.test()
    # x, y = reader.next_batch(1)
    # print(x, y)
    # print(x.max(), x.min(), x.shape, x.dtype)


from django.contrib import admin
from django.urls import path
from app import views
from django.conf.urls import url
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', views.FirstView.as_view(), name='first'),
    path('home/', views.BoardView.as_view(), name='index'),
    path('<int:pk>/', views.PostDetailView.as_view(), name='detail'),
    path('edit/<int:pk>', views.postedit, name='edit'),
    path('create/', views.postcreate, name='create'),
    path('delere/<int:pk>/', views.postdelete, name='delete'),
    path('login/', views.LogView.as_view(), name='login'),
    path('register/', views.RegisterView.as_view(), name='register'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),

]


class Hand:
    """Represents a hand of cards and their associated wager.

    Attributes:
        cards: a list of chars representing the cards in the hand.
               possible cards are A,2,3,4,5,6,7,8,9,X. These limitations of
               the possible chars are not enforced, care must be used when
               setting.
        bet: the value of the bet placed on the hand.
        is_split: a boolean that is true iff the hand was a result of a split.
        is_split_aces: a boolean that is true iff the hand was a result of
            splitting aces.

    """

    def __init__(self, hand, bet, is_split, is_split_aces):
        """initialize a new hand with 2 cards and a wager(bet).

        Args:
            hand(list of char): a list of two chars representing
                the initial two cards of a Blackjack hand.
            bet(int): the value of the initial bet on this hand.
            is_split(bool): true iff the hand was a result of a split.
            is_split_aces(bool): true iff the hand was a result of split aces.

        """
        self.hand = hand
        self.bet = bet
        self.is_split = is_split
        self.is_split_aces = is_split_aces

    def add_card(self, card):
        """add a card to the hand.

        Args:
            card(char): a char representing the value of the card added.
        """
        self.hand.append(card)

    def double_down(self, card):
        """add a card to the hand and doubles the bet.

        In Blackjack, after a double down move is played, no additional cards
        may be added to the hand after the double down card. However, this
        function does not enforce this behavior.

        Args:
            card(char): a char representing the value of the card added.
        """
        self.add_card(card)
        self.bet *= 2

    def get_value(self):
        """return the value of the hand."""
        result = 0
        num_aces = 0
        for card in hand:
            if card.isdigit():
                result += int(str)
            elif card == "X":
                result += 10
            elif card == "A":
                result += 11
                num_aces += 1
            else:
                #Something went wrong
                raise ValueError("Illegal Card")


# IMPORT
import hashlib
import json
import math
from   NetworkManager.ActionsStructure import ActionsMap

# SOURCE AND TARGET ARE THE SPOT
# KEY IS THE MD5 VALUE BETWEEN:
#    - GLOBAL ANNOTATION SOURCE MD5
#    - GLOBAL ANNOTATION TARGET MD5
# RELATIONS IS A DICT:
#    - ACTION LENGTH
#         - ACTION MD5 CODE: SCORE * FREQ
# WEIGHT IS THE TF-IDF
class Edge:
    def __init__(self):
        self.key         = None
        self.source      = None
        self.target      = None
        self.relations   = {}
        self.mrho        = []
        self.tf          = {}
        self.weight      = 0.0
        self.aid         = []

    def edge_configuration(self, code, source_node, dest_node, edge_info, actions):
        self.key         = code
        self.source      = source_node.global_annotation
        self.target      = dest_node.global_annotation
        self.mrho        = [(float(source_node.rho) + float(dest_node.rho)) / 2.0]
        act_cod, act_scr = self._relation_setting(edge_info[2], actions, edge_info[3])
        self.tf          = {edge_info[0]: {"tf": act_scr}}
        return act_cod, act_scr

    def edge_updating(self, source_node, dest_node, edge_info, actions):
        self.mrho.append((float(source_node.rho) + float(dest_node.rho)) / 2.0)
        act_cod, act_scr = self._relation_setting(edge_info[2], actions, edge_info[3])
        if edge_info[0] not in self.tf: self.tf[edge_info[0]] = {"tf": act_scr}
        else: self.tf[edge_info[0]]["tf"] += act_scr
        return act_cod, act_scr

    def _relation_setting(self, action, actions, bio_scores):
        action_obj   = actions.add_action_in_map(action, bio_scores)
        if action_obj.action_size not in self.relations:
            self.relations[action_obj.action_size] = {}
        size_struct  = self.relations[action_obj.action_size]
        if action_obj.code not in size_struct:
            size_struct[action_obj.code] = 0.0
        size_struct[action_obj.code] += action_obj.action_score
        return action_obj.code, action_obj.action_score

    def tf_computing(self, doc_num, docs_sents):
        idf = math.log10(doc_num / len(self.tf))
        tf  = sum([
            doc["tf"] / docs_sents[doc_id].document_edges
            for doc_id, doc in self.tf.items()
        ])
        self.weight = (tf * idf) if idf != 0 else tf

#
# ---> CLASS INFORMATION
# GRAPH NODE:
#   - KEY  IS THE GLOBAL ANNOTATION MD5.
#   - SIZE IS THE NODE FREQUENCY
#   - EDGE PART CONTAINS THE SCORE OF EACH IN COMING AND
#     OUT COMING EDGE
class Node:
    def __init__(self, node_info):
        self.key         = None
        self.size        = 0
        self.pagerank    = None
        self._node_configuration(node_info)

    def _node_configuration(self, node_info):
        self.key         = node_info.global_annotation
        self.size        = 1

    def node_updating(self):
        self.size       += 1

#
# --->CLASS INFO
# DOCUMENT SENTENCE STRUCTURE
#   - sentence_obj CONTAINS THE SPACY SENTENCE OBJECT
#   - edges IS A TUPLE CONTAINS THE SENTENCE'S EDGE INFORMATION
#     --> (edge_code, action_code)
# WHERE:
#     edge_code   IS THE md5 OF (src.md5, dst.md5)
#     action_code IS THE md5 OF THE ACTION (VERBS) OBJECT
class SentenceEdges:
    def __init__(self, sentence):
        self.sentence_obj = sentence
        self.edges_new    = {}

    def add_edge_info(self, edge_code, action_code, snode, tnode, action_pos):
        if edge_code not in self.edges_new:
            self.edges_new[edge_code] = {
                "sources": [],
                "targets": [],
                "actions": [],
                "act_pos": [],
            }
        action_pos = [(tuple_[0] - self.sentence_obj.spacy_offset, tuple_[1] - self.sentence_obj.spacy_offset) for tuple_ in action_pos]
        self.edges_new[edge_code]["sources"].append((snode.start_pos - self.sentence_obj.start_pos, snode.end_pos - self.sentence_obj.start_pos))
        self.edges_new[edge_code]["targets"].append((tnode.start_pos - self.sentence_obj.start_pos, tnode.end_pos - self.sentence_obj.start_pos))
        self.edges_new[edge_code]["actions"].append(action_code)
        self.edges_new[edge_code]["act_pos"].append(action_pos)

    def data_cleaning(self):
        edge_new_elab = {}
        for edge_code, edge_data in self.edges_new.items():
            if len(edge_data["sources"]) == 1:
                edge_new_elab[edge_code] = edge_data
                continue
            edge_new_elab[edge_code] = {
                "sources": [],
                "targets": [],
                "actions": [],
                "act_pos": [],
            }
            hash_vals  = []
            for i in range(len(edge_data["sources"])):
                hash_v = hashlib.md5(json.dumps(
                    (edge_data["sources"][i], edge_data["targets"][i], edge_data["actions"][i], edge_data["act_pos"][i]),
                    sort_keys=True).encode('utf-8')
                ).hexdigest()
                if hash_v in hash_vals: continue
                hash_vals.append(hash_v)
                edge_new_elab[edge_code]["sources"].append(edge_data["sources"][i])
                edge_new_elab[edge_code]["targets"].append(edge_data["targets"][i])
                edge_new_elab[edge_code]["actions"].append(edge_data["actions"][i])
                edge_new_elab[edge_code]["act_pos"].append(edge_data["act_pos"][i])
        self.edges_new = edge_new_elab

#
# --> CLASS DOCUMENTATION
# THIS CLASS IS USED TO STORE THE WHOLE SET OF SELECTED DOCUMENT
# SENTENCES WITHIN sentences ATTRIBUTE. THE SECOND ATTRIBUTE,
# INSTEAD, CONTAINS THE TOTAL NUMBER OF DOCUMENT'S EDGE
class DocumentSentences:
    def __init__(self):
        self.sentences      = {}
        self.document_edges = 0

    def add_edge_data(self, sentence, edge_code, action_code, snode, tnode, action_pos):
        if sentence.end_pos not in self.sentences:
            self.sentences[sentence.end_pos] = SentenceEdges(sentence)
        sent_obj = self.sentences[sentence.end_pos]
        sent_obj.add_edge_info(edge_code, action_code, snode, tnode, action_pos)
        self.document_edges += 1

class Network:
    def __init__(self):
        self.type         = None
        self.actions      = ActionsMap()
        self.docs_sents   = {}
        self.nodes        = {}
        self.edges        = {}
        self.adj_list     = {}
        self.max_prn_node = 300

    # edge: (
    #     -> source_annotation,
    #           0          1                  2                       3                           4
    #     -> (doc_id, sentence_obj, [verb_1, ..., verb_n], [bio_s_1, ..., bio_s_n], [verb_1_pos, ..., verb_n_pos])
    #     -> dest_annotation
    # )
    def add_edge(self, edge):
        sannot, edge_info, dannot = edge
        snode_id = self._add_node(sannot)
        dnode_id = self._add_node(dannot)
        edge_id  = hashlib.md5((snode_id + "_" + dnode_id).encode("utf-8")).hexdigest()
        if edge_id not in self.edges:
            edge      = Edge()
            action_id = edge.edge_configuration(edge_id, sannot, dannot, edge_info, self.actions)
            self.edges[edge_id] = edge
        else:
            edge      = self.edges[edge_id]
            action_id = edge.edge_updating(sannot, dannot, edge_info, self.actions)
        if edge_info[0] not in self.docs_sents:
            self.docs_sents[edge_info[0]] = DocumentSentences()
        self.docs_sents[edge_info[0]].add_edge_data(edge_info[1], edge_id, action_id, sannot, dannot, edge_info[-1])

    def _add_node(self, annotation_obj):
        if annotation_obj.global_annotation not in self.nodes:
            node_obj = Node(annotation_obj)
            self.nodes[node_obj.key] = node_obj
            return node_obj.key
        self.nodes[annotation_obj.global_annotation].node_updating()
        return annotation_obj.global_annotation

    def edge_score_computing(self):
        doc_num = len(self.docs_sents)
        max_edge_score = -1
        for edge in self.edges.values():
            edge.tf_computing(doc_num, self.docs_sents)
            max_edge_score = max(edge.weight, max_edge_score)
        for edge_id, edge in self.edges.items():
            edge.weight      = edge.weight/max_edge_score
            edge.mrho        = sum(edge.mrho) / len(edge.mrho)
            edge.aid         = list(edge.tf.keys())
            src, dst         = edge.source, edge.target
            if src not in self.adj_list: self.adj_list[src] = []
            self.adj_list[src].append((dst, edge_id))

    def node_score_normalization(self):
        max_score     = -1
        for node in self.nodes.values():
            max_score = max(max_score, node.size)
        for node in self.nodes.values():
            node.size = node.size / max_score
        self.nodes = dict(sorted(self.nodes.items(), key=lambda x: x[1].size, reverse=True))


import re
from typing import Literal
input = '1113222113'

cycles = 50

for i in range(cycles):
    process = re.finditer(r'(\d)\1{1,}|(\d{1})', input)
    newInput = []

    for match in process:
        pos = match.span()[0]
        count = len(str(match.group()))
        newProcess = str(count) + str(match.group()[0])
        newInput.append([newProcess, pos])
    # order newInput by position
    newInput.sort(key=lambda x: x[1])
    # write newInput to input
    input = ''
    for i in newInput:
        input += i[0]

print("Length of input: " + str(len(input)))
print("Done")


import ast
from glob import glob
import os
from typing import Union
from markdown_it import MarkdownIt
from markdown_it.token import Token
import pytest
import re
from .lib.nb_helper import is_h1, is_markdown, is_python, read_notebook

def check_metadata(notebook, file, expected_kernel):
    metadata = notebook.metadata
    runtime = metadata.kernelspec.display_name

    assert runtime == expected_kernel
    assert metadata.language_info.version.startswith("3.")

    if "colab" in metadata:
        colab_name = metadata["colab"]["name"]
        assert colab_name == file, f"Name in metadata doesn't match filename for {file}."

def check_file(file, expected_kernel="Python [conda env:python-public-policy] *"):
    notebook = read_notebook(file)
    check_metadata(notebook, file, expected_kernel)

notebooks = glob("*.ipynb")
notebooks.sort()
crash_course = os.path.join(os.path.dirname(__file__), "pandas_crash_course.ipynb")
all_notebooks = notebooks + [crash_course]

@pytest.mark.parametrize("notebook", notebooks)
def test_class_notebooks(notebook):
    check_file(notebook)

def test_colab():
    # run in Google Colab
    check_file(crash_course, "Python 3")

@pytest.mark.parametrize("file", all_notebooks)
def test_one_h1(file):
    notebook = read_notebook(file)
    num_h1s = sum(is_h1(cell) for cell in notebook.cells)
    assert num_h1s == 1

@pytest.mark.parametrize("file", all_notebooks)
def test_heading_levels(file):
    notebook = read_notebook(file)
    for cell in notebook.cells:
        meta = cell.metadata
        source = cell.source
        if is_markdown(cell) and "slideshow" in meta and source.startswith("#"):
            # slide with a heading
            slide_type = meta["slideshow"]["slide_type"]
            if slide_type == "slide":
                assert source.startswith(("# ", "## ")), "should be an H1 or H2"
            elif slide_type == "subslide":
                assert source.startswith("###"), "should be H3+"

@pytest.mark.parametrize("file", notebooks)
def test_nested_lists(file):
    """JupyterBook's markdown parser doesn't support nested lists with two spaces."""

    notebook = read_notebook(file)
    for cell in notebook.cells:
        if is_markdown(cell):
            source = cell.source
            for line in source.splitlines():
                match = re.match(r"^( +)(-|\d\.)", line)
                if match:
                    num_spaces = len(match[1])
                    assert (
                        num_spaces % 3 == 0 or num_spaces % 4 == 0
                    ), f"Lists should be indented in multiples of three or four spaces. Text:\n\n{source}\n"

def check_link(token: Token, parent: Token = None):
    if token.type == "link_open":
        href = token.attrGet("href")
        # escaped Jinja2 tags
        if not re.match(r"http|#|%7B%7B", href):
            source = parent.content if parent else token.content
            assert False, f"Link should be absolute. Text:\n\n{source}\n"

@pytest.mark.parametrize("file", notebooks)
def test_links(file):
    """To ensure that links work from the coding environment, ensure all links are absolute."""

    md = MarkdownIt()

    notebook = read_notebook(file)
    for cell in notebook.cells:
        if is_markdown(cell):
            source = cell.source
            tokens = md.parse(source)
            for token in tokens:
                check_link(token)
                if token.type == "inline":
                    for child in token.children:
                        check_link(child, token)

def base_obj(node: ast.Call) -> Union[str, None]:
    """If this is a method call, return the name of the base object it was called on"""
    if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name):
        return node.func.value.id
    else:
        return None

class PlotChecker(ast.NodeVisitor):
    def visit_Call(self, node):
        if base_obj(node) == "px":
            args = [kw.arg for kw in node.keywords]
            method = node.func.attr

            if method == "get_trendline_results":
                # `title` not applicable
                return

            assert "title" in args, f"call to `{method}()` missing a `title`"

@pytest.mark.parametrize("file", notebooks)
def test_chart_titles(file):
    """Make sure all charts have titles"""

    notebook = read_notebook(file)
    for cell in notebook.cells:
        tags = cell.metadata.get("tags", [])
        if "skip-plot-check" in tags or not is_python(cell):
            continue

        tree = ast.parse(cell.source)
        checker = PlotChecker()
        checker.visit(tree)

hw_notebooks = glob("hw_*.ipynb")

@pytest.mark.parametrize("file", hw_notebooks)
def test_reminders(file):
    notebook = read_notebook(file)

    assert any(
        "assignments.html" in cell.source for cell in notebook.cells
    ), "Missing assignment submission instructions"

    assert any(
        "participation" in cell.source for cell in notebook.cells
    ), "Missing participation reminder"


import numpy as np

T_shape = np.zeros([3,3]) #T
T_shape[0,0]=T_shape[0,1] =T_shape[0,2] =T_shape[1,1] =T_shape[2,1] = 1
T_shape_90 = np.zeros([3,3])
T_shape_90[0,2]=T_shape_90[1,0]=T_shape_90[1,1]=T_shape_90[1,2]=T_shape_90[2,2]=1
T_shape_180 = np.zeros([3,3])
T_shape_180[0,1] =T_shape_180[1,1]=T_shape_180[2,0]=T_shape_180[2,1]=T_shape_180[2,2]=1
T_shape_270 = np.zeros([3,3])
T_shape_270[0,0] =T_shape_270[1,0] =T_shape_270[1,1] =T_shape_270 [1,2]=T_shape_270[2,0] =1

short_T_shape = np.zeros([3,3]) #T
short_T_shape[0,0]=short_T_shape[0,1] =short_T_shape[0,2] =short_T_shape[1,1] = 1
short_T_shape_90 = np.zeros([3,3])
short_T_shape_90[0,2]=short_T_shape_90[1,1]=short_T_shape_90[1,2]=short_T_shape_90[2,2]=1
short_T_shape_180 = np.zeros([3,3])
short_T_shape_180[1,1]=short_T_shape_180[2,0]=short_T_shape_180[2,1]=short_T_shape_180[2,2]=1
short_T_shape_270 = np.zeros([3,3])
short_T_shape_270[0,0] =short_T_shape_270[1,0] =short_T_shape_270[1,1] =short_T_shape_270[2,0] =1

LargeL_shape = np.zeros([3,3]) #LargeL
LargeL_shape[0,0]=LargeL_shape[1,0]=LargeL_shape[2,0]=LargeL_shape[2,1]=LargeL_shape[2,2]=1
LargeL_shape_90 = np.zeros([3,3]) #LargeL
LargeL_shape_90[0,0]=LargeL_shape_90[0,1]=LargeL_shape_90[0,2]=LargeL_shape_90[1,0]=LargeL_shape_90[2,0]=1
LargeL_shape_180 = np.zeros([3,3]) #LargeL
LargeL_shape_180[0,0]=LargeL_shape_180[0,1]=LargeL_shape_180[0,2]=LargeL_shape_180[1,2]=LargeL_shape_180[2,2]=1
LargeL_shape_270 = np.zeros([3,3]) #LargeL
LargeL_shape_270[0,2]=LargeL_shape_270[1,2]=LargeL_shape_270[2,0]=LargeL_shape_270[2,1]=LargeL_shape_270[2,2]=1

L_shape = np.zeros([3,3]) #LargeL
L_shape[0,0]=L_shape[1,0]=L_shape[2,0]=L_shape[2,1]=1
L_shape_90 = np.zeros([3,3]) #LargeL
L_shape_90[0,0]=L_shape_90[0,1]=L_shape_90[0,2]=L_shape_90[1,0]=1
L_shape_180 = np.zeros([3,3]) #LargeL
L_shape_180[0,1]=L_shape_180[0,2]=L_shape_180[1,2]=L_shape_180[2,2]=1
L_shape_270 = np.zeros([3,3]) #LargeL
L_shape_270[1,2]=L_shape_270[2,0]=L_shape_270[2,1]=L_shape_270[2,2]=1

inverse_L_shape = np.zeros([3,3]) #LargeL
inverse_L_shape[0,2]=inverse_L_shape[1,2]=inverse_L_shape[2,1]=inverse_L_shape[2,2]=1
inverse_L_shape_90 = np.zeros([3,3]) #LargeL
inverse_L_shape_90[1,0]=inverse_L_shape_90[2,0]=inverse_L_shape_90[2,1]=inverse_L_shape_90[2,2]=1
inverse_L_shape_180 = np.zeros([3,3]) #LargeL
inverse_L_shape_180[0,0]=inverse_L_shape_180[0,1]=inverse_L_shape_180[1,0]=inverse_L_shape_180[2,0]=1
inverse_L_shape_270 = np.zeros([3,3]) #LargeL
inverse_L_shape_270[0,0]=inverse_L_shape_270[0,1]=inverse_L_shape_270[0,2]=inverse_L_shape_270[1,2]=1

small_L_shape = np.zeros([2,2])
small_L_shape[0,0]=small_L_shape[1,0]=small_L_shape[1,1]=1
small_L_shape_90 = np.zeros([2,2])
small_L_shape_90[0,0]=small_L_shape_90[0,1]=small_L_shape_90[1,1]=1

square = np.zeros([2,2])
square += 1

five = np.zeros([1,5])
five+=1

ver_five = np.zeros([5,1])
ver_five+=1

four = np.zeros([1,4])
four+=1

ver_four = np.zeros([4,1])
ver_four+=1

three = np.zeros([1,3])
three+=1

ver_three = np.zeros([3,1])
ver_three+=1

two = np.zeros([1,2])
two+=1

ver_two = np.zeros([2,1])
ver_two+=1

one = np.zeros([1,1])
one+=1

mo_shape = np.zeros([3,3])
mo_shape[0,0]=mo_shape[0,1]=mo_shape[0,2]=mo_shape[1,0]=mo_shape[1,2]=1
mo_shape_90 = np.zeros([3,3])
mo_shape_90[0,1]=mo_shape_90[0,2]=mo_shape_90[1,2]=mo_shape_90[2,1]=mo_shape_90[2,2]=1
mo_shape_180 = np.zeros([3,3])
mo_shape_180[1,0]=mo_shape_180[1,2]=mo_shape_180[2,0]=mo_shape_180[2,1]=mo_shape_180[2,2]=1
mo_shape_270 = np.zeros([3,3])
mo_shape_270[0,0]=mo_shape_270[0,1]=mo_shape_270[1,0]=mo_shape_270[2,0]=mo_shape_270[2,1]=1

s_shape = np.zeros([3,3])
s_shape[1,1]=s_shape[1,2]=s_shape[2,0]=s_shape[2,1]=1
s_shape_90 = np.zeros([3,3])
s_shape_90[0,1]=s_shape_90[1,1]=s_shape_90[1,2]=s_shape_90[2,2]=1
inverse_s_shape = np.zeros([3,3])
inverse_s_shape[1,0]=inverse_s_shape[1,1]=inverse_s_shape[2,1]=inverse_s_shape[2,2]=1
inverse_s_shape_90 = np.zeros([3,3])
inverse_s_shape_90[0,1]=inverse_s_shape_90[1,0]=inverse_s_shape_90[1,1]=inverse_s_shape_90[2,0]=1

board = np.zeros([9,9])

while True:
    shape = input('step:')
    if shape =='T_shape':
        print(T_shape)
    if shape =='T_shape_90':
        print(T_shape_90)
    if shape =='T_shape_180':
        print(T_shape_180)
    if shape =='T_shape_270':
        print(T_shape_270)
    if shape =='short_T_shape':
        print(short_T_shape)
    if shape =='short_T_shape_90':
        print(short_T_shape_90)
    if shape =='short_T_shape_180':
        print(short_T_shape_180)
    if shape =='short_T_shape_270':
        print(short_T_shape_270)
    if shape =='LargeL_shape':
        print(LargeL_shape)
    if shape =='LargeL_shape_90':
        print(LargeL_shape_90)
    if shape =='LargeL_shape_180':
        print(LargeL_shape_180)
    if shape =='LargeL_shape_270':
        print(LargeL_shape_270)
    if shape =='L_shape':
        print(L_shape)
    if shape =='L_shape_90':
        print(L_shape_90)
    if shape =='L_shape_180':
        print(L_shape_180)
    if shape =='L_shape_270':
        print(L_shape_270)
    if shape =='inverse_L_shape':
        print(inverse_L_shape)
    if shape =='inverse_L_shape_90':
        print(inverse_L_shape_90)
    if shape =='inverse_L_shape_180':
        print(inverse_L_shape_180)
    if shape =='inverse_L_shape_270':
        print(inverse_L_shape_270)
    if shape =='small_L_shape':
        print(small_L_shape)
    if shape =='small_L_shape_90':
        print(small_L_shape_90)
    if shape =='mo_shape':
        print(mo_shape)
    if shape =='mo_shape_90':
        print(mo_shape_90)
    if shape =='mo_shape_180':
        print(mo_shape_180)
    if shape =='mo_shape_270':
        print(mo_shape_270)
    if shape =='s_shape':
        print(s_shape)
    if shape =='s_shape_90':
        print(s_shape_90)
    if shape =='inverse_s_shape':
        print(inverse_s_shape)
    if shape =='inverse_s_shape_90':
        print(inverse_s_shape_90)
    if shape =='square':
        print(square)
    if shape =='ver_five':
        print(ver_five)
    if shape =='five':
        print(five)
    if shape =='ver_four':
        print(ver_four)
    if shape =='four':
        print(four)
    if shape =='ver_three':
        print(ver_three)
    if shape =='three':
        print(three)
    if shape =='ver_two':
        print(ver_two)
    if shape =='two':
        print(two)
    if shape =='one':
        print(one)


from django.contrib import admin, messages
from django.contrib.admin import AdminSite
# from .views import updateProductionData
from .models import InstalledCmm, DeliveredCmm, NewOrder, WaitingOrderAndInventory, InstalledEachYear
from django.urls import path
from django.http import HttpResponseRedirect
from .productionUpdate import updateProduction

class InsalledCmmAdmin(admin.ModelAdmin):
    fields = ['Year','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    list_display = ('Year','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
    search_fields = ['Year']
    # actions = ['update_data']

    change_list_template = 'op/update_changelist.html'
    # def save_model(self, rquest, obj, form, change):
    #     if 'update_data' in form.changed_data:
    #         messages.add_message(rquest, messages.INFO, 'Car has been sold')
    #     super(InsalledCmmAdmin, self).save_model(rquest, obj, form, change)
    def get_actions(self, request):
        actions = super().get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    def get_urls(self):
        urls = super().get_urls()
        my_urls = [
            path('immortal/', self.update_data),

        ]
        return my_urls + urls

    def update_data(self, request):
        message = updateProduction()
        if "全部更新成功" in message:
            self.message_user(request, message)
        else:
            messages.error(request, message)
        return HttpResponseRedirect("../")

    # update_data.short_description='更新数据'

    # def get_actions(self, request):
    #     actions = super().get_actions(request)
    #     if 'delete_selected' in actions:
    #         del actions['delete_selected']
    #     return actions

class WaitingOrderAndInventoryAdmin(admin.ModelAdmin):
    fields = ['YearAndMonth','OrderQty','ShipmentQty','AuctalAssemblyQty','ToBeExcutedTendency','BackLogTendency','NetAvailableTendency','Backlog','ToBeExcutedOrder','NetAvailable']
    list_display = ('YearAndMonth','OrderQty','ShipmentQty','AuctalAssemblyQty','ToBeExcutedTendency','BackLogTendency','NetAvailableTendency','Backlog','ToBeExcutedOrder','NetAvailable')
    search_fields = ['YearAndMonth']
    def get_actions(self, request):
        actions = super().get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions
    change_list_template = 'op/update_changelist.html'
    def get_urls(self):
        urls = super().get_urls()
        my_urls = [
            path('immortal/', self.update_data),

        ]
        return my_urls + urls

    def update_data(self, request):
        message = updateProduction()
        if "全部更新成功" in message:
            self.message_user(request, message)
        else:
            messages.error(request, message)
        return HttpResponseRedirect("../")

class InstalledEachYearAdmin(admin.ModelAdmin):
    fields = ['Year','Global_A','Global_B','Global_C','Global_D','Global_EF','Explorer','Inspector_Pioneer_InspectorP_GlobalP','MH3D_Inspector454_Explorer454','Optive_Vision','Toro_ToroImage','Micro_Plus','Alpha_Apollo','Function_Pluse','Zoo_ZC','Stinger_ll','Global_Mini','Auctual_Build_Qty']
    list_display = ('Year','Global_A','Global_B','Global_C','Global_D','Global_EF','Explorer','Inspector_Pioneer_InspectorP_GlobalP','MH3D_Inspector454_Explorer454','Optive_Vision','Toro_ToroImage','Micro_Plus','Alpha_Apollo','Function_Pluse','Zoo_ZC','Stinger_ll','Global_Mini','Auctual_Build_Qty')
    search_fileds = ['Year']
    def get_actions(self, request):
        actions = super().get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions
    change_list_template = 'op/update_changelist.html'
    def get_urls(self):
        urls = super().get_urls()
        my_urls = [
            path('immortal/', self.update_data),

        ]
        return my_urls + urls

    def update_data(self, request):
        message = updateProduction()
        if "全部更新成功" in message:
            self.message_user(request, message)
        else:
            messages.error(request, message)
        return HttpResponseRedirect("../")

admin.site.register(InstalledCmm, InsalledCmmAdmin)
admin.site.register(DeliveredCmm, InsalledCmmAdmin)
admin.site.register(NewOrder, InsalledCmmAdmin)
admin.site.register(WaitingOrderAndInventory, WaitingOrderAndInventoryAdmin)
admin.site.register(InstalledEachYear, InstalledEachYearAdmin)

admin.site.site_header = "Hexagon"
admin.site.site_title = "管理页面"
admin.site.index_title = "欢迎来到管理页面"

########## duplicated ######
class ProducedAdminSite(AdminSite):
    site_header = 'Installed Admin Site'
    site_title = "Installed Admin Site"
    index_title = 'Installed Admin Site'

produced_admin_site = ProducedAdminSite(name='produced_admin')

produced_admin_site.register(InstalledCmm)
produced_admin_site.register(DeliveredCmm)
produced_admin_site.register(NewOrder)
produced_admin_site.register(WaitingOrderAndInventory)
produced_admin_site.register(InstalledEachYear)


leiviska = int(input('Anna leiviskät '))
naulat = int(input('Anna naulat '))
luodit = float(input('Anna luodit '))

luotiPaino = 13.3
naulaPaino = 32 * luotiPaino
leiviskaPaino = 20 * naulaPaino

kokonaisPaino = (leiviskaPaino*leiviska) + (naulaPaino*naulat) + (luotiPaino*luodit)
painoKilo = kokonaisPaino // 1000
painoGram = kokonaisPaino - painoKilo*1000

print(f'Massa nykymittojen mukaan: {painoKilo:.0f} kilogrammaa ja {painoGram:.2f} grammaa')


# 函数（http://docs.python.org/3/library/functions.html#abs）

# 一、内置函数：Python 内置了很多函数可以直接调用：

# abs() 函数，只能有一个参数
print('abs(-10) =', abs(-10))

# max() 函数，可以接收多个参数，并返回最大的数，但是不能 整数和字串比较
print('max(2, 5, 3, 9, -1) =', max(2, 5, 3, 9, -1))     # 9
print("max('coral', 'bella') =", max('coral', 'bella')) # coral
print(max(9, 2.0)) # 9

# 数据类型转换函数，int()函数 -> 将其他数据类型转为整数
print(int('123')) # 123
print(int(12.34)) # 12
print(int(12.59)) # 12
print(int(-11.2)) # -11
print(int(-11.5)) # -11

print(str(1.23))  # 1.23

print(bool(1))    # True
print(bool(''))   # False

# 给函数起别名：将函数名赋给一个变量
a = abs
print(a(-1))  # 1

# 二、定义函数
# 使用 def语句，格式： def 函数名(参数名): 在缩进块中写函数体，return 返回值

def my_abs(x):
	if x >= 0:
		return x
	else:
		return -x

print('my_abs(-2) =', my_abs(-2)) # my_abs(-2) = 2

# 函数引用：若在文件 myfunction.py 中定义了函数 my_abs() ，则
from python_2_myfunc import my_sum
my_sum(10)  # 1 + 2 + ... + 10 = 45

# 空函数：一个什么事都不做的空函数，用 pass 语句
def pop():
	if (True):
		pass
	pass  # pass 可以作为占位符，如没想好函数体，可先放一个pss，让代码跑起来

# 函数返回多个值，其实是一种假象，返回仍是单一值，且是一个 tuple
import math  # 表示导入 math包
def move(x, y, step, angle = 0):
	nx = x + step * math.cos(angle)
	ny = y - step * math.sin(angle)
	return nx, ny

# move:  (151.96152422706632, 70.0)
print('move: ', move(100, 100, 60, math.pi / 6))

# 总结：
# 1. 定义函数时，需要先确定函数名和参数个数；
# 2. 若有必要，可以先对参数进行数据类型检查；
# 3. 函数体内部可以用 return 随时返回函数结果；
# 4. 函数无返回数据执行 return 时，自动 return None;
# 5. 函数可以同时返回多个值，但其实就是一个 tuple。

# 练习
import math
def quadratic(a, b, c):
	if (a == 0):
		if b:
			return c / b
	x1 = (-b + math.sqrt(b * b - 4 * a * c)) / (2 * a)
	x2 = (-b - math.sqrt(b * b - 4 * a * c)) / (2 * a)
	return x1, x2

print(quadratic(2, 3, 1))  # (-0.5, -1.0)
print(quadratic(0, 3, 1))  # 0.3333333333333333
print(quadratic(1, 3, -4)) # (-0.5, -1.0)

# 三、函数的参数

# def power(x):
# 	return x * x
# print(power(2))  # 4

# 默认参数 n = 2，当调用 power(5) = power(5, 2)，
# 也即是一个参数时，默认计算平方， n>2 ，则计算 x 的n次方
def power(x, n = 2):
	s = 1
	while n > 0:
		n = n - 1
		s = s * x
	return s
print(power(5, 3))	# 125

# 1. 默认参数
# 说明：1）必选参数在前，默认参数在后，否则解释器会报错；
#      2) 如何设置默认参数？当函数有多个参数时，把变化大的参数放前面，变化小的放后面，变化小的参数就可作默认参数。
# 好处：降低调用函数的难度，无论简单还是复杂调用，函数只需要定义一个。

# 例子：将年龄和城市设置为默认参数
def enroll(name, gender, age = 6, city = 'Beijing'):
	print('name: %s, gender: %s, age: %d, city: %s' % (name, gender, age, city))
enroll('Coral', 'Female')
enroll('Coral', 'Female', 24)
# enroll('Coral', 'Female', 'Shanghai')  # 报错
enroll('Coral', 'Female', 24, 'Shanghai')

# name: Coral, gender: Female, age: 6, city: Beijing
# name: Coral, gender: Female, age: 24, city: Beijing
# name: Coral, gender: Female, age: 6, city: Shanghai
# name: Coral, gender: Female, age: 24, city: Shanghai

# 默认参数特殊情况
def add_end(arr = []):
	arr.append('END')
	return arr
print(add_end())  # ['END']
print(add_end())  # ['END', 'END']

# 注：这里有一个问题，默认参数为 [] ，L为变量指向对象[]，
# 每次调用该函数，若改变了 L 的内容，下次调用时，默认参数内容就改变，不在是函数定义时的 [] 了。
# 因此，默认参数必须指向不变对象！

# 修改上述函数
def add_end2(arr = None):
	if arr is None:
		L = []
	L.append('END')
	return L
print(add_end2())  # ['END']
print(add_end2())  # ['END'] 为 None 时重新赋值

# 2. 可变参数
# 说明：传入参数个数可变，在函数调用时，自动组装为一个 tuple
# 例子： 计算 a2 + b2+ ...

# 方式一：参数以 list 或者 tuple 传入
def calculate(numbers):
	sum = 0
	for n in numbers:
		sum = sum + n * n
	return sum
print('cal(1, 2, 3) =', calculate([1, 2, 3]))   # cal(1, 2, 3) = 14
print('cal(1, 2, 3, 4, 5, 6) =', calculate([1, 2, 3, 4, 5, 6]))  # cal(1, 2, 3, 4, 5, 6) = 91

# 方式二：可变参数-参数个数可变
def calculate2(*numbers):
	sum = 0
	for n in numbers:
		sum = sum + n * n
	return sum
print('cal(1, 2, 3) =', calculate2(1, 2, 3))   # cal(1, 2, 3) = 14
print('cal(1, 2, 3, 4, 5, 6) =', calculate2(1, 2, 3, 4, 5, 6))

# *nums 将一个数组的所有元素都作为可变参数传入
nums = [1, 2, 3]
print(calculate2(*nums))

# 3. 关键字参数
# 说明：允许传入0-n个含参数名的参数，这些关键字参数在函数内部自动组装为一个 dict。

def person(name, age, **kw):
	print('name:', name, 'age:', age, 'other:', kw)
person('Michael', 30)              # name: Michael age: 30 other: {}
person('Bob', 35, city='Beijing')  # name: Bob age: 35 other: {'city': 'Beijing'}
person('Adam', 45, gender='M', job='Engineer')    # name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
myDict = { 'city': 'Beijing', 'job': 'Engineer' }
person('Jack', 20, **myDict)       # name: Jack age: 20 other: {'city': 'Beijing', 'job': 'Engineer'}
# 注：kw 获得的dict是 myDict 的一份拷贝，对 kw 的改变不会影响到函数外的 myDict 。

# 4. 命名关键字参数：限定只接受某几个参数，使用 * 标志其后面的参数为命名关键字参数。
def person2(name, age, *args, city, job):
    print(name, age, args, city, job)

person2('Jane', 1, 'hello', city = 'shanghai', job = 'Paint')

# 5. 多个参数组合，单参数定义顺序必须是：必选参数、默认参数、可变参数、命名关键字参数 和 关键字参数
def f1(a, b, c=0, *args, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)

def f2(a, b, c=0, *, d, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)

args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
f1(*args, **kw)

########################################################
# 四、递归函数

# 1. 计算阶乘 n! = 1 * 2 * ... * n .
def fact(n):
	if n == 1:
		return 1
	return n * fact(n - 1)

print('fact(%d) = %d' % (5, fact(5)))

# 注：类似 fact(n) 递归函数要防止栈溢出，递归调用次数过多，会导致栈溢出。
# 解决递归调用栈溢出方法：尾递归优化，在函数返回时，调用自身本身，并且 return 语句不能包含表达式。
# 改变上述递归为尾递归：
def fact2(n):
	return fact_iter(n, 1)

def fact_iter(num, product):
	if (num == 1):
		return product
	return fact_iter(num - 1, num * product)

print('fact2(%d) = %d' % (5, fact2(5)))

# 练手：汉罗塔，打印出把n个盘子从A借助B移动到C的方法，n表示3个柱子中第一个柱子A的盘子数量。
def move(n, a, b, c):
	if n == 1:
		printStep(n, a, b, c)
	else:
		move(n - 1, a, c, b) # 将 n-1 个盘子从 A -> B
		move(1, a, b, c)     # 将最底下一个从 A -> C
		move(n - 1, b, a, c) # 将剩余 n-1 个盘子从 B -> A （一轮结束，重复上述步骤）

def printStep(n, first, second, third):
	if (n == 1):
		print('把第%d个盘子从%s -> %s' % (n, first, third))
	else:
		print('把剩余%d个盘子从%s -> %s' % (n, first, third))

move(3, 'A', 'B', 'C')


import tensorflow as tf
from tensorflow.keras import layers

from main.config import Config

class CommonPoseDiscriminator(tf.keras.Model):
    """ For pose, theta is first converted to K many 3 × 3 rotation matrices via the Rodrigues formula.
        Each rotation matrix is sent to a common embedding network of two fully connected layers with
        32 hidden neurons.
    """

    def __init__(self):
        super(CommonPoseDiscriminator, self).__init__(name='common_pose_discriminator')
        self.config = Config()

        l2_regularizer = tf.keras.regularizers.l2(self.config.DISCRIMINATOR_WEIGHT_DECAY)
        conv_2d_params = {
            'filters': 32,
            'kernel_size': [1, 1],
            'padding': 'same',
            'data_format': 'channels_last',
            'kernel_regularizer': l2_regularizer
        }
        self.conv_2d_one = layers.Conv2D(**conv_2d_params, name='conv_2d_one')
        self.conv_2d_two = layers.Conv2D(**conv_2d_params, name='conv_2d_two')

    # [batch x K x 9]
    def call(self, inputs, **kwargs):
        batch_size = inputs.shape[0] or self.config.BATCH_SIZE
        shape = (batch_size, self.config.NUM_JOINTS, 9)
        assert inputs.shape[1:] == shape[1:], 'shape mismatch: should be {} but is {}'.format(shape, inputs.shape)

        x = tf.expand_dims(inputs, 2)  # to batch x K x 1 x 9 ('channels_last' default)
        x = self.conv_2d_one(x, **kwargs)
        x = tf.nn.relu(x)
        x = self.conv_2d_two(x, **kwargs)
        x = tf.nn.relu(x)
        return x  # to [batch x K x 1 x 32]

    def compute_output_shape(self, input_shape):
        return None, self.config.NUM_JOINTS, 1, 32

class SingleJointDiscriminator(tf.keras.Model):
    """The outputs of the common embedding network are sent to K different discriminators
        (single joint discriminators) that output 1-D values.
    """

    def __init__(self):
        super(SingleJointDiscriminator, self).__init__(name='single_joint_discriminator')
        self.config = Config()

        l2_regularizer = tf.keras.regularizers.l2(self.config.DISCRIMINATOR_WEIGHT_DECAY)
        self.joint_discriminators = []
        for i in range(self.config.NUM_JOINTS):
            self.joint_discriminators.append(layers.Dense(1, kernel_regularizer=l2_regularizer, name="fc_{}".format(i)))

    # [batch x K x 1 x 32]
    def call(self, inputs, **kwargs):
        batch_size = inputs.shape[0] or self.config.BATCH_SIZE
        shape = (batch_size, self.config.NUM_JOINTS, 1, 32)
        assert inputs.shape[1:] == shape[1:], 'shape mismatch: should be {} but is {}'.format(shape, inputs.shape)

        single_joint_outputs = []
        for i in range(self.config.NUM_JOINTS):
            single_joint_outputs.append(self.joint_discriminators[i](inputs[:, i, :, :], **kwargs))

        output = tf.squeeze(tf.stack(single_joint_outputs, 1))
        return output  # [batch x K]

    def compute_output_shape(self, input_shape):
        return None, self.config.NUM_JOINTS

class FullPoseDiscriminator(tf.keras.Model):

    def __init__(self):
        super(FullPoseDiscriminator, self).__init__(name='full_pose_discriminator')
        self.config = Config()

        l2_regularizer = tf.keras.regularizers.l2(self.config.DISCRIMINATOR_WEIGHT_DECAY)
        self.flatten = layers.Flatten()
        self.fc_one = layers.Dense(1024, kernel_regularizer=l2_regularizer, name="fc_0")
        self.fc_two = layers.Dense(1024, kernel_regularizer=l2_regularizer, name="fc_1")
        self.fc_out = layers.Dense(1, kernel_regularizer=l2_regularizer, name="fc_out")

    # [batch x K x 1 x 32]
    def call(self, inputs, **kwargs):
        batch_size = inputs.shape[0] or self.config.BATCH_SIZE
        shape = (batch_size, self.config.NUM_JOINTS, 1, 32)
        assert inputs.shape[1:] == shape[1:], 'shape mismatch: should be {} but is {}'.format(shape, inputs.shape)

        x = self.flatten(inputs)
        x = self.fc_one(x, **kwargs)
        x = tf.nn.relu(x)
        x = self.fc_two(x, **kwargs)
        x = tf.nn.relu(x)
        x = self.fc_out(x, **kwargs)
        return x  # [batch x 1]

    def compute_output_shape(self, input_shape):
        return None, 1

class ShapeDiscriminator(tf.keras.Model):
    def __init__(self):
        super(ShapeDiscriminator, self).__init__(name='shape_discriminator')
        self.config = Config()

        l2_regularizer = tf.keras.regularizers.l2(self.config.DISCRIMINATOR_WEIGHT_DECAY)
        self.fc_one = layers.Dense(10, kernel_regularizer=l2_regularizer, name="fc_0")
        self.fc_two = layers.Dense(5, kernel_regularizer=l2_regularizer, name="fc_1")
        self.fc_out = layers.Dense(1, kernel_regularizer=l2_regularizer, name="fc_out")

    # [batch x beta]
    def call(self, inputs, **kwargs):
        batch_size = inputs.shape[0] or self.config.BATCH_SIZE
        shape = (batch_size, self.config.NUM_SHAPE_PARAMS)
        assert inputs.shape[1:] == shape[1:], 'shape mismatch: should be {} but is {}'.format(shape, inputs.shape)

        x = self.fc_one(inputs, **kwargs)
        x = tf.nn.relu(x)
        x = self.fc_two(x, **kwargs)
        x = tf.nn.relu(x)
        x = self.fc_out(x, **kwargs)
        return x  # [batch x 1]

    def compute_output_shape(self, input_shape):
        return None, 1

class Discriminator(tf.keras.Model):

    def __init__(self):
        super(Discriminator, self).__init__(name='discriminator')
        self.config = Config()

        self.common_pose_discriminator = CommonPoseDiscriminator()
        self.single_joint_discriminator = SingleJointDiscriminator()
        self.full_pose_discriminator = FullPoseDiscriminator()
        self.shape_discriminator = ShapeDiscriminator()

    def call(self, inputs, **kwargs):
        batch_size = inputs.shape[0] or self.config.BATCH_SIZE
        shape = (batch_size, self.config.NUM_JOINTS * 9 + self.config.NUM_SHAPE_PARAMS)
        assert inputs.shape[1:] == shape[1:], 'shape mismatch: should be {} but is {}'.format(shape, inputs.shape)

        # inputs batch x (pose: 207, shape: 10)
        poses = inputs[:, :self.config.NUM_JOINTS * 9]
        shapes = inputs[:, -self.config.NUM_SHAPE_PARAMS:]

        poses = tf.reshape(poses, [batch_size, self.config.NUM_JOINTS, 9])
        # compute common embedding features [batch x K x 1 x 32]
        common_pose_features = self.common_pose_discriminator(poses, **kwargs)

        # compute joint specific discriminators [batch x K]
        single_joint_outputs = self.single_joint_discriminator(common_pose_features, **kwargs)

        # compute full pose discriminator [batch x 1]
        full_pose_outputs = self.full_pose_discriminator(common_pose_features, **kwargs)

        # compute shape discriminators [batch x 1]
        shape_outputs = self.shape_discriminator(shapes, **kwargs)

        # [batch x (K + 1 + 1)]
        return tf.concat((single_joint_outputs, full_pose_outputs, shape_outputs), 1)


import sys
# sys.path.insert(0, 'lib')
import glob
import os
import math
import findvar
import kendals_tau

def select( query_wise_rankings_directory, ranking_scores_directory, k, balancing_factor):

    """ List of the importance scores of each feature
    """
    feat_subset = []

    """To set the value of K (Number of features to be selected)
    """
    ranking_score_files = glob.glob(  os.path.join(ranking_scores_directory, "*")  )
    feature_numbers = map( lambda file_path: int(os.path.basename(file_path).replace("F", "").replace(".txt", "")) , ranking_score_files)

    query_wise_rankings_files = glob.glob( os.path.join(query_wise_rankings_directory, "*") )
    query_ids = list(set(map( lambda file_path: int(os.path.basename(file_path).split("q")[1]), query_wise_rankings_files)))

    FkDocs = []

    fscores, vx = findvar.var_rel(ranking_scores_directory, feature_numbers, query_ids)
    max_feature, fscores = find_max(fscores)
    feat_subset.append(max_feature)

    for cnt in range(k):

        FkDocs = find_doclist(max_feature, FkDocs, query_wise_rankings_directory, query_ids)
        max_feature, fscores = upd_rel_score(FkDocs,fscores, feat_subset, ranking_scores_directory, query_wise_rankings_directory, feature_numbers, query_ids, balancing_factor)
        feat_subset.append(max_feature)

    #print "The features selected for MPT method are"
    return (feat_subset)

""" To find top 10 documents of newly added feature and append it to the old list  since at every step the
    importance score of the remaining features is calculated based on all the features selected so far
"""
def find_doclist(max_feaure, FkDocs, query_wise_rankings_directory, query_ids):
    fiList_doc = []

    for q in query_ids:
        x = []
        qryfile = os.path.join(query_wise_rankings_directory, "f{}q{}".format(max_feaure, q) )

        fi = open(qryfile,'r')
        start = str(q) + " "
        for i in range(10):
             line=fi.next().strip()
             if line.startswith(start):
                 a = line.split()
                 x.append(int(a[2]))
        fiList_doc.append(x)
    FkDocs.append(fiList_doc)
    return FkDocs

"""To find feature with maximum importance score
    Input: List of importance scores
    Output: feature with highest score
"""
def find_max(score_data):
    ind = score_data.index(max(score_data))
    score_data[ind] = float("-inf")
    return (ind+1,score_data)

"""This function is used to update the importance scores of the remaining features based on the last selected feature
   Input : Top 10 documents of all features selected so far,List of importance scores
   Output : Updated importance scores
"""

def upd_rel_score(feat_subset, scores, feat_subset1, ranking_scores_directory, query_wise_rankings_directory, feature_numbers, query_ids, balancing_factor):
    """ Variances of each feature based on all queries"""
    scores_copy = scores
    a, fvar = findvar.var_rel(ranking_scores_directory, feature_numbers, query_ids)

    Fk = len(feat_subset)

    for j in feature_numbers:
        b=0.0000001
        fjList_doc = []
        if scores[j-1] != float("-inf"):
            y = []

            for q in query_ids:
                y = []
                qryfile = os.path.join(query_wise_rankings_directory, "f{}q{}".format(j, q) )
                fj = open(qryfile,'r')
                start = str(q) + " "
                for k in range(10):
                    line=fj.next().strip()
                    if line.startswith(start):
                        a = line.split()
                        y.append(int(a[2]))
                fjList_doc.append(y)

            """ To calculate sum of s.d of f(j) * sim(fi,fj) over all features selected so far"""
            Sim_sum = 0
            for d in range(0,Fk):
                fiList_doc = feat_subset[d]
                tauSum = 0
                for avg in range(0,len(query_ids)):
                    t = kendals_tau.tau_distance(fiList_doc[avg], fjList_doc[avg])

                    tauSum = tauSum + t

                tauAvg = tauSum / len(query_ids)
                prev_feature = feat_subset1[d]
                Sim_sum = Sim_sum + (math.sqrt(fvar[prev_feature - 1])*tauAvg)

            """ Update score based on formula for MPT"""
            scores[j-1] = scores[j-1] - ((balancing_factor*fvar[j-1]) + (2 * balancing_factor * math.sqrt(fvar[j-1]) * Sim_sum))

    t = scores.index(max(scores))
    scores_copy[t] = float("-inf")

    return (t+1, scores_copy)

# select("query_wise_rankings", "ranking_scores", 4, 0.5)


# coding=utf-8
import socket

target_host = "www.baidu.com"
target_port = 80

# 建立一个socket对象
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 连接客户端
client.connect((target_host, target_port))

# 发送一些数据
client.send("GET / HTTP/1.1\r\nHost: baidu.com\r\n\r\n".encode('utf-8'))

# 接收一些数据
response = client.recv(4096)

print(response.decode())