'''
Game where the computer tosses a fair coin. The computer starts the game with a
certain amount on hand . The cpmouter wins R1.00 for heads and losses R1.50 for tails.
The game is over when the computer's balance is less or equal to 0.
'''
from random import randint

def main():
	head = 1
	tail = 0
	num_tosses = 0
	balance = float(input('Enter your starting amount: '))

	while balance >= 0:
		num_tosses += 1
		rand_number = randint(1, 2)
		if rand_number == 1:
			balance += 1.0
			print('Heads: Current amount: {0}'.format(balance))
		else:
			balance -= 1.5
			print('Tails: Current amount: {0}'.format(balance))

	print('Game over :( Current amount {0}. Coin tosses: {1}'.format(balance, num_tosses))

if __name__ == '__main__':
	main()


# https://projecteuler.net/problem=3
# Largest prime factor of the number 600851475143

import math

class LargestPrimeFactor(object):

    def __init__(self, number):
        self.number = number
        self.num_list = []

    def factors(self):
        i = self.number
        while i > 0:
            if self.number % i == 0:
                yield i
            i -= 1

    def factor_generator(self):
        operator = self.factors()
        next(operator)

        for value in operator:
            if self.is_prime(value):
                self.num_list.append(value)

        print("The list is: {}".format(self.num_list))
        print(max(self.num_list))

    def is_prime(self, fact):
        if fact <= 1:
            return
        elif fact == 2:
            return True
        elif fact % 2 == 0:
            return False
        for current in range(3, int(math.sqrt(fact) + 1), 2):
            if fact % current == 0:
                return False
        return True

ob = LargestPrimeFactor(600851475143)
ob.factor_generator()


__author__ = 'dmanheim'

import time
import twitter
import json
from itertools import islice
from PrivateKeys import ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET

api = twitter.Api(
    CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET, sleep_on_rate_limit=True, tweet_mode='extended'
)

# First, we need to find tweets that are replies or quote tweets.

from Tweet_File_Analysis_Functions import Get_FileList_Of_JSON_Files, AppendToListFile, GetListFile

# Scan_Files_For_Thread_Items(TweetIDlist, Filelist)
# This scans a file, or list of files, for Replies and Quote-Tweets that are in the list of IDs.

def Scan_Files_For_Replies(Filelist, OutFile): # Outfile has a list of tweet IDs that were replied to/quoted, to find.
    if not isinstance(Filelist, list): #Assume it's a filename.
        Filelist=[Filelist]

    TweetCount=0

    List_to_Add = list() # List of tuples, containing:
    # Original Tweet ID, ReplyID, Original User ID, Reply to User ID, Type)

    for file in Filelist:
        Sublist=list()
        print("Scanning File:", file)
        input_file = open(file, 'r')
        raw_batch = islice(input_file, None)
        for current_line in raw_batch:
            tweet_item = json.loads(current_line)
            if tweet_item["in_reply_to_status_id"] is not None:
                new_tuple = (tweet_item["id"], tweet_item["in_reply_to_status_id"],
                             tweet_item["user"]["id"], tweet_item["in_reply_to_user_id"], "Reply")
                if tweet_item["is_quote_status"]:
                    # print(tweet_item["full_text"][0:2])
                    # print(tweet_item.keys())
                    if "quoted_status" in tweet_item.keys():
                        # print(tweet_item["user"]["screen_name"], tweet_item["id"])
                        new_tuple = (tweet_item["id"], tweet_item["quoted_status_id"],
                                     tweet_item["user"]["id"], tweet_item["quoted_status"]["user"]["id"], "Quote")
                        Sublist.append(new_tuple)
                Sublist.append(new_tuple)
            elif tweet_item["is_quote_status"]:
                # print(tweet_item["full_text"][0:2])
                # print(tweet_item.keys())
                if "quoted_status" in tweet_item.keys():
                    # print(tweet_item["user"]["screen_name"], tweet_item["id"])
                    new_tuple = (tweet_item["id"], tweet_item["quoted_status_id"],
                                tweet_item["user"]["id"], tweet_item["quoted_status"]["user"]["id"], "Quote")
                    Sublist.append(new_tuple)
        List_to_Add.extend(Sublist)
        with open(Outfile, 'w+') as f:
            f.write(json.dumps(List_to_Add))
            f.close()
    return(len(List_to_Add))

def get_tweets_by_IDs(api=None, ID_List=None, Outfile="tests.json"):
    retrieved = api.GetStatuses(ID_List)
    print("Get Successful...")
    with open(Outfile, 'a') as f:
        for tweet in retrieved:
            f.write(json.dumps(tweet._json))
            f.write('\n')
    return(len(retrieved))

if __name__ == "__main__":
    # Outfile = "Data\Thread_Tweet_Structure_at_" + str(time.time()) + ".json"
    # All_data_files = Get_FileList_Of_JSON_Files("data", "Tweets_by")
    # with open(Outfile, 'w+') as f:
    #     f.close()

    # Scan_Files_For_Replies(All_data_files, Outfile)

    # After the above was done, We try to retrieve those other tweets. First, build a list:
    Tweet_Structure_files = Get_FileList_Of_JSON_Files("data", "Thread_Tweet_Structure")
    ListofReplyStruct = list()
    Tweet_Structure_files.sort()
    ListofReplyStruct.extend(GetListFile(Tweet_Structure_files[-1])) # Because the most recent one has everything.

    # Each entry has: (Original Tweet ID, ReplyID, Original User ID, Reply to User ID, Type)
    print("Extract what to retrieve from file")
    List_to_get = list()
    for entry in ListofReplyStruct:
        List_to_get.append(entry[1]) # Item 1 is the IF of the tweet replied to / embedded.

    # This is too big. Let's get 5k/time. (100 per request * 50 requests - limit at 300 requests / 15 minutes)
    Running_list_File = 'Thread_Tweets_Retrieved.json'
    # Create that file: f = open('Thread_Tweets_Retrieved.json', 'w+'); f.write(json.dumps([])); f.close()
    Outfile = 'data\\tweets_By_ID_at_' + str(time.time()) + '.json'

    from numpy import setdiff1d
    Dontget = GetListFile(Running_list_File) #This broke before. Rebuilding is below.

    # Rebuild Dontget from actual retrieved data:
    # f = open('Thread_Tweets_Retrieved.json', 'w+'); f.write(json.dumps([])); f.close()
    # Dontget= list()
    # All_reply_data_files = Get_FileList_Of_JSON_Files("data", "tweets_By_ID_at")
    # for file in All_reply_data_files:
    #     print("checking file:", file)
    #     MoreTweets = list()
    #     with open(file, 'r') as f:
    #         raw_batch = islice(f, None)
    #         for current_line in raw_batch:
    #             tweet_item = json.loads(current_line)
    #             MoreTweets.append(tweet_item["id"])
    #     AppendToListFile(MoreTweets,'Thread_Tweets_Retrieved.json')
    #     Dontget.extend(MoreTweets)

    Still_Needed = setdiff1d(List_to_get, Dontget)
    print("There are", len(Dontget), "identified tweets to retreive, all but ", len(Still_Needed), "are already pulled",
          "with a total set of", len(List_to_get), "tweet reply items so far.")

    Chunks = [Still_Needed[x: x+5000] for x in range(0, len(Still_Needed), 5000)] # Get Chunks.
    #That's a numpy data type. Bad. int above to allow jsonify, fix zip below to make list not tuple.
    # print(Chunks[0])
    for chunk in Chunks:
        print("Get another", len(chunk), "items")
        get_tweets_by_IDs(api, chunk, Outfile)
        AppendToListFile([int(id) for id in chunk], Running_list_File)
        print("Chunk Retrieved and written")

    print("Retrieval finished. Now getting new structures from retrieved data")

    All_reply_data_files = Get_FileList_Of_JSON_Files("data", "tweets_By_ID_at")
    Outfile = "Data\Thread_Tweet_Structure_at_" + str(time.time()) + ".json"
    with open(Outfile, 'w+') as f:
        f.close()
    All_reply_data_files.sort()

    # Marginal data only:
    #new_tweets_to_get = Scan_Files_For_Replies(All_reply_data_files[-1:], Outfile)
    # Struct with everything:
    new_tweets_to_get = Scan_Files_For_Replies(All_reply_data_files, Outfile)

    print("File(s) scanned, and", new_tweets_to_get, "new tweets reply structs are now in:", Outfile)

    #Just keep re-running. Looping would be better, but it's not worth re-doing now.
    # The tail is longer than expected. If I weren't stupidly stubborn I'd code a loop now.
    # Looks like there are at least 30 with chains of 100 tweets or more...
    # And probably 10 that are 200...
    # I'm only somewhat reassured by the understanding that all chains must terminate.
    # Stopping for now, with only 5 threads still going - at least a few of which are clearly trolls.


import os
import glob
import datetime
import email.parser
import codecs

from .formats import format_for_extension, UnknownExtension

def gather_files(path, recursive=False):
    gathered_files = []

    files = glob.glob(os.path.join(path, '*'))
    while files:
        f = files.pop(0)
        if os.path.isdir(f):
            if recursive:
                files += glob.glob(os.path.join(f, '*'))
        else:
            gathered_files.append(f.replace(path, '').lstrip('/'))

    return gathered_files

def email_to_dict(file_descriptor):
    message = email.parser.Parser().parse(file_descriptor)

    # body
    email_dict = { 'body': [ message.get_payload() ] }

    # headers
    for (key, value) in message.items():
        key = key.lower() # lowercase them all to make for easy comparison
        if key not in email_dict:
            email_dict[key] = []
        email_dict[key].append(value)

    return email_dict

class Parser(object):

    def __init__(self, manager, **global_defaults):
        self.manager = manager
        self.defaults = global_defaults
        self._header_map = {
            'author': 'authors',
            'date': 'created_on',
            'created-date': 'created_on',
            'publish-date': 'publish_on',
        }

    def _create_doc(self, **extra):
        data = dict(self.defaults)
        data.update(extra)
        return self.manager.document_class(**data)

    def map_header_to_field(self, **extra):
        self._header_map.update(extra)

    def parse(self, source_path, recursive=False, **defaults):
        self.parse_folder(source_path, recursive=recursive, **defaults)

    def parse_folder(self, path, recursive=False, **defaults):
        path = os.path.abspath(path)

        # get all the files that are candidates for parsing
        files = gather_files(path, recursive=recursive)

        # filter all the filters that haven't changed
        # files = self.filter_files(path, files, last_run=FOOBAR)

        for file in files:
            self.parse_file(path, file, **defaults)

    def parse_file(self, path, filepath, **defaults):
        doc = self._create_doc(**defaults)
        self.build_document(path, filepath, doc)
        self.manager.save(doc)

    def build_document(self, path, filepath, doc):
        self.load_file_info(path, filepath, doc)
        self.load_file_content(path, filepath, doc)

    def load_file_info(self, path, filepath, doc):
        mtime = os.path.getmtime(os.path.join(path, filepath))
        mod_dt = datetime.datetime.fromtimestamp(mtime)

        (doc_path, ext) = os.path.splitext(filepath)

        doc.path = doc_path
        doc.created_on = mod_dt
        doc.modified_on = mod_dt
        doc.publish_on = mod_dt

        try:
            doc.format = format_for_extension(ext)
        except UnknownExtension:
            pass

    def load_file_content(self, path, filepath, doc):
        with codecs.open(os.path.join(path, filepath), mode='r', encoding='utf-8') as fd:
            data = email_to_dict(fd)

        # Grab any alternate slugs
        alts = data.pop('alt-slug', [])

        # Populate the document
        for (field, values) in data.iteritems():
            for value in values:
                doc.assign(self._header_map.get(field, field), value)

        # Create the redirects
        for alt in alts:
            redirect_doc = doc.create_redirect(alt)
            self.manager.save(redirect_doc)


import numpy as np
from sklearn import datasets,linear_model
import sklearn
from matplotlib import pyplot as plt
from planar_utils import *

def layer_sizes(X,Y):
    n_x=X.shape[0]
    n_y=Y.shape[0]
    n_h=4
    return (n_x,n_h,n_y)
def initalize_paramters(n_x,n_h,n_y):
    np.random.seed(2)
    W1=np.random.randn(n_h,n_x)*0.01
    b1=np.zeros((n_h,1))
    W2=np.random.randn(n_y,n_h)*0.01
    b2=np.zeros((n_y,1))
    assert(W1.shape==(n_h,n_x))
    assert(b1.shape == (n_h, 1))
    assert(W2.shape == (n_y, n_h))
    assert(b2.shape == (n_y, 1))
    parameters={'W1':W1,
                'b1':b1,
                'W2':W2,
                'b2':b2}
    return parameters
def forward_progagation(X,parameters):
    W1=parameters['W1']
    b1=parameters['b1']
    W2=parameters['W2']
    b2=parameters['b2']

    Z1 = np.dot(W1,X)+b1
    A1 = np.tanh(Z1)
    Z2 = np.dot(W2,A1)+b2
    A2 = sigmoid(Z2)

    assert(A2.shape==(1,X.shape[1]))

    cache={
        'Z1':Z1,
        'A1':A1,
        'Z2':Z2,
        'A2':A2
    }

    return A2,cache
def compute_cost(A2,Y,parameters):
    m = Y.shape[1]
    cost = -1/m*np.sum(
    np.multiply(Y,np.log(A2))+
    np.multiply(1-Y,np.log(1-A2))
    )
    assert(isinstance(cost,float))
    return cost

def backward_progagation(parameters,cache,X,Y):
    m=X.shape[1]
    W1=parameters['W1']
    b1=parameters['b1']
    W2=parameters['W2']
    b2=parameters['b2']
    Z1=cache['Z1']
    A1=cache['A1']
    Z2=cache['Z2']
    A2=cache['A2']

    dZ2 = A2 - Y
    dw2=np.dot(dZ2,A1.T)/m
    db2=np.sum(dZ2,axis=1,keepdims=True)/m
    dz1=np.multiply(np.dot(W2.T,dZ2),(1-A1**2))
    dw1=np.dot(dz1,X.T)
    db1=np.sum(dz1,axis=1,keepdims=True)/m

    grads={
        "dW1":dw1,
        "db1":db1,
        "dW2":dw2,
        "db2":db2
    }
    return grads

def update_parameters(parameters,grads,learning_rate=1.2):
    W1=parameters["W1"]
    W2=parameters["W2"]
    b1=parameters["b1"]
    b2=parameters["b2"]
    dW1=grads["dW1"]
    dW2=grads["dW2"]
    db1=grads["db1"]
    db2=grads["db2"]

    W1 -= learning_rate * dW1
    b1 -= learning_rate * db1
    W2 -= learning_rate * dW2
    b2 -= learning_rate * db2

    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}

    return parameters

def nn_model(X,Y,n_h,num_iterations=10000,print_cost=False):
    np.random.seed(3)
    n_x,n_hh,n_y=layer_sizes(X,Y)

    parameters = initalize_paramters(n_x,n_h,n_y)

    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    for i in range(0,num_iterations):
        A2,cache=forward_progagation(X,parameters)#前向传播节点
        cost = compute_cost(A2, Y, parameters)#计算损失函数
        grads=backward_progagation(parameters,cache,X,Y)#计算后向传播梯度
        parameters=update_parameters(parameters,grads,learning_rate=1.2)#使用梯度更新W，b一次

        if print_cost and i % 1000 == 0:
            print ("Cost after iteration %i: %f" %(i, cost))

    return parameters

def predict(parameters,X):
    A2, cache = forward_progagation(X, parameters)
    predictions = (A2 > 0.5)
    return predictions

X,Y=loat_planar_dataset()
parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)
# Plot the decision boundary
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
plt.title("Decision Boundary for hidden layer size " + str(4))
plt.show()
predictions=predict(parameters,X)
print ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%')


#!/usr/bin/env python3

import os
import sys
import csv
import math
import statistics
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from os.path import exists

cumulative_st = []

if exists('tailbench_st.txt'):
    ftbst = open('tailbench_st.txt','r')
else:
    print("tailbench_st file not found")
    exit(-1)

line = ftbst.readline()
while line:
    if not ('core' in line):
        st=int(line.split(',')[0])
        st_in_us=st/2000
        cumulative_st.append(st_in_us)

    line=ftbst.readline()

f_st_summary = open('tailbench_st_summary.txt','w')
avgst = str(sum(cumulative_st)/len(cumulative_st))
p90 = str(np.percentile(cumulative_st, 90))
p95 = str(np.percentile(cumulative_st, 95))
p99 = str(np.percentile(cumulative_st, 99))
f_st_summary.write('avg_st, '+avgst +',\n')
f_st_summary.write('p90 , '+p90 +',\n')
f_st_summary.write('p95 , '+p95 +',\n')
f_st_summary.write('p99 , '+p99 +',\n')

f_st_summary.close()

os.system("cat tailbench_st_summary.txt");


import torch
from torch import nn
from torch_geometric.loader import DataLoader
import os
from torch_geometric.transforms import ToDevice
import time

def text_progress_bar(fraction):
    nchars = 50
    nfilled = int(nchars * fraction)
    return (
        "["
        + "=" * nfilled
        + " " * (nchars - nfilled)
        + "] "
        + f"{int(100*fraction):3d}%"
    )

def make_weights_dir():
    if not os.path.isdir("saved_weights"):
        os.mkdir("saved_weights")

def summary(epoch_train_loss, epoch_val_loss, epoch, epoch_time):
    print(
        f"Epoch {epoch}: \t Training loss {epoch_train_loss:.3f}"
        " \t Val loss {epoch_val_loss:.3f}"
        " \t Time for epoch: {epoch_time/60.:.3f} min",
        flush=True,
    )

class Logger:
    def __init__(self, filename, keys):
        self.filename = filename
        assert isinstance(keys, list)
        self.n_keys = len(keys)

        self.log_string = "{:>5d}" + self.n_keys * "  {:.4e}" + "\n"

        with open(filename, "w") as fp:
            fp.write("epoch," + ",".join(keys) + "\n")

    def log(self, epoch, values):
        values = tuple(values)
        with open(self.filename, "a") as fp:
            fp.write(self.log_string.format(epoch, *values))

def train_model(
    model,
    device,
    train_dataset,
    val_dataset,
    batch_size=64,
    num_epochs=30,
    learning_rate=1e-2,
    target_index=0,  # 0=dipole, 4=homo-lumo gap
    gamma=0.999,
):
    opt = torch.optim.Adam(model.parameters(), lr=learning_rate)
    scheduler = torch.optim.lr_scheduler.ExponentialLR(opt, gamma=gamma)
    loader_train = DataLoader(
        train_dataset, batch_size=batch_size, shuffle=True
    )
    loader_val = DataLoader(
        val_dataset, batch_size=len(val_dataset), shuffle=True
    )  # Just a single batch...
    # batch_to_device = ToDevice(device)
    batch_to_device = ToDevice(
        device, ["edge_index", "pos", "z", "batch", "y"]
    )

    logger = Logger("history.txt", ["train_loss", "val_loss"])
    make_weights_dir()
    tic = time.time()

    loss_fn = nn.MSELoss()
    train_loss = []
    val_loss = []
    for epoch in range(num_epochs):
        tic = time.time()
        epoch_train_loss = 0
        for batch in loader_train:
            batch = batch_to_device(batch)
            pred = model(batch)
            loss = loss_fn(pred.flatten(), batch.y[:, target_index].flatten())
            opt.zero_grad()
            loss.backward()
            opt.step()
            scheduler.step()
            epoch_train_loss += loss.item()

        epoch_train_loss_mean = epoch_train_loss / len(loader_train)
        train_loss.append(epoch_train_loss_mean)

        with torch.no_grad():
            for batch in loader_val:
                batch = batch_to_device(batch)
                pred = model(batch)
                loss = loss_fn(
                    pred.flatten(), batch.y[:, target_index].flatten()
                )
                epoch_val_loss = loss.item()

        val_loss.append(epoch_val_loss)

        # Save every epoch
        # torch.save(model.state_dict(), f'saved_weights/{epoch}_weights.pt')

        # Check if best validation loss and if so save to `BEST.pt`
        if epoch_val_loss <= min(val_loss):
            print(" - BEST SCORE, SAVING WEIGHTS to `BEST.pt`")
            torch.save(model.state_dict(), "saved_weights/BEST.pt")
            torch.save(
                model.state_dict(),
                f"saved_weights/weights_{epoch:0>4d}_{epoch_val_loss:.4e}.pt",
            )
            best_epoch = epoch

        print(
            text_progress_bar(float((epoch + 1) / num_epochs)),
            end="\r",
            flush=True,
        )
        toc = time.time()

        logger.log(epoch, [epoch_train_loss_mean, epoch_val_loss])
        summary(epoch_train_loss_mean, epoch_val_loss, epoch, toc - tic)

        # Check for early stopping
        n_since_best = epoch - best_epoch
        if n_since_best > 5:
            break

    print("\n")

    return train_loss, val_loss


# -*- coding:utf-8 -*-
'''
Created on 2018年2月28日
@author: ning.lin
'''
'''
大图地址class或id有big字样 的

小图地址

'''
# url="http://search.jiayuan.com/v2/search_v2.php"

import json
import urllib.parse

import requests

# url='http://sou.zhaopin.com/jobs/searchresult.ashx?jl=%E5%B9%BF%E5%B7%9E&kw=%E8%BF%90%E7%BB%B4&p=1&isadv=0'
url = 'http://search.jiayuan.com/v2/index.php?key=&sex=f&stc=&sn=default&sv=1&p=1&pt=1454903&ft=off&f=select&mt=d'
url = 'http://search.jiayuan.com/v2/search_v2.php'
a = '%E8%BF%90%E7%BB%B4'
b='喂,要幸福\x0e_33岁_32595588'
c='\u3000\u3000'
print("aa",urllib.parse.unquote(c))
data = {
    'sex': 'f',
    'key':'',
    'stc':'',
    'sn': 'default',
    'sv': 2,
    'p': 2,
    'f': 'select',
    'listStyle': 'bigPhoto',
    'pri_uid':'',
    'jsversion': 'v5',
}
# 1
# requests.post(url, data=json.dumps(data))
req = requests.get(url)

# 2-json参数会自动将字典类型的对象转换为json格式
req = requests.post(url, json=data)
# print(req.text)
a = json.loads(req.text)
print(type(a),a)


"""Widgets for editing the 'column-display' annotation.
"""
from PyQt5.QtWidgets import QVBoxLayout, QWidget
from deriva.core import tag, ermrest_model as _erm
from .common import raise_on_invalid, MultipleChoicePropertyWidget, SimpleNestedPropertyManager, \
    SimpleTextPropertyWidget
from .markdown_patterns import MarkdownPatternForm
from .sortkeys import SortKeysWidget
from .tabbed_contexts import EasyTabbedContextsWidget

class ColumnDisplayEditor(EasyTabbedContextsWidget):
    """Editor for the column-display contexts.
    """

    def __init__(self, column: _erm.Column, parent: QWidget = None):
        """Initialize the widget.

        :param column: an ermrest column instance
        :param parent: the parent widget
        """
        raise_on_invalid(column, _erm.Column, tag.column_display)
        super(ColumnDisplayEditor, self).__init__(
            tag.column_display,
            column.annotations,
            create_context_value=lambda context: {},
            create_context_widget_fn=lambda context, parent=None: _ColumnDisplayContextEditor(column, column.annotations[tag.column_display][context], parent=parent),
            purge_on_empty=False,
            allow_context_reference=True,
            parent=parent)

class _ColumnDisplayContextEditor(MarkdownPatternForm):
    """Editor for a column-display annotation (single entry).
    """

    __column_order__ = 'column_order'

    def __init__(self, column: _erm.Column, body: dict, parent: QWidget = None):
        """Initialize the widget.

        :param column: the ermrest column instance
        :param body: the annotation body for the given context
        :param parent: the parent widget
        """
        super(_ColumnDisplayContextEditor, self).__init__(
            [('markdown_pattern', 'Markdown Pattern')],
            body,
            include_template_engine=True,
            parent=parent
        )

        # ...column order widget
        self.form.addRow(
            'Column Order',
            MultipleChoicePropertyWidget(
                self.__column_order__,
                body,
                {
                    'Accept the default sorting behavior': None,
                    'Sorting by this column should not be offered': False
                },
                other_key='Sort by the following columns',
                other_widget=SortKeysWidget(
                    self.__column_order__,
                    body,
                    [c.name for c in column.table.columns],
                    parent=self
                ),
                layout=QVBoxLayout(),
                parent=self
            )
        )

        # pre_format
        pre_format = SimpleNestedPropertyManager('pre_format', body, parent=self)

        # ...format
        format = SimpleTextPropertyWidget(
            'format',
            pre_format.value,
            'Enter a POSIX standard format string',
            parent=self
        )
        format.valueChanged.connect(pre_format.onValueChanged)
        self.form.addRow('Format', format)

        # ...bool_true_value
        bool_true_value = SimpleTextPropertyWidget(
            'bool_true_value',
            pre_format.value,
            'Alternate display text for "true" value',
            parent=self
        )
        bool_true_value.valueChanged.connect(pre_format.onValueChanged)
        self.form.addRow('Alt. True', bool_true_value)

        # ...bool_false_value
        bool_false_value = SimpleTextPropertyWidget(
            'bool_false_value',
            pre_format.value,
            'Alternate display text for "false" value',
            parent=self
        )
        bool_false_value.valueChanged.connect(pre_format.onValueChanged)
        self.form.addRow('Alt. False', bool_false_value)


#%%
from collections import defaultdict
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import seaborn as sns

#%%
models = ['gpt2',
          'gpt2-medium',
          'gpt2-large',
          'gpt2-xl',
          'opt-2.7b',
          'opt-6.7b',
          'opt-13b',
          'llama-7B',
          'llama-13B',
          'llama-30B',
          ]

for model in models:
    df = pd.read_csv(f'experiment3/{model}.csv')
    animacy_norms = pd.read_csv('experiment3/animacy_norms.csv')
    verb_df = df[df.prompt_type == 'VERB']
    df['kl_diff'] = df['animate_no_context_inanimate_no_context_kl'] - df['animate_no_context_experimental_kl']
    df['emd_diff'] = df['animate_no_context_inanimate_no_context_emd'] - df['animate_no_context_experimental_emd']

    ###
    mental_animacy = defaultdict(int)
    mental_animacy.update({word:score for word, score in zip(animacy_norms['Word'], animacy_norms['AnimMental'])})
    physical_animacy = defaultdict(int)
    physical_animacy.update({word:score for word, score in zip(animacy_norms['Word'], animacy_norms['AnimPhysical'])})

    ###
    nouns_list = list(set(df['noun']))

    noun_summary_dict = {'noun': nouns_list}
    for column in df.columns:
        if df[column].dtype == np.float64:
            noun_summary_dict[column] = [df[(df.noun == noun) & (~pd.isna(df[column]))][column].mean() for noun in nouns_list]
    noun_summary_df = pd.DataFrame.from_dict(noun_summary_dict)
    noun_summary_df['AnimMental'] = [mental_animacy[noun] if noun in mental_animacy else np.nan for noun in nouns_list]
    noun_summary_df['AnimPhysical'] = [physical_animacy[noun] if noun in mental_animacy else np.nan for noun in nouns_list]

    verbs_list = list(set(df['verb']))
    verbs_list = list(set(df['verb']))
    verb_summary_dict = {'verb': verbs_list}
    for column in df.columns:
        if df[column].dtype == np.float64:
            verb_summary_dict[column] = [df[(df.verb == verb) & (~pd.isna(df[column]))][column].mean() for verb in verbs_list]
    verb_summary_df = pd.DataFrame.from_dict(verb_summary_dict)

    ###
    # LOADING VERBS

    verb_info = pd.read_csv('verbs.csv')

    verb_types = {}
    verb_frequencies = {}

    for verb, verb_frequency, verb_type in zip(verb_info['verb'], verb_info['frequency'], verb_info['type']):
        verb_types[verb] = verb_type
        verb_frequencies[verb] = verb_frequency

    verb_summary_df['verb_frequency'] = [verb_frequencies[verb] for verb in verb_summary_df['verb']]
    verb_summary_df['verb_frequency_color'] = ['r' if freq == 'HIGH' else ('y' if freq == 'HIGH-MID' else 'b') for freq in verb_summary_df['verb_frequency']]
    verb_summary_df['verb_category'] = [verb_types[verb] for verb in verb_summary_df['verb']]
    verb_summary_df['verb_category_color'] = ['r' if cat == 'physical' else 'b' for cat in verb_summary_df['verb_category']]

    ###
    plot_df = df.copy()
    plot_df['Animacy Divergence'] = plot_df['animate_no_context_experimental_kl'] * 10000
    fig, axs_dict = plt.subplot_mosaic('ABC', sharey=True) #plt.subplots(1, 3, sharey=True)
    axs = list(axs_dict.values())
    (ax1, ax2, ax3) = axs
    sns.kdeplot(data=plot_df, x="Animacy Divergence", hue='prompt_type', common_norm=False, ax=ax1, hue_order=['VERB', 'ADJ'])
    sns.kdeplot(data=plot_df, x="Animacy Divergence", hue='verb_category', common_norm=False, ax=ax2, hue_order=['physical', 'psychological'])
    sns.kdeplot(data=plot_df, x="Animacy Divergence", hue='verb_frequency', common_norm=False, ax=ax3, hue_order=['HIGH', 'HIGH-MID', 'MID'])
    for k, ax in axs_dict.items():
        ax.ticklabel_format(axis='x', style='sci', scilimits=(-4, 6))
        ax.get_xaxis().get_label().set_visible(False)
        ax.text(0.05, 0.85, k, transform=ax.transAxes,
            size=20, weight='bold')

    fig.supxlabel("Animacy Divergence (1e-4)")
    fig.set_size_inches(8.5, 3)
    fig.suptitle("Animacy Divergence Distribution by Prompt Type, Verb Category, and Verb-Human Co-occurrence")
    fig.tight_layout()
    fig.show()
    if model == 'llama-7B':
        fig.savefig(f'paper-plots/distributions-{model}.pdf')
    fig.suptitle(f"Animacy Divergence Dist. by Prompt Type, Verb Category, and Verb-Human Co-occ. ({model})")
    #fig.savefig(f'paper-plots-png/distributions-{model}.png')
    fig.savefig(f'exp3-paper-plots/distributions-{model}.pdf')

    ###
    col = 'animate_no_context_experimental_kl'
    print(stats.f_oneway(*[df[df.verb_frequency == freq][col] for freq in ['HIGH', 'HIGH-MID', 'MID']]))
    print(stats.ttest_ind(df[df.verb_frequency == 'HIGH'][col], df[df.verb_frequency == 'HIGH-MID'][col]))
    print(stats.ttest_ind(df[df.verb_frequency == 'MID'][col], df[df.verb_frequency == 'HIGH-MID'][col]))
    print(stats.ttest_ind(df[df.verb_frequency == 'HIGH'][col], df[df.verb_frequency == 'MID'][col]))
    print(stats.ttest_ind(df[df.verb_category == 'physical'][col], df[df.verb_category == 'psychological'][col]))

    ###
    colorcycle = plt.rcParams['axes.prop_cycle'].by_key()['color']

    fig, axs_dict = plt.subplot_mosaic('D;E', sharex=True)
    axs = list(axs_dict.values())
    (ax1, ax2) = axs

    plot_df = verb_summary_df.copy()
    plot_df['Animacy Divergence'] = plot_df['animate_no_context_experimental_kl'] * 10000
    s1 = ax1.scatter(plot_df["Animacy Divergence"], np.zeros(len(plot_df)), alpha=0.25, c=colorcycle[0])

    plot_df = noun_summary_df.copy()
    plot_df['Animacy Divergence'] = plot_df['animate_no_context_experimental_kl'] * 10000
    s2 = ax2.scatter(plot_df["Animacy Divergence"], np.zeros(len(plot_df)), alpha=0.25, c=colorcycle[1])
    for k, ax in axs_dict.items():
        ax.text(0.02, 0.68, k, transform=ax.transAxes,
            size=20, weight='bold')
    fig.set_size_inches(5.66, 3)
    fig.supxlabel("Animacy Divergence (1e-4)")
    fig.suptitle("Mean Animacy Divergence per Verb and Noun")
    fig.legend([s1,s2], ['Verbs', 'Nouns'], loc=(0.8, 0.47), framealpha=1.0)
    fig.tight_layout()
    fig.show()
    if model == 'llama-7B':
        fig.savefig(f'paper-plots/scatters-{model}.pdf')
    fig.suptitle(f"Mean Animacy Divergence per Verb and Noun ({model})")
    #fig.savefig(f'paper-plots-png/scatters-{model}.png')
    fig.savefig(f'exp3-paper-plots/scatters-{model}.pdf')

# %%


# Module to draw a heap using graphviz in a nice "textbook" layout
# Created by Zachary Friggstad, 2018
# Only works with the BinaryHeap class we developed in 275

from graphviz import Digraph
from binary_heap import BinaryHeap
import random
import copy

def convert_pos_string(pos, padding):
    return str(pos[0]*padding)+','+str(pos[1])+'!'

def heapviz(heap, just_keys = False, padding = 0.6):
    """
    Draw a list representing a binary heap using graphviz.

    heap: An instance of BinaryHeap

    padding: reflects the amount of space between nodes (horizontally)
    Increase it beyond the default 0.6 if the circles are mashed together.

    just_keys: True if only the keys should be displayed. False
    if the (item, key) pairs should be displayed.
    """

    dot = Digraph()

    nodes = heap.nodes

    dot.attr("node", fontname="helvetica-bold", fontsize="20")

    if len(heap) == 0:
        dot.node("empty heap", style="dashed")
        return dot

    # if len(heap) == 1:
    #     dot.node(str(heap[0]))
    #     return dot

    max_level = 0
    while 2**(max_level+1)-1 < len(heap):
        max_level += 1

    pos = {0:[0,0]}

    def draw_label(i):
        if just_keys:
            output = str(nodes[i][1])
        else:
            output = str(nodes[i][0]) + "," + str(nodes[i][1])
        dot.node(str(i), output, pos=convert_pos_string(pos[i], padding))

    #dot.node(str(heap[0]), pos=convert_pos_string(pos[0], padding))
    draw_label(0)

    level = 0
    for i in range(1, len(heap)):
        if i >= 2**(level+1)-1:
            level += 1
        parent = (i-1)//2
        pos[i] = copy.copy(pos[parent])
        if i%2 == 0:
            pos[i][0] += 2**(max_level-level)
        else:
            pos[i][0] -= 2**(max_level-level)
        pos[i][1] -= 1

        #dot.node(str(heap[i]), pos=convert_pos_string(pos[i], padding))
        draw_label(i)
        dot.edge(str(parent), str(i))

    dot.engine="neato"
    return dot

if __name__ == "__main__":
    heap = BinaryHeap()

    for c in ["dog", "cat", "bear", "deer", "cat", "monkey", "hippo",
              "hawk", "frog", "dog", "dog", "moose", "fish", "cougar"]:
        heap.insert(c, random.randrange(10))

    # dot = heapviz(heap, padding = 1.2)

    # try the one below, only the keys are displayed
    dot = heapviz(heap, just_keys = True, padding = 0.8)

    dot.render(view=True)


#!/usr/bin/env python
import sys
import random
"""

"""

def gen_expr(argin):
  out_str = "c[i] = "
  if int(argin) == 1:
    out_str += "%f*a[i]" % random.random()
  elif int(argin) == 2:
    out_str += "%f*a[i] + a[i]" % random.random()
  else:
    for i in range(int((int(argin)+1)/2)):
      out_str += "%f*a[i] + " % random.random()
    out_str = out_str[0:-2]
    if int(argin) % 2 == 0:
      out_str += " + a[i]"
  return out_str

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


#Create a pdf file with a logo and footer
#Check the directory and open the pdf file called professor.pdf

from fpdf import FPDF

class pdf_document(FPDF):
    def header(self):

        self.image('professor.png', 11, 8, 33)
        # Times bold 10
        self.set_font('Times', 'B', 10)
        # Adjust the size
        self.cell(70)
        # Title
        self.cell(50, 11, 'Python Programming Class', 1, 0, 'C')
        # Line break
        self.ln(20)

    # Page footer
    def footer(self):

        self.set_y(-15)
        #Set font to times 8
        self.set_font('Times', 'I', 8)

        self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')

p = pdf_document()

p.alias_nb_pages()
p.add_page()
p.set_font('Times', '', 12)
for i in range(1, 30):
    p.cell(0, 10, 'The best Python Professor ' + str(i), 0, 1)
p.output('professor.pdf', 'F')


import socket
import math
import random
global prime, root

host = "127.0.0.1"
port = 4455
addr = (host, port)

""" Creating the UDP socket """
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Key Information
def secretNumber ():
    secret = int(random.randint(0,100))
    return secret
mySecretKey = 96
root = 3 # agreed root
prime = 17
# server public key (variable)
myPublicKey = 1
def calculateSharedKey(receivedPublicKey):
    print("calculating shared key")
    mySharedKey = (int(receivedPublicKey) ** mySecretKey) % prime
    print("client shared key" , mySharedKey)

# Request file

askKey = "KEY".encode("utf-8")
client.sendto(askKey, addr)
data, addr = client.recvfrom(1024)
data = data.decode("utf-8")
if(data[:3]=='KEY'):
    print(f"{data}")
    getKeyFromData = f"{data}"[4:]
    calculateSharedKey(getKeyFromData)

while True:

    data = input("Enter your input: ")
    filename = data

    if data == "exit":
        data = data.encode("utf-8")
        client.sendto(data, addr)
        print("Disconneted from the server.")
        client.close()
        exit()

    data = data.encode("utf-8")
    client.sendto(data, addr)

    data, addr = client.recvfrom(1024)
    data = data.decode("utf-8")

    if(data[:6]=='EXISTS'):
        filesize = int(data[6:])
        print(filesize, "filesize")
        f = open('new_'+filename, 'wb')
        data,addr = client.recvfrom(1024)
        totalRecv = len(data)
        print("writing data")
        f.write(data)
        while totalRecv < filesize:
            data,addr = client.recvfrom(1024)
            totalRecv+=len(data)
            f.write(data)
            # print("{0:.2f}".format((totalRecv/float(filesize))*100)+ "% Done")
        print("download complete !!")

        f.close()
        # client.close()
    elif(data=='!EXISTS'):
        print("file does'nt exist")
# client.close()


#################################################
# entry.py
# this is the entry object that will allow me to get user input in the GUI
#
# Your name: Joyce Truong
# Your andrew id: btruong
# Section: C1
#################################################

# From CMU 112 Animation Part 1 Notes:
# https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html
from cmu_112_graphics import *

class Entry(object):

    def __init__(self, label, promptLocation, inputLocation, lineLength,
                    maxLines):
        self.input = ''
        self.label = label
        self.promptLocation = promptLocation
        self.inputLocation = inputLocation
        self.lineLength = lineLength
        self.maxLines = maxLines

        self.currentLineLength = 0
        self.isTyping = False
        self.styles = {'normal': True,
                       'bolded': False,
                       'italicized': False}
        self.isHeading = False
        self.lastLineLength = 0
        self.lastKeyEnter = False

    def __repr__(self):
        return self.input

    def typing(self, event):
        bannedKeys = {'Up', 'Down', 'Left', 'Right'}
        if (self.isTyping == True):
            if (event.key == 'Space'):
                self.input += ' '
                self.currentLineLength += 1
                self.lastKeyEnter = False
            elif (event.key == 'Delete'):
                if (self.input == ''):
                    pass
                elif ((len(self.input) >= 2) and (self.input[-2] == '`')):
                    self.input = self.input[:-2]
                    self.currentLineLength -= 2
                    if (self.currentLineLength == 0):
                        self.isHeading = False
                elif ((len(self.input) >= 6)
                    and ((self.input[-6:-1] == '~BLD~')
                    or (self.input[-6:-1] == '~ITL~'))):
                    self.input = self.input[:-6]
                elif ((len(self.input) >= 6) and (self.input[-6:] == 'DOUB\n\n')):
                    if (self.lastKeyEnter == True):
                        self.currentLineLength = self.lastLineLength
                        self.input = self.input[:-6]
                    elif (self.lastLineLength == 0):
                        self.currentLineLength = 0
                        self.input = self.input[:-6]
                    elif (self.lastLineLength < self.lineLength):
                        self.currentLineLength = self.lastLineLength - 1
                        self.input = self.input[:-8]
                    else:
                        self.currentLineLength = self.lineLength
                        self.input = self.input[:-8]
                    self.isHeading = True
                elif (self.lastKeyEnter == True):
                    self.input = self.input[:-1]
                    self.currentLineLength = self.lastLineLength
                elif (self.input[-1] == '\n'):
                    if (self.lastLineLength == 0):
                        self.currentLineLength  = 0
                        self.input = self.input[:-1]
                    elif (self.lastLineLength < self.lineLength):
                        self.currentLineLength = self.lastLineLength - 1
                        self.input = self.input[:-2]
                    else:
                        self.currentLineLength = self.lineLength - 1
                        self.input = self.input[:-2]
                    self.isHeading = False
                else:
                    self.input = self.input[:-1]
                    self.currentLineLength -= 1
                self.lastKeyEnter = False
            elif (event.key == 'Enter'):
                if (self.isHeading == True):
                    self.input += 'DOUB\n\n'
                    self.isHeading = False
                    self.lastLineLength = self.currentLineLength
                    self.currentLineLength = 0
                else:
                    self.input += '\n'
                    self.lastLineLength = self.currentLineLength
                    self.currentLineLength = 0
                self.lastKeyEnter = True

            elif (event.key in bannedKeys):
                pass
            else:
                if (self.input.count('\n') < self.maxLines):
                    style = self.getStyle()
                    if (style == 'normal'):
                        if (event.key == '??'):
                            pass
                        else:
                            if ((event.key == '#')
                                and (self.currentLineLength == 0)):
                                self.isHeading = True
                            elif (self.isHeading == True):
                                self.input += '`' + event.key
                                self.currentLineLength += 2
                            else:
                                self.input += event.key
                                self.currentLineLength += 1
                    elif (style == 'bolded'):
                        if (event.key == '??'):
                            pass
                        self.input += '~BLD~' + event.key
                        self.currentLineLength += 1
                    elif (style == 'italicized'):
                        if (event.key == '??'):
                            pass
                        self.input += '~ITL~' + event.key
                        self.currentLineLength += 1
                    if (self.currentLineLength >= self.lineLength):
                        if (self.isHeading == True):
                            self.input += 'DOUB\n\n'
                            self.lastLineLength = self.lineLength
                            self.currentLineLength = 0
                            self.isHeading = False
                        else:
                            self.input += '\n'
                            self.lastLineLength = self.lineLength
                            self.currentLineLength = 0
                self.lastKeyEnter = False

    def drawInputPrompt(self, canvas):
        canvas.create_text(self.promptLocation[0], self.promptLocation[1],
                            text=self.label, font='Gilroy 20 bold',
                            fill='gray20', anchor=W)

    def showTyping(self, canvas):
        writing = []
        index = 0
        while (len(self.input) != index):
            if ((len(self.input) >= 6)
                and ((self.input[index:index+5] == '~BLD~')
                or (self.input[index:index+5] == '~ITL~'))):
                writing += [self.input[index:index+6]]
                index += 6
            elif ((len(self.input) >= 4) and self.input[index:index+4] == 'DOUB'):
                index += 4
                pass
            elif ((len(self.input) >= 2) and (self.input[index] == '`')):
                writing += [self.input[index:index+2]]
                index += 2
            else:
                 writing += [self.input[index]]
                 index += 1

        xStart,yStart = self.inputLocation
        dx = dy = 0

        for char in writing:
            if (char == '\n'):
                dx = 0
                dy += 25
            else:
                if (char.startswith('~BLD~')):
                    canvas.create_text(xStart+dx, yStart+dy, text=char[-1],
                                    font='Menlo 20 bold', anchor=NW)
                    dx += 12
                elif (char.startswith('~ITL~')):
                    canvas.create_text(xStart+dx, yStart+dy, text=char[-1],
                                    font='Menlo 20 italic', anchor=NW)
                    dx += 12
                elif (char.startswith('`')):
                    canvas.create_text(xStart+dx, yStart+dy, text=char[-1],
                                    font='Menlo 40 bold', anchor=NW)
                    dx += 22
                else:
                    canvas.create_text(xStart+dx, yStart+dy, text=char,
                                        font='Menlo 20', anchor=NW)
                    dx += 12

    def showPromptAnswerTyping(self, canvas):
        canvas.create_text(self.inputLocation[0], self.inputLocation[1],
                            text=self.input, font='Menlo 20', anchor=NW)

    def getStyle(self):
        for style in self.styles:
            if (self.styles[style] == True):
                return style

    def setStyle(self, newStyle):
        self.styles[self.getStyle()] = False
        self.styles[newStyle] = True


from haversine import haversine
from operator import itemgetter
import csv

origin = (59.911491, 10.757933)
places = []
travel_distance = 24 * 7274

with open('input/verda.txt', newline='') as csvfile:
    r = csv.reader(csvfile, delimiter="\t")
    header = None

    for row in r:
        if not header:
            header = row
            continue

        places.append(dict(zip(header, row)))

capitals = [place for place in places if place['Stadtype bokmål'] == 'Hovedstad']
has_already = {}
unique_capitals = []

for cap in capitals:
    cap['distance'] = haversine(origin, (float(cap['Lat']), float(cap['Lon'])))
    k = str(cap['distance']) + '_' + cap['Stadnamn bokmål']

    if k in has_already:
        continue

    unique_capitals.append(cap)
    has_already[k] = True

unique_capitals = sorted(unique_capitals, key=itemgetter('distance'))

count = 0

for cap in unique_capitals:
    print("Visiting " + cap['Stadnamn bokmål'] + " at distance " + str(cap['distance']) + " " + str(travel_distance) + " to go.")
    travel_distance -= cap['distance'] * 2

    if travel_distance < 0:
        print(count)
        break

    count += 1

#print(unique_capitals[:3])


#Ankita Chowdhry, August 2016

import sys
import time
from Tkinter import *

class Activity(object):
	name=""
	time=0

	def __init__(self, name, time):
		self.name=name
		self.time=time

things_to_do={}
count=0
#to_do = open(sys.argv[1],'w')
to_do=open("to_do.txt",'w')
sched=open('sched.txt','w')
total_time=0
break_time=0
work_time=0
breaks=0

def addActivity():
	global count
	name=raw_input("Thing to do: ")
	time=input("Minutes it will take: ")
	things_to_do[count]=Activity(name,time)
	count+=1

"""def printToDo():
	print("To Do: ")
	for key in things_to_do:
		print(things_to_do[key].name)
		print("Time to do: " + things_to_do[key].time + " minutes")"""

def printToDo():
	to_do.write("To Do: " + '\n')
	global total_time
	global break_time
	for key in things_to_do:
		to_do.write('\n')
		to_do.write(things_to_do[key].name + '\n')
		to_do.write("Time to do: " + str(things_to_do[key].time) + " minutes" + '\n')
	wk = round(work_time/60.0,2)
	to_do.write('\n'+ "Total work time: " + str(wk) + " hours" + '\n')
	to_do.write("Total break time: " + str(break_time) + " minutes" + '\n')

def totalWorkTime():
	global break_time
	work=0
	for key in things_to_do:
		work=work+things_to_do[key].time
	break_time=total_time-work
	return work

print("Welcome to schedule maker!")
print("Please enter your activities according to priority")
print("Let's begin!")
hours=input("How much time do you have to work today? (hours) ")
br=input("If you want to take breaks today, enter 1. If you do not want breaks, enter 0. ")
if br==1:
	breaks=input("How long do you want each break to be? (minutes) ")
else:
	breaks=0
total_time=hours*60

cont = raw_input("Add an activity? (yes/no) ")
while (cont.find("yes")>-1):
	addActivity()
	cont = raw_input("Add an activity? (yes/no) ")

work_time=totalWorkTime()
printToDo()
schedule={}
sched_count=0
tomorrow={}
work_tom=0

"""print(str(total_time))
print(str(break_time))
print(str(work_time))
print(str(breaks))"""

def schedAdd(item):
	global sched_count
	schedule[sched_count]=item
	sched_count+=1

def doTomorrow(num):
	global count
	nums=0

	for x in range(num,count):
		tomorrow[nums]=things_to_do[x]
		nums+=1

def makeSchedule():
	global break_time
	global total_time
	global work_time
	global breaks
	global work_tom
	global br

	for key in things_to_do:
		if (total_time-(things_to_do[key].time))>=0:
			schedAdd(things_to_do[key])
			total_time=total_time-things_to_do[key].time
			work_time=work_time-things_to_do[key].time
			if things_to_do[key].time<30 or break_time<=0 or br==0:
				continue
			else:
				schedAdd(Activity('break',breaks))
				break_time=break_time-breaks
				total_time=total_time-breaks
		else:
			print("Looks like you'll need to work tomorrow as well")
			work_tom=1
			doTomorrow(key)
			break

makeSchedule()

def printSched():
	global total_time
	global break_time
	global work_tom
	sched.write("Your schedule for " + time.strftime("%d/%m/%Y") + " :" + '\n')
	for key in schedule:
		sched.write('\n')
		sched.write(schedule[key].name + '\n')
		sched.write("Time to do: " + str(schedule[key].time) + " minutes" + '\n')

	if work_tom==1:
		sched.write('\n')
		sched.write("Tomorrow you'll have to finish: " + '\n')
		for key in tomorrow:
			sched.write('\n')
			sched.write(tomorrow[key].name + '\n')
			sched.write("Time to do: " + str(tomorrow[key].time) + " minutes" + '\n')

printSched()

master=Tk()

topLabel=Label(master, text="Your schedule for " + time.strftime("%d/%m/%Y") + " :" + '\n',font=('Helvetica', 16, 'bold'))
topLabel.grid(row=0,column=0)
#contentLabel=Label(master,text="To Do").grid(row=1,column=0)
doneLabel=Label(master, text="Done?").grid(row=1,column=2)
#timeLabel=

for key in schedule:
	col="#ffffff"
	if schedule[key].name=="break":
		col="#beeeea"
	Label(master, text=schedule[key].name, borderwidth=1, relief=RIDGE, font=('Helvetica', 14), bg=col).grid(row=key+2,column=0,sticky=NSEW)
	Label(master,text=str(schedule[key].time)+" minutes", borderwidth=1, relief=RIDGE, font=('Helvetica', 12), bg=col).grid(row=key+2,column=1,sticky=NSEW)
	Checkbutton(master, width=2, height=1).grid(row=key+2,column=2)

master.mainloop()


import os
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

PRINT_NAMES = False

def get_image_name(lastfmObject):
    name = lastfmObject.name.replace('/', '_')
    return name + '.jpg'

def add_text(text: str, img):
    width = img.size[0]
    height = img.size[1]

    if len(text) >= 19:
        text = text[:16]
        text = text + '...'

    draw = ImageDraw.Draw(img, 'RGBA')
    font = ImageFont.truetype("../config/arial.ttf", int(width/10))
    bbox = draw.textbbox((width / 2, 9 * height / 10),
                         text, font=font, anchor='mm')
    left, top, right, bottom = draw.textbbox(
        (width / 2, 9 * height / 10), text, anchor='mm', font=font)
    draw.rectangle((left - 5, top - 5, right + 5,
                   bottom+5), fill=(255, 255, 255, 130))
    draw.text((width / 2, 9 * height / 10),
              text=text, fill='black', anchor="mm", font=font)

def create_collage(lastfmObjects, X_SIZE, Y_SIZE):
    os.chdir('./cache/')

    im = Image.open(get_image_name(lastfmObjects[0]))

    width = im.size[0]
    height = im.size[1]

    im = Image.new("RGB", (width * X_SIZE, height * Y_SIZE))

    for y in range(0, Y_SIZE):
        for x in range(0, X_SIZE):
            try:
                obj = lastfmObjects[y * X_SIZE + x]
                im_buff = Image.open(get_image_name(
                    obj))

                if im_buff.format != 'RGB':
                    im_buff = im_buff.convert('RGB')

                im_buff = im_buff.resize((width, height))

                if PRINT_NAMES:
                    add_text(obj.name, im_buff)
            except Exception as e:
                print(e)
                im_buff = Image.new('RGB', (width, height), 'black')
            im.paste(im_buff, (x * width, y * height))

    os.chdir('../')

    im.save(f"{lastfmObjects[0].__class__.__name__}.jpeg")


from algorithms.DFS import *
from structs.graph import Type

def print_times(aux: DFSAuxiliar):
    for v in aux.color:
        print('', v, '=> Chegada:', aux.d[v], '\tFinalização:', aux.f[v])

def read_file(fileName):
    '''Realiza a leitura do arquivo texto que contem
    o grafo, recebe nome do arquivo'''
    f = open(fileName, "r")
    contents = f.read().split("\n")
    return contents

def generate_graph(contents: list, val: bool, t_struct: bool):
    """Função recebe uma lista de arestas e cria o grafo
        t_struct: True => AdjList e False => AdjMat
    """
    if t_struct:
        graph = AdjList(int(contents[1]), Type.DIGRAPH, val)
    else:
        graph = AdjMatrix(int(contents[1]), Type.DIGRAPH, val)
    for x in contents[2:]:
        x = x.split()
        if(len(x) == 1):
            graph.make_relation(x[0])
        elif(len(x) == 2):
            graph.make_relation(x[0], x[1])
        else:
            graph.make_relation(x[0], x[1], int(x[2]))

    # graph.print_all()
    return graph

if __name__ == "__main__":
    contents = read_file("test/test_files/09_bellman_ford_slide.txt")
    graph = generate_graph(contents, True, False)
    print_times(DFS(graph, input('start:'), True))


from django.urls import path
from task_server.api.views.task.index import createTask, getTasks, updateTask, updateTaskState, getTask

urlpatterns = [
    path('create', createTask, name='create-task'),
    path('list/<int:pk>', getTasks, name='get-tasks'),
    path('<int:pk>', getTask, name='get-task'),
    path('update/<int:pk>', updateTask, name='update-task'),
    path('state/<int:pk>', updateTaskState, name='update-task-state'),
]


""" Used for creating session and bucket object  """
import os
import boto3
from moto import mock_s3

@mock_s3
def test_get_bucket_obj():
    """
    Function to get bucket object from aws
    """
    conn = boto3.resource('s3', region_name='us-east-1')
    conn.create_bucket(Bucket='buckettest')
    bucket_object = conn.Bucket('buckettest')
    file_path = os.path.join(os.path.join(os.getcwd(), 'tests'), 'data_file.csv')
    bucket_object.upload_file(file_path, "csv/data_file.csv")
    return bucket_object


# Prints a pyramid of blocks to the screen, not dissimalar from a pyramid climbed in a 2D Mario game.
# The purpose of the program is to practice the differnces in loops between python and C

from cs50 import get_int

# Prompt user for blocks, 0-23
while True:
    h = get_int("Positive number: ")
    if h > -1 and h < 24:
        break

# Print out this many rows
for i in range(h):

    # Print the appropriate number of spaces, left blocks, 2 spaces, and right blocks
    for k in range(i+1, h):
        print(" ", end="")

    for j in range(h-i-1, h):
        print("#", end="")

    print("  ", end="")

    for l in range (h-i-1, h):
        print("#", end="")
    # Print a new line
    print()


import csv
import sys
import pickle
from datetime import datetime, timedelta
from statistics import mean, median
import numpy
from scipy import stats

with open('bacteriemia.pickle', 'rb') as datafile:
    bact = pickle.load(datafile)

list_bact=dict()
list_genus=dict()
name_bact=dict()
with open('bacteria_def.csv') as bacteria_file:
    reader_b = csv.reader(bacteria_file)
    for row in reader_b:
        list_bact[row[0]] = row[2]
        name_bact[row[0]] = row[1]
        list_genus[row[0]] = row[1].split(" ")[0]

service_list=set()
for x in bact:
    service_list.add(x[3])

bact_per_service=[]
bact_ana=[]
for w in service_list:
    num=0
    num_ana=0
    bact_sp=dict()
    for x in bact:
        if x[3] == w:
            num += 1
            for y in x[0][0]:
                if (list_bact[y] == '3' or list_bact[y] == '4'):
                    if str(x[0][0]) in bact_sp:
                        bact_sp[str(x[0][0])] += 1
                    else:
                        bact_sp[str(x[0][0])] = 1
                    num_ana += 1
                    bact_ana.append(x)
                    break
    bact_per_service.append([w,num,num_ana,bact_sp])

# share of plurimicrobial episodes
count_bact = 0
total_bact = 0
len_bact=dict()
for x in bact:
    try:
        len_bact[len(x[0][0])] += 1
    except KeyError:
        len_bact[len(x[0][0])] = 1
    if len(x[0][0]) > 1:
        count_bact += 1
    total_bact += 1
moy_bact=0
denom_bact=0
for x in len_bact:
    if x != 1:
        moy_bact += x*len_bact[x]
        denom_bact += len_bact[x]
print("mean number of species per polymicrobial episode : " + str(moy_bact/denom_bact))
print("repartition of the numbers of species per episode : " + str(len_bact))
print("number of plurimicrobial bacteriemia : " + str(count_bact))
print("total number of episodes : "+ str(total_bact))
print("frequence of plurimicrobial episodes within all episodes : " + str(count_bact/total_bact) + "\n")
count_bact_pluri = count_bact
total_bact_pluri = total_bact

# share of plurimicrobial episodes within BIAB
count_bact = 0
total_bact = 0
len_bact=dict()
for x in bact_ana:
    try:
        len_bact[len(x[0][0])] += 1
    except KeyError:
        len_bact[len(x[0][0])] = 1
    if len(x[0][0]) > 1:
        count_bact += 1
    total_bact += 1
moy_bact=0
denom_bact=0
for x in len_bact:
    if x != 1:
        moy_bact += x*len_bact[x]
        denom_bact += len_bact[x]
print("mean number of species per BIAB episodes : " + str(moy_bact/denom_bact))
print("repartition of the numbers of species per episode : " + str(len_bact))
print("number of plurimicrobial bacteriemia within BIAB : " + str(count_bact))
print("total number of BIAB episodes : "+ str(total_bact))
print("frequence of plurimicrobial episodes within BIAB episodes : " + str(count_bact/total_bact))
obs=numpy.array([[count_bact,total_bact-count_bact],[count_bact_pluri,total_bact_pluri-count_bact_pluri]])
print("p-value " + str(stats.chi2_contingency(obs)[1]) + ".")
print("\n")

# number of BIAB with only AB
only_ana=0
only_multiana=0
for x in bact_ana:
    for y in x[0][0]:
        if list_bact[y] in ("3","4"):
            continue
        else:
            break
    else:
        only_ana += 1
        if len(x[0][0]) > 1:
            only_multiana += 1
print("number of BIAB with only AB : " + str(only_ana))
print("number of polymicrobial BIAB episodes with only AB : " + str(only_multiana) + "\n")

# number of episodes, of BIAB episodes, per service, plus description of episodes
print('all data')
for x in bact_per_service:
    print(x)
print("\n")

# frequencies of BIAB within all episodes, in ICM, for each service
freq_bactana=[]
freq_bactana_serv=dict()
print("frequencies of BIAB within all episodes, in ICM, for each service")
for x in bact_per_service:
    if x[1] > 10 and x[0][:3] == 'ICM':
        print(x)
        print(str(x[2]/x[1]))
        freq_bactana.append(x[2]/x[1])
        freq_bactana_serv[x[0]] = x[2]/x[1]
print(freq_bactana_serv)
with open('freq_bact_per_serv_icm.csv','w', newline='') as outputfile:
    writer = csv.writer(outputfile)
    writer.writerow(['service','frequence'])
    for key,value in freq_bactana_serv.items():
        writer.writerow([key,value])
print("minimal frequency ICM >=10 : " + str(min(freq_bactana)))
print("maximal frequency ICM >=10 : " + str(max(freq_bactana)))
print("mean of frequency ICM >=10 : " + str(mean(freq_bactana)))
print("median of frequency ICM >=10 : " + str(median(freq_bactana)) + "\n")

# frequencies of BIAB within all episodes, in CHU, for each service
freq_bactana=[]
freq_bactana_serv=dict()
print("frequencies of BIAB within all episodes, in ICM, for each service")
for x in bact_per_service:
    if x[1] > 10 and x[0][:3] != 'ICM':
        print(x)
        print(str(x[2]/x[1]))
        freq_bactana.append(x[2]/x[1])
        freq_bactana_serv[x[0]] = x[2]/x[1]
with open('freq_bact_per_serv_chu.csv','w', newline='') as outputfile:
    writer = csv.writer(outputfile)
    writer.writerow(['service','frequence'])
    for key,value in freq_bactana_serv.items():
        writer.writerow([key,value])
print("minimal frequency CHUM >=10 : " + str(min(freq_bactana)))
print("maximal frequency CHUM >=10 : " + str(max(freq_bactana)))
print("mean of frequency CHUM >=10 : " + str(mean(freq_bactana)))
print("median of frequency CHUM >=10 : " + str(median(freq_bactana)) + "\n")

# Statistics between CHU and ICM
bact_icm=0
bactana_icm=0
bact_chu=0
bactana_chu=0
for x in bact_per_service:
    if x[0][:3] == 'ICM':
        bact_icm += x[1]
        bactana_icm += x[2]
    else:
        bact_chu += x[1]
        bactana_chu += x[2]
print('chu: '
      + str(bactana_chu)
      + ' bacteriemies ana sur '
      + str(bact_chu) + ' bacteriemie soit '
      + str(bactana_chu/bact_chu*100)
      + '%')
print('ICM: '
      + str(bactana_icm)
      + ' bacteriemies ana sur '
      + str(bact_icm)
      + ' bacteriemie soit '
      + str(bactana_icm/bact_icm*100)
      + '%')
obs=numpy.array([[bactana_chu,bactana_icm],[bact_chu-bactana_chu,bact_icm-bactana_icm]])
print("p-value " + str(stats.chi2_contingency(obs)[1]) + ".")
print("\n")

# frequency of species isolation in BIAB
occur=dict()
for x in list_bact:
    if (list_bact[x] == '3' or list_bact[x] == '4'):
        occur[x] = 0
        for y in bact_per_service:
            for z in y[3]:
                if x in z:
                    occur[x] += y[3][z]
print("frequency of species isolation")
for x in occur:
    print(str(x) + ' : ' + str(occur[x]))
with open("occur_spp.csv", 'w', newline="") as occur_file:
    writer_file = csv.writer(occur_file, delimiter=';')
    writer_file.writerow(["species","name","occurence"])
    for row in occur:
        writer_file.writerow([str(row),str(name_bact[row]),str(occur[row])])
print("\n")

# frequency of genus isolation in BIAB
occur_gen=dict()
for x in list_bact :
    if (list_genus[x] not in occur_gen and (list_bact[x] == '3' or list_bact[x] == '4')): # pas besoin de relancer list_genus[x] si déjà fait
        for y in bact_per_service:
            for z in y[3]:
                for w in z.split(","):
                    if list_genus[x] == list_genus[w[2:8]] and (list_bact[w[2:8]] == '3' or list_bact[w[2:8]] == '4'):
                        try:
                            occur_gen[list_genus[x]] += y[3][z]
                        except KeyError:
                            occur_gen[list_genus[x]] = y[3][z]
                        break
print("frequency of genus isolation :")
for x in occur_gen:
    print(str(x) + ' : ' + str(occur_gen[x]))
with open("occur_gen.csv", 'w', newline="") as occur_file:
    writer_file = csv.writer(occur_file, delimiter=';')
    for row in occur_gen:
        writer_file.writerow([str(row),str(occur_gen[row])])

# frequency of BFG isolation in BIAB
occur_frag_grp=0
for y in bact_per_service:
    for z in y[3]:
        for w in z.split(","):
            if list_genus[w[2:8]] in ('Bacteroides','Parabacteroides'):
                occur_frag_grp += y[3][z]
                break
print("\n" + "Number of episodes with BFG : " + str(occur_frag_grp) + "\n")


from sklearn import linear_model
import matplotlib.pyplot as plt
import numpy as np
# 线性回归
reg = linear_model.LinearRegression(fit_intercept=True)
# 稳健回归
# reg = linear_model.RANSACRegressor()
x = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
y = [1, 2, 3, 10, 5]
print(x)
print(y)
reg.fit(x, y)
# print(reg.estimator_.coef_)
# print(reg.estimator_.intercept_)
print(reg.coef_)
print(reg.intercept_)
result = reg.predict(x)
print(result)

广义线性模型/线性回归.py


"""
smee

Differentiably evaluate energies of molecules using SMIRNOFF force fields
"""

from . import _version
from ._models import (
    NonbondedParameterMap,
    ParameterMap,
    TensorConstraints,
    TensorForceField,
    TensorPotential,
    TensorSystem,
    TensorTopology,
    TensorVSites,
    ValenceParameterMap,
    VSiteMap,
)
from .geometry import add_v_site_coords, compute_v_site_coords
from .potentials import compute_energy, compute_energy_potential

__version__ = _version.get_versions()["version"]

__all__ = [
    "ValenceParameterMap",
    "NonbondedParameterMap",
    "ParameterMap",
    "VSiteMap",
    "TensorConstraints",
    "TensorTopology",
    "TensorSystem",
    "TensorPotential",
    "TensorVSites",
    "TensorForceField",
    "__version__",
    "add_v_site_coords",
    "compute_v_site_coords",
    "compute_energy",
    "compute_energy_potential",
]


import random
from numpy.random import choice
from matplotlib import pyplot as plt

# import sys
# import os
# sys.path.insert(0, os.path.abspath(
#     os.path.join(os.path.dirname(__file__), '..')))

from learning_automata.variable_action_set import VariableActionSet  # NOQA

class SymmetricVariableDepthHybrid:
    def __init__(self, action_number, state_number, reward_rate, penalty_rate, max_state_number):
        self.fsla_action_number = action_number
        self.fsla_state_number = state_number

        self.fsla_chosen_action = 0
        self.fsla_chosen_action_depth_status = 0
        self.fsla_state_transition_counter = 0
        self.fsla_depth_transition_counter = 0
        self.fsla_min_state = 1
        self.fsla_max_state = max_state_number

        '''
            grow --> Action 0
            stop --> Action 1
            shrink --> Action 2
        '''
        self.variable_action_set_action_number = 3
        self.variable_action_set = VariableActionSet(
            self.variable_action_set_action_number, reward_rate, penalty_rate)
        self.variable_action_set_first_run = True

        self.total_number_of_rewards = []
        self.total_number_of_action_switching = []

        self.action_selection_status = [[]
                                        for _ in range(self.fsla_action_number)]

    # *****************************************************************************************
    def choose_action(self, sub_action_list):
        self.__action_switching_by_scaling(sub_action_list)

        return self.fsla_chosen_action

    # *****************************************************************************************
    def choose_random_action(self):
        # Choose random action for first running
        self.chosen_action = random.randint(0, self.fsla_action_number-1)
        self.fsla_chosen_action_depth_status = 1

        return self.fsla_chosen_action

    # *****************************************************************************************
    def receive_environment_signal(self, beta):
        if beta == 1:
            self.__punish_automata()
            self.total_number_of_rewards.append(
                0 + self.total_number_of_rewards[-1] if len(self.total_number_of_rewards) > 0 else 0)
        else:
            self.__suprise_automata()

            self.total_number_of_rewards.append(
                1 + self.total_number_of_rewards[-1] if len(self.total_number_of_rewards) > 0 else 1)
            self.total_number_of_action_switching.append(
                0 + self.total_number_of_action_switching[-1] if len(self.total_number_of_action_switching) > 0 else 0)
        return

    # *****************************************************************************************
    def visualization_calculations(self):
        for action in range(self.fsla_action_number):
            if action == self.fsla_chosen_action:
                self.action_selection_status[action].append(
                    1 + self.action_selection_status[action][-1] if len(self.action_selection_status[action]) > 0 else 1)
            else:
                self.action_selection_status[action].append(
                    0 + self.action_selection_status[action][-1] if len(self.action_selection_status[action]) > 0 else 0)

    # *****************************************************************************************
    @property
    def get_total_number_of_rewards(self):
        return self.total_number_of_rewards

    # *****************************************************************************************
    @property
    def get_total_number_of_action_switching(self):
        return self.total_number_of_action_switching

    # *****************************************************************************************
    def get_action_selection_status(self, action_number):
        return self.action_selection_status[action_number]

    # *****************************************************************************************
    def __suprise_automata(self):
        if self.fsla_chosen_action_depth_status < self.fsla_state_number:
            self.fsla_chosen_action_depth_status += 1

        self.fsla_state_transition_counter += 1
        if self.__is_fsla_on_depth():
            self.fsla_depth_transition_counter += 1

        return

    # *****************************************************************************************
    def __punish_automata(self):
        if self.fsla_chosen_action_depth_status > 1:
            self.fsla_chosen_action_depth_status -= 1

            self.fsla_state_transition_counter += 1

            self.total_number_of_action_switching.append(
                0 + self.total_number_of_action_switching[-1] if len(self.total_number_of_action_switching) > 0 else 0)
        else:
            if not self.variable_action_set_first_run:
                self.__evaluate_variable_action_set()
            else:
                self.variable_action_set_first_run = False

            self.__action_switching()

        return

    # *****************************************************************************************
    def __is_fsla_on_depth(self):
        return self.fsla_chosen_action_depth_status == self.fsla_state_number

    # *****************************************************************************************
    def __choose_new_action_clockwise(self):
        if self.fsla_chosen_action < self.fsla_action_number - 1:
            self.fsla_chosen_action += 1
        else:
            self.fsla_chosen_action = 0

        self.fsla_chosen_action_depth_status = 1

        return

    # *****************************************************************************************
    def __action_switching(self):
        self.__choose_new_action_clockwise()
        self.__update_fsla_depth()

        self.fsla_state_transition_counter = 1
        self.fsla_depth_transition_counter = 0

        self.total_number_of_action_switching.append(
            1 + self.total_number_of_action_switching[-1] if len(self.total_number_of_action_switching) > 0 else 1)

        return

    # *****************************************************************************************
    def __evaluate_variable_action_set(self):
        variable_action_set_beta = 1 - (self.fsla_depth_transition_counter / self.fsla_state_transition_counter)  # NOQA

        self.variable_action_set.receive_environment_signal(
            variable_action_set_beta)

        return

    # *****************************************************************************************
    def __update_fsla_depth(self):
        new_depth_decision = 0

        if self.fsla_state_number == self.fsla_max_state:
            new_depth_decision = self.variable_action_set.choose_action([1, 2])
        elif self.fsla_state_number == self.fsla_min_state:
            new_depth_decision = self.variable_action_set.choose_action([0, 1])
        else:
            new_depth_decision = self.variable_action_set.choose_action([0, 1, 2])  # NOQA

        if new_depth_decision == 0:
            self.fsla_state_number += 1  # Grow
        # elif new_depth_decision == 1:
        #     # Do Nothing --> Stop
        elif new_depth_decision == 2:
            self.fsla_state_number -= 1  # Shrink

        return

    # *****************************************************************************************
    def __action_switching_by_scaling(self, sub_action_list):
        for action in sub_action_list:
            if self.fsla_chosen_action == action:
                return

        self.__choose_new_action_clockwise()

        self.fsla_state_transition_counter = 1
        self.fsla_depth_transition_counter = 0

        return


def maxUncrossedLines( nums1, nums2) -> int:
        m = len(nums1)
        n = len(nums2)
        dp = [[0 for i in range (n + 1)] for j in range(m + 1)]
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                print(i ,j )
                print(nums1[i - 1] , nums2[j - 1])
                if nums1[i - 1] == nums2[j - 1]:
                    print(dp[i][j], dp[i - 1][j - 1] , nums1[i-1], nums2[j-1])
                    dp[i][j] = dp[i - 1][j - 1] + 1
                else:
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
        print(dp)
        return dp[m][n]
maxUncrossedLines([10,5,2,1,5,2],
[2,5,1,2,5])


#!/usr/bin/env python

import paramiko
import time

def deploy(key, server):
    print("Connecting to box")
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(server, key_filename=key)
    ssh.exec_command('sudo yum install git -y')
    ssh.exec_command('rm -rf theia; '
                     'git clone https://github.com/akkiittiwari/theia.git;')
    print("Launching Flask Server")
    time.sleep(2)
    ssh.exec_command('python $(pwd)/theia/flask_server.py')
    print("Pull from Github successful")
    time.sleep(2)
    print("Script fully executed ... exiting")
    ssh.close()
# deploy('PEM_FILE_PATH', 'ec2-54-212-196-78.us-west-2.compute.amazonaws.com')


t = int(input())
for _ in range(t):
    n = int(input())
    speeds = list(map(int, input().strip().split()))
    max_speed = speeds[0]
    count = 0
    for i in speeds:
        if max_speed >= i:
            count += 1
            max_speed = i
    print(count)


import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
plt.rc("font", size=14)
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_validate, train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import LinearSVC
from sklearn.calibration import CalibratedClassifierCV
from sklearn import metrics
from statistics import mean
import xgboost as xgb
import pickle
from sklearn.utils import shuffle
import seaborn as sns
sns.set(style="white")
sns.set(style='whitegrid', color_codes=True)

df = pd.read_csv("/home/ppf/Ilyas_dataset/accept_21_features.csv", sep=",", encoding="ISO-8859-1")

# 'cmssw'
project_list = ['react', 'django', 'nixpkgs', 'scikit-learn', 'yii2', 'cdnjs', 'terraform', 'cmssw', 'salt', 'tensorflow', 'pandas',
                'symfony', 'moby', 'rails', 'rust', 'kubernetes'#, 'angular.js', 'laravel', 'curriculum', 'opencv', 'githubschool'
                 ]

# Handle missing values
# df.loc[(df.Forks_Count == 0) & (df.Project_Name == 'cdnjs'), 'Forks_Count'] = 3384
# df.loc[(df.Forks_Count == 0) & (df.Project_Name == 'terraform'), 'Forks_Count'] = 3659
# df.loc[(df.Forks_Count == 0) & (df.Project_Name == 'kubernetes'), 'Forks_Count'] = 11639

print(df.Timeline[df['PR_Latency']==0])

# Remove some of the PRs with negative latency
ID = df.Pull_Request_ID[df.latency_after_first_response < 0]
df = df.loc[~df.Pull_Request_ID.isin(ID)]

scoring = ['precision', 'recall', 'f1', 'roc_auc', 'accuracy']
#results = pd.DataFrame(columns=['Model', 'AUC', 'Precision', 'Recall', 'F-measure', 'Test_Accuracy', 'Train_Accuracy'])

def get_classifiers():
    return {
        'Randomforest': RandomForestClassifier(n_jobs=4, bootstrap=False, class_weight='balanced'), # n_jobs=4, bootstrap=False, class_weight='balanced', max_depth=15, min_samples_leaf=1, n_estimators=400
        'LinearSVC': LinearSVC(max_iter=2500),
        'LogisticRegression': LogisticRegression(solver='lbfgs', n_jobs=4, multi_class='auto', max_iter=1200),
        'XGBoost':xgb.XGBClassifier(**params),
    }

params = {
			'objective': 'binary:logistic',
			'eta': 0.08,
			'colsample_bytree': 0.886,
			'min_child_weight': 1.1,
			'max_depth': 7,
			'subsample': 0.886,
			'gamma': 0.1,
			'lambda':10,
			'verbose_eval': True,
			'eval_metric': 'auc',
			'scale_pos_weight':6,
			'seed': 201703,
			'missing':-1
	   }

def encode_labels(df1, column_name):
    encoder = preprocessing.LabelEncoder()
    df1[column_name] = [str(label) for label in df1[column_name]]
    encoder.fit(df1[column_name])
    one_hot_vector = encoder.transform(df1[column_name])
    return one_hot_vector

# print(df.columns)
# print(df.shape)

df['Language'] = encode_labels(df, 'Language')
# df_proj['Maintenance_And_Evolution_Category'] = encode_labels(df_proj, 'Maintenance_And_Evolution_Category')
# df_proj['Title_Body_Sentiment'] = encode_labels(df_proj, 'Title_Body_Sentiment')
df['Project_Domain'] = encode_labels(df, 'Project_Domain')

# df = df[['Project_Age', 'Project_Accept_Rate', 'Language', 'Watchers', 'Stars', 'Team_Size', 'Additions_Per_Week',
#      'Deletions_Per_Week', 'Comments_Per_Merged_PR', 'Contributor_Num', 'Churn_Average', 'Sunday', 'Monday',
#      'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Close_Latency', 'Comments_Per_Closed_PR', 'Forks_Count',
#      'File_Touched_Average', 'Merge_Latency', 'Rebaseable', 'Intra_Branch', #'Project_Domain',#'Mergeable',
#      'Additions', 'Deletions', 'Day', 'Wait_Time', 'Contain_Fix_Bug', 'PR_Latency', 'Files_Changed',
#      'Label_Count', 'Assignees_Count', 'Workload', 'Review_Comments_Count', 'Comments_Count',  'Commits_PR',
#      'Commits_Average', 'Contributor', 'Followers', 'Closed_Num', 'Public_Repos', 'Organization_Core_Member',
#      'Accept_Num', 'User_Accept_Rate', 'Contributions', 'Closed_Num_Rate', 'Following', 'Prev_PRs',
#      'Last_Comment_Mention', 'Point_To_IssueOrPR', 'Open_Issues', 'Participants_Count',
#      'first_response', 'latency_after_first_response', 'X1_0', 'X1_1', 'X1_2', 'X1_3', 'X1_4', 'X1_5', 'X1_6', 'X1_7', 'X1_8', 'X1_9',
#       'PR_accept', 'PR_Date_Created_At', 'PR_Time_Create_At', 'PR_Date_Closed_At', 'PR_Time_Closed_At', 'Project_Name']]

df = df[['Comments_Count', 'Following', 'Project_Accept_Rate', 'Public_Repos', 'Additions', 'Saturday', 'Team_Size',
       'Deletions_Per_Week', 'Prev_PRs', 'Commits_PR', 'Files_Changed', 'File_Touched_Average', 'Day',
       'Organization_Core_Member',  'Deletions', 'Assignees_Count', 'Label_Count', 'Additions_Per_Week', 'Project_Age',
        'Accept_Num', 'Stars', 'Workload', 'Comments_Per_Merged_PR', 'Language', 'Last_Comment_Mention', 'Project_Domain',
        'Project_Size', 'Merge_Latency', 'Rebaseable', 'Commits_Average','Open_Issues', 'Tuesday', 'Watchers', 'Wednesday',
        'Closed_Num', 'Participants_Count', 'Thursday', 'Review_Comments_Count', 'Close_Latency', 'Contributor', 'Forks_Count',
         'Contributions', 'Friday', 'Monday', 'Intra_Branch', 'Point_To_IssueOrPR', 'Mergeable_State', 'Contributor_Num',
       'Sunday', 'Comments_Per_Closed_PR', 'Followers', 'Wait_Time', 'Closed_Num_Rate', 'Contain_Fix_Bug', 'User_Accept_Rate',
        'first_response', 'latency_after_first_response', 'conflict', 'title_words_count', 'body_words_count',
        'comments_reviews_words_count', 'Churn_Average', 'X1_0', 'X1_1', 'X1_2', 'X1_3', 'X1_4', 'X1_5', 'X1_6',
       'X1_7', 'X1_8', 'X1_9', 'PR_Latency', 'Project_Name', 'PR_Date_Created_At', 'PR_Time_Create_At', 'PR_Date_Closed_At',
       'PR_Time_Closed_At', 'Pull_Request_ID', 'PR_accept']]

# shuffle the data
df = shuffle(df)

target = 'PR_accept'

predictors = [x for x in df.columns if x not in [target, 'PR_Date_Created_At', 'PR_Time_Create_At', 'PR_Date_Closed_At',
                                                 'PR_Time_Closed_At', 'Project_Name']]

X = df
y= df[target]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, stratify=y, random_state=143)

def get_under_sampled_dataset():
    # Class count
    count_class_1, count_class_0 = X_train[target].value_counts()

    print(f'0 count: {count_class_0}, 1 count: {count_class_1}')
    # Divide by class
    df_class_0 = X_train[X_train[target] == 0]
    df_class_1 = X_train[X_train[target] == 1]
    print(f'Negative samples shape: {df_class_0.shape}')
    print(f'Positive samples shape: {df_class_1.shape}')

    df_class_1_under = df_class_1.sample(count_class_0)
    df_test_under = pd.concat([df_class_1_under, df_class_0], axis=0)

    print('Random under-sampling:')
    print(df_test_under[target].value_counts())
    shuffle(df_test_under)
    y_df = df_test_under[target]

    return df_test_under, y_df

def get_over_sampled_dataset():
    # Class count
    count_class_1, count_class_0 = X_train[target].value_counts()

    print(f'0 count: {count_class_0}, 1 count: {count_class_1}')
    # Divide by class
    df_class_0 = X_train[X_train[target] == 0]
    df_class_1 = X_train[X_train[target] == 1]
    print(f'Negative samples shape: {df_class_0.shape}')
    print(f'Positive samples shape: {df_class_1.shape}')

    df_class_0_over = df_class_0.sample(count_class_1, replace=True)
    df_test_over = pd.concat([df_class_0_over, df_class_1], axis=0)

    print('Random over-sampling:')
    print(df_test_over[target].value_counts())
    shuffle(df_test_over)
    y_df = df_test_over[target]

    return df_test_over, y_df

# X_train, y_train = get_over_sampled_dataset()

print("Total Train dataset size: {}".format(X_train.shape))
print("Total Test dataset size: {}".format(X_test.shape))

# Scale the training dataset: StandardScaler
def scale_data_standardscaler(df_):
    scaler_train =StandardScaler()
    df_scaled = scaler_train.fit_transform(np.array(df_).astype('float64'))
    df_scaled = pd.DataFrame(df_scaled, columns=predictors)

    return df_scaled

X_train_scaled = scale_data_standardscaler(X_train[predictors])
X_test_scaled = scale_data_standardscaler(X_test[predictors])
#X_val_scaled = scale_data_standardscaler(X_val[predictors])

def train_XGB_model(alg, x_train, y_train, x_test, cv_folds=3, early_stopping_rounds=50):

    xgb_param = alg.get_xgb_params()
    xgtrain = xgb.DMatrix(x_train, label=y_train)
    cvresult = xgb.cv(xgb_param, xgtrain, num_boost_round=alg.get_params()['n_estimators'], nfold=cv_folds, stratified=True,
                      metrics='auc', early_stopping_rounds=early_stopping_rounds)
    alg.set_params(n_estimators=cvresult.shape[0])

    # Fit the algorithm on the data
    alg.fit(x_train, y_train, eval_metric='auc')

    # Save the model
    # with open('response_xgb_16.pickle.dat', 'wb') as f:
    #     pickle.dump(alg, f)

    # Load the model
    # with open('response_xgb_16.pickle.dat', 'rb') as f:
    #     load_xgb = pickle.load(f)

    y_pred_train = alg.predict(x_train)
    y_predprob_train = alg.predict_proba(x_train)[:, 1]

    y_pred = alg.predict(x_test)
    y_predprob = alg.predict_proba(x_test)[:, 1]

    return y_pred_train, y_predprob_train, y_pred, y_predprob

def train_SVM_model(clf, x_train, y_train, x_test, cv_folds=3):
    svm = CalibratedClassifierCV(clf, cv=cv_folds)
    svm.fit(x_train, y_train)
    # train
    y_pred_train = svm.predict(x_train)
    y_predprob_train = svm.predict_proba(x_train)[:, 1]
    # test
    y_pred = svm.predict(x_test)
    y_predprob = svm.predict_proba(x_test)[:, 1]

    return y_pred_train, y_predprob_train, y_pred, y_predprob

def train_RF_LR_model(clf, x_train, y_train, x_test, cv_folds=3):
    cv_results = cross_validate(clf, x_train, y_train, cv=cv_folds)
    print('Validation scores')
    print("Test accuracy: {}".format(cv_results['test_score'].mean()))
    print("Train accuracy: {}".format(cv_results['train_score'].mean()))
    clf.fit(x_train, y_train)
    # train
    y_pred_train = clf.predict(x_train)
    y_predprob_train = clf.predict_proba(x_train)[:, 1]
    # test
    y_pred = clf.predict(x_test)
    y_predprob = clf.predict_proba(x_test)[:, 1]

    # Save the model
    # with open('prioritizer.pickle.dat', 'wb') as f:
    #     pickle.dump(clf, f)

    # Load the model
    # with open('response_xgb_16.pickle.dat', 'rb') as f:
    #     load_xgb = pickle.load(f)

    return y_pred_train, y_predprob_train, y_pred, y_predprob

def start_train_models():
    results = pd.DataFrame(
        columns=['Model', 'AUC', 'Precision', 'Recall', 'F-measure', 'Test_Accuracy', 'Train_Accuracy'])
    classifiers = get_classifiers()

    for name, value in classifiers.items():
            clf = value
            print('Classifer: ', name)
            if name == 'XGBoost':
                y_pred_train, y_predprob_train, y_pred, y_predprob = train_XGB_model(clf, X_train_scaled, y_train, X_test_scaled, cv_folds=10)
            elif name == 'LinearSVC':
                y_pred_train, y_predprob_train, y_pred, y_predprob = train_SVM_model(clf, X_train_scaled, y_train, X_test_scaled, cv_folds=10)
            elif name == 'LogisticRegression':
                y_pred_train, y_predprob_train, y_pred, y_predprob = train_RF_LR_model(clf, X_train_scaled, y_train, X_test_scaled, cv_folds=10)
            else:
                y_pred_train, y_predprob_train, y_pred, y_predprob = train_RF_LR_model(clf, X_train_scaled, y_train, X_test_scaled, cv_folds=10)

            # Print model report:
            print("\nModel Report")
            print("Train Accuracy : %.4g" % metrics.accuracy_score(y_train, y_pred_train))
            print("Test Accuracy : %.4g" % metrics.accuracy_score(y_test, y_pred))
            print('Train error: {:.3f}'.format(1 - metrics.accuracy_score(y_train, y_pred_train)))
            print('Test error: {:.3f}'.format(1 - metrics.accuracy_score(y_test, y_pred)))
            print("AUC Score : %f" % metrics.roc_auc_score(y_test, y_predprob))
            print("Recall : %f" % metrics.recall_score(y_test, y_pred))
            print("Precision : %f" % metrics.precision_score(y_test, y_pred))
            print("F-measure : %f" % metrics.f1_score(y_test, y_pred))
            c_matrix = metrics.confusion_matrix(y_test, y_pred)
            print('========Confusion Matrix==========')
            print("          Rejected    Accepted")
            print('Rejected     {}      {}'.format(c_matrix[0][0], c_matrix[0][1]))
            print('Accepted     {}      {}'.format(c_matrix[1][0], c_matrix[1][1]))
            results= results.append(
                {'Model': name, 'AUC': metrics.roc_auc_score(y_test, y_predprob),
                 'Precision': metrics.precision_score(y_test, y_pred),
                 'Recall': metrics.recall_score(y_test, y_pred),
                 'F-measure': metrics.f1_score(y_test, y_pred),
                 'Test_Accuracy': metrics.accuracy_score(y_test, y_pred),
                 'Train_Accuracy': metrics.accuracy_score(y_train, y_pred_train)},
                ignore_index=True)

    results.to_csv('Results/accept_10_fold_3.csv', sep=',', encoding='utf-8', index=False)

# start_train_models()


import asyncio
from aiohttp import ClientSession, ClientError
from grazyna.utils.event_loop import loop
from grazyna.format import color, bold

API_URL = "https://api.github.com/repos/{user}/{repo}/{action}"
state_colors = {
    'open': color.green,
    'closed': color.red,
    'reopened': color.green,
    'subscribed': color.green,
    'merged': color.green,
    'assigned': color.purple,
    'unassigned': color.purple,
    'milestoned': color.olive,
    'demilestoned': color.olive,
    'locked': color.red,
    'unlocked': color.green,
    'renamed': color.dark_gray
}

class NothingChangeException(Exception):
    pass

POSSIBLE_EXCEPTIONS = (
    ClientError, IndexError, NothingChangeException, asyncio.TimeoutError
)

@loop(time_config_key="commits_time", default=60)
def commits(irc_protocol, plugin, config):
    try:
        data = yield from github_action('commits', plugin, config)
    except POSSIBLE_EXCEPTIONS:
        return

    msg = "‼ {commit} '{msg}' by {committer} {url}".format(
        commit=bold('COMMIT'),
        msg=strip(data['commit']['message']),
        committer=data['commit']['author']['name'],
        url=data['html_url']
    )

    for chan in config['channels'].split(','):
        irc_protocol.say(chan.strip(), msg)

@loop(time_config_key="events_time", default=60)
def events(irc_protocol, plugin, config):
    try:
        data = yield from github_action('issues/events', plugin, config)
    except POSSIBLE_EXCEPTIONS:
        return

    issue = data['issue']
    state = data['event']
    state_color = state_colors.get(state, color.black)
    assignee = issue['assignee']
    assignee_login = assignee['login'] if assignee is not None else None
    msg = ("‼ {issue} {labels} '{title}' by {user} "
           "{assignee} {state} {url}").format(
        issue=bold('ISSUE'),
        labels=' '.join('[%s]' % label['name'] for label in issue['labels']),
        title=strip(issue['title']),
        state=bold(color(' %s ' % state, color.white, state_color)),
        user=issue['user']['login'],
        assignee="assigned to %s" % assignee_login if assignee_login else '',
        url=issue['html_url'],
    )

    for chan in config['channels'].split(','):
        irc_protocol.say(chan.strip(), msg)

@loop(time_config_key="comments_time", default=60)
def comments(irc_protocol, plugin, config):
    try:
        data = yield from github_action('issues/comments', plugin, config)
    except POSSIBLE_EXCEPTIONS:
        return

    msg = "‼ {issue} by {nick} '{msg}' {url}".format(
        issue=bold('COMMENT'),
        msg=strip(data['body']),
        nick=data['user']['login'],
        url=data['html_url'],
    )

    for chan in config['channels'].split(','):
        irc_protocol.say(chan.strip(), msg)

def strip(msg):
    lines = msg.splitlines()
    line = lines[0]
    if len(lines) == 0:
        return ''
    elif len(lines) == 1:
        return line if len(line) < 50 else line[:50] + "…"
    else:
        return line[:50] + "…"

@asyncio.coroutine
def github_action(action, plugin, config, sort_by='updated'):
    url = API_URL.format(
        api=API_URL,
        user=config['user'],
        repo=config['repository'],
        action=action,
    )
    query = {
        'sort': sort_by,
        'direction': 'desc',
        'sha': config.get('branch', 'master')
    }
    headers = {'Accept': 'application/vnd.github.v3+json'}
    etag = plugin.temp.get(action)
    if etag is not None:
        headers['If-None-Match'] = etag

    session = ClientSession()
    try:
        resp = yield from asyncio.wait_for(
            session.get(url, params=query, headers=headers),
            timeout=5
        )
        try:
            plugin.temp[action] = resp.headers.get('etag')
            if resp.status != 200 or etag is None:  # etag must be cached first
                raise NothingChangeException(etag)
            data = yield from resp.json()
        finally:
            resp.close()
    finally:
        session.close()
    return data[0]


import asyncio
import logging

from aiohttp import web

from db import init_pg, close_pg
from periodic_tasks.user_cleaner import init_task, close_task
from routes import setup_routes
from settings import get_config

async def init_app(app):
    app.on_startup.append(init_pg)
    # app.on_startup.append(init_task)

async def destroy_app(app):
    await app.on_cleanup.append(close_pg)
    # await app.on_cleanup.append(close_task)

def init(loop=None):
    config = get_config()
    app = web.Application(loop=loop)
    app['config'] = config

    app.on_startup.append(init_app)
    if loop:
        app.on_cleanup.append(destroy_app)

    setup_routes(app)

    return app

def main():
    logging.basicConfig(level=logging.DEBUG)
    loop = asyncio.get_event_loop()
    app = init(loop)
    web.run_app(app,
                host=app['config']['HOST'],
                port=app['config']['PORT'])

if __name__ == '__main__':
    main()


#!/usr/bin/env python

import os
import json

import jinja2

from subprocess import Popen

HA_CONFIG_TMPL_PATH = 'haproxy.cfg.tmpl'
HA_CONFIG_PATH = '/etc/haproxy/haproxy.cfg'
PROXY_PATH = 'proxies.json'
NUM_PROXIES = int(os.environ.get('NUM_PROXIES', 5))

def render(tpl_path, context):
    """render haconfig from template

    Parameters
    -----------------
    tpl_path : str
        location of the template file to render
    context : dict
        information to include in the template i.e proxy details

    Returns
    ----------------
    str
        rendered haproxy config as string
    """
    path, filename = os.path.split(tpl_path)
    template = jinja2.Environment(
        loader=jinja2.FileSystemLoader(path or './'), autoescape=True
    ).get_template(filename)
    return template.render(context)

def create_proxy_config(backends):
    """create haproxy config using the data from proxy list

    Parameters
    --------------
    backends : list(dict)
        list of proxy details i.e ipaddress and port

    Returns
    -------------
    str
        rendered haproxy config containing proxies defined in the backends parameters
    """
    context = {'backends': backends}
    return render(HA_CONFIG_TMPL_PATH, context)

def preprocess_proxy(proxy):
    """fix proxy list to IPAddress,Port format from dictionary to ipaddress,port

    Parameters
    ----------------
    proxy : dict
        proxy details form the proxy json file

    Returns
    ---------------
    dict
        constaining keys ipaddress and port for the proxy
    """
    return {'ipaddress': proxy['IPAddress'], 'port': proxy['Port']}

def preprocess_proxy_list():
    """convert json proxy file to proxy formet list

    Returns
    ---------------
    list(dict)
        list of proxies with ipaddress and ports
    """
    proxies_list = read_proxy_config(PROXY_PATH)

    return [ preprocess_proxy(proxy) for proxy in proxies_list ]

def read_proxy_config(file_name):
    """convert proxy file from json file to python data structure

    Parameters
    --------------
    file_name : str
        location of proxies json list file

    Returns
    -------------
    object
        datastructure representation of json file
    """
    with open(file_name) as data_file:
        data = json.load(data_file)
    return data

def write_ha_proxy_config(config):
    """write haproxy file to location `HA_CONFIG_PATH`

    Parameters
    --------------
    config : str
        haproxy config string
    """
    with open(HA_CONFIG_PATH, 'w') as file:
        file.write(config)
        file.flush()

def prepare_requested_proxies(backends, num_proxies):
    """validate the proxies and select that match the requested numbers form json list

    Parameters
    --------------
    backends : list(dict)
        list of proxy config i,e ipaddress and port
    num_proxies: int
        number of proxies to create

    Returns
    -------------
    list(dict)
        spliced list of proxies based on the `num_proxies`
    """
    if len(backends) < num_proxies:
        return backends
    # TODO check for active proxies
    return backends[:num_proxies]

backends = preprocess_proxy_list()
active_backends = prepare_requested_proxies(
    backends=backends, num_proxies=NUM_PROXIES
)

ha_config = create_proxy_config(active_backends)
write_ha_proxy_config(ha_config)

p = Popen(['haproxy -d -f {}'.format(HA_CONFIG_PATH)], shell=True)
p.wait()
print('done running')


'''
Approved for Public Release: 12-3351. Distribution Unlimited
			(c)2012-The MITRE Corporation.
Licensed under the Apache License, Version 2.0 (the "License");
			you may not use this file except in compliance with the License.
			You may obtain a copy of the License at
			http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'''

from brainstorming.models import UserProfile, Group, Program, Brainstorming, TopN, Pairwise, Participant, Node, PairwiseVote
from brainstorming.models import Survey, SurveyGroup, SurveyRespondent, SurveyQuestion, SurveyDataPoint
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm
from django.contrib import admin
from django.forms import ModelForm

admin.site.register(UserProfile)
admin.site.register(Program)
admin.site.register(Brainstorming)
admin.site.register(Pairwise)
admin.site.register(TopN)
admin.site.register(Participant)
admin.site.register(PairwiseVote)
admin.site.register(Node)
admin.site.register(Group)

admin.site.register(Survey)
admin.site.register(SurveyGroup)
admin.site.register(SurveyRespondent)
admin.site.register(SurveyQuestion)
admin.site.register(SurveyDataPoint)

class UserForm(ModelForm):
    class Meta:
        model = User

    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        #self.fields['email'].required = True
        #self.fields['first_name'].required = True
        #self.fields['last_name'].required = True

class UserAdmin(admin.ModelAdmin):
	form = UserForm
	#list_display = ('first_name','last_name','email','is_active')
	exclude = ('password',)

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

'''
class CustomUserChangeForm(UserChangeForm):
    def __init__(self, *args, **kwargs):
        super(CustomUserChangeForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True

	class Meta:
		exclude = ['password']

class CustomUserAdmin(UserAdmin):
    form = CustomUserChangeForm

admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
'''
'''
class UserForm(forms.ModelForm):
    class Meta:
        model = User

    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        #self.fields['email'].required = True
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True

class UserAdmin(admin.ModelAdmin):
    #form = UserForm
	list_display = ('first_name','last_name','is_active')
	exclude = ['password']

class UserAdmin(admin.ModelAdmin):
	exclude = ['password']
	pass

admin.site.unregister(User)
admin.site.register(User)
'''