import time
import pandas as pd
import numpy as np
import sys

CITY_DATA = { 'chicago': 'chicago.csv',
              'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }

def get_filters():
    """
    Asks user to specify a city, month, and day to analyze as per suggested in question.

    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """
    print('Hello! Let\'s explore some US bikeshare data!')
    day_count=0
    month_count=0
    city_count=0
    # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
    while city_count<=4:
        city_list = ["chicago", "new york city", "washington"]
        try:
          city = input('Would you like to see data for city Chicago, New York City or Washington?\n')
          if city.lower() in city_list:
              break
          else:
              print('The city {} entered is invalid!\n'.format(city))
        except:
          print('Provide valid city name! You have max 3 trials to enter the correct value\n')
          continue
        city_count = city_count + 1
        if city_count>3:
         print('You have tried maximum attempts to enter the value!\n')
         print('-'*110)
         sys.exit()

    # get user input for month (all, january, february, ... , june)
    while month_count<=4:
        month_list = ["january", "february", "march","april","may","june","all"]
        try:
          month = input('Which month do you want to choose? (January, February, March, April, May, June or All) \n')
          if month.lower() in month_list:
              break
          else:
              print('The city {} entered is invalid!\n'.format(month))
        except:
          print('Provide valid month name! You have max 3 trials to enter the correct value \n')
          continue
        month_count = month_count + 1
        if month_count>3:
         print('You have tried maximum attempts to enter the value!/n')
         print('-'*110)
         sys.exit()
    # get user input for day of week (all, monday, tuesday, ... sunday)
    while day_count<=4:
       days= ['monday','tuesday','wednesday','thursday','friday','saturday','sunday','all']
       try:
          day = input('Which day you want to choose? (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday,All) \n')
          if day.lower() in days:
              break
          else:
              print('The day {} entered is invalid!\n'.format(day))
       except:
           print('Provide valid day! You have max 3 trials to enter the correct value\n')
           continue
       day_count = day_count + 1
       if day_count>3:
        print('You have tried maximum attempts to enter the value! \n')
        print('-'*110)
        sys.exit()
    print('-'*110)
    return city, month, day

def load_data(city, month, day):
    """
    Loads data for the specified city and filters by month and day if applicable.

    Args:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    Returns:
        df - Pandas DataFrame containing city data filtered by month and day
    """
    print('\nTo filter bikeshare data you have selected {} city, {} month and {} day of the week'.format(city.lower(),month.lower(),day.lower()))
    #Load data for city
    print("\nLoading data......................................................................................")
    try:
      df = pd.read_csv(CITY_DATA[city.lower()])
      #Convert the Start Time column to datetime
      df['Start Time'] = pd.to_datetime(df['Start Time'])
      #Extract month and day of week from Start Time to create new columns
      df['month'] = df['Start Time'].dt.month
      df['day_of_week'] = df['Start Time'].dt.day_name()
      #Filter by month to create the new dataframe
      print(type(df['day_of_week']))
      # use the index of the months list to get the corresponding int
      if month != 'all':
         months = ['january', 'february', 'march', 'april', 'may', 'june']
         month = months.index(month.lower())+1

      # filter by month to create the new dataframe
         df = df[df['month']==month]
      # filter by day of week if applicable
      # filter by day of week to create the new dataframe
      if day != 'all':
         df = df[df['day_of_week']==day.title()]
    except:
        print("Either file not found or Error in .py file")

    return df

def time_stats(df):
    """Displays statistics on the most frequent times of travel."""

    print('\nCalculating The Most Frequent Times of Travel...\n')
    start_time = time.time()
    print(start_time)
    # display the most common month
    popular_month=df['month'].mode()[0]
    print("Most Popular Month Between January To June: {}".format(popular_month))
    # display the most common day of week
    popular_day=df['day_of_week'].mode()[0]
    print("Most Popular Day Between Sunday To Saturday: {}".format(popular_day))
    # display the most common start hour
    df['hour'] = df['Start Time'].dt.hour
    popular_hour = df['hour'].mode()[0]
    print("Most Popular Hour in a day : {}".format(popular_hour))
    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*110)

def station_stats(df):
    """Displays statistics on the most popular stations and trip."""

    print('\nCalculating The Most Popular Stations and Trip...\n')
    start_time = time.time()
    # display most commonly used start station
    most_used_start_station = df['Start Station'].mode()[0]
    print("The most commonly used start station: {}".format(most_used_start_station))
    # display most commonly used end station
    most_used_end_station = df['End Station'].mode()[0]
    print("The most commonly used end station: {}".format(most_used_end_station))
    # display most frequent combination of start station and end station trip
    df['combined']=df['Start Station']+" "+"to"+" "+ df['End Station']
    common_start_end = df['combined'].mode()[0]
    print("The most commonly used start and end station combination: {}".format(common_start_end))
    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*110)

def trip_duration_stats(df):
    """Displays statistics on the total and average trip duration."""
    print('\nCalculating Trip Duration...\n')
    start_time = time.time()
    # display total travel time
    sum_duration=df['Trip Duration'].sum()
    minute,second= divmod(sum_duration,60)
    hour, minute = divmod(minute, 60)
    print("Total duration of trip is {} in hour, {} in minutes, {} in second".format(hour,minute,second))
    # display mean travel time
    average_duration = round(df['Trip Duration'].mean())
    print("Total mean average time: {}".format(average_duration))
    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*110)

def user_stats(df,city):
    """Displays statistics on bikeshare users."""

    print('\nCalculating User Stats...\n')
    start_time = time.time()

    # Display counts of user types
    user_type=df['User Type'].value_counts()
    print("The type of useres and details are: {}".format(user_type))
    # Display counts of gender
    if city.title() == 'Chicago' or city.title() == 'New York City':
       gender = df['Gender'].value_counts()
       print("The counts of gender are: {}".format(gender))

    # Display earliest, most recent, and most common year of birth
       earliest = int(df['Birth Year'].min())
       recent = int(df['Birth Year'].max())
       common_year = int(df['Birth Year'].mode()[0])
       print("The earliest year birthday in the list: {}".format(earliest))
       print("The recent year birthday in the list: {}".format(recent))
       print("The common year birthday in the list: {}".format(common_year))
       print("\nThis took %s seconds." % (time.time() - start_time))
       print('-'*110)

def display_data(df):
    """Displays 5 rows of data from the csv file for the selected city."""
    count=0
    counter=0
    response_list=["yes","no"]
    while count<=3:
      try:
         response = input("Do you want to view top 5 all data for selected city? (Enter Yes or No)\n")
         if (response.lower() in response_list) and (response.lower()=='yes') :
             print(df.head())
             break
         elif (response.lower() in response_list) and (response.lower()=='no'):
             break
         else:
             print('Input {} does not seem to match any of the accepted responses!\n'.format(response))
      except:
         print('Provide valid response! You have max 3 trials to enter the correct value\n')
         continue
      count = count + 1
      if count>2:
       print('You have tried maximum attempts to enter the value!\n')
       print('-'*110)
       sys.exit()

      """Displays 5 more rows of data from the csv file for the selected city."""
    while response == 'yes':
      response_f = input("Do you want to next 5 data for selected city? (Enter Yes or No)\n")
      counter += 5
      #If user opts for it, this displays next 5 rows of data
      if response_f.lower() == 'yes':
          print(df[counter:counter+5])
      elif response_f == 'no':
          print("You have selected option to not view further data!")
          break
      else:
          print("Entered response is invalid. Thus, ending the filter!")
          break
    print('-'*110)

def main():
    while True:
        city, month, day = get_filters()
        df = load_data(city, month, day)

        time_stats(df)
        station_stats(df)
        trip_duration_stats(df)
        user_stats(df,city)
        display_data(df)

        restart = input('\nWould you like to restart? Enter yes or no.\n')
        if restart.lower() != 'yes':
            break

if __name__ == "__main__":
	main()


"""
    Test file for func module
"""

import os
import unittest
from symupy.func import Simulator

class Test_func(unittest.TestCase):

    def test_load_SymuViaLib(self):
        """
        Test library load
        """
        tRelLibPath = ('symuvia',
                       'Contents',
                       'Frameworks',
                       'libSymuvia.dylib')
        sLibPath = os.path.join(os.getcwd(), *tRelLibPath)
        print(f'Test dir: {sLibPath}')
        # objSimulator = Simulator(sLibPath)

if __name__ == "__main__":
    unittest.main()


from SegregPicCore import config

# SINGLETON
class LoggerMetaclass(type):
    instance = None

    def __call__(cls, *args, **kwargs):
        if not cls.instance:
            cls.instance = super(LoggerMetaclass, cls).__call__(*args, **kwargs)

        return cls.instance

class Logger(metaclass=LoggerMetaclass):
    def __init__(self, log_file_full_path, log_file_name):
        self.log_file_full_path = log_file_full_path
        self.log_file_name = log_file_name

        self.is_file_already_created = False

        self.file_handler = self.create_log_file()

        self.PRINT_PROLOG = [
                                "",
                                "   SUCCESS!:",
                                "   WARNING:",
                                "   ERROR:"
                            ]

    def create_log_file(self):
        if self.is_file_already_created:
            raise FileIsAlreadyCreatedError("Log file is already created!")

        file = open(self.log_file_full_path + config.PATH_SEPARATOR + self.log_file_name, 'x')

        self.is_file_already_created = True

        return file

    def info_output(self, message, print_prologue=True):
        level = config.INFO_print_level
        self.__output_method(message, level, print_prologue)

    def success_output(self, message, print_prologue=True):
        level = config.SUCCESS_print_level
        self.__output_method(message, level, print_prologue)

    def warning_output(self, message, print_prologue=True):
        level = config.WARNING_print_level
        self.__output_method(message, level, print_prologue)

    def error_output(self, message, print_prologue=True):
        level = config.ERROR_print_level
        self.__output_method(message, level, print_prologue)

    def __output_method(self, message, level, print_prologue):
        if config.PRINT_PERMITS[level]:
            self.__print_stdout(message, level, print_prologue)

        if config.WRITE_TO_FILE_PERMITS[level]:
            self.write_to_file(message, level, print_prologue)

    def __print_stdout(self, message, level, print_prologue):
        if print_prologue:
            print(config.PRINT_OPTIONS[level] + self.PRINT_PROLOG[level])

        try:
            print(config.PRINT_OPTIONS[level] + message)
        except (TypeError, UnicodeEncodeError):
            # config.PRINT_OPTIONS[0]  # reset
            textp = message.encode("UTF-8")
            print(textp)

        config.PRINT_OPTIONS[0]  # reset

    def write_to_file(self, message, level, print_prologue):
        if print_prologue:
            self.file_handler.write(self.PRINT_PROLOG[level] + '\n')

        try:
            self.file_handler.write(message + '\n')
        except (TypeError, UnicodeEncodeError):
            textp = message.encode("UTF-8")
            self.file_handler.write(str(textp) + '\n')

    def close_file(self):
        if self.file_handler is not None:
            self.file_handler.close()

class FileIsAlreadyCreatedError(Exception):
    pass


import pygame
import random

#---------------------------Цвета----------------------
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red  = (255, 0, 0)
#свои цвета
ber = (25,170,175)# березовый
lber = ( 9,220,190)# l - светлый березовый
Dpurple = (70,2,90)# D - темный фиолетовый
purple = ( 190,40,175)# фиолетовый
lroze = (255,170,175) # легкий розовый
pygame.init ()

size = (700, 500)
screen = pygame.display.set_mode (size)
pygame.display.set_caption ("My game alpha 0.001")
# Цикл, пока пользователь не нажмет кнопку закрытия.
done = False
#------------------глобальные переменные------------------
rect_x = 50
rect_y = 50
rect_change_x = 5
rect_change_y = 5
snow_list = []
for i in range(50):
    x = random.randrange(0, 700)
    y = random.randrange(0, 400)
    snow_list.append([x, y])
# Скорость, пикселей за кадр
x_speed = 0
y_speed = 0
# Текущая позиция
x_coord = 10
y_coord = 10
star_list = []
#---------------------------------------------------
# Используется для управления скоростью обновления экрана.
clock = pygame.time.Clock ()

#----------------------Функции элементов----------------------

#функция отскока прямоугольника от краев
def Priam():
    global rect_x,rect_y,rect_change_x,rect_change_y
    pygame.draw.rect(screen, purple, [rect_x, rect_y, 50, 50])
    pygame.draw.rect(screen, red, [rect_x + 10, rect_y + 10, 30, 30])
    rect_x += rect_change_x
    rect_y += rect_change_y
    # Заставить прямоугольник отпрыгнуть, если нужно
    if rect_y > 450 or rect_y < 0:
        rect_change_y = rect_change_y * -1
    if rect_x > 650 or rect_x < 0:
        rect_change_x = rect_change_x * -1

#функция снега
def snow_up():

    for i in range(len(snow_list)):

        # рисует круг, по координате, а потом по координате -1, и так двигает
        pygame.draw.circle(screen, lroze, snow_list[i], 2)
        # меняет местоположение снежинки(скорость),направление
        snow_list[i][1] -= 1

        # если снег зашел за экран ( вверх)
        if snow_list[i][1] == 0:
            # новая позиция игрика
            y = random.randrange(401, 402)
            snow_list[i][1] = y

#функция заднего фона
def background():
    for y_offset in range(0, 140, 10):
        for x_offset in range(0,140,10):
            pygame.draw.line(screen, ber, [0, 400 + y_offset], [700, 400 + y_offset], 2)
            pygame.draw.line(screen, Dpurple, [0, 405 + y_offset], [700, 405 + y_offset], 8)
# попытка сделать градиент
    global grber
    for y_offset in range(0, 230, 5):
        grber =(255-y_offset ,170,175) #gr - градиент
        pygame.draw.line(screen, grber, [0, 400 - (1.75 *y_offset)],
                         [700, 400 - (1.75*y_offset)],9)

#функция человечка
def draw_stick_figure(screen, x, y):
    # Голова
    pygame.draw.ellipse(screen, black, [1 + x, y, 10, 10], 0)

    # Ноги
    pygame.draw.line(screen, black, [5 + x, 17 + y], [10 + x, 27 + y], 2)
    pygame.draw.line(screen, black, [5 + x, 17 + y], [x, 27 + y], 2)

    # Тело
    pygame.draw.line(screen, red, [5 + x, 17 + y], [5 + x, 7 + y], 2)

    # Руки
    pygame.draw.line(screen, red, [5 + x, 7 + y], [9 + x, 17 + y], 2)
    pygame.draw.line(screen, red, [5 + x, 7 + y], [1 + x, 17 + y], 2)
# Спрятать курсор мыши
pygame.mouse.set_visible(1)
# -------- Основной программный цикл -----------
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

# ------------- Логика игры должна идти здесь--------------
    screen.fill (lber)

# ---------- Код рисования должен идти здесь ----------------
#задний план
    background()
#снег
    snow_up()

#------------------------------------------------------------
    pygame.display.flip ()
    clock.tick (30)
pygame.quit ()


# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of integers
    def postorderTraversal(self, root):
        if not root:
            return []
        dumnd = TreeNode(root.val)
        stk=[]
        stk.append(root)
        curnd=root.left
        res=[]
        while stk or curnd:
            if curnd:
                stk.append(curnd)
                curnd=curnd.left
            elif not (stk[-1] is dumnd):
                curnd = stk[-1].right
                stk.append(dumnd)
            else:
                stk.pop()
                printnd=stk.pop()
                res.append(printnd.val)
        return res

postorder traversal/dumd node post order traversal.py


from matplotlib import pyplot as plt
from matplotlib.pyplot import MultipleLocator

y_3=[11,17,16,11,12,11,12,6,6,7,8,9]
y_10=[26,26,28,19,21,17,16,19,18,20,20,19]
x_3=range(1,13)
x_10=range(21,33)

plt.figure(figsize=(200,100),dpi=60)

_x=list(x_3)+list(x_10)
_xtick_labels=["3.{}".format(i) for i in x_3]
_xtick_labels+=["10.{}".format(i-20) for i in x_10]

plt.xticks(_x,_xtick_labels,rotation=45)
plt.xlabel("TIME")
plt.ylabel("TEMPERATURE")
plt.title("Change of Temperature")

plt.scatter(x_3,y_3,label="3rd month")
plt.scatter(x_10,y_10,label="10th month")

plt.legend(loc="upper left")

plt.show()


import argparse
from collections import defaultdict
import pickle
# from ipdb import set_trace
import numpy as np
import os
from sklearn.linear_model import SGDClassifier
from sklearn.naive_bayes import BernoulliNB
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import f1_score, accuracy_score
from sklearn.metrics import precision_recall_fscore_support as score
import sys

from tadat.core import helpers

def get_features(data_path, features):
	with open(data_path,"rb") as fid:
		train_data = pickle.load(fid)
		X = None
		Y = np.array(train_data[1])
		label_dict = train_data[3]
		#remove extension from filename
		data_path = os.path.splitext(data_path)[0]
		#get features
		for ft in features:
			feat_suffix = "-"+ft+".npy"
			x = np.load(data_path+feat_suffix, allow_pickle=True)
			#check if this is a sparse matrix (which have no 'shape')
			try:
				_ = x.shape[0]
			except IndexError:
				x = x.item()
			if X is None:
				X = x
			else:
				X = np.concatenate((X,x),axis=1)
	return X, Y, label_dict

def hypertune(train, dev, features, obj, hyperparams, res_path=None):
	X_train, Y_train, _ = get_features(train, features)
	X_dev,  Y_dev, _  = get_features(dev, features)
	best_hp = None
	best_score = 0
	for hp in hyperparams:
		#initialize model with the hyperparameters
		model = SGDClassifier(random_state=1234,**hp)
		model.fit(X_train,Y_train)
		Y_hat = model.predict(X_dev)
		score = obj(Y_dev, Y_hat)
		if score > best_score:
			best_score = score
			best_hp = hp
		res = {"score":round(score,3), "hyper":repr(hp)}
		if res_path is not None:
			helpers.save_results(res,res_path)
		helpers.print_results(res)
	print("\n[best conf: {} | score: {}]".format(repr(best_hp),round(best_score,3)))
	return best_hp, best_score

def main(train, test, run_id, features, hyperparameters=None, res_path=None):
	if not hyperparameters: hyperparameters = {}
	#train and evalute model
	if features[0].lower() == "naive_bayes":
		X_train, Y_train, labels = get_features(train, ["bow-bin"])
		X_test,  Y_test, labels  = get_features(test, ["bow-bin"])
		model = BernoulliNB()
		model_name = "NaiveBayes"
	elif features[0].lower() == "mlp":
		X_train, Y_train, labels = get_features(train, ["bow-bin"])
		X_test,  Y_test, labels  = get_features(test, ["bow-bin"])
		model = MLPClassifier(solver='lbfgs', activation="logistic", hidden_layer_sizes=[400])
		model_name = "MLP"
	elif features[0].lower() == "mlp-2":
		X_train, Y_train, labels = get_features(train, ["bow-bin"])
		X_test,  Y_test, labels  = get_features(test, ["bow-bin"])
		model = MLPClassifier(solver='lbfgs', activation="logistic", hidden_layer_sizes=[400,100])
		model_name = "MLP-2"
	else:
		X_train, Y_train, labels = get_features(train, features)
		X_test,  Y_test, labels  = get_features(test, features)
		#initialize model with the hyperparameters
		model = SGDClassifier(random_state=1234,**hyperparameters)
		model_name = "+".join(features)
	model.fit(X_train,Y_train)
	Y_hat = model.predict(X_test)
	avgF1 = f1_score(Y_test, Y_hat,average="macro")
	acc = accuracy_score(Y_test, Y_hat)
	res = {"acc":round(acc,3), \
			"avgF1":round(avgF1,3),	\
			"model":model_name, \
			"dataset":os.path.basename(test), \
			"run_id":run_id, \
			"train_size":X_train.shape[0], \
			"test_size":X_test.shape[0], \
			"hyper":repr(hyperparameters)}
	cols = ["dataset", "run_id", "acc", "avgF1","hyper"]
	helpers.print_results(res, columns=cols)
	precision, recall, fscore, support = score(Y_test, Y_hat)
	for l, i in labels.items():
		print("\n== {} ==".format(l))
		print('precision: {}'.format(round(precision[i],3)))
		print('recall: {}'.format(round(recall[i],3)))
		print('fscore: {}'.format(round(fscore[i],3)))
		print('support: {}'.format(round(support[i],3)))
		print("")
	if res_path is not None:
		cols = ["dataset", "model", "run_id", "acc", "avgF1"]
		helpers.save_results(res, res_path, sep="\t", columns=cols)
	return res

def get_parser():
	par = argparse.ArgumentParser(description="Document Classifier")
	par.add_argument('-train', type=str, required=True, help='train data')
	par.add_argument('-dev', type=str, help='dev data')
	par.add_argument('-test', type=str, required=True, help='test data')
	par.add_argument('-features', type=str, required=True, nargs='+', help='features')
	par.add_argument('-run_id', type=str, help='run id')
	par.add_argument('-res_path', type=str, help='results file')
	par.add_argument('-silent', action="store_true",help='silent')
	par.add_argument('-pos_label', type=str, default="positive", \
					help='label for the positive class')
	par.add_argument('-neg_label', type=str, default="negative", \
					help='label for the negative class')
	par.add_argument('-cv', type=int, help='crossfold')
	par.add_argument('-hyperparams_path', type=str, default="", help='path to a dictionary of hyperparameters')

	return par

if __name__=="__main__":
	parser = get_parser()
	args = parser.parse_args()
	#open datasets
	#train
	print("[features: {}]".format("+".join(args.features)))
	if args.run_id is None: args.run_id = "+".join(args.features)
	hyper_results_path = None

	hyperparams_grid = []
	if os.path.isfile(args.hyperparams_path):
		assert args.dev is not None, "Need a dev set for hyperparameter search"
		hyperparams_grid = helpers.get_hyperparams(args.hyperparams_path, {})
		print("[tuning hyperparameters from @ {}]".format(args.hyperparams_path))
		if args.res_path is not None:
			fname, _ = os.path.splitext(args.res_path)
			hyper_results_path = fname+"_"+os.path.basename(args.test)+"_hyper.txt"
		else:
			hyper_results_path = None
		scorer = lambda y_true,y_hat: f1_score(y_true, y_hat,average="macro")

	if args.cv is None:
		if len(hyperparams_grid) > 0:
			best_hyper, _ = hypertune(args.train, args.dev, args.features, \
									scorer, hyperparams_grid, res_path=hyper_results_path)
		else:
			best_hyper = {}
		#run model with the best hyperparams
		main(args.train, args.test, args.run_id, args.features, best_hyper, args.res_path)
	else:
		assert args.cv > 2, "need at leat 2 folds for cross-validation"
		results = []
		cv_results_path = None
		if args.res_path is not None:
			#in CV experiments save the results of each fold in an external file
			fname, _ = os.path.splitext(args.res_path)
			cv_results_path = fname+"_"+os.path.basename(args.test)+"_CV.txt"
		#loop through cross-validation folds
		for cv_fold in range(1, args.cv+1):
			if len(hyperparams_grid) > 0:
				best_hyper, _ = hypertune(args.train, args.dev, args.features, \
										scorer, hyperparams_grid, res_path=hyper_results_path)
			else:
				best_hyper = {}
			print(cv_results_path)
			#run model with the best hyperparams
			res = main(args.train+"_"+str(cv_fold), args.test+"_"+str(cv_fold), \
				args.run_id+"_"+str(cv_fold), args.features, best_hyper, cv_results_path)
			results.append(res)

		accs = [res["acc"] for res in results ]
		f1s = [res["avgF1"] for res in results ]

		cv_res = {"acc_mean":round(np.mean(accs),3), \
				"acc_std":round(np.std(accs),3), \
				"avgF1_mean":round(np.mean(f1s),3), \
				"avgF1_std":round(np.std(f1s),3), \
				"model":"+".join(args.features), \
				"dataset":os.path.basename(args.test), \
				"run_id":args.run_id}
		helpers.print_results(cv_res)
		#save the results of each run
		if args.res_path is not None:
			colz = ["dataset", "run_id", "model", "acc_mean","acc_std","avgF1_mean","avgF1_std"]
			helpers.save_results(cv_res, args.res_path, columns=colz)


from django import forms
from django.utils.translation import ugettext as _
from django.forms.util import ValidationError

from autocomplete.widgets import AutoCompleteWidget
from geo.models import City, State, Address

class CityField(forms.ModelChoiceField):
    def clean(self, value):
        forms.Field.clean(self, value)
        if self.required and value in (None, ''):
            raise ValidationError(self.error_messages['required'])
        return value

class BaseAddressForm(forms.ModelForm):
    street = forms.CharField(label=_("Street"), max_length=255)
    state = forms.ModelChoiceField(queryset=State.objects.all(), required=True)
    city = CityField(queryset=City.objects, to_field_name="name", required=True,
                    widget=AutoCompleteWidget(
                        channel=('autocomplete', None, ('geo', 'city')),
                        options={'minChars': 1, 'width': '207px',},
                        related_fields=("state", )))
    postal_code = forms.CharField(label=_("Zip"), required=True)

    def __init__(self, *args, **kwargs):
        prefix = kwargs.get("prefix")
        super(BaseAddressForm, self).__init__(*args, **kwargs)
        if prefix:
            self.fields["city"].widget.set_prefix_suffix(prefix)
        instance = kwargs.get("instance", None)
        if not instance is None and instance.city:
            self.initial['city'] = instance.city
            self.initial['state'] = instance.city.state.id

    def clean(self):
        cd = self.cleaned_data
        state = cd.get('state', None)
        city = cd.get('city', None)
        if state:
            if city:
                city_field = self.fields['city']
                value, new = city_field.queryset.get_or_create(\
                                    **{city_field.to_field_name or 'pk': city,
                                       "state":state })
                cd['city'] = value
        else:
            cd["city"] = None
        return cd

    class Meta:
        model = Address
        fields = ('street', 'state', 'city', 'postal_code')

class AddressNotRequiredForm(BaseAddressForm):
    def __init__(self, *args, **kwargs):
        super(AddressNotRequiredForm, self).__init__(*args, **kwargs)
        self.fields["street"].required = False
        self.fields["state"].required = False
        self.fields["city"].required = False
        self.fields["postal_code"].required = False


# -*- coding: utf-8 -*-
"""
Created on Thu Nov  8 10:50:08 2018

@author: sanket
"""

import socket
import nodes
import time
import threading
import json
import copy

'''ONLY CHANGE NODE_NO FOR NEW NODES'''
NODE_NO = 2
NODE_ADDRESS = nodes.node_list[NODE_NO]
FANOUT = nodes.fanout
HEARTBEAT = nodes.heartbeat
NEIGHBORS = []
OTHER_NODES = copy.deepcopy(nodes.node_list)
OTHER_NODES.remove(NODE_ADDRESS)

#extra
members = nodes.memberlist;

#semaphore
sem = threading.Semaphore()

def hb_fun(sock, neighbors, members,):
    try:
        while True:
            time.sleep(HEARTBEAT)
            sem.acquire();
            members[NODE_ADDRESS][0]= members[NODE_ADDRESS][0]+1;
            members[NODE_ADDRESS][1] = time.time();
            d = {}
            nodes.encode_memberlist(members, d)
            msg_json = json.dumps(d)
            for destination in NEIGHBORS:
                try:
                    sock.sendto( msg_json.encode(), destination);
                except ConnectionResetError: #that node closed the connection
                    continue
            sem.release()
    except:
        print("Closed")

k=1;
i  = (NODE_NO+1)%len(nodes.node_list)

while i != NODE_NO and k <= FANOUT:
    NEIGHBORS.append(nodes.node_list[i])
    k = k+1
    i = (i+1)%len(nodes.node_list)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
sock.bind(NODE_ADDRESS);
received_data, sender_address = sock.recvfrom(1024);

#first time gossip recived
m={}
nodes.decode_memberlist( json.loads( received_data.decode() ), m)
t1 = threading.Thread(target=hb_fun, args=(sock, NEIGHBORS,members,))
t1.start()
sock.settimeout(2);
#Infected
t2 = time.time()

try:
    while True:
       try:
           received_data, sender_address = sock.recvfrom(1024); #should be power of two
       except socket.timeout:
           if abs(time.time()-t2) >= nodes.T_Failure:
               print("No one is responding");
               print("Close?")
               raise Exception('No one is responding!');
           else:
              continue;
       except ConnectionResetError:
           #Reciving data corrupted due to forcefully port close at the sender
           #do the timing trick here, and exit the program thereafter
           continue;
       t2 = time.time()
       m = {}
       nodes.decode_memberlist( json.loads( received_data.decode() ), m);
       sem.acquire();
       nodes.compare_members(members, m);
       print("Node No:", NODE_NO,"Address:", NODE_ADDRESS);
       nodes.print_nodes(members)
       print('-'*60);
       sem.release();
except KeyboardInterrupt:
    print('Server closing')
    sock.close()
    t1.join()
except:
    sock.close()
    t1.join()
    input()


from odoo import api, fields, models, _

class StockPicking(models.Model):
    _inherit = "stock.picking"

    def invoice_line_non_kit(self):
        inv_obj = self.env['account.invoice'].search([('sale_id','=', self.origin)],limit=1)
        invoice_line_obj = self.env['account.invoice.line']
        sale_order  =  self.env['sale.order'].search([('name', '=',self.origin )])
        sale_order_line_obj = self.env['sale.order.line']
        inv_line = False
        for pick_line in self.move_lines:
            account = self.get_account_properties()
            inv_line = invoice_line_obj.create({
                    'name': pick_line.name,
                    'account_id': account.id,
                    'invoice_id':inv_obj.id,
                    'price_unit': pick_line.price_unit *-1,
                    'quantity': pick_line.product_uom_qty,
                    'uom_id': pick_line.product_id.uom_id.id,
                    'product_id': pick_line.product_id.id,
                    })
            order_line_ids = sale_order_line_obj.search([('order_id', '=', sale_order.id),('product_id', '=',pick_line.product_id.id )])
            for order_line in order_line_ids:
                order_line .write({'qty_to_invoice':pick_line.product_uom_qty,'invoice_lines':[(4,inv_line.id)]})

                tax_ids = []
                if order_line and order_line_ids[0]:
                    for tax in order_line[0].tax_id:
                        tax_ids.append(tax.id)

                inv_line.write({'price_unit':order_line[0].price_unit, 'discount': order_line[0].discount, 'invoice_line_tax_ids': [(6,0,tax_ids)]   })
                inv_obj.compute_taxes()
        return True

    def get_account_properties(self):
        ir_property_obj = self.env['ir.property']
        account_obj = self.env['account.account']
        account = False
        for pick_line in self.move_lines:
            if pick_line.product_id.property_account_income_id:
                account = pick_line.product_id.property_account_income_id
            elif pick_line.product_id.categ_id.property_account_income_categ_id:
                account = pick_line.product_id.categ_id.property_account_income_categ_id
            else:
                account_search = ir_property_obj.search([('name', '=', 'property_account_income_categ_id')])
                account = account_search.value_reference
                account = account.split(",")[1]
                account = account_obj.browse(account)
        return account

    def invoice_lines_creation(self):
        account_invoice_obj = self.env['account.invoice'].search([('sale_id','=', self.origin)],limit=1)
        account = self.get_account_properties()
        sale_order  =  self.env['sale.order'].search([('name', '=',self.origin )])
        for inv_lines in account_invoice_obj.invoice_line_ids:
            inv_lines.unlink()
        invoice_line_obj = self.env['account.invoice.line']
        for sale_line in sale_order.order_line:
            inv_line_id = invoice_line_obj.create({'name': sale_line.name,
                'account_id': account.id,
                'invoice_id': account_invoice_obj.id,
                'price_unit': sale_line.price_unit,
                'quantity': 0.0,
                'uom_id': sale_line.product_id.uom_id.id,
                'product_id': sale_line.product_id.id})
            sale_line .write({'qty_to_invoice':sale_line.qty_delivered})
            tax_ids = []
            if sale_line[0]:
                for tax in sale_line[0].tax_id:
                    tax_ids.append(tax.id)

                    inv_line_id.write({'price_unit':sale_line[0].price_unit, 'discount': sale_line[0].discount, 'invoice_line_tax_ids': [(6,0,tax_ids)]})
                    account_invoice_obj.compute_taxes()
        return True

    @api.multi
    def action_done(self):
        for mo_id in self.move_lines:
            for moves in mo_id.move_line_ids:
                inital_qty = moves.product_uom_qty
                ship_qty = moves.qty_done
        res = super(StockPicking, self).action_done()
        account_invoice_obj = self.env['account.invoice'].search([('sale_id','=',self.origin)],limit=1)
        sale_order  =  self.env['sale.order'].search([('name', '=',self.origin )])
        inv_line_obj = self.env['account.invoice.line']
        flag = 0
        if sale_order:
            account = self.get_account_properties()
            for inv_lines in account_invoice_obj.invoice_line_ids:
                inv_lines.unlink()
            for sale_line in sale_order.order_line:
                if sale_line.product_id.product_tmpl_id.bom_ids:
                    if inital_qty != ship_qty:
                        self.invoice_lines_creation()
                    else:
                        invoice_line_id = inv_line_obj.create({
                                        'name': sale_line.name,
                                        'account_id': account.id,
                                        'invoice_id':account_invoice_obj.id,
                                        'price_unit': sale_line.price_unit,
                                        'quantity': sale_line.product_uom_qty,
                                        'uom_id': sale_line.product_id.uom_id.id,
                                        'product_id': sale_line.product_id.id})
                        sale_line .write({'qty_to_invoice':sale_line.qty_delivered})
                        tax_ids = []
                        if sale_line[0]:
                            for tax in sale_line[0].tax_id:
                                tax_ids.append(tax.id)
                        invoice_line_id.write({'price_unit':sale_line[0].price_unit, 'discount': sale_line[0].discount, 'invoice_line_tax_ids': [(6,0,tax_ids)]})
                        account_invoice_obj.compute_taxes()
                else:
                    flag = 1
            if flag == 1:
                self.invoice_line_non_kit()
        return True


# This program is based on the color.c program written by Naofumi.

import os, sys
from GUI import Window, application
from GUI.GL import GLView, GLConfig
from OpenGL.GL import glClearColor, glClear, glBegin, glColor3f, glVertex2i, glEnd, \
	GL_COLOR_BUFFER_BIT, GL_TRIANGLES
from TestInput import TestKeyEvents, TestMouseEvents
from testing import say

class TriangleView(TestKeyEvents, TestMouseEvents, GLView):

	def init_context(self):
		glClearColor(0.0, 0.0, 0.0, 0.0)

	def render(self):
		glClear(GL_COLOR_BUFFER_BIT)
		glBegin(GL_TRIANGLES)
		glColor3f(1.0, 0.0, 0.0)
		glVertex2i(0, 1)
		glColor3f(0.0, 1.0, 0.0)
		glVertex2i(-1, -1)
		glColor3f(0.0, 0.0, 1.0)
		glVertex2i(1, -1)
		glEnd()

def make_view(db, options):
	pf = GLConfig(double_buffer = db)
	pf.alpha = "a" in options
	pf.depth_buffer = "d" in options
	pf.stencil_buffer = "s" in options
	pf.aux_buffers = "x" in options
	pf.accum_buffer = "A" in options
	view = TriangleView(pf, size = (200, 200))
	win = Window(
		title = "%s Buffered GLView" % ["Single", "Double"][db],
		size = (240, 240))
	win.place(view, left = 20, top = 20, sticky = "nsew")
	view.become_target()
	win.show()

def get_args():
	args = sys.argv[1:]
	if not 0 <= len(args) <= 2:
		badusage()
	if args:
		sd = args[0][0]
	else:
		sd = "d"
	if sd == "s":
		db = False
	elif sd == "d":
		db = True
	else:
		badusage()
	if len(args) > 1:
		options = args[1]
	else:
		options = ""
	return db, options

def badusage():
	sys.stderr.write("Usage: python %s s[ingle]|d[ouble] [adsxA]\n" % os.path.basename(sys.argv[0]))
	sys.exit(1)

instructions = """
There should be a window containing an OpenGL view, 20 pixels
from the edge of the window on all sides. There should be a
coloured triangle filling the view over a black background.

Mouse and keyboard events in the view should be reported.
The view and the triangle it contains should resize smoothly
with the window.
"""

make_view(*get_args())
say(instructions)
application().run()


import nltk
import requests

with open ("/Users/markvsteinbach/Downloads/siddh01.txt", "r") as myfile:
    data=myfile.read().replace('\r\n', '')

words = nltk.word_tokenize(data)
my_bigrams = nltk.bigrams(words)
my_trigrams = nltk.trigrams(words)
# print words, my_bigrams, my_trigrams

words_file = open("words.txt", "w")
words_file.write(raw_input(words))
words_file.close()

bigrams_file = open("bigrams.txt", "w")
bigrams_file.write(raw_input(my_bigrams))
bigrams_file.close()

trigrams_file = open("trigrams.txt", "w")
trigrams_file.write(raw_input(my_trigrams))
trigrams_file.close()


import os
import sys
import glob
import numpy as np
import cv2
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from detection_pipeline import curveFit

def adjust_gamma(image, gamma=1.0):
    invGamma = 1.0 / gamma
    table = np.array([((i / 255.0) ** invGamma) * 255
        for i in np.arange(0, 256)]).astype("uint8")
    return cv2.LUT(image, table)

def hist_equalize(img):
    hist,bins = np.histogram(img.flatten(),256,[0,256])
    cdf = hist.cumsum()
    cdf_m = np.ma.masked_equal(cdf,0)
    N = img.shape[0]*img.shape[1]
    cdf_m = cdf_m*255/N
    cdf = np.ma.filled(cdf_m,0).astype('uint8')
    img = cdf[img]

    return img

def hough_tf(img, img_):

    lower_color_bound = (0, 150, 180)
    upper_color_bound = (200, 180, 190)

    img_thresh = cv2.inRange(img, lower_color_bound, upper_color_bound) ## Does a yellow filter and keeps the white lanes as well.

    edges = cv2.Canny(img_thresh, 20, 20, apertureSize=3) ## finds lines on a thresholded image using canny. output is edges in random directions

    edges = cv2.GaussianBlur(edges,(35,35),0) # Blurred the random direction edges to no longer see them as edges but as spots on lanes

    if np.median(img_) < 100: # when entering the shaded area, enhance the edges and then do the operation on the image

        img_sharped = cv2.addWeighted(img, 8, cv2.blur(img, (35, 35)), -8, 128) # sharpen

        lower_color_bound = (140, 150, 135) ## use a filter to find points on the lanes
        upper_color_bound = (200, 250, 220) ## use a filter to find points on the lanes , this was very tricky and a narrow range.
        img_thresh = cv2.inRange(img_sharped, lower_color_bound, upper_color_bound) # thresholding

        edges = cv2.Canny(img_thresh, 20, 20, apertureSize=3)

        edges = cv2.GaussianBlur(edges,(35,35),0)

    elif np.median(img) > 158: # when exiting the shaded area,

        lower_color_bound = (120, 180, 200) ## use a filter to find points on the lanes
        upper_color_bound = (200, 250, 250) ## use a filter to find points on the lanes , this was very tricky and a narrow range.
        img_thresh = cv2.inRange(img, lower_color_bound, upper_color_bound) # thresholding

        edges = cv2.Canny(img_thresh, 20, 20, apertureSize=3)
        edges = cv2.GaussianBlur(edges,(35,35),0)

    lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, 10, 10)

    left_pts = []
    right_pts = []
    for x1, y1, x2, y2, in lines[:,0,:]:

        if np.abs((y2 - y1)/(x2 - x1)) < 5: ## allow lines which are only > ~65degs
            continue

        if (x1 < 120 or x2 < 130) or (x1 > 300 or x2 > 350) and (x1 < img.shape[1]-300 or x2 < img.shape[1]-350):
            continue

        if x1 < img.shape[1]/2:

            left_pts.append(([x1,y1]))
        elif x1 > img.shape[1]/2:

            right_pts.append(([x1,y1]))
        if x2 < img.shape[1]/2:

            left_pts.append(([x1,y1]))
        elif x2 > img.shape[1]/2:
            right_pts.append(([x1,y1]))

        cv2.line(img, (x1,y1), (x2, y2), (0,255,0), 2)
    left_pts = np.asarray(left_pts)
    right_pts = np.asarray(right_pts)
    if left_pts.shape == (0,):
        if right_pts.shape == (0,):
            left_pts = [[0,0], [0,0]]
            right_pts = [[0,0], [0,0]]
        else:
            left_pts = np.zeros_like(right_pts)
    elif right_pts.shape == (0,):
        if left_pts.shape == (0,):
            left_pts = [[0,0], [0,0]]
            right_pts = [[0,0], [0,0]]
        else:
            right_pts = np.zeros_like(left_pts)

    cv2.imshow(" s", img)
    #cv2.waitKey(0)
    return left_pts, right_pts, img

def hough_tf_image(img, img_):

    _, img_thresh = cv2.threshold(img_, 220, 255, cv2.THRESH_BINARY) # thresholding image to get a high intensity

    edges = cv2.GaussianBlur(img_thresh,(49,49),0) # Blur the edges to so that random direction lines are just seen as edge patches rather than edges

    if np.median(img_) < 100:

        _, img_thresh2 = cv2.threshold(img_, 80, 255, cv2.THRESH_BINARY) # threshold the histogram equalised img

        edges2 = cv2.Canny(img_thresh2, 3, 3, apertureSize=3) #

        edges2 = cv2.GaussianBlur(edges2,(5,5),0)

        edges = edges + edges2
        edges = adjust_gamma(edges, 1.4)

    lines = cv2.HoughLinesP(edges, 1, np.pi/180, 30, 10, 10)
    left_pts = []
    right_pts = []
    for x1, y1, x2, y2, in lines[:,0,:]:
        if np.abs((y2 - y1)/(x2 - x1)) < 2:
            continue

        if (x1 < 20 or x2 < 30) or (x1 > img.shape[1]-30 or x2 > img.shape[1]-35):
            continue

        if x1 < img.shape[1]/2:
            left_pts.append(([x1,y1]))
        elif x1 > img.shape[1]/2:
            right_pts.append(([x1,y1]))
        if x2 < img.shape[1]/2:
            left_pts.append(([x1,y1]))
        elif x2 > img.shape[1]/2:
            right_pts.append(([x1,y1]))

        cv2.line(img, (x1,y1), (x2, y2), (0,255,0), 2)
    left_pts = np.asarray(left_pts)
    right_pts = np.asarray(right_pts)
    if left_pts.shape == (0,):
        left_pts = np.zeros_like(right_pts)
    elif right_pts.shape == (0,):
        right_pts = np.zeros_like(left_pts)
    cv2.imshow(" s", img)
    return left_pts, right_pts, img

def hist_count(img, img_):
    fig1 = plt.figure()
    ax1 = fig1.gca(projection='3d')
    graph = np.zeros([img.shape[0], img.shape[1], 2])
    graph[:,:,0] = img[:,:,0]
    graph[:,:,1] = (img[:,:,1] + img[:,:,2])/(abs(img[:,:,1] - img[:,:,2]) + 1)
    X = np.arange(0,graph.shape[0])
    Y = np.arange(0,graph.shape[1])

    X, Y = np.meshgrid(X, Y)
    Z = (img[X, Y,1] + img[X,Y,2])/(abs(img[X,Y,1] - img[X,Y,2]) + 1)
    surf = ax1.plot_surface(X, Y, Z)
    fig2 = plt.figure()
    ax2 = fig2.gca(projection='3d')
    Z2 = img[X,Y,0]
    surf = ax2.plot_surface(X, Y, Z2)
    plt.show()
    exit(-1)

    cv2.imshow("lines",img)
    #cv2.waitKey(0)

if __name__ == '__main__':

    if sys.argv[2] == 'mp4':
        video_file = sys.argv[1]
        cap = cv2.VideoCapture(video_file)
        vidWriter = cv2.VideoWriter("./video_output.mp4",cv2.VideoWriter_fourcc(*'mp4v'), 24, (1280,720))

        arrl_store = []
        arrr_store = []
        while (cap.isOpened()):

            ret, img = cap.read()
            if ret == False:
                break

            src_pt = np.array([[407, 615], [886, 615],[312, 677],[962, 677] ])
            dst_pt = np.array([[150, 630], [1080, 630], \
                    [150, 701], [1080, 701]])

            H, _ = cv2.findHomography(src_pt, dst_pt)
            warped = cv2.warpPerspective(img, H, (1280, 720))
            warped_ = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)

            left_pts, right_pts, lines = hough_tf(warped, warped_)
            # hist_count(warped, warped_)

            left_pts = np.asarray(left_pts)
            right_pts = np.asarray(right_pts)

            if len(arrl_store)<3:
                arrl_store.append(left_pts)
                arrr_store.append(right_pts)
            elif right_pts[right_pts.shape[0]-2,0]!=0 and left_pts[left_pts.shape[0]-2,0]!=0:
                arrr_store.pop()
                arrr_store.append(right_pts)
                arrl_store.pop()
                arrl_store.append(left_pts)
            arr_templ = np.asarray(arrl_store)
            arr_tempr = np.asarray(arrr_store)
            lefty = arr_templ[arr_templ.shape[0]-1]
            righty = arr_tempr[arr_tempr.shape[0]-1]
            flag =1
            lines,prediction = curveFit(lefty,righty,lines,flag)
            Hinv = np.linalg.inv(H)
            Hinv = Hinv/Hinv[2,2]
            blank_white = 255*np.ones([720, 1280, 3])
            blank_backProj = cv2.warpPerspective(blank_white, Hinv, (1280, 720))
            _, thresh1 = cv2.threshold(blank_backProj, 127, 255, cv2.THRESH_BINARY_INV)

            patch = np.logical_and(img, thresh1)
            img_dummy = np.zeros_like(img)
            img_dummy[patch] = img[patch]
            backProjected = cv2.warpPerspective(lines, Hinv, (1280, 720))

            img_dummy = img_dummy + backProjected

            cv2.putText(img_dummy, prediction, (200, 50),cv2.FONT_HERSHEY_SIMPLEX, 1.5,(0,255,0),2,\
            cv2.LINE_AA)
            cv2.imshow("test", img_dummy)

            vidWriter.write(img_dummy.astype(np.uint8))

    elif sys.argv[2] == 'png':

        files = np.sort(glob.glob(sys.argv[1] + '/*', recursive=True))
        vidWriter = cv2.VideoWriter("video_output.mp4",cv2.VideoWriter_fourcc(*'mp4v'), 24, (1392,512))
        arrl_store = []
        arrr_store = []
        for file in files:
            img = cv2.imread(file)

            src_pt = np.array([[526, 322], [767, 328],[354, 428],[866, 434] ])
            dst_pt = np.array([[200, img.shape[0]-450], [img.shape[1]-100, img.shape[0]-450], \
                    [200, img.shape[0] - 50], [img.shape[1]-100, img.shape[0] - 50]])

            H, _ = cv2.findHomography(src_pt, dst_pt)
            warped = cv2.warpPerspective(img, H, (img.shape[1], img.shape[0]))
            warped_ = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
            left_pts, right_pts, lines = hough_tf_image(warped, warped_)
            if len(arrl_store)<3:
                arrl_store.append(left_pts)
                arrr_store.append(right_pts)
            elif right_pts[right_pts.shape[0]-2,0]!=0 and left_pts[left_pts.shape[0]-2,0]!=0:
                arrr_store.pop()
                arrr_store.append(right_pts)
                arrl_store.pop()
                arrl_store.append(left_pts)
            arr_templ = np.asarray(arrl_store)
            arr_tempr = np.asarray(arrr_store)
            lefty = arr_templ[arr_templ.shape[0]-1]
            righty = arr_tempr[arr_tempr.shape[0]-1]
            flag = 0
            lines,prediction = curveFit(lefty,righty,lines,flag)
            Hinv = np.linalg.inv(H)
            Hinv = Hinv/Hinv[2,2]
            blank_white = 255*np.ones([img.shape[0], img.shape[1], 3])
            blank_backProj = cv2.warpPerspective(blank_white, Hinv, (img.shape[1], img.shape[0]))
            _, thresh1 = cv2.threshold(blank_backProj, 127, 255, cv2.THRESH_BINARY_INV)
            patch = np.logical_and(img, thresh1)
            img_dummy = np.zeros_like(img)
            img_dummy[patch] = img[patch]
            backProjected = cv2.warpPerspective(lines, Hinv, (img.shape[1], img.shape[0]))
            img_dummy = img_dummy + backProjected
            cv2.putText(img_dummy, prediction, (200, 50),cv2.FONT_HERSHEY_SIMPLEX, 1.5,(0,255,0),2,\
            cv2.LINE_AA)

            vidWriter.write(img_dummy.astype(np.uint8))

    vidWriter.release()


import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/mGalarnyk/Python_Tutorials/master/Kaggle/BreastCancerWisconsin/data/data.csv')
sns.boxplot(x='diagnosis', y='area_mean', data=df)
malignant = df[df['diagnosis']=='M']['area_mean']
benign = df[df['diagnosis']=='B']['area_mean']
fig = plt.figure()
ax = fig.add_subplot(111)
ax.boxplot([malignant,benign], labels=['M', 'B'])
df.boxplot(column = 'area_mean', by = 'diagnosis')
plt.title('')
malignant = df[df['diagnosis']=='M']['area_mean']
benign = df[df['diagnosis']=='B']['area_mean']
fig = plt.figure()
ax = fig.add_subplot(111)
ax.boxplot([malignant,benign], notch = True, labels=['M', 'B'])
plt.show()


n=int(input())
'''
count=0
for i in range(2,n+1):
    for j in range(2,int(n**0.5)+1):
        if i%j==0:
            count+=1
sum=0
for i in range(1,count+1):
    sum=sum*i*(n-i)
if n==1 or n==2:
    print(1)
else:
    print(sum%(10**9+7))
'''
primes, st, cnt, MOD = [0]*(n + 1), [0]*(n + 1), 0, 10**9 + 7
for i in range(2, n + 1):
    if not st[i]:
        primes[cnt] = i
        cnt += 1
    j = 0
    while primes[j] <= n//i:
        st[primes[j] * i] = 1
        if i % primes[j] == 0:
            break
        j += 1
print(math.factorial(cnt)%MOD * math.factorial(n - cnt)%MOD)%MOD


from django.forms import ModelForm, widgets
from django import forms
from app.models import Ficha_salud
from django.forms import ModelForm, widgets

class AddSalud(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for i in self.visible_fields():
            i.field.widget.attrs['class'] = 'form-control'
            i.field.widget.attrs['autocomplete'] = 'off'
        self.fields['NomEnfer_fichsa'].widget.attrs['autofocus'] = True

    class Meta:
        model = Ficha_salud
        fields = '__all__'
        widgets = {
            'descripcion_fichsal' : widgets.Textarea(attrs={'class':'form-control'})}

class FormSalud(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for i in self.visible_fields():
            i.field.widget.attrs['class'] = 'form-control'
            i.field.widget.attrs['autocomplete'] = 'off'
        # self.fields['id_est'].widget.attrs['disabled'] = True
        # self.fields['fecha_est'].widget.attrs['hidden'] = True
    class Meta:
        model = Ficha_salud
        fields = '__all__'
        exclude = ('id_est','')


# Find the sum of all the multiples of 3 or 5 below 1000.

import Utilities

def FindMultiplesof3and5():
	sum = 0

	for i in range(0, 1000):
		if (i % 3 == 0) or (i % 5 == 0):
			sum += i

	print(sum)
	return sum

FindMultiplesof3and5()

# Returns 233168


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

from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError

from dashboard.models import Task, TaskLog

class TaskForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(TaskForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs['class'] = 'form-control'

    def save(self, commit=True, author=False, user=False):
        data = None
        action = TaskLog.UPDATE_TASK

        task = super(TaskForm, self).save(commit=False)

        if not user:
            raise ValidationError('User was lost')

        if not task.author:  # Create task
            if author:
                action = TaskLog.CREATE_TASK
                task.author = author
            else:
                raise ValidationError('Author already exists')

        else:  # Update task
            data = {}
            origin = self.Meta.model.objects.get(pk=self.instance.pk)
            check_username = lambda x: x.username if isinstance(x, User) else x

            for field in self.cleaned_data:
                old_value = getattr(origin, field, None)
                new_value = self.cleaned_data.get(field)

                if old_value != new_value:
                    if field == 'assigned_to':
                        data[field] = [
                            check_username(old_value),
                            check_username(new_value)
                        ]
                    else:
                        data[field] = [old_value, new_value]

        if commit:
            task.save()
            TaskLog.objects.create(
                action=action,
                task=task,
                data=data or None,
                user=user,
            )
        return task

    class Meta(object):
        model = Task
        fields = (
            'subject', 'status', 'assigned_to', 'time_estimate', 'body_text',
        )


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

import pandas as pd

get_df = pd.read_csv('dump.csv', sep=',', header=0)                		#read data from scv

tcp_df = pd.DataFrame(get_df[get_df['Protocol'] == 'TCP'])				#select only tcp form dump

tcp_df.drop(['No.','Time','Length','Protocol'], axis=1, inplace=True)	#delete unnecessary columns

tcp_df['Info'].replace(													#regular expression for
			to_replace='(\[((\w+\s)|[^\]])+\]\s*)|(\w+\=\d+)|\s+', 		#getting port numbers
			value='', 													#from string Info
			inplace=True,
			regex=True
			)

tcp_df = pd.concat(														#expand column Info on
			[tcp_df,tcp_df['Info'].str.split('>', expand=True)], 		#two 0 and 1
			axis=1
			)

tcp_df = tcp_df.rename(columns={0:'Src name port', 1:'Dst name port'})	#rename columns 0 and 1

tcp_df.drop(['Info'], axis=1, inplace=True)								#delete coloumn Info

result = pd.DataFrame(tcp_df.groupby(									#create result table
				['Source',
				'Destination',
				'Src name port',
				'Dst name port'
				])['Source'].count());

result.sort_values(by=['Source'], ascending=False, inplace=True)		#sort by decrease

result = result.rename(columns={'Source':'Number of requests'})			#rename sort colunm

print(result)															#show dataframe in terminal

result.to_csv('result.csv')                                      		#save result in file


import torch
import unittest

test = unittest.TestCase()

import hw2.blocks as blocks

from hw2.grad_compare import compare_block_to_torch

def test_block_grad(block: blocks.Block, x, y=None, delta=1e-2):
    diffs = compare_block_to_torch(block, x, y)

    # Assert diff values
    for diff in diffs:
        test.assertLess(diff, delta)

N = 100
in_features = 200
num_classes = 10

def linear():
    fc = blocks.Linear(in_features, 1000)
    x_test = torch.randn(N, in_features)
    # Test forward pass
    z = fc(x_test)
    test.assertSequenceEqual(z.shape, [N, 1000])
    # Test backward pass
    test_block_grad(fc, x_test)

def test_relu():
    relu = blocks.ReLU()
    x_test = torch.randn(N, in_features)
    # Test forward pass
    z = relu(x_test)
    test.assertSequenceEqual(z.shape, x_test.shape)
    # Test backward pass
    test_block_grad(relu, x_test)

def test_sigmoid():
    # Test Sigmoid
    sigmoid = blocks.Sigmoid()
    x_test = torch.randn(N, in_features)
    # Test forward pass
    z = sigmoid(x_test)
    test.assertSequenceEqual(z.shape, x_test.shape)
    # Test backward pass
    test_block_grad(sigmoid, x_test)

def test_cross_entropy():
    global cross_entropy
    # Test CrossEntropy
    cross_entropy = blocks.CrossEntropyLoss()
    scores = torch.randn(N, num_classes)
    labels = torch.randint(low=0, high=num_classes, size=(N,), dtype=torch.long)
    # Test forward pass
    loss = cross_entropy(scores, labels)
    expected_loss = torch.nn.functional.cross_entropy(scores, labels)
    test.assertLess(torch.abs(expected_loss - loss).item(), 1e-5)
    print('loss=', loss.item())
    # Test backward pass
    test_block_grad(cross_entropy, scores, y=labels)

def test_sequential():
    # Test Sequential
    # Let's create a long sequence of blocks and see
    # whether we can compute end-to-end gradients of the whole thing.
    seq = blocks.Sequential(
        blocks.Linear(in_features, 100),
        blocks.Linear(100, 200),
        blocks.Linear(200, 100),
        blocks.ReLU(),
        blocks.Linear(100, 500),
        blocks.Linear(500, 200),
        blocks.ReLU(),
        blocks.Linear(200, 500),
        blocks.ReLU(),
        blocks.Linear(500, 1),
        blocks.Sigmoid(),
    )
    x_test = torch.randn(N, in_features)
    # Test forward pass
    z = seq(x_test)
    test.assertSequenceEqual(z.shape, [N, 1])
    # Test backward pass
    test_block_grad(seq, x_test)

# linear()
# test_relu()
# test_sigmoid()
# test_cross_entropy()
# test_sequential()

import hw2.models as models

# Create MLP model
mlp = models.MLP(in_features, num_classes, hidden_features=[100, 50, 100])
print(mlp)

# Test MLP architecture
N = 100
in_features = 10
num_classes = 10
for activation in ('relu', 'sigmoid'):
    mlp = models.MLP(in_features, num_classes, hidden_features=[100, 50, 100], activation=activation)
    test.assertEqual(len(mlp.sequence), 7)

    num_linear = 0
    for b1, b2 in zip(mlp.sequence, mlp.sequence[1:]):
        if (str(b2).lower() == activation):
            test.assertTrue(str(b1).startswith('Linear'))
            num_linear += 1

    test.assertTrue(str(mlp.sequence[-1]).startswith('Linear'))
    test.assertEqual(num_linear, 3)

    # Test MLP gradients
    # Test forward pass
    x_test = torch.randn(N, in_features)
    labels = torch.randint(low=0, high=num_classes, size=(N,), dtype=torch.long)
    z = mlp(x_test)
    test.assertSequenceEqual(z.shape, [N, num_classes])

    # Create a sequence of MLPs and CE loss
    # Note: deliberately using the same MLP instance multiple times to create a recurrence.
    seq_mlp = blocks.Sequential(mlp, mlp, mlp, blocks.CrossEntropyLoss())
    loss = seq_mlp(x_test, y=labels)
    test.assertEqual(loss.dim(), 0)
    print(f'MLP loss={loss}, activation={activation}')

    # Test backward pass
    test_block_grad(seq_mlp, x_test, y=labels)


import random

WORDS = ("питон", "анаграмма", "простая", "сложная", "ответ", "подстаканник")
word = random.choice(WORDS)
wlen = len(word)
count = 5
yes=""
no=""

print("В этом слове ", wlen, " букв")

while count != 0:

    choice = input("your choice: ")
    if choice in word:
        yes +=choice
        print("1")
    else:
        print("0")
        no +=choice
    count-=1
print("В этом слове есть буквы: ", yes)
print("В этом слове нет букв:", no)
change = input("\nВведите слово: ")
if change==word:
    print("Вы выиграли!")
else:
    print("Вы проиграли!")

input("\nНажмите Enter, для выхода из программы")


"""
This module is responsible for linting document file.
"""
from textx_langserv.utils import _utils
from textx_langserv.infrastructure.lsp import Diagnostic

__author__ = "Daniel Elero"
__copyright__ = "textX-tools"
__license__ = "MIT"

LINT_DEBOUNCE_S = 0.5

@_utils.debounce(LINT_DEBOUNCE_S)
def lint(doc_uri, workspace):
    """
    Create and return diagnostic object which contains all parsing errors
    """
    if doc_uri in workspace.documents:
        diagnostic = Diagnostic()
        txdoc = workspace.get_document(doc_uri)
        errors = txdoc.all_errors
        for e in errors:
            msg = str(e)
            try:
                msg = msg.split(' at')[0]
                diagnostic.error(e.line, e.col, msg)
            except:
                diagnostic.error(e.line, e.col, msg)

        workspace.publish_diagnostics(doc_uri, diagnostic.get_diagnostics())


import itertools
import sys

if sys.version_info >= (3,0):
    import pycosat
else:
    #import pycosat.pycosat
    import pycosat
import json
import copy
import time
import collections

### XXX working to make not global?
var_map = dict()
num_to_var = dict()

# Adapting the version written to my standard to work for xir json

# Overall interface creates a SAT problem from a list of nodes and connections, solves it,
# and writes out the assignment in 'network' form
# Note: for 3000 resources, generating the clauses takes 60 seconds and solving takes 4.5 seconds on a 2015 macbook pro.
# In production it may be possible to generate some or all of the resource clauses ahead of time.
#       - see 'todo' for generate_clauses
def solve(request, resources, print_debug=False, print_vars=False, print_names=False, print_assignment=True, print_timing=True):
    global var_map, num_to_var
    start = time.time()
    clauses = generate_clauses(request, resources, print_debug)
    create = time.time()
    if print_timing:
        # Print 2.x
        #print 'Creating', len(clauses), 'clauses and', len(var_map), 'variables took', (create-start)
        #
        # Print 3.x
        print("Creating %d clauses and %d variables took %.2f" % (len(clauses),len(var_map),create-start))
    #solution = pycosat.pycosat.solve(clauses)
    solution = pycosat.solve(clauses)
    if print_timing:
        # Print 2.x
        #print 'Solving took', (time.time()-create)
        #
        # Print 3.x
        print('Solving took %.2f' % (time.time()-create))
    #print solution  # , list(clauses)
    if print_vars:
        #print 'True vars:'
        print('True vars:')
    # Just print the match vars and variables about matched resources and topos, and say how many are true in total
    num_true = 0
    names = []
    if solution == 'UNSAT':
        #print 'no solution found for', len(clauses), 'clauses'
        print('No solution found for %d clauses' % len(clauses))
        return None, None
    #return None, None

    for variable in solution:
        if variable > 0:
            num_true += 1
            var = num_to_var[variable]
            if 'matched_to' in var:
                if print_vars:
                    #print variable, var
                    print("%d %s" % (variable, var))
                names.append((var[0:var.index("_matched")], var[var.index("matched_to_") + 11:]))
    if print_vars:
        for variable in solution:
            if variable > 0 and [x for (x, y) in names if x in num_to_var[variable]]:
                #print num_to_var[variable]
                print(num_to_var[variable])
        #print num_true, 'were true'
        print("%d were true" % num_true)
    if print_names:
        #print 'names:', names
        print("Name: ")
        print(names)
    # Print the ids of the matched pairs for verification. This is slow, probably need another dict or two
    if print_assignment:
        for pair in names:
            #print [n['props']['name'] for n in request['nodes'] if n['id'] == pair[0]][0],  # skip id pair[0]
            matches = [[n['props']['name'] for n in rsrc['nodes'] if n['id'] == pair[1]] for rsrc in resources]
            #print 'matched to', [(m[0], i) for i, m in enumerate(matches) if m != []]
    return names, solution

# Generate clauses for solver from the realization request spec and resource spec
# resource_specs should include specific resources and also the '(repeat freq node)' construct used to create
# identical elements, so that they can be matched without creating and matching a large list. This is not yet implemented.
def generate_clauses(request, resources, print_debug=False):
    global var_map, num_to_var, id_link_map

    var_map = {}  # Map of variable names to numbers, e.g. 'droid.software.version=O' -> 1
    num_to_var = {}  # Map from variable numbers to names
    potential_match_map = {}
    clauses = []
    node_site_map = {}  # Each node mapped to its site, to help find across-site solutions later.
    for i, resource in enumerate(resources):
        node_site_map.update({n['id']: i for n in resource['nodes']})
    # First, every node in request should be matched to one node in resources. Each match should be unique unless
    # the resource can be a container.
    # Then, the matching node should be able to satisfy the constraints of the topo node.
    resource_nodes = sum([resource['nodes'] for resource in resources], [])
    #print(resource_nodes)
    #for resource in resources:
    #    print(resource['nodes'])
    #    print("NEXT")
    #exit(1)
    if print_debug:
        #print len(request['nodes']), 'request nodes and', len(resource_nodes), 'resource nodes'
        print("%d request nodes and %d resource nodes" % (len(request['nodes']), len(resource_nodes)))
    for node in request['nodes']:
        #print 'checking request node', node['props']
        # Pairwise exclusivity for query nodes (node bound to at most one resource)
        for rsrc in resource_nodes:
            clauses += [[-match_var(node, rsrc), -match_var(node, r2)] for r2 in resource_nodes if r2 > rsrc]
        #print 'finding clauses from', node['props']['name'], node['props']
        request_clauses = walk_props_for_constraints(node['props'], [])  # path was node.name() but now anonymized
        if print_debug:
            #print 'clauses for', node['props']['name'], request_clauses
            print("Clauses for")
            print(node['props']['name'])
            print(request_clauses)
        # Combine the constraints into every matchable resource node and check which can match
        potential_matches = []
        for rsrc in resource_nodes:
            # If node is matched to r1, then the constraints on node should be true for r1
            #short = short_ids(rsrc)
            # Hide endpoints for now
            #print 'applying these clauses to resource:', {k: short[k] for k in short if k != 'endpoints'}
            #for clause in request_clauses:
            #    print clause
            rclauses = []
            potential_match = True
            for clause in request_clauses:
                grounded = grounded_clause(clause, rsrc)
                if grounded and True not in grounded: # Don't add the clause if it contains True, as it is satisfiable without making a choice
                    rclauses.append([[-match_var(node, rsrc)] + grounded])
                elif not grounded:  # If one clause can't be satisfied, the resource can't be used for the request node
                    potential_match = False
                    break
            if potential_match:
                clauses += rclauses
                potential_matches.append(rsrc)
            for clause in request_clauses:
                for (t, path, value) in clause:
                    v, found = find_or_add_var(rsrc['id'] + "." + reduce(lambda x, y: str(x) + "." + str(y), path), value)
                    if not found:  # First time we encounter the variable on a resource, check its truth
                        clauses.append([v * walk_resource_for_truth(rsrc['props'], path, value)])
                # The node is matched to some resource that can match the constraints
        potential_match_map[node['props']['name']] = potential_matches
        clauses.append([match_var(node, potential_resource) for potential_resource in potential_matches])
    # Pairwise exclusive for resource nodes
    for r in resource_nodes:
        for t1 in request['nodes']:
            clauses += [[-match_var(t1, r), -match_var(t2, r)] for t2 in request['nodes'] if t2 > t1]
    # Check links and add pairwise exclusive for match variables that would imply impossible link constraints
    # First create a link map for all the resource links since we'll be looking them up maybe n^2 times
    id_link_map = {}
    for resource in resources:
        for link in resource['links']:
            for ep in link['endpoints']:
                id_link_map[ep['id']] = link
    for link in request['links']:
        if print_debug:
            #print 'link:', link['id'], link['props']
            print("link: %s %s" % (link['id'], link['props']))
        endpoints = [e['id'] for e in link['endpoints']]
        if print_debug:
            #print '  endpoints:', endpoints
            print(endpoints)
        link_nodes = [n for n in request['nodes'] if [id for id in [en['id'] for en in n['endpoints']] if id in endpoints]]
        if print_debug:
            #print '    matches:', [ln['props']['name'] for ln in link_nodes]
            print("	matches:" )
            print([ln['props']['name'] for ln in link_nodes])
        # for every pair of possible matches for the two request nodes, check the link exists and matches the specs,
        #  and if not add a mutually exclusive constraint
        some_link_ok = False
        for pma in potential_match_map[link_nodes[0]['props']['name']]:
            for pmb in potential_match_map[link_nodes[1]['props']['name']]:
                if not link_ok(pma, pmb, link['props'], id_link_map, node_site_map):
                    # if the link won't work, don't use this pair of matches
                    clauses += [[-match_var(link_nodes[0], pma), -match_var(link_nodes[1], pmb)]]
                else:
                    some_link_ok = True
        if not some_link_ok and print_debug:
            print('  link unmatched')
    return clauses

# Recursively walk over the dict for a query node gathering constraints.
# Currently this returns a triple: (truth (+/-1), path, value), which is turned into a variable for each resource.
def walk_props_for_constraints(desc, path):
    res = []
    for key in desc:
        if key == 'name' or key == 'config':  # Don't add constraints for these (maybe infer from config later)
            continue
        if isinstance(desc[key], list):
            #print 'adding constraints for', path, key, desc[key]
            # Parse constraints here
            new_var_path = path + [key]
            if desc[key][0] == 'in':  # Add a clause with each possible value in a conjunction, and pairwise exclusive
                res += [[(1, new_var_path, value) for value in desc[key][1]]]  # Was the var with this name
                for value in desc[key][1]:
                    res += [[(-1, new_var_path, value), (-1, new_var_path, other)]
                            for other in desc[key][1] if other > value]  # was the var with these names
            elif desc[key][0] in ['>=', '>', '<=', '<']:  # Add a token for a generic value satisfying the inequality
                res += [[(1, new_var_path, "|" + desc[key][0] + str(desc[key][1]) + "|")]]  # Was the var with this name
            else:
                #print 'not currently translating the constraint:', path, key, desc[key]
                print("not currently translating the constraint: ")
                print(path)
                print(key)
                print(desc[key])
        elif isinstance(desc[key], dict) and 'constraint__' in desc[key]:  # This is a constraint
            res.append([(1, path + [key], desc[key])])
        elif isinstance(desc[key], dict):
            res += walk_props_for_constraints(desc[key], path + [key])
        elif key != "name" or path != "":  # Add an equality constraint for a value, except the object name
            res.append([(1, path + [key], desc[key])])
    return res

def grounded_clause(constraint_clause, resource):
    # The clause is a list of unbounded variables to be bound to the resource (ultimately to other constraint vars to)
    # For efficiency, also checks truth and skips any constraint_var in the clause that cannot be true.
    # If none can be true then generate_clauses turns into the unary clause saying the resource cannot match.
    # It might be more efficient never to generate this match variable but it's only a unary clause..
    return [x for x in [grounded_prop(prop, resource) for prop in constraint_clause] if x != [] and x is not False]

def grounded_prop(triple, resource, indent=""):
    (truth, path, value) = triple
    s = short_ids(resource)
    #print indent+'need to ground', (truth, path, value), '\n  '+indent+'with', follow_path(path, s['props'])
    props = resource['props']
    if isinstance(value, dict) and 'constraint__' in value:
        if value['constraint__'] == '?':  # choice
            res = []
            for sub_value in value['value__']:
                grounded = grounded_prop((truth, path, sub_value), resource, indent + "  ")
                if grounded is True:
                    return True
                elif grounded is not False and grounded != []:
                    res.append(grounded)
            return res
        elif value['constraint__'] == '[]':  # One of a list
            res_vals = follow_path(path, props)
            return isinstance(res_vals, list) and value['value__'] in res_vals
        elif value['constraint__'] in ['>=', '>', '<', '<=']:
            res_val = follow_path(path, props)
            #print 'here', value, res_val
            if value['constraint__'] == '>=':
                return res_val >= value['value__']  # brittle right now
            elif value['constraint__'] == '>':
                return res_val > value['value__']  # brittle right now
            if value['constraint__'] == '<=':
                return res_val <= value['value__']  # brittle right now
            elif value['constraint__'] == '<':
                return res_val < value['value__']  # brittle right now
        else:
            #print 'not currently translating the constraint:', value, 'on', props
            print("not currently translating the constraint:")
            print(value)
            #print(on)
            print(props)
            # Will crash
    else:
        return 1

# Recursively walk a path on a dict. Returns None if there is no path.
def follow_path(path, d):
    if path == []:
        return d
    elif path[0] in d:
        return follow_path(path[1:], d[path[0]])

# Recursively walk over a resource given a constraint path, value and corresponding variable. Return +/-1
# depending on the values in the resource. Doesn't yet handle 'image' list of possible images.
def walk_resource_for_truth(d, path, value):
    # print 'checking', path, '=', value, 'on', d
    if not path or path[0] not in d:
        return -1
    elif len(path) == 1:
        if d[path[0]] == value:
            return 1
        elif isinstance(value, str) and value.startswith('|>='):  # Need the other cases
            return 1 if d[path[0]] >= float(value[3:-1]) else -1
        else:
            return -1
    elif isinstance(d[path[0]], dict):
        return walk_resource_for_truth(d[path[0]], path[1:], value)
    else:
        return -1

# Define a variable stating that this resource satisfies this constraint
def resource_constraint_var(resource, path, value):
    if isinstance(value, dict):
        #print 'dict is', value
        print("dict is %s" % value)
    else:
        return find_or_add_var(resource['id'] + path, value)  # Equality variable

def link_ok(n1, n2, link_props, id_link_map, node_site_map):
    #print 'checking', n1['props']['name'], n2['props']['name'], link_props
    # Find the link, or allow if they are on different groups, assuming an internet link
    # If they are on the same site, assume there's a switch. Otherwise assume a slow internet link
    return True
    if node_site_map[n1['id']] != node_site_map[n2['id']]:
        #print '  link ok, they are on different sites'
        return True
    link = None
    for ep in n1['endpoints']:
        if ep['id'] not in id_link_map:
            #print 'end point not linked:', ep['id']
            continue
        req_link = id_link_map[ep['id']]
        other_ep = [epo['id'] for epo in req_link['endpoints'] if epo['id'] != ep['id']][0]
        if other_ep in [ep2['id'] for ep2 in n2['endpoints']]:
            #print '  link is', req_link
            link = req_link
            break
    if link is None:
        #print '  no link'
        return False
    return True

# Convenience. Return the variable that says this query node is matched to this resource node in the solution
def match_var(query_node, resource_node):
    v, found = find_or_add_var(query_node['id'], resource_node['id'], '_matched_to_')
    return v

# Return the variable that says this path should have this value. Create if necessary.
def find_or_add_var(path, value, relation="="):
    global var_map, num_to_var
    var_name = path + relation + str(value)
    found = True
    if var_name not in var_map:
        found = False
        var_map[var_name] = len(var_map) + 1
        num_to_var[var_map[var_name]] = var_name
    return var_map[var_name], found

# Functions that help manipulate sets of solutions.
def count_solutions(request, resources):
    clauses = generate_clauses(request, resources)
    #iter = pycosat.pycosat.itersolve(clauses)
    iter = pycosat.itersolve(clauses)
    count = 0
    try:
        while True:
            iter.next()
            count += 1
    except:
        return count
    return count

# Assuming there is a solution using this set of resources, is there a solution with a smaller set?
# Inefficient to constantly re-generate the clauses but if there are not too many resources it's not too bad.
def sub_enclave_solution(request, resources):
    sub_solutions = []
    for res in resources:
        sublist = list(resources)
        sublist.remove(res)
        names, solution = solve(request, sublist)
        if solution is not None:
            #print 'found a sub-enclave solution leaving out', res
            print("found a sub-enclave solution leaving out %s " % res)
            sub_solutions.append((names, solution))
    return sub_solutions

# Take a list of enclaves and produce the list of property values for each property found for nodes. Will generalize.
def gather_properties(enclaves):
    v = dict()
    v['endpoints'] = dict()
    for enclave in enclaves:
        for n in enclave['nodes']:
            if 'props' in n:
                add_to_properties(n['props'], v)
            if 'endpoints' in n:
                for e in n['endpoints']:
                    if 'props' in e:
                        add_to_properties(e['props'], v['endpoints'])
    return v

def add_to_properties(data, val_dict, indent=0):
    for prop in data:
        if prop == 'nic' or prop == 'name':  # Remove these for now, though we could help a user address specific resources
            continue
        node_value = data[prop]
        # Replace {'value__': X, 'constraint__': '='} with X. I don't see why resources would have other kinds of constraints
        if type(node_value) is dict and 'value__' in node_value and 'constraint__' in node_value and node_value['constraint__'] == '=':
            node_value = node_value['value__']
        if type(node_value) is list:
            if prop not in val_dict:
                val_dict[prop] = set()
            for val in node_value:
                if isinstance(val, collections.Hashable):  # Should recursively add values
                    val_dict[prop].add(val)
        elif type(node_value) is dict:  # Should recursively add values
            #print ' '*indent, indent, 'recursively adding values for', prop, data[prop]
            if prop not in val_dict:
                val_dict[prop] = dict()
            add_to_properties(node_value, val_dict[prop], indent + 2)
        else:
            if prop not in val_dict:
                val_dict[prop] = set()
            val_dict[prop].add(node_value)

# To help look at this, remove the long id names
ids = dict()

def short_ids(orig_site):
    site = copy.deepcopy(orig_site)
    rec_shorten_ids(site)
    return site

def rec_shorten_ids(d):
    for k in d:
        if k in ['id', 'nic']:
            if d[k] not in ids:
                ids[d[k]] = len(ids)
            d[k] = ids[d[k]]
        elif isinstance(d[k], dict):
            rec_shorten_ids(d[k])
        elif isinstance(d[k], list):
            for v in d[k]:
                if isinstance(v, dict):
                    rec_shorten_ids(v)

def trySubsets(request, resources):
    indexSet = set([])
    indexSet.update(range(0, len(resources)))
    combos = set([])
    for i in range(1, len(resources)):
        combos.update(set(itertools.combinations(indexSet, i)))

    solutions = []

    for combo in combos:
        subresourcelist = []
        for x in combo:
            subresourcelist.append(resources[x])
        names, solution = solve(request, subresourcelist)
        print(list(combo))
        comboResult = {}
        comboResult['site_combo'] = list(combo)
        if names != None:
            print("Has solution:")
            print(names)
            comboResult['solution'] = True
        else:
            print("Has no solution")
            comboResult['solution'] = False
        solutions.append(comboResult)

    print(solutions)

if __name__ == "__main__":

    # Import json resources for the example sites
    #root = "/Users/jim/repo/Projects/Bridge/CEF/git/xir/examples/"
    root = ""
    with open(root + "sites/emu.json") as f:
        emu_json = json.load(f)
    with open(root + "sites/cellular.json") as f:
        cellular_json = json.load(f)
    with open(root + "sites/iot.json") as f:
        iot_json = json.load(f)
    #with open(root + "experiments/small-world.json") as f:
    #    small_world_json = json.load(f)
    with open(root + "experiments/test.json") as f:
        small_world_json = json.load(f)

    resources = [emu_json, cellular_json, iot_json]

    r = gather_properties(resources)
    #print(r['image'])
    #exit()

    trySubsets(small_world_json, resources)
    exit()

    # Solve the problem and look for solutions with fewer enclaves
    print(small_world_json)
    print(resources)
    names, solution = solve(small_world_json, resources)
    print("Names: ")
    print(names)
    print("Solutions ")
    print(solution)

    #print '\n** Seeking solutions with fewer groups of resources'
    print("\n** Seeking solutions with fewer groups of resources")
    sub_solutions = sub_enclave_solution(small_world_json, resources)

    # Create ranges of possible values for features of requested nodes and networks based on the resources
    ranges = gather_properties(resources)

    # To count the number of solutions call this (may take time, not yet smart about combinatorics)
    #print '\n** Counting solutions'
    print("\n** Counting solutions")
    count = count_solutions(small_world_json, resources)
    #print 'found', count, 'solutions'
    print("Found %d solutions" % (count))


mat_name = 'CubeMat'
tex_name = 'CubeTex'

# use yt to input an image? or link to an image sequence
use_yt = False

#filevoxout = '/Users/jillnaiman1/Desktop/test1_ytl4_l1en27.bvox'

def translate(value, leftMin, leftMax, rightMin, rightMax):
    # Figure out how 'wide' each range is
    leftSpan = leftMax - leftMin
    rightSpan = rightMax - rightMin
    # Convert the left range into a 0-1 range (float)
    valueScaled = float(value - leftMin) / float(leftSpan)
    # Convert the 0-1 range into a value in the right range.
    return rightMin + (valueScaled * rightSpan)

import yt
import numpy as np
datafile = '~/data/IsolatedGalaxy/galaxy0030/galaxy0030'
ds = yt.load(datafile)
dd = ds.all_data()
level = 4
all_data = ds.covering_grid(level=level, left_edge=[0,0.0,0.0],dims=ds.domain_dimensions*2**level)
#pointdata = dd['density']/dd['density'].max()
pointdata = np.log10(all_data['density']).flatten()
pointdata_save = np.array(pointdata)
# rescale from 0->1
minp = pointdata.min()
maxp = pointdata.max()
for i in range(0,len(pointdata)):
    pointdata[i] = translate(pointdata[i], minp, maxp, 0, 1.)
# set low bounds = 0
pointdata[pointdata_save < -27] = 0.0
#pointdata /= pointdata.max()

# format the data following: http://pythology.blogspot.com/2014/08/you-can-do-cool-stuff-with-manual.html

nx, ny, nz, nframes = all_data['density'].shape[0], all_data['density'].shape[1], all_data['density'].shape[2],1
header = np.array([nx,ny,nz,nframes])
#binfile = open(filevoxout,'wb')
#header.astype('<i4').tofile(binfile)
#pointdata.astype('<f4').tofile(binfile)

# now, we'll make a "fake" bvox file
#from yt.extern.six.moves import StringIO # because we need something that works in py3 & 2

# example
#output = StringIO.StringIO()
#output.write('First line.\n')
#print >>output, 'Second line.'
#
## Retrieve file contents -- this will be
## 'First line.\nSecond line.\n'
#contents = output.getvalue()
#
## Close object and discard memory buffer --
## .getvalue() will now raise an exception.
#output.close()

hp = np.array([header,pointdata])
#outfile = StringIO()
from io import BytesIO
outfile = BytesIO(hp)
#outfile.write(header.tostring())# + pointdata.tostring())

#---------------------------------

def setMaterial(ob, mat):
    me = ob.data
    me.materials.append(mat)

# first create but if it does exist
flagg = True
# do we have cube?
for ob in bpy.data.objects:
    if ob.name == 'Cube':
        flagg = False

if flagg:
    bpy.ops.mesh.primitive_cube_add(radius=1.0)

# put it in the center
bpy.data.objects['Cube'].location = (0,0,0.)

# make a material
mat = bpy.data.materials.new(mat_name)
mat.type = 'VOLUME'
mat.volume.density = 0.0 # lower?
mat.volume.density_scale = 2.0 # upper in the slice plot
# more scattering = less the light penatrates into volume
mat.volume.scattering = 1.4
# make particles emissive?  I assume?... looks like it... we might have to
#  make different materials with different emissivities for different
#  emissivity of the gas
mat.volume.emission = 0.0
mat.transparency_method = 'Z_TRANSPARENCY'

setMaterial(bpy.data.objects['Cube'], mat)

# Create texture from image sequence
mtex = mat.texture_slots.add()
mat.active_texture_index = 0

# this should work but it doesnt right now...
tex = bpy.data.textures.new(tex_name, type = 'VOXEL_DATA')
#bpy.ops.texture.new()
#tex = bpy.data.textures['Texture']
#tex.name = tex_name
mat.active_texture = tex

tex.use_color_ramp = True

tex.voxel_data.domain_object = bpy.data.objects['Cube']

#tex.voxel_data.file_format = 'IMAGE_SEQUENCE'
tex.voxel_data.file_format = 'BLENDER_VOXEL'

#if not use_yt: # generate from image seq
#bpy.ops.image.open(filepath=image_seq_dir+image_seq)
#bpy.ops.image.open(filepath=image_seq_dir+image_seq)#, directory = image_seq_dir, files = [{"name":image_seq, "name":image_seq}], relative_path=True)

#img = bpy.data.images[image_seq]
#tex.voxel_data.filepath = image_seq_dir + image_seq
#tex.image = img

#img.source = 'SEQUENCE'

tex.voxel_data.filepath = filevoxout

mat.texture_slots[0].texture_coords = 'ORCO' # generated coords
mat.texture_slots[0].mapping = 'CUBE' # map to a cube

# NO idea
ts = mat.texture_slots[0]
ts.use_map_density = True
ts.density_factor = 1.0
ts.use_map_emission = True
ts.emission_factor = 1.0
ts.use_map_color_emission = True
ts.emission_color_factor = 1.0


from sense_hat import SenseHat
from time import sleep
import random
sense=SenseHat()
sense.clear()
green = (0, 255, 0)
yellow = (255, 255, 0)
blue = (0, 0, 255)
red = (255, 0, 0)
white = (255,255,255)
nothing = (0,0,0)
pink = (255,105, 180)
array=[green,yellow,blue,red,pink]
a=random.randint(1,101)
num=2.55
#print(a) #Uncomment for the computer to print the answer immediately after running
while True:
  x=int(input("Enter a number 1-100:"))
  if x>a:
    ans=x-a
    ans=float(ans)
    ans*=num
    ans=int(ans)
    if ans<9:
      ans=9
    sense.clear((ans,0,0))
  elif x<a:
    ans=a-x
    ans=float(ans)
    ans*=num
    ans=int(ans)
    if ans<9:
      ans=9
    sense.clear((0,0,ans))
  else:
    sense.show_message("You got the number!",text_colour=green,back_colour=red)


class HashTable:
    """
    A class for a hash table. We solve data coliision here by inforcing
    unique key. If a same key is passed in, it will replace the previous one.
    The default size is 17 so as easy to debug, but is subject to change as
    one input variable.
    Noitce that we only take in str as key.
    """

    def __init__(self, size=17):
        self.entries_count = 0
        self.alphabet_size = 52
        self.table_size = size
        self.hashtable = [[] for _ in range(size)]
        # usually we would like size to be a prime number
        #  to reduce chance of data collision

    def __repr__(self):
        return "<HashTable: {}>".format(self.hashtable)

    def __len__(self):
        return self.entries_count

    def _hash_key(self, key):
        """
        Takes in string key and turn that into a hash result.
        input: key (str)
        output: hash value (int)
        """
        if len(key) == 0:
            return 0
        _key = ''.join(str(ord(c)) for c in key)
        return int(_key) % self.table_size

    def put(self, key, value):
        """
        Add a key and value into the hash table.
        input: key(str), value(*)
        output: None
        """
        if not isinstance(key, str):
            raise TypeError("Only strings can be used as keys")

        hash_ = self._hash_key(key)
        for i, item in enumerate(self.hashtable[hash_]):
            if item[0] == key:
                del self.hashtable[hash_][i]
                self.entries_count -= 1
        self.hashtable[hash_].append((key, value))
        self.entries_count += 1

    def get(self, key):
        """
        Retrieve a value from the hash table by key.
        input: key (str)
        output: associated value (*)
        """
        hash_ = self._hash_key(key)
        for i, item in enumerate(self.hashtable[hash_]):
            # why enumerate as we don't really use i?
            if item[0] == key:
                return item[1]
        # raise KeyError("Key not in hash table.")
        return False


from flask import request
from app import app
from basic.database import db
from basic.models import *
from basic.util import token_required, create_response

@app.route('/products/<int:product_id>/reviews/', methods=['GET'])
def get_product_reviews(product_id):
    product = Product.query.filter_by(id=product_id).first()
    if not product:
        return create_response({'message': 'Product not found!'}, 404, '*')
    return create_response({'reviews': [review.data() for review in product.reviews]}, 200, '*')

@app.route('/products/<int:product_id>/reviews/<int:review_id>', methods=['GET'])
def get_product_review(product_id, review_id):
    product = Product.query.filter_by(id=product_id).first()
    if not product:
        return create_response({'message': 'Product not found!'}, 404, '*')

    reviews = [review for review in product.reviews if review.id == review_id]
    if len(reviews) < 1:
        return create_response({'message': 'Review not found!'}, 404, '*')

    return create_response(reviews[0].data(), 200, '*')

@app.route('/products/<int:product_id>/reviews/', methods=['POST'])
@token_required
def create_product_review(current_user, product_id):

    if not current_user.admin:
        return create_response({'message': 'Permission denied!'}, 403, '*')

    product = Product.query.filter_by(id=product_id).first()
    if not product:
        return create_response({'message': 'Product not found!'}, 404, '*')

    data = request.get_json()

    try:
        date = data['date']
    except:
        date = None

    product_id = db.Column(db.Integer, db.ForeignKey('product.id'))
    title = db.Column(db.String(50), default='Review')
    stars = db.Column(db.Float(), default=2.5)
    text = db.Column(db.String(16000000), default='<Product Review Text>')

    review = Review(product_id=product.id,
                    title=data.get('title', None),
                    stars=data.get('stars', None),
                    text=data.get('text', None))

    db.session.add(review)
    product.reviews.append(review)
    db.session.commit()

    return create_response({'message': 'Review added!', 'id': review.id}, 200, '*')

@app.route('/products/<int:product_id>/reviews/<int:review_id>', methods=['PUT'])
@token_required
def modify_product_review(current_user, product_id, review_id):

    if not current_user.admin:
        return create_response({'message': 'Permission denied!'}, 403, '*')

    product = Product.query.filter_by(id=product_id).first()
    if not product:
        return create_response({'message': 'Product not found!'}, 404, '*')

    reviews = [review for review in product.reviews if review.id == review_id]
    if len(reviews) < 1:
        return create_response({'message': 'Review not found!'}, 404, '*')

    data = request.get_json()

    review = reviews[0]

    for key in data.keys():
        if key == 'title':
            review.title = data['title']
        elif key == 'stars':
            review.stars = data['stars']
        elif key == 'text':
            review.text = data['text']

    db.session.commit()

    return create_response({'message': 'Review updated!'}, 200, '*')

@app.route('/products/<int:product_id>/reviews/<int:review_id>', methods=['DELETE'])
@token_required
def delete_product_review(current_user, product_id, review_id):

    if not current_user.admin:
        return create_response({'message': 'Permission denied!'}, 403, '*')

    product = Product.query.filter_by(id=product_id).first()
    if not product:
        return create_response({'message': 'Product not found!'}, 404, '*')

    product.reviews = [
        review for review in product.reviews if review.id != review_id]
    review = Product.query.filter_by(id=review_id).first()
    if review:
        db.session.delete(review)
    db.session.commit()

    return create_response({'message': 'Review deleted!'}, 200, '*')


import RPi.GPIO as GPIO
import os
from time import strftime, time, sleep

######################Axelle Jamous 2EA1#########################

##############################setup##############################
IRS = 11
BTN = 5
LED = 3

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(IRS, GPIO.IN) #Read output from IR motion sensor
GPIO.setup(BTN, GPIO.IN)
GPIO.setup(LED, GPIO.OUT)

##############################declarations##############################
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))

fileFlag = buttonFlag = 0
alarmState = 0
ledState = False

##############################functions##############################
def readFile(fileName):
    #read file line per line w timestamps
    f = open(os.path.join(__location__, fileName), "r")
    lines = f.readlines() #list
    f.close()
    return lines

def appendFile(fileName, stringToFile):
    f = open(os.path.join(__location__, fileName), "a")
    f.write(stringToFile)
    f.close()

def writeFile(fileName, stringToFile):
    f = open(os.path.join(__location__, fileName), "w")
    f.write(stringToFile)
    f.close()

def timeToFile():
    #writes the time that the alarm was triggered to a timeFile.txt
    global fileFlag

    if fileFlag==0:
        fileFlag = 1 #tell the program that the first time has passed
        appendFile("timeFile.txt", "{}\n".format(strftime("%a, %d %b %Y %H:%M:%S"))) #output time to file

def alarm():
    global alarmState, ledState

    if alarmState == 1: #alarm on
        ledState = not ledState
    elif alarmState == 0: #alarm off
        ledState = False
    GPIO.output(LED, ledState) #write change to led

def timerCallback(self):
    global alarmState, buttonFlag

    start_time = time()

    while GPIO.input(self) == 0: # Wait for the button up
        pass

    buttonTime = time() - start_time    # How long was the button down?
    print(str(buttonTime))

    if buttonTime >= 5:
        alarmState = 0
        buttonFlag = 1

def main():
    global fileFlag, alarmState, buttonFlag

    i=GPIO.input(IRS) #read infrared sensor output
    if i==0:
        fileFlag = buttonFlag = 0
        alarmState = 0
#       print("Door closed " + str(i))

    elif i==1:
        timeToFile()
        if buttonFlag == 0:
            alarmState = 1
#       print("Door open " + str(i))

    alarm()
    sleep(0.2)

##############################listeners/interrupts##############################
GPIO.add_event_detect(BTN, GPIO.FALLING, callback=timerCallback, bouncetime=500)

##############################toplevel script##############################
if __name__ == '__main__':
    while True:
        try:
            main()
        except KeyboardInterrupt:
            print("Closing.")
            GPIO.cleanup()