#!flask/bin/python
from flask import Flask, jsonify, make_response, request, Response, url_for, render_template, Markup
from flask_httpauth import HTTPBasicAuth
from functools import wraps
from passlib.hash import sha256_crypt
import pika
import Events
import json
import datetime
import time

app = Flask(__name__)

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) #deze zou dus gwn moeten werken als je alleen je Flask ergens anders (openlijk) runt, als ie maar nogsteeds bij de localhost kan...
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)

#        connection.close()

###Auth
auth = HTTPBasicAuth()
def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    pw = "$5$rounds=535000$TbjfFguG9yEaDQWS$6joRKlWuiXMBP8dTYoMQ5woWDepmcfcGWBKZtX9vvT0"
                        #TODO Nergy hashen
    passed = username == 'Nergy' and sha256_crypt.verify(password, pw)
    if not passed:
        date = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')

        payload = Events.loginFailedEvent(date, password)  # maak loginSuccesEvent
        message = json.dumps(payload.__dict__)  # naar json
        channel.basic_publish(exchange='',
                              routing_key='task_queue',
                              body=message,
                              properties=pika.BasicProperties(
                                  delivery_mode=2,  # make message persistent
                              ))

        payload = Events.loginSuccesEvent(date)  # maak loginSuccesEvent
        message = json.dumps(payload.__dict__)  # naar json
        channel.basic_publish(exchange='',
                              routing_key='task_queue',
                              body=message,
                              properties=pika.BasicProperties(
                                  delivery_mode=2,  # make message persistent
                              ))

    return passed

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)

    return decorated

###RESTFULL
#adds urls to jsonstring
def make_public_tasks(task):

    new_task = {}
    for field in task:
        if field == 'id':
            new_task['uri'] = url_for('get_tasks', task_id=task['id'], _external=True)
        else:
            new_task[field] = task[field]
    return new_task

def make_public_task(task):

    new_task = {}
    for field in task:
        if field == 'id':
            new_task['uri'] = url_for('get_task', task_id=task['id'], _external=True)
        else:
            new_task[field] = task[field]
    return new_task

##DB

#TODO tasks uit binarized bestand trekken, ietsje meer veiligheid

tasks = [
    {
        'id': 1,
        'title': u'Destroy Stratis',
        'description': u'Kill All Humans',
        'done': False
    },
    {
        'id': 2,
        'title': u'Liberate Altis',
        'description': u'Liberate them... Right.',
        'done': False
    }
]
### API-Controller
@app.route('/', methods=['GET', "POST", "PUT"]) # fancy
def home():
    if request.method == "POST":
        text = open('text.txt', 'r').read()
        knop = Markup('<form method="put"><input class="button button5" type="submit" value="UNDO_HACKS" ></form>')
        time.sleep(2)
        return render_template('hacked.html', status = "INTERNAL_FAILURE", text = text, extraknop = knop )

    else:
        date = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
        ip = str({'ip': request.remote_addr})
        ip="Your IP is: "+ip[8:-2]

        payload = Events.pageVisitedEvent("Home", date, ip)
        message = json.dumps(payload.__dict__)  # naar json
        channel.basic_publish(exchange='',
                              routing_key='task_queue',
                              body=message,
                              properties=pika.BasicProperties(
                                  delivery_mode=2,  # make message persistent
                              ))

        return render_template('hackpage.html', ip = ip)

@app.route('/todo/api/v1.0/tasks', methods=['GET']) # fancy
@requires_auth
def get_tasks():
    return jsonify({'tasks': [make_public_tasks(task) for task in tasks]})

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        not_found(404)
    return jsonify({'task': make_public_task(task[0])})

@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 403)

@app.route('/todo/api/v1.0/tasks', methods=['POST'])
@requires_auth
def create_task():
    if not request.json or not 'title' in request.json:
        not_found(400)
    task = {
        'id': tasks[-1]['id'] + 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False
    }
    tasks.append(task)
    return jsonify({'task': task}), 201

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['PUT'])
@requires_auth
def update_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        not_found(404)
    if not request.json:
        bad_request(400)
    # if 'title' in request.json and type(request.json['title']):
    #     not_found(400)
    # if 'description' in request.json and type(request.json['description']) is not unicode:
    #     not_found(400)
    # if 'done' in request.json and type(request.json['done']) is not bool:
    #     not_found(400)
    task[0]['title'] = request.json.get('title', task[0]['title'])
    task[0]['description'] = request.json.get('description', task[0]['description'])
    task[0]['done'] = request.json.get('done', task[0]['done'])
    return jsonify({'task': task[0]})

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['DELETE'])
@requires_auth
def delete_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        not_found(404)
    tasks.remove(task[0])
    return jsonify({'result': True})

## Error handlers
@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Page Not found'}), 404)

@app.errorhandler(400)
def bad_request(error):
    return make_response(jsonify({'error': 'Bad Request'}), 400)

if __name__ == '__main__':
    app.run(host="192.168.1.30", port=5000)       #zelf beslissen hiermee         //192.168.1.30
   #app.run(debug=True) #localhost:5000


import redis
from data import Data

def gen(head="CX",endtime="2016.10.1",amount=200):
    salt = endtime + endtime + endtime
    for i in range(1,amount+1):
        yield head + str(abs(hash(str(i) + salt + str(i))))

x = gen()
d = Data(hashName = "0003")

print(123)
for i in list(x):
    d.set(i,i)

for i in list(x):
    print(d.get(i))
    print(1)

def check(f,code):
    x = f()
    if code in list(x):
        return True
    return False

print(check(gen,"CX4380371458663503116"))
d.set("asd","111")
print(d.get("CX3871706864350190952"))


import sys
from daemon import Daemon
import logging
import logging.handlers
import config_info as config

import socket

from datetime import date
from dateutil.relativedelta import relativedelta
from apscheduler.schedulers.blocking import BlockingScheduler

# Server infomation for Socket
HOST = config.cfg['host']
PORT = int(config.cfg['port'])
#HOST = 'm2u-da.eastus.cloudapp.azure.com'

#######################################################
def job_cron_day():
	logger.info("===== Start data analysis for one day =====")

	today = date.today()
	minusDay = relativedelta(days=121)
	startDate = today - minusDay
	endDate = startDate

	sendDate = '{"start_date":"'+ startDate.strftime('%Y-%m-%d') + '", "end_date":"' + endDate.strftime('%Y-%m-%d') + '", "time_interval":15}'
	sendDate = sendDate.encode()

	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #소켓생성
	s.connect((HOST,PORT))
	s.send(sendDate)
#	s.send(b'{"start_date": "2017-02-03", "end_date": "2017-02-03", "time_interval": 15}') #문자를 보냄
	data = s.recv(2048) #서버로 부터 정보를 받음
	s.close()
	print('Received',repr(data))

def job_cron_week():
	logger.info("===== Start data analysis for one week =====")

	today = date.today()
	minusDay = relativedelta(days=123)
	oneWeek = relativedelta(days=6)
	endDate = today - minusDay
	startDate = endDate - oneWeek

	sendDate = '{"start_date":"'+ startDate.strftime('%Y-%m-%d') + '", "end_date":"' + endDate.strftime('%Y-%m-%d') + '", "time_interval":60}'
	sendDate = sendDate.encode()

	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #소켓생성
	s.connect((HOST,PORT))
	s.send(sendDate)
	#s.send(b'{"start_date": "2017-02-07", "end_date": "2017-02-07", "time_interval": 60}') #문자를 보냄
	data = s.recv(2048) #서버로 부터 정보를 받음
	s.close()
	print('Received',repr(data))

def job_cron_month():
	logger.info("===== Start data analysis for one month =====")

	today = date.today()
	premonth = today - relativedelta(months=5)
	startDate = date(premonth.year, premonth.month, 1)
	endDate = date(today.year, today.month, 1) - relativedelta(months=4) - relativedelta(days=1)
	sendDate = '{"start_date":"'+ startDate.strftime('%Y-%m-%d') + '", "end_date":"' + endDate.strftime('%Y-%m-%d') + '", "time_interval":60}'
	sendDate = sendDate.encode()

	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #소켓생성
	s.connect((HOST,PORT))
	s.send(sendDate)
	#s.send(b'{"start_date": "2017-02-07", "end_date": "2017-02-07", "time_interval": 60}') #문자를 보냄
	data = s.recv(2048) #서버로 부터 정보를 받음
	s.close()
	print('Received',repr(data))

class Start_scheduler(object):

	def run(self):
		logger.info("ELDA Scheduler start...")
		while True:
			sched = BlockingScheduler()

			sched.add_job(job_cron_day, 'cron', max_instances=10, hour=0)
			sched.add_job(job_cron_week, 'cron', max_instances=10, day_of_week='mon', hour=0)
			sched.add_job(job_cron_month, 'cron', max_instances=10, day=1, hour=1)
			sched.start()

class SchedulerDaemon(Daemon):
	def run(self):
		startdaemon = Start_scheduler()
		startdaemon.run()

if __name__ == '__main__':
	# make logger instance
	logger = logging.getLogger("Scheduler_Log")
	logger.setLevel(logging.INFO)

	# make formatter
	formatter = logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s > %(message)s')

	# make handler to output Log for stream and file
	fileMaxByte = 1024 * 1024 * 100 #100MB
	fileHandler = logging.handlers.RotatingFileHandler(config.cfg['apscheduler_path'], maxBytes=fileMaxByte, backupCount=10)
	# specify formatter to each handler
	fileHandler.setFormatter(formatter)
	# attach stream and file handler to logger instance
	logger.addHandler(fileHandler)

	daemon = SchedulerDaemon(config.cfg['schePID_path'])

	if len(sys.argv) == 2:
		if 'start' == sys.argv[1]:
			daemon.start()
		elif 'stop' == sys.argv[1]:
			daemon.stop()
		elif 'restart' == sys.argv[1]:
			daemon.restart()
		else:
			print("unknown command")
			sys.exit(2)
		sys.exit(0)
	else:
		print("usage: %s start|stop|restart" % sys.argv[0])
		sys.exit(2)
	#######################################################


import arcade
import math
import random
from util.constants import *

class MidRangePlayer(arcade.Sprite):
    def equipshield(self):
        self.set_texture(1)
        self.health += PLAYER_HEALTH*.5
        self.shield +=1
    def throwfire(self):
        fireball = Fireball("images/fire.png", .1)
        fireball.center_x = self.center_x
        fireball.center_y = self.center_y
        fireball.start_x = self.center_x # for tracking
        fireball.start_y = self.center_y # fireball distance
        fireball.angle = self.angle-90
        fireball.change_x = -ARROW_SPEED*math.sin(math.radians(self.angle))
        fireball.change_y = ARROW_SPEED*math.cos(math.radians(self.angle))

        self.fireball_list.append(fireball)

        hit = HitBox("images/fire.png")
        hit._set_alpha(0)
        hit._set_height(math.sqrt(SCREEN_WIDTH**2 + SCREEN_HEIGHT**2))
        hit._set_width(ARROW_IMAGE_HEIGHT)
        hit.angle = self.angle
        hit.center_x = self.center_x + -math.sin(math.radians(hit.angle)) * hit.height/2
        hit.center_y = self.center_y + math.cos(math.radians(hit.angle)) * hit.height/2

        fireball.hit = hit
        self.hitbox_list.append(hit)

    def update(self):
        self.curtime += 1
        x_diff = self.opponent.center_x - self.center_x
        y_diff = self.opponent.center_y - self.center_y
        self.angle = math.degrees(math.atan2(y_diff,x_diff))-90
        self.d = math.sqrt(x_diff**2 +y_diff**2)
        if len(self.opponent_hitbox_list) > 0:
            if arcade.check_for_collision_with_list(self,self.opponent_hitbox_list) and self.health <PLAYER_HEALTH*.7:
                randmove_x = random.choices([1,-1])[0]
                randmove_y = random.choices([1,-1])[0]
                self.center_x += (MOVEMENT_SPEED * MID_SPEED_HANDICAP) * randmove_x
                self.center_y += (MOVEMENT_SPEED * MID_SPEED_HANDICAP) * randmove_y
            elif abs(y_diff) + abs(x_diff) != 0:
                self.change_x = (x_diff)/(abs(y_diff) + abs(x_diff))
                self.change_y = (y_diff)/(abs(y_diff) + abs(x_diff))
                if self.d > 240:
                    self.center_x += self.change_x * (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                    self.center_y += self.change_y * (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                else:
                    if abs(self.center_x - 0) > 5 and abs(SCREEN_WIDTH - self.center_x) > 5:
                        self.center_x += -self.change_x * (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                    else:
                        if self.center_y > SCREEN_HEIGHT/2:
                            self.center_y += (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                        else:
                            self.center_y += -(MOVEMENT_SPEED * MID_SPEED_HANDICAP)

                    if abs(self.center_y - 0) > 5 and abs(SCREEN_HEIGHT - self.center_y) > 5:
                        self.center_y += -self.change_y * (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                    else:
                        if self.center_x > SCREEN_WIDTH/2:
                            self.center_x += (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                        else:
                            self.center_x += -(MOVEMENT_SPEED * MID_SPEED_HANDICAP)
        else:
            if abs(y_diff) + abs(x_diff) != 0:
                self.change_x = (x_diff)/(abs(y_diff) + abs(x_diff))
                self.change_y = (y_diff)/(abs(y_diff) + abs(x_diff))
                if self.d > 230:
                    self.center_x += self.change_x * (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                    self.center_y += self.change_y * (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                else:
                    if abs(self.center_x - 0) > 5 and abs(SCREEN_WIDTH - self.center_x) > 5:
                        self.center_x += -self.change_x * (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                    else:
                        if self.center_y > SCREEN_HEIGHT/2:
                            self.center_y += (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                        else:
                            self.center_y += -(MOVEMENT_SPEED * MID_SPEED_HANDICAP)

                    if abs(self.center_y - 0) > 5 and abs(SCREEN_HEIGHT - self.center_y) > 5:
                        self.center_y += -self.change_y * (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                    else:
                        if self.center_x > SCREEN_WIDTH/2:
                            self.center_x += (MOVEMENT_SPEED * MID_SPEED_HANDICAP)
                        else:
                            self.center_x += -(MOVEMENT_SPEED * MID_SPEED_HANDICAP)

        if self.curtime >=30:
            if self.d <= 300:
                self.throwfire()
            self.curtime = 0

        for fireball in self.fireball_list:
            diff_x = fireball.start_x-fireball.center_x
            diff_y = fireball.start_y-fireball.center_y
            fireball_dist = math.sqrt(diff_x**2 + diff_y**2)
            if fireball_dist>200:
                fireball.kill()
        if self.health <=PLAYER_HEALTH*.5 and self.shield < 1:
            self.equipshield()


"""Functions for downloading and reading MNIST data."""
from __future__ import print_function
import gzip
import os
from six.moves import urllib

import numpy as np
import tensorflow as tf

SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'

tf.app.flags.DEFINE_string("dir_data", "./data", "data directory")

tf.app.flags.DEFINE_integer("batch_size", 100, "batch size")

FLAGS = tf.app.flags.FLAGS
#VALIDATION_SIZE = 10000
TRAIN_SIZE = 50000
VALIDATION_SIZE = 60000 - TRAIN_SIZE
NUM_CLASSES = 10

train_data_filename = None
train_labels_filename = None
test_data_filename = None
test_labels_filename = None
iter_per_epoch = None

def init():
  """
  do initialization of this module.
  If we don't have files in local, this start to download.
  """
  global train_data_filename
  global train_labels_filename
  global test_data_filename
  global test_labels_filename
  global iter_per_epoch

  print ("start data download")
  train_data_filename = maybe_download('train-images-idx3-ubyte.gz')
  train_labels_filename = maybe_download('train-labels-idx1-ubyte.gz')
  test_data_filename = maybe_download('t10k-images-idx3-ubyte.gz')
  test_labels_filename = maybe_download('t10k-labels-idx1-ubyte.gz')

  print ("finish data download")

  iter_per_epoch = VALIDATION_SIZE / FLAGS.batch_size

def train_input():
  train_data = extract_data(train_data_filename, 60000)
  train_labels = extract_labels(train_labels_filename, 60000)

  data = train_data[:TRAIN_SIZE, ...]
  labels = train_labels[:TRAIN_SIZE]

  image, label = tf.train.slice_input_producer((data, labels), shuffle=True, capacity=4096, name="label_input")
  return make_batch(image, label)

def validate_input():
  train_data = extract_data(train_data_filename, 60000)
  train_labels = extract_labels(train_labels_filename, 60000)

  data = train_data[TRAIN_SIZE:, ...]
  labels = train_labels[TRAIN_SIZE:]

  image, label = tf.train.slice_input_producer((data, labels), shuffle=False, capacity=4096, name="validate_input")
  return make_batch(image, label, need_onehot=False)

def test_input():
  data = extract_data(test_data_filename, 10000)
  labels = extract_labels(test_labels_filename, 10000)

  image, label = tf.train.slice_input_producer((data, labels), shuffle=False)
  return make_batch(image, label, need_onehot=False)

def get_image(idx):
  data = extract_data(test_data_filename, 10000)
  target = data[idx]
  preprocessed = preprocess(target)
  reshaped = preprocessed.reshape(1, 28, 28, 1)
  return target, reshaped

def preprocess(src):
  """
  do common image preprocess among train and test.
  [0,255] -> [-0.5, 0.5]

  Args:
    src: Tensor [h, w, channel]
  Returns:
    dest: Tensor [h*w*channel]
  """
  #src = tf.reshape(src,[-1])

  return (src / 255) - 0.5

def make_batch(image, label=None, need_onehot=True):
  """
  preprocess image and labe. Than make batch.
  This doesn't shuffle.

  Args:
    image: Tensor of image data
    label: Tensor of label data. If None, label is not contained in batch
    need_onehot: whether to make onehot vector for label
  """
  preprocessed = preprocess(image)

  if need_onehot and label is not None:
    label_vector = tf.one_hot(label, NUM_CLASSES, dtype=tf.float32)
  else:
    label_vector = label

  num_preprocess_threads = 8
  #num_preprocess_threads = 2
  capacity = 256

  if label is not None:
    images, label_batch = tf.train.batch(
      [preprocessed, label_vector],
      batch_size=FLAGS.batch_size,
      num_threads=num_preprocess_threads,
      capacity=capacity,
      name="label_batch"
    )

    return images, label_batch

  else:
    images = tf.train.batch(
      [preprocessed],
      batch_size=FLAGS.batch_size,
      num_threads=num_preprocess_threads,
      capacity=capacity,
      name="unlabel_batch"
    )

    return images

def maybe_download(filename):
  """Download the data from Yann's website, unless it's already here."""
  WORK_DIRECTORY = FLAGS.dir_data

  if not tf.gfile.Exists(WORK_DIRECTORY):
    tf.gfile.MakeDirs(WORK_DIRECTORY)
  filepath = os.path.join(WORK_DIRECTORY, filename)
  if not tf.gfile.Exists(filepath):
    filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)
    with tf.gfile.GFile(filepath) as f:
      size = f.Size()
    print('Successfully downloaded', filename, size, 'bytes.')

  return filepath

def extract_data(filename, num_images):
  """
  Extract the images into a 4D tensor.

  Args:
    filename: image filename
    num_images: the numer of image in file

  Returns:
    data : image ranges [0,255] Tensor(image index, y, x, channels)
  """
  IMAGE_SIZE = 28
  NUM_CHANNELS = 1

  with gzip.open(filename) as bytestream:
    bytestream.read(16)
    buf = bytestream.read(IMAGE_SIZE * IMAGE_SIZE * num_images * NUM_CHANNELS)
    data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
    data = data.reshape(num_images, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS)

    return data

def extract_labels(filename, num_images):
  """Extract the labels into a vector of int64 label IDs."""
  print('Extracting', filename)
  with gzip.open(filename) as bytestream:
    bytestream.read(8)
    buf = bytestream.read(1 * num_images)
    labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64)
  return labels


#!/usr/bin/env python
# encoding: utf-8
"""
customer.py

Created by Timothy Hopper on 2012-06-18.
Copyright (c) 2012 __MyCompanyName__. All rights reserved.
"""

class AbstractCustomer(object):
    ID = 0

    def __init__(self, directCost, indirectCost, numScenarios, q):
        self.numScenarios = numScenarios
        self.directCost = directCost
        self.indirectCost = indirectCost
        self.ID = AbstractCustomer.ID
        self.q = q
        Customer.ID += 1

class Customer(AbstractCustomer):
    ID = 0

    def __init__(self, directCost, indirectCost, q, durations = None, numScenarios = None, distribution = None, distributionParams = None):
        self.distribution = distribution
        self.distributionParams = distributionParams
        if self.distribution != None:
            self.durations = list(self.distribution.rvs(*distributionParams, size = numScenarios)) # List of possible durations
            self.expectedDuration = self.distribution.mean(*distributionParams)
        else:
            self.durations = durations
            self.expectedDuration = sum(durations)/float(len(durations))
            numScenarios = len(durations)
        # print self.expectedDuration

        super(Customer, self).__init__(directCost = directCost, indirectCost = indirectCost, q = q, numScenarios = numScenarios)

    def increaseDurations(self, num):
        self.numScenarios = num
        self.durations = list(self.distribution.rvs(*self.distributionParams, size = num)) # List

    def printRedis(self):
        return repr(str(self.ID) + self.distribution.__class__.__name__ + str(self.distributionParams))

    def __repr__(self):
        return repr(str(self.ID) + "d" + str(self.directCost) + "i" + str(self.indirectCost) + "q" + str(self.q) + self.distribution.__class__.__name__ + str(self.distributionParams))

    def printComp(self):
        return repr("d" + str(self.directCost) + "i" + str(self.indirectCost) + self.distribution.__class__.__name__ + str(self.distributionParams))

class PodCustomer(AbstractCustomer):

    def __init__(self, directCost, indirectCost, q, setupDistribution, infusionDistribution, setupDistributionParams, infusionDistributionParams, numScenarios = 1000):
        super(PodCustomer, self).__init__(directCost = directCost, indirectCost = indirectCost, q = q, numScenarios = numScenarios)
        self.setupDistribution = setupDistribution
        self.infusionDistribution = infusionDistribution
        self.setupDistributionParams = setupDistributionParams
        self.infusionDistributionParams = infusionDistributionParams
        setupDurations = list(self.setupDistribution.rvs(*setupDistributionParams, size = numScenarios)) # List of possible durations
        infusionDurations = list(self.infusionDistribution.rvs(*infusionDistributionParams, size = numScenarios)) # List of possible durations
        self.durations = zip(setupDurations, infusionDurations)
        self.expectedDuration = (self.setupDistribution.mean(*setupDistributionParams), self.infusionDistribution.mean(*infusionDistributionParams))

    def printRedis(self):
        return repr(str(self.ID) + self.infusionDistribution.__class__.__name__ + str(self.infusionDistributionParams) + \
            self.setupDistribution.__class__.__name__ + str(self.setupDistributionParams))

    def increaseDurations(self, num):
        self.numScenarios = num
        setupDurations = list(self.setupDistribution.rvs(*self.setupDistributionParams, size = num)) # List of possible durations
        infusionDurations = list(self.infusionDistribution.rvs(*self.infusionDistributionParams, size = num)) # List of possible durations
        self.durations = zip(setupDurations, infusionDurations)


#finds and counts all files in a specified directory
import os

def getNumFiles(path):
    size= 0
    if not os.path.isfile(path):
        lst= os.listdir(path)
        for sub in lst:
            size+= getNumFiles(path + "\\" + sub)
    else:
        size+= 1
    return size

if __name__ == '__main__':
    path= input("Enter a directory: ").strip()
    try:
        print("The number of files is ", getNumFiles(path))
    except:
        print("Directory does not exist")


import random
from .FishHelperFunctions import *
from .Fishes import Fishes

class FishingActivities():

	def castPole():
		chars = [',', '.', ':', '\'']
		chars2 = [] + chars
		chars2.reverse()
		totalChars = chars + chars2
		for char in totalChars:
			for i in range(0, 3):
				specialPrint(char)
				rapidTween()
				i += i
		print()

	@classmethod
	# cls is used to show I'm calling the methods
	# inside of the class instead of
	# referring to self
	def goFishing(cls, user):
		if 'fishing rod' in user.userInventory.inventory:
			outcomes = ['win', 'lose', 'draw']
			print("You are using the fishing rod\n")
		elif 'bread rod' in user.userInventory.inventory:
			outcomes = ['win', 'trade', 'snag', 'snag']
			print("You are fishing with the bread rod\n")
		elif 'fly rod' in user.userInventory.inventory:
			outcomes = ['win', 'win', 'win', 'snag']
			print("You are fishing with the fly rod\n")
		elif 'lured rod' in user.userInventory.inventory:
			outcomes = ['win', 'win', 'win', 'snag']
			print("You are fishing with the lured rod\n")
		elif 'worm rod' in user.userInventory.inventory:
			outcomes = ['win', 'trade', 'trade']
			print("You are fishing with the worm rod\n")

		cls.castPole()
		random.shuffle(outcomes)
		currentFishingOutcome = outcomes[0]

		if (currentFishingOutcome == 'win'):
			user.addToInventory(cls.catchFish())
		if (currentFishingOutcome == 'lose'):
			print('you did not catch a fish this time')
		if (currentFishingOutcome == 'draw'):
			print('you caught a lure')
			user.addToInventory('lure')
		if (currentFishingOutcome == 'snag'):
			user.loseLure()
		if (currentFishingOutcome == 'trade'):
			user.loseLure()
			print("but, ")
			user.addToInventory(cls.catchFish())

	def catchFish():
		random.shuffle(Fishes)
		randomFish = Fishes[0]
		print('you caught a ' + randomFish)
		return randomFish


'''
Created on 2016年5月4日

@author: lin_jiang_yi
'''
# increase horizen increase hori ...
# importan segment 0-2 2-7 7-16 -> 1/2*n^2+n
# but i just don't know how to compute by a reverse function...

def checkio(number):
    func1 = lambda n:n*(n+1)*(2*n+1)/12+n*(n+1)*3/4 #max for n pigeon
    func2 = lambda n:func1(n-1)+n #min for n pigeon
    func3 = lambda n:n*(n+1)/2 #return value
    i = 1
    n = func2(i)
    while n<number:
        i+=1
        n=func2(i)
    if number <= func1(i-1):
        return func3(i-1)
    return func3(i-1)+(number-func1(i-1))

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert checkio(1) == 1, "1st example"
    assert checkio(2) == 1, "2nd example"
    assert checkio(5) == 3, "3rd example"
    assert checkio(10) == 6, "4th example"


from django.conf.urls import url

from oscar.core.application import Application
from oscar.core.loading import get_class
from .views import CategoryFilterCreateView, FilterOptionCreateView,\
    CategoryFilterListView, FilterEditView, FilterDeleteView
from .views import ProductAddressCreateView, ProductAddressEditView,\
    ProductAddressDeleteView, ProductAddressListView, DeliveryCreateView,\
    DeliveryOptionCreateView, DeliveryListView, DeliveryEditView,\
    DeliveryDeleteView

class CatalogueApplication(Application):
    name = None

    default_permissions = ['is_staff', ]
    permissions_map = _map = {
        'catalogue-product': (['is_staff'], ['partner.dashboard_access']),
        'catalogue-product-create': (['is_staff'],
                                     ['partner.dashboard_access']),
        'catalogue-product-list': (['is_staff'], ['partner.dashboard_access']),
        'catalogue-product-delete': (['is_staff'],
                                     ['partner.dashboard_access']),
        'catalogue-product-lookup': (['is_staff'],
                                     ['partner.dashboard_access']),
    }

    product_list_view = get_class('dashboard.catalogue.views',
                                  'ProductListView')
    product_lookup_view = get_class('dashboard.catalogue.views',
                                    'ProductLookupView')
    product_create_redirect_view = get_class('dashboard.catalogue.views',
                                             'ProductCreateRedirectView')
    product_createupdate_view = get_class('dashboard.catalogue.views',
                                          'ProductCreateUpdateView')
    product_delete_view = get_class('dashboard.catalogue.views',
                                    'ProductDeleteView')

    product_class_create_view = get_class('dashboard.catalogue.views',
                                          'ProductClassCreateView')
    product_class_update_view = get_class('dashboard.catalogue.views',
                                          'ProductClassUpdateView')
    product_class_list_view = get_class('dashboard.catalogue.views',
                                        'ProductClassListView')
    product_class_delete_view = get_class('dashboard.catalogue.views',
                                          'ProductClassDeleteView')

    category_list_view = get_class('dashboard.catalogue.views',
                                   'CategoryListView')
    category_detail_list_view = get_class('dashboard.catalogue.views',
                                          'CategoryDetailListView')
    category_create_view = get_class('dashboard.catalogue.views',
                                     'CategoryCreateView')
    category_update_view = get_class('dashboard.catalogue.views',
                                     'CategoryUpdateView')
    category_delete_view = get_class('dashboard.catalogue.views',
                                     'CategoryDeleteView')

    stock_alert_view = get_class('dashboard.catalogue.views',
                                 'StockAlertListView')

    def get_urls(self):
        urls = [
            url(r'^products/(?P<pk>\d+)/$',
                self.product_createupdate_view.as_view(),
                name='catalogue-product'),
            url(r'^products/create/$',
                self.product_create_redirect_view.as_view(),
                name='catalogue-product-create'),
            url(r'^products/create/(?P<product_class_slug>[\w-]+)/$',
                self.product_createupdate_view.as_view(),
                name='catalogue-product-create'),
            url(r'^products/(?P<parent_pk>[-\d]+)/create-variant/$',
                self.product_createupdate_view.as_view(),
                name='catalogue-product-create-child'),
            url(r'^products/(?P<pk>\d+)/delete/$',
                self.product_delete_view.as_view(),
                name='catalogue-product-delete'),
            url(r'^$', self.product_list_view.as_view(),
                name='catalogue-product-list'),
            url(r'^stock-alerts/$', self.stock_alert_view.as_view(),
                name='stock-alert-list'),
            url(r'^product-lookup/$', self.product_lookup_view.as_view(),
                name='catalogue-product-lookup'),
            url(r'^categories/$', self.category_list_view.as_view(),
                name='catalogue-category-list'),
            url(r'^categories/(?P<pk>\d+)/$',
                self.category_detail_list_view.as_view(),
                name='catalogue-category-detail-list'),
            url(r'^categories/create/$', self.category_create_view.as_view(),
                name='catalogue-category-create'),
            url(r'^categories/create/(?P<parent>\d+)$',
                self.category_create_view.as_view(),
                name='catalogue-category-create-child'),

            #Filter Links
            url(r'^categories/filters/create/$',
                CategoryFilterCreateView,
                name='filter-create'), #end create
            url(r'^categories/filters/list/$',
                CategoryFilterListView,
                name='filter-list'), #end list
            url(r'^categories/filters/options/create/(?P<pk>\d+)$',
                FilterOptionCreateView,
                name='filter-option-create'), #end filter list
            url(r'^categories/filters/edit/(?P<pk>\d+)$',
                FilterEditView,
                name='filter-edit'), #end filter edit
            url(r'^categories/filters/delete/(?P<pk>\d+)$',
                FilterDeleteView,
                name='filter-delete'), #end filter delete

            #Delivery Links
            url(r'^categories/delivery/provider/create/$',
                DeliveryCreateView,
                name='delivery-provider-create'), #end create
            url(r'^categories/delivery/option/create/(?P<pk>\d+)$',
                DeliveryOptionCreateView,
                name='delivery-option-create'), #end option create
            url(r'^categories/delivery/provider/list/$',
                DeliveryListView,
                name='delivery-provider-list'), #end list
            url(r'^categories/delivery/provider/edit/(?P<pk>\d+)$',
                DeliveryEditView,
                name='delivery-provider-edit'), #end provider edit
            # url(r'^categories/delivery/option/delete/(?P<ppk>\d+)/(?P<opk>\d+)$',
            #     DeliveryOptionDeleteView,
            #     name='delivery-option-delete'), #end option delete
            url(r'^categories/delivery/provider/delete/(?P<pk>\d+)$',
                DeliveryDeleteView,
                name='delivery-provider-delete'), #end provider delete

            #Addresses' Links
            url(r'categories/address/create/$',
                ProductAddressCreateView,
                name='address-create'), #end create
            url(r'categories/address/edit/(?P<pk>\d+)$',
                ProductAddressEditView,
                name='address-edit'), #end edit
            url(r'categories/address/delete/(?P<pk>\d+)$',
                ProductAddressDeleteView,
                name='address-delete'), #end delete
            url(r'categories/address/list/$',
                ProductAddressListView,
                name='address-list'), #end list

            url(r'^categories/(?P<pk>\d+)/update/$',
                self.category_update_view.as_view(),
                name='catalogue-category-update'),
            url(r'^categories/(?P<pk>\d+)/delete/$',
                self.category_delete_view.as_view(),
                name='catalogue-category-delete'),
            url(r'^product-type/create/$',
                self.product_class_create_view.as_view(),
                name='catalogue-class-create'),
            url(r'^product-types/$',
                self.product_class_list_view.as_view(),
                name='catalogue-class-list'),
            url(r'^product-type/(?P<pk>\d+)/update/$',
                self.product_class_update_view.as_view(),
                name='catalogue-class-update'),
            url(r'^product-type/(?P<pk>\d+)/delete/$',
                self.product_class_delete_view.as_view(),
                name='catalogue-class-delete'),
        ]
        return self.post_process_urls(urls)

application = CatalogueApplication()


#!/usr/bin/python
from AgentEventHandler import AgentEventHandler
import unittest
import os
import logging
from testfixtures import LogCapture
import subprocess

class TestAgentEventHandler(unittest.TestCase):

    CID = "ce6437097f5683f0b9fdf01295450753ba600e33562cd4675500fdb03bfd1ff0"
    WRONG_CID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\
                XXX"
    PAYLOAD_WITH_TARGET = "TARGET=" + CID + " MEMORY_LEVEL=80"
    PAYLOAD_NO_TARGET = "MEMORY_LEVEL=80"
    TARGET_ARGUMENT_KEY = "TARGET"
    TARGET_ARGUMENT_PAIR = "TARGET=" + CID
    TARGET_ARGUMENT_VALUE = CID
    MEMORY_LEVEL_ARGUMENT_KEY = "MEMORY_LEVEL"
    MEMORY_LEVEL_ARGUMENT_PAIR = "MEMORY_LEVEL=80"
    MEMORY_LEVEL_ARGUMENT_VALUE = "80"

    def setUp(self):
        pass

    def testGetPayload(self):
        agentEventHandler = AgentEventHandler(
            self.PAYLOAD_WITH_TARGET)
        self.assertEqual(
            self.PAYLOAD_WITH_TARGET, agentEventHandler.getPayload())

    def testGetArgumentPairs(self):
        agentEventHandler = AgentEventHandler(
            self.PAYLOAD_WITH_TARGET)
        self.assertEqual(
            self.TARGET_ARGUMENT_PAIR,
            agentEventHandler.getArgumentPair(self.TARGET_ARGUMENT_KEY))
        self.assertEqual(
            self.MEMORY_LEVEL_ARGUMENT_PAIR,
            agentEventHandler.getArgumentPair(self.MEMORY_LEVEL_ARGUMENT_KEY))

    def testGetArgumentValues(self):
        agentEventHandler = AgentEventHandler(
            self.PAYLOAD_WITH_TARGET)
        self.assertEqual(
            self.TARGET_ARGUMENT_VALUE,
            agentEventHandler.getArgumentValue(self.TARGET_ARGUMENT_PAIR))
        self.assertEqual(
            self.MEMORY_LEVEL_ARGUMENT_VALUE,
            agentEventHandler.getArgumentValue(
                self.MEMORY_LEVEL_ARGUMENT_PAIR))

    def testGetCIDDefault(self):
        agentEventHandler = AgentEventHandler(
            self.PAYLOAD_WITH_TARGET)
        self.assertEqual("", agentEventHandler.getCID())

    def testGetCID(self):
        agentEventHandler = AgentEventHandler(
            self.PAYLOAD_WITH_TARGET, self.CID)
        self.assertEqual(self.CID, agentEventHandler.getCID())

    def testCorrectTargetWithCorrectCID(self):
        agentEventHandler = AgentEventHandler(
            self.PAYLOAD_WITH_TARGET, self.CID)
        self.assertEqual(True, agentEventHandler.correctTarget())

    def testCorrectTargetWithInCorrectCID(self):
        agentEventHandler = AgentEventHandler(
            self.PAYLOAD_WITH_TARGET, self.WRONG_CID)
        self.assertEqual(False, agentEventHandler.correctTarget())

    def testCorrectTargetWithNoTargetInPayload(self):
        agentEventHandler = AgentEventHandler(self.PAYLOAD_NO_TARGET, self.CID)
        self.assertEqual(True, agentEventHandler.correctTarget())

    def testEnvVarWithOsEnviron(self):
        agentEventHandler = AgentEventHandler(
            self.PAYLOAD_NO_TARGET, self.CID, os.environ)
        self.assertEqual(None, agentEventHandler.getEnvVar("TEST!"))

    def testEnvVarWithMockOsEnviron(self):
        agentEventHandler = AgentEventHandler(
            self.PAYLOAD_NO_TARGET,
            self.CID,
            {"SERF_EVENT": "user", "SERF_USER_EVENT": "TEST_SET_MEMORY"})
        self.assertEqual("user", agentEventHandler.getEnvVar("SERF_EVENT"))

    def testSerfEventIs(self):
        agentEventHandler = AgentEventHandler(
            self.PAYLOAD_NO_TARGET,
            self.CID,
            {"SERF_EVENT": "user", "SERF_USER_EVENT": "TEST_SET_MEMORY"})
        self.assertEqual(True, agentEventHandler.serfEventIs("user"))

    def testLogging(self):
        def testMemoryHandler(event, payload):
            logger = logging.getLogger(__name__)
            logger.info("Called memory handler")

        with LogCapture() as l:
            agentEventHandler = AgentEventHandler(
                payload=self.PAYLOAD_WITH_TARGET,
                CID=self.CID,
                envVars={"SERF_EVENT": "user",
                         "SERF_USER_EVENT": "TEST_SET_MEMORY"},
                handlers={"TEST_SET_MEMORY": testMemoryHandler})
            agentEventHandler.handleShit()
            self.checkLogMessages(l,
                                  "Processing user event: TEST_SET_MEMORY",
                                  "Called memory handler",
                                  "Processed")

    def checkLogMessages(self, log, *messages):
        log_str = str(log)
        ind = 0
        for m in messages:
            try:
                new_ind = log_str.index(m, ind)
                ind = new_ind + len(m)
            except ValueError:
                self.fail('Message "%s" did not appear in: \n %s'
                          % (m, log_str[ind:-1]))

    def testCommandLineCall(self):
        #Check what happens when we replicate a serf call
        subprocess.check_call(["python", "AgentEventHandler.py"],
                              env={"SERF_EVENT": "user",
                                   "SERF_USER_EVENT": "TEST_SET_MEMORY"})

        #Test with std-in
        p = subprocess.Popen(["python", "AgentEventHandler.py"],
                             stdin=subprocess.PIPE,
                             env={"SERF_EVENT": "user",
                                  "SERF_USER_EVENT": "TEST_SET_MEMORY"})
        p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n')[0]
        self.assertEqual(p.returncode, 0)

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


#! /usr/bin/python

## Sample client.
##

import socket
import json
import argparse
#from pprint import pprint

# get settings
try:
    json_data = open('settings.json')
    settings = json.load(json_data)
    json_data.close()
except IOError:
    raise IOError("settings.json not found. Please run setup-stuff.py")

parser = argparse.ArgumentParser()
parser.add_argument("-i", "--ip", type=str, help="IP address or hostname of the server you want to connect to.", default=socket.gethostname())
parser.add_argument("-p", "--port", type=int, help="Port you want to connect to.", default=int(settings['port']))
args = parser.parse_args()

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

print("Connecting to: {0}:{1}".format(args.ip, args.port))

encoding = 'UTF-8'

try:
    sock.connect((args.ip, args.port))

    for i in range(2):
        msg = "hello! {0}".format(i)
        print("sending: {0}.".format(msg))
        sock.sendall(bytes(msg, encoding))
finally:
    sock.close()


import sys
import pytest
from sdl2 import ext as sdl2ext
from sdl2 import SDL_WasInit, SDL_INIT_VIDEO, SDL_FlushEvent, SDL_USEREVENT, \
    SDL_FIRSTEVENT, SDL_LASTEVENT, SDL_Event, SDL_UserEvent, SDL_PushEvent

class TestSDL2Ext(object):
    __tags__ = ["sdl", "sdl2ext"]

    def test_init_quit(self):
        try:
            sdl2ext.init()
        except sdl2ext.SDLError:
            raise pytest.skip('Video subsystem not supported')
        assert SDL_WasInit(SDL_INIT_VIDEO) == SDL_INIT_VIDEO
        sdl2ext.quit()
        assert SDL_WasInit(SDL_INIT_VIDEO) != SDL_INIT_VIDEO
        sdl2ext.init()
        sdl2ext.init()
        sdl2ext.init()
        assert SDL_WasInit(SDL_INIT_VIDEO) == SDL_INIT_VIDEO
        sdl2ext.quit()
        assert SDL_WasInit(SDL_INIT_VIDEO) != SDL_INIT_VIDEO
        sdl2ext.quit()
        sdl2ext.quit()
        sdl2ext.quit()
        assert SDL_WasInit(SDL_INIT_VIDEO) != SDL_INIT_VIDEO

    def test_get_events(self):
        try:
            sdl2ext.init()
        except sdl2ext.SDLError:
            raise pytest.skip('Video subsystem not supported')
        SDL_FlushEvent(SDL_FIRSTEVENT, SDL_LASTEVENT)
        for x in range(10):
            event = SDL_Event()
            event.type = SDL_USEREVENT + 1
            event.user = SDL_UserEvent(type=event.type, timestamp=0,
                                       windowID=0, code=0)
            SDL_PushEvent(event)
        results = sdl2ext.get_events()
        assert len(results) == 10
        for ev in results:
            assert ev.type == (SDL_USEREVENT + 1)

    def test_get_events_issue_6(self):
        try:
            sdl2ext.init()
        except sdl2ext.SDLError:
            raise pytest.skip('Video subsystem not supported')
        SDL_FlushEvent(SDL_FIRSTEVENT, SDL_LASTEVENT)
        for x in range(12):
            event = SDL_Event()
            event.type = SDL_USEREVENT + x
            event.user = SDL_UserEvent(type=event.type, timestamp=0,
                                       windowID=0, code=0)
            SDL_PushEvent(event)
        results = sdl2ext.get_events()
        for idx, r in enumerate(results):
            assert idx == r.type - SDL_USEREVENT

    def test_TestEventProcessor(self):
        proc = sdl2ext.TestEventProcessor()
        assert isinstance(proc, sdl2ext.TestEventProcessor)


# coding: utf-8
# license: GPLv3

from solar_objects import Star, Planet

def read_space_objects_data_from_file(input_filename):
    """Cчитывает данные о космических объектах из файла, создаёт сами объекты
    и вызывает создание их графических образов
    Параметры:
    **input_filename** — имя входного файла
    """

    objects = []
    with open(input_filename) as input_file:
        for line in input_file:
            if len(line.strip()) == 0 or line[0] == '#':
                continue  # пустые строки и строки-комментарии пропускаем
            object_type = line.split()[0].lower()
            if object_type == "star":
                star = Star()
                parse_star_parameters(line, star)
                objects.append(star)
            elif object_type == "planet":
                planet = Planet()
                parse_planet_parameters(line, planet)
                objects.append(planet)
            else:
                print("Unknown space object")

    return objects

def parse_star_parameters(line, star):
    """Считывает данные о звезде из строки.
    Входная строка должна иметь слеюущий формат:
    Star <радиус в пикселах> <цвет> <масса> <x> <y> <Vx> <Vy>
    Здесь (x, y) — координаты зведы, (Vx, Vy) — скорость.
    Пример строки:
    Star 10 red 1000 1 2 3 4
    Параметры:
    **line** — строка с описание звезды.
    **star** — объект звезды.
    """

    star.R = float(line.split()[1])
    star.color = line.split()[2]
    star.m = float(line.split()[3])
    star.x = float(line.split()[4])
    star.y = float(line.split()[5])
    star.Vx = float(line.split()[6])
    star.Vy = float(line.split()[7])

def parse_planet_parameters(line, planet):
    """Считывает данные о планете из строки.
    Предполагается такая строка:
    Входная строка должна иметь слеюущий формат:
    Planet <радиус в пикселах> <цвет> <масса> <x> <y> <Vx> <Vy>
    Здесь (x, y) — координаты планеты, (Vx, Vy) — скорость.
    Пример строки:
    Planet 10 red 1000 1 2 3 4
    Параметры:
    **line** — строка с описание планеты.
    **planet** — объект планеты.
    """
    planet.R = float(line.split()[1])
    planet.color = line.split()[2]
    planet.m = float(line.split()[3])
    planet.x = float(line.split()[4])
    planet.y = float(line.split()[5])
    planet.Vx = float(line.split()[6])
    planet.Vy = float(line.split()[7])

def write_space_objects_data_to_file(output_filename, space_objects):
    """Сохраняет данные о космических объектах в файл.
    Строки должны иметь следующий формат:
    Star <радиус в пикселах> <цвет> <масса> <x> <y> <Vx> <Vy>
    Planet <радиус в пикселах> <цвет> <масса> <x> <y> <Vx> <Vy>
    Параметры:
    **output_filename** — имя входного файла
    **space_objects** — список объектов планет и звёзд
    """
    with open(output_filename, 'w') as out_file:
        for obj in space_objects:
            out_file.write("{0} {1} {2} {3} {4} {5} {6} {7} \n".format(obj.type.capitalize(),
                obj.R, obj.color, obj.m, obj.x, obj.y, obj.Vx, obj.Vy))

def adding_statistics(stat_filename, planet, star, time):
    '''Добавляет статистику в данный момент в конец файла.
    Параметры:
    **stat_filename** - файл статистики
    **planet** - планета, по которой ведётся статистика
    **star** - звезда, по которой ведётся статистика
    **time** - значение времени в текущий момент
    '''
    with open(stat_filename, 'a') as stat_file:
        stat_file.write("{0} {1} {2} \n".format(str(time), str((planet.Vx**2 + planet.Vy**2)**0.5),
            str(((star.x - planet.x)**2 + (star.y - planet.y)**2)**0.5)))

def statistics_read(stat_filename):
    '''Считывает статистику из файла для построения графиков.
    Параметры:
    **stat_filename** - имя файла статистики
    Возвращает:
    **time_list** - упорядоченный список значений времени
    **speed_list** - упорядоченный список значений модуля скорости
    **distance_list** - упорядоченный список значений расстояния
    '''
    time_list = []
    speed_list = []
    distance_list = []
    with open(stat_filename, 'r') as stat_file:
        for line in stat_file:
            time_list.append(float(line.split()[0]))
            speed_list.append(float(line.split()[1]))
            distance_list.append(float(line.split()[2]))
    return time_list, speed_list, distance_list

if __name__ == "__main__":
    print("This module is not for direct call!")


from pdf2image import convert_from_path
from tkinter import *
from tkinter import messagebox

#https://www.geeksforgeeks.org/convert-pdf-to-image-using-python/

def pdf2img():
    try:
        images = convert_from_path(str(e1.get()))
        for img in images:
            img.save('new_folder\output.jpg', 'JPEG')

    except  :
        Result = "NO pdf found"
        messagebox.showinfo("Result", Result)

    else:
        Result = "success"
        messagebox.showinfo("Result", Result)

if __name__ == "__main__":
    master = Tk()
    Label(master, text="File Location").grid(row=0, sticky=W)

    e1 = Entry(master)
    e1.grid(row=0, column=1)

    b = Button(master, text="Convert", command=pdf2img)
    b.grid(row=0, column=2,columnspan=2, rowspan=2,padx=5, pady=5)

    mainloop()


#!/usr/bin/env python
# coding: utf-8

import pandas as pd
import numpy as np
from scipy import stats

from matplotlib import pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')

from scipy import stats

import seaborn as sns

import tkinter as tk
from tkinter import filedialog
from pandas import DataFrame

#Below script for toilet activity

log_entry = 'rule-toilet.csv'
hole_csv = 'days-toilet_failure.csv'
out_file = 'out.csv'
result_file = 'out.csv'
graph_title = 'Visiting the toilet activity'
label_y1 = 'Average duration in seconds'
label_y2 = 'Number of passage per month'
figure = 'toilet.pdf'
folder = 'result'

activity = pd.read_csv(log_entry, delimiter = ';', decimal="," ,
                          names=["date", "annotation", "activity_count", "duration"],
                          parse_dates=["date"], index_col="date")

#days_number_on = [0,0,0,0,0.05,0,0.74,0.85,0.88,0.74,0.74,0.68]

#activity.duration = activity.duration/60
#activity.rename(columns={'duration':'durationMin'}, inplace=True)

#out = activity.resample('M').agg({"activity_count":'sum', "durationMin":['mean', 'sem']})
out = activity.resample('M').agg({"activity_count":'sum', "duration":['mean', 'sem']})

export_csv = out.to_csv (out_file, index = True, header=True, sep = ';')

activity_dataset = pd.read_csv(out_file, delimiter =';', decimal=",",
                       names=["date", "sum", "mean", "sem"],
                       parse_dates=["date"], index_col="date")

activity_dataset = activity_dataset.drop('date')
activity_dataset = activity_dataset.loc[activity_dataset.index.dropna()]

activity_dataset.index = pd.to_datetime(activity_dataset.index)

#idx = pd.date_range('2017-08-31', '2018-08-31', freq='m')

idx = pd.date_range('2017-01-31', '2017-12-31', freq='m')

activity_dataset = activity_dataset.reindex(idx, fill_value=0)

activity_dataset.index = activity_dataset.index.strftime("%Y-%m")
activity_dataset = pd.read_csv(out_file, delimiter =';', decimal=",",
                       names=["date", "sum", "mean", "sem"],
                       parse_dates=["date"], index_col="date")

toilet_hole = pd.read_csv(hole_csv, delimiter =';', decimal=","
                              ,names=["date", "toilet_hole"],
                              parse_dates=["date"], index_col="date")

toilet_hole.index =  toilet_hole.index.strftime("%Y-%m")

#number of days where there was no failure
#toilet_hole = (30 - door_toilet)/35

activity_dataset = activity_dataset.drop('date')
activity_dataset = activity_dataset.loc[activity_dataset.index.dropna()]

activity_dataset.index = pd.to_datetime(activity_dataset.index)

#idx = pd.date_range('2017-08-31', '2018-08-31', freq='m')
idx = pd.date_range('2017-01-31', '2017-12-31', freq='m')

activity_dataset = activity_dataset.reindex(idx, fill_value=0)

activity_dataset.index = activity_dataset.index.strftime("%Y-%m")

result = pd.concat([activity_dataset, toilet_hole], axis=1, join_axes=[activity_dataset.index])

result.index.rename('date', inplace=True)

export_csv = result.to_csv (result_file, index = True, header=False, sep = ';')

result_activity = pd.read_csv(result_file, delimiter =';',
                         names=["date", "sum", "mean", "sem", "width"])
result_activity = result_activity.fillna(0)
result_activity['width'] = (31 - result_activity['width'])/35

#for exits devide the value by 60 to convert from seconds to minutes
result_activity['mean'] = result_activity['mean'] #/60
#result_activity['sem'] = result_activity['sem']/60

result_activity.loc[result_activity['width'] == 0, 'on'] = 0
result_activity.loc[result_activity['width'] > 0, 'on'] = -10
plt.rcParams['figure.figsize'] = [9, 7]
x = np.arange(12)
plt.bar(x , result_activity['mean'], width=result_activity['width'], yerr=result_activity['sem'],
         color="#1f77b4"
        )
plt.bar(x, result_activity['on'], width=result_activity['width'], color='green')
plt.gcf().autofmt_xdate()
plt.title(graph_title)
plt.xticks(x, result_activity.date)
plt.xlabel('Date')
plt.ylabel(label_y1, color="#1f77b4")
plt.tick_params(axis="y", labelcolor="#1f77b4")
plt.twinx()
plt.ylabel(label_y2, color="r")
plt.tick_params(axis="y", labelcolor="r", labelsize = 8)
plt.plot(result_activity['sum'], "-r")
plt.xticks(x, result_activity.date)

sns.set_style("dark")
result_activity
#plt.savefig('/path/'+folder+'/'+figure)
#plt.savefig('/path/toilet.pdf')
#plt.show()


import datetime
import time
import calendar
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from datetime import datetime, timedelta
from django import forms
from leave.models import LeavePlan, LeaveHoliday, LeaveEmployee, LeaveType, EmployeeInstance
from django.forms.widgets import HiddenInput
from django.contrib.auth.models import User
from decimal import Decimal
from django.db.models import Sum
from .rules import *
from django.utils.dateparse import parse_datetime
from django import forms
from django.template.defaultfilters import filesizeformat
from django.forms import Textarea

current_year = datetime.now().year
standard_start_working_hour = 0
standard_stop_working_hour = 23

class EmployeeM1247Form(forms.ModelForm):
    start_working_hour = 0
    stop_working_hour = 59
    hour_range = ((0,'00'),(1,'01'),(2,'02'),(3,'03'),(4,'04'),(5,'05'),(6,'06'),(7,'07'),(8,'08'),(9,'09'),(10,'10'),(11,'11'),(12,'12'),(13,'13'),(14,'14'),(15,'15'),(16,'16'),(17,'17'),(18,'18'),(19,'19'),(20,'20'),(21,'21'),(22,'22'),(23,'23'))
    minute_range = ((0,'00'),(30,'30'),(59,'59'))

    leave_type = forms.ModelChoiceField(label=_('Select Leave Type'), queryset=None, required=True)

    start_date = forms.DateField(label=_('Start'), required=True, error_messages={'required': 'กรุณาป้อนข้อมูลวันที่ลา'})
    start_hour = forms.IntegerField(widget=forms.Select(choices=hour_range))
    start_minute = forms.IntegerField(widget=forms.Select(choices=minute_range))

    end_date = forms.DateField(label=_('End'), required=True, error_messages={'required': 'กรุณาป้อนข้อมูลลาถึงวันที่'})
    end_hour = forms.IntegerField(widget=forms.Select(choices=hour_range))
    end_minute = forms.IntegerField(widget=forms.Select(choices=minute_range))

    employee_type = forms.CharField(required=False, widget=forms.HiddenInput(), initial="M1247")
    document = forms.FileField(required=False)
    leave_reason = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 2, 'cols': 20}), max_length=200)

    search_emp_id = forms.CharField(widget=forms.HiddenInput())

    class Meta:
        model = EmployeeInstance
        fields = ['start_date', 'end_date', 'leave_type', 'lve_act', 'lve_act_hr', 'document', 'leave_reason']

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(EmployeeM1247Form, self).__init__(*args, **kwargs)

        default_end_date =  datetime.now()+timedelta(days=1)
        self.fields['leave_type'].widget.attrs={'class': 'form-control'}
        self.fields['leave_type'].queryset=LeaveType.objects.filter(leaveplan__emp_id=self.user.username, leaveplan__lve_year=current_year)

        self.fields['start_date'].widget.attrs={'class': 'form-control datepicker border-bottom-1 border-left-0 rounded-0 bg-white'}
        self.initial['start_date'] = datetime.now().strftime("%Y-%m-%d")
        self.fields['start_date'].widget.attrs['placeholder'] = "YYYY-MM-DD"
        self.fields['start_hour'].widget.attrs={'class': 'form-control border-top-0 border-left-1 rounded-0 bg-white'}
        self.initial['start_hour'] = 8
        self.fields['start_minute'].widget.attrs={'class': 'form-control border-top-0 rounded-0 bg-white'}
        self.initial['start_minute'] = 0

        self.fields['end_date'].widget.attrs={'class': 'form-control datepicker border-bottom-1 border-left-0 rounded-0 bg-white'}
        self.initial['end_date'] = datetime.now().strftime("%Y-%m-%d") #default_end_date.strftime("%Y-%m-%d")
        self.fields['end_date'].widget.attrs['placeholder'] = "YYYY-MM-DD"
        self.fields['end_hour'].widget.attrs={'class': 'form-control border-top-0 border-left-1 rounded-0 bg-white'}
        self.initial['end_hour'] = 17
        self.fields['end_minute'].widget.attrs={'class': 'form-control border-top-0 rounded-0 bg-white'}
        self.initial['end_minute'] = 0

        self.fields['leave_reason'].widget.attrs={'class': 'form-control rounded-0'}

        self.initial['search_emp_id'] = ""

    def clean(self):
        datetime_format = "%Y-%m-%d %H:%M:%S"
        cleaned_data = super(EmployeeM1247Form, self).clean()

        leave_type = self.cleaned_data.get('leave_type')
        leave_type_id = self.data.get('leave_type')

        start_date = self.cleaned_data.get('start_date')
        start_hour = self.cleaned_data.get('start_hour')
        start_minute = self.cleaned_data.get('start_minute')

        end_date = self.cleaned_data.get('end_date')
        end_hour = self.cleaned_data.get('end_hour')
        end_minute = self.cleaned_data.get('end_minute')

        document = self.cleaned_data.get('document')
        if document is not None:
            document_type = document.content_type.split('/')[1]
            print("type:",  document_type)
            if document_type in settings.CONTENT_TYPES:
                if document.size > settings.MAX_UPLOAD_SIZE:
                    raise forms.ValidationError(_('ไฟล์แนบมีขนาดเกิน 5 เมกะไบท์'))
            else:
                raise forms.ValidationError(_('ระบบสามารถแนบไฟล์ (png, jpg, jpeg, pdf) ได้เท่านั้น'))

        # raise forms.ValidationError(_('Test'))

        search_emp_id = self.cleaned_data.get('search_emp_id')
        print("search_emp_id = ", search_emp_id)
        # username = self.user.username
        # username = search_emp_id
        employee_type = 'M1'

        d1 = str(start_date) + ' ' + str(start_hour) + ':' + str(start_minute) + ':00'
        d2 = str(end_date) + ' ' + str(end_hour) + ':' + str(end_minute) + ':00'
        start_date = datetime.strptime(d1, datetime_format)
        end_date = datetime.strptime(d2, datetime_format)

        if start_date != None:
            # ------------------------------------------------
            # Check master remaining hour (Leave_Plan table)
            # ------------------------------------------------
            leave_plan = LeavePlan.objects.filter(emp_id__exact=search_emp_id).filter(lve_id__exact=leave_type_id).filter(lve_year=current_year).values_list('lve_plan', flat=True).get()
            print("Plan111 : " + str(leave_plan))
            total_leave_quota_remaining_day = LeavePlan.objects.filter(emp_id__exact=search_emp_id).filter(lve_id__exact=leave_type_id).filter(lve_year=current_year).values_list('lve_miss', flat=True).get()
            print("remain day : " + str(total_leave_quota_remaining_day))
            total_leave_quota_remaining_hour = LeavePlan.objects.filter(emp_id__exact=search_emp_id).filter(lve_id__exact=leave_type_id).filter(lve_year=current_year).values_list('lve_miss_hr', flat=True).get()
            print("remain hour : " + str(total_leave_quota_remaining_hour))
            grand_total_leave_quota_remaining_hour = (total_leave_quota_remaining_hour + (total_leave_quota_remaining_day * 8))
            # 26d + 0h
            # 26 * 8 = 208
            print("total remain hour : " + str(grand_total_leave_quota_remaining_hour))

            # ------------------------------------------------
            # Check transaction remaing hour (leave_employeeinstance table) (filter status = p, a, F)
            # ------------------------------------------------
            total_pending_approve_syncfail_status_history_day = EmployeeInstance.objects.filter(emp_id__exact=search_emp_id).filter(leave_type_id__exact=leave_type_id).filter(status__in=('p','a')).aggregate(sum=Sum('lve_act'))['sum'] or 0
            print("sync day : " + str(total_pending_approve_syncfail_status_history_day))
            total_pending_approve_syncfail_status_history_hour = EmployeeInstance.objects.filter(emp_id__exact=search_emp_id).filter(leave_type_id__exact=leave_type_id).filter(status__in=('p','a')).aggregate(sum=Sum('lve_act_hr'))['sum'] or 0
            print("sync hour : " + str(total_pending_approve_syncfail_status_history_hour))
            grand_total_pending_approve_syncfail_status_history_hour = total_pending_approve_syncfail_status_history_hour + (total_pending_approve_syncfail_status_history_day * 8)
            # 25d + 16h
            # (25 * 8) + 16 = 216
            print("total sync hour : " + str(grand_total_pending_approve_syncfail_status_history_hour))

            grand_total_leave_quota_remaining_hour = grand_total_leave_quota_remaining_hour - grand_total_pending_approve_syncfail_status_history_hour
            print("grand : " + str(grand_total_leave_quota_remaining_hour))

            # ------------------------------------------------
            # Check Standard Business Rules
            # ------------------------------------------------
            found_standard_error = checkM1247StandardBusinessRules(start_date, end_date, leave_type_id)
            if found_standard_error[0]:
                raise forms.ValidationError(_(found_standard_error[1]))

            # ------------------------------------------------
            # Check M1247 Business Rules
            # ------------------------------------------------
            found_m1247_error = checkM1247BusinessRules('M1247', start_date, end_date, leave_type_id)
            if found_m1247_error[0]:
                raise forms.ValidationError(found_m1247_error[1])
            else:
                total_leave_request_hour = found_m1247_error[1]

            #raise forms.ValidationError(total_leave_request_hour)
            print(str(total_leave_request_hour) + " : total_leave_request_hour")
            print(str(grand_total_leave_quota_remaining_hour) + " : 1grand_total_leave_quota_remaining_hour")

            # RULE 1: Check not over leave quota
            # print("rule1", total_leave_request_hour, grand_total_leave_quota_remaining_hour, "TEST")

            if (total_leave_request_hour) > grand_total_leave_quota_remaining_hour:
                raise forms.ValidationError(_("เลือกวันเกินจำนวนสิทธิ์ที่กำหนด"))
            else:
                if grand_total_leave_quota_remaining_hour <= 0:
                    raise forms.ValidationError(_("ใช้วัน" + str(leave_type) + "หมดแล้ว"))

            # RULE 2: Check duplicate leave
            #select id from leave_employeeinstance where not (start_date > @end_date OR end_date < @start_date)
            sql = "select id from leave_employeeinstance where not (start_date > '" + str(end_date.strftime("%Y-%m-%d %H:00") + "' or end_date < '" + str(start_date.strftime("%Y-%m-%d %H:01")) + "')") + " and emp_id=" + search_emp_id + " and status in ('a','p','C','F')"
            print(sql)
            print(search_emp_id, start_date, end_date)
            queryset = EmployeeInstance.objects.raw("select id from leave_employeeinstance where not (start_date > '" + str(end_date.strftime("%Y-%m-%d %H:00") + "' or end_date < '" + str(start_date.strftime("%Y-%m-%d %H:01")) + "')") + " and emp_id=" + search_emp_id + " and status in ('a','p','C','F')")
            if len(queryset) > 0:
                raise forms.ValidationError(_("วันที่ " + str(start_date) + " - " + str(end_date) + " มีการลาไปแล้ว"))

            # RULE 3: Check public holidays
            if checkLeaveTypeIncludePublicHoliday(leave_type_id):
                queryset = LeaveHoliday.objects.filter(hol_date__range=(start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d"))).values_list('pub_th', flat=True)
                holiday_list = str(list(queryset)).replace("'", '')
                if len(queryset) > 0:
                    #raise forms.ValidationError({'start_date': "เลือกวันลาตรงกับวันหยุด - " + str(holiday_list)})
                    raise forms.ValidationError(_("ช่วงวันลาตรงกับวันหยุดนักขัตฤกษ์ - " + str(holiday_list)))

            # RULE 4: Check not allow over month
            if(checkLeaveRequestOverMonth("M1", start_date, end_date)):
                #raise forms.ValidationError({'start_date': "เลือกวันลาข้ามเดือน"})
                raise forms.ValidationError(_("ไม่สามารถเลือกวันลาข้ามเดือน กรุณาแบ่งทำ 2 รายการแยกเดือนกัน"))

        return cleaned_data


#!/usr/bin/env python

"Internet Time Protocol - TCP server"

import socket
import logging
import time
import struct

logging.basicConfig(level=logging.INFO)

HOSTNAME='localhost'
PORT=3737
TIME1970 = 2208988800

def main():
    service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    service.bind((HOSTNAME, PORT))
    service.listen(1)
    logging.info("NTP Server accepting connections on port %d" % PORT)

    while True:
        channel, info = service.accept()
        logging.info("New client connection from '%s'" % info[0])
        t = int(time.time()) + TIME1970
        logging.info("Current timestamp is %d" % t)
        t = struct.pack("!I", t)
        channel.send(t)
        channel.close()
        logging.info("Connection closed")

if __name__ == '__main__':
    main()


import logging
from followthemoney import model
from servicelayer.worker import Worker
from servicelayer.jobs import JobStage as Stage

from ingestors.manager import Manager

log = logging.getLogger(__name__)

class IngestWorker(Worker):
    """A long running task runner that uses Redis as a task queue"""

    def dispatch_next(self, stage, context, entities):
        next_stage = context.get('next_stage')
        if next_stage is None:
            return
        next_queue = Stage(stage.conn,
                           next_stage,
                           stage.job.id,
                           stage.dataset,
                           priority=stage.priority)
        log.info("Sending %s entities to: %s", len(entities), next_stage)
        for entity_id in entities:
            next_queue.queue_task({'entity_id': entity_id}, context)

    def handle(self, stage, payload, context):
        manager = Manager(stage, context)
        entity = model.get_proxy(payload)
        log.debug("Ingest: %r", entity)
        manager.ingest_entity(entity)
        manager.close()
        self.dispatch_next(stage, context, manager.emitted)


#from Codepoints import LINE_FEED
LINE_FEED = 10

#! with or without lineends
class CodePointIterator:
    '''
    Iterate codepoints from some Source.

    Should:
    ++
    - return unicode codepoints
    - Right strip and replaces linends with (Linuxy) cp = 10
    - throw StopIteration
    - do any tidy, such as file descriptor closing
    +
    Returned streams will include line ends.
    Line ends will be unified to a single codepoint,
    Codepoints.LINE_FEED.
    '''
    def __iter__(self):
        return self

# The problem is, doesn't close files on exception
class FileIteratorUnstripped(CodePointIterator):
    '''
    Much simpler than the usual FileIterator, but bulk loads whole file
    and will not rstrip()
    '''
    #NB Changes the syntax from read-a-char
    # to __next__-for-a-char iteration
    def __init__(self, path):
        self.path = path
        self.fd = open(path, 'r')
        line = self.fd

    def __next__(self):
        c = None
        c = self.fd.read(1)
        if (not c):
            self.fd.close()
            raise StopIteration
        return ord(c)

# The problem is, doesn't close files on exception
class FileIteratorByLine(CodePointIterator):
    #NB Changes the syntax from read-a-char
    # to __next__-for-a-char iteration
    def __init__(self, path):
        self.path = path
        self.fd = open(path, 'r')
        self.loadNewLine()

    def loadNewLine(self):
        self.line = self.fd.readline()
        if (self.line == ''):
            self.fd.close()
            raise StopIteration
        # ensuring newline
        self.line = self.line.rstrip()
        self.line += chr(LINE_FEED)
        self.charNum = 0
        self.lineCharLen = len(self.line)

    def __next__(self):
        if(self.charNum >= self.lineCharLen):
            self.loadNewLine()
        c = self.line[self.charNum]
        self.charNum += 1
        return ord(c)

class FileIterator(CodePointIterator):
    #NB Changes the syntax from read-a-char
    # to __next__-for-a-char iteration
    def __init__(self, path):
        self.path = path
        self.lineNum = -1
        self.cpNum = 0
        with open(path, 'r') as f:
            self.lineList = f.readlines()
        self.linesLen = len(self.lineList)
        self.lineCPLen = 0
        self.loadNewLine()

    def loadNewLine(self):
        self.lineNum += 1
        if (self.lineNum >= self.linesLen):
            raise StopIteration
        self.line = self.lineList[self.lineNum]
        # ensuring newline
        self.line = self.line.rstrip()
        self.line += chr(LINE_FEED)
        self.cpNum = 0
        self.lineCPLen = len(self.line)

    def __next__(self):
        if(self.cpNum >= self.lineCPLen):
            self.loadNewLine()
        c = self.line[self.cpNum]
        self.cpNum += 1
        return ord(c)

#$ Clumsy for Python, but keeping it generic.
class StringIterator(CodePointIterator):

    def __init__(self, line):
        # ensuring newline
        self.line = line.rstrip()
        self.line += chr(LINE_FEED)
        self.i = 0
        self.lineLen = len(self.line)

    def __next__(self):
        if (self.i >= self.lineLen):
            raise StopIteration
        else:
            r = ord(self.line[self.i])
            self.i += 1
            return r

class StringsIterator(CodePointIterator):

    def __init__(self, strings):
        assert (len(strings) > 0), "supplied 'strings' data has no content"
        self.strings = strings
        # ensure line ends
        self.strings = [line.rstrip() + chr(LINE_FEED) for line in self.strings]
        self.lineI = 0
        self.line = self.strings[0]
        self.linesLen = len(self.strings)
        self.cpI = 0
        self.lineLen = len(self.line)

    def _nextLine(self):
        self.lineI += 1
        if (self.lineI >= self.linesLen):
            raise StopIteration
        self.line = self.strings[self.lineI]
        self.lineLen = len(self.line)
        self.cpI = 0

    def __next__(self):
        if (self.cpI >= self.lineLen):
            self._nextLine()
        r = ord(self.line[self.cpI])
        self.cpI += 1
        return r