'''MIT License

Copyright (c) 2018 Marcel Meisner (Irrgeist)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''

import bpy
from .helper import Helper
from .operators import OperatorImportAppLink
from .operators import OperatorExportAppLink
from .operators import OperatorNewPBRMaterial
from .operators import OperatorSelectImage

class GUIProperties(bpy.types.PropertyGroup):

    export_mode = bpy.props.EnumProperty(name='Export type',
                                         items=(('ppp', 'Per-pixel painting', "Loads the mesh into 3DC's paint room for per-pixel painting"),
                                                ('mv', 'Microvertex painting', "Loads the mesh into 3DC's paint room for microvertex painting"),
                                                ('ptex', 'Ptex painting', "Loads the mesh into 3DC's paint room for Ptex painting"),
                                                ('uv', 'UV-mapping', "Loads the mesh into the UV room for UV-mapping"),
                                                ('ref', 'Reference mesh', "Loads the mesh as a reference object into 3DC"),
                                                ('retopo', 'Retopo mesh (new layer)', "Loads the mesh as a new layer into the Retopo room"),
                                                ('vox', 'Voxel object', "Loads the mesh as a voxel object into 3DC"),
                                                ('voxcombine','Single voxel object (merge all)', "Loads the mesh into 3DC as a single voxel object, all objects will be merged together in one volume"),
                                                ('alpha', 'New pen alpha', "Loads the mesh as a new pen alpha into 3DC"),
                                                ('prim', 'Voxel primitive', "Loads the mesh as a new merging primitve for voxels"),
                                                ('curv', 'Curve profile', "Loads the mesh as a curve profile into 3DC"),
                                                ('autopo', 'Auto-retopology', "Loads the mesh into the Retopo room for AUTOPO")
                                                ),
                                            default='ppp'
                                         )

    export_workflow = bpy.props.EnumProperty(name='Workflow type',
                                         description='Choose the PBR workflow for texture',
                                         items=(('metalness', 'Metalness/Roughness', 'Used Maps: color, metalness, roughness, normal, emissive'),
                                                ('manual', 'Manual', '3D-Coat will ask on import/export'),
                                                ),
                                        default='metalness'
                                         )

    color_map = bpy.props.StringProperty(
                                    name="File Path",
                                    description="Albedo/Color Map",
                                    maxlen=255,
                                    subtype='FILE_PATH',
                                    default=Helper.supported_images(),
                                    )

    metal_map = bpy.props.StringProperty(
                                    name="File Path",
                                    description="Metalness Map",
                                    maxlen=255,
                                    subtype='FILE_PATH',
                                    default=Helper.supported_images(),
                                    )

    rough_map = bpy.props.StringProperty(
                                    name="File Path",
                                    description="Roughness Map",
                                    maxlen=255,
                                    subtype='FILE_PATH',
                                    default=Helper.supported_images(),
                                    )

    normal_map = bpy.props.StringProperty(
                                    name="File Path",
                                    description="Normal Map",
                                    maxlen=255,
                                    subtype='FILE_PATH',
                                    default=Helper.supported_images(),
                                    )

    emissive_map = bpy.props.StringProperty(
                                    name="File Path",
                                    description="Emissive Map",
                                    maxlen=255,
                                    subtype='FILE_PATH',
                                    default=Helper.supported_images(),
                                    )
# Create main panel and layout
class AppLink3DCoatPanel(bpy.types.Panel):
    '''3D-Coat AppLink panel for Blender'''

    bl_idname = 'OBJECT_PT_applink_3dcoat_panel'
    bl_label = 'AppLink'
    bl_category = '3D-Coat'
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_context = 'objectmode'

    def draw(self, context):
        layout = self.layout
        props = bpy.context.scene.irrgeist_3dc

        sel_obj = Helper.get_selected_mesh(context)
        object_name = sel_obj.name if Helper.is_mesh(sel_obj, context) else None
        has_exchange_folder = Helper.pref_exchange_directory() != ''

        box = layout.box()
        #   Title/Description
        row = box.row()
        if object_name and has_exchange_folder:
            row.label(text='Transfer "' + object_name + '" from/to 3D-Coat')
        elif has_exchange_folder:
            row.label(text='Select a mesh to transfer from/to 3D-Coat')
        else:
            row.label(text='Set exchange folder in the add-on preferences')

        # Export type selection box
        row = box.row()
        row.prop(props, 'export_mode', text='')

        # PBR workflow selection
        row = box.row()
        row.prop(props, 'export_workflow', text='', icon='TEXTURE_SHADED')

        # Buttons for triggering import
        row = box.row(align=True)
        row.operator('pilgway.3dcoat_import', text='Import', icon='IMPORT')
        row.operator('pilgway.3dcoat_export', text='Export', icon='EXPORT')
        row.enabled = object_name != None and has_exchange_folder

        # Create New PBR material to use in Blender
        box = layout.box()
        row = box.row()
        row = box.row()
        if object_name and has_exchange_folder:
            row.label(text='Create new PBR material for "' + object_name + '"')
        elif has_exchange_folder:
            row.label(text='Select a mesh to create a new material')
        else:
            row.label(text='Set exchange folder in the add-on preferences')

        # row = box.row()
        # row.prop(props, 'color_map', text='Color', icon='TEXTURE')

        # row = box.row()
        # row.prop(props, 'metal_map', text='Metalness', icon='TEXTURE')

        # row = box.row()
        # row.prop(props, 'rough_map', text='Roughness', icon='TEXTURE')

        # row = box.row()
        # row.prop(props, 'normal_map', text='Normal', icon='TEXTURE')

        # row = box.row()
        # row.prop(props, 'emissive_map', text='Emissive', icon='TEXTURE')

        #props = layout.operator(OperatorSelectImage.bl_idname)

        row = box.row()
        row.operator('pilgway.3dcoat_new_material', text='Create new material', icon='MATERIAL')
        row.enabled = object_name != None and has_exchange_folder


"""
Profile groupfitter

See where the bulk of computation occurs.

Examples on how to profile with python
https://docs.python.org/2/library/profile.html
"""

import cProfile
import logging
import numpy as np
import pstats
import sys

sys.path.insert(0, '..')
from chronostar.synthdata import SynthData
from chronostar import tabletool
from chronostar import compfitter

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, filename='compfitter.log')
    save_dir = ''
    group_savefile = save_dir + 'origins_stat.npy'
    xyzuvw_init_savefile = save_dir + 'xyzuvw_init_stat.npy'
    astro_savefile = save_dir + 'astro_table_stat.txt'
    xyzuvw_conv_savefile = save_dir + 'xyzuvw_conv_stat.fits'

    pars = np.array([0., 0., 0., 0., 0., 0., 5., 2., 1e-8])
    starcount = 100
    error_frac = 1.
    synth_data = SynthData(pars=pars, starcounts=starcount)
    synth_data.synthesise_everything()
    tabletool.convert_table_astro2cart(synth_data.table)
    data = tabletool.build_data_dict_from_table(synth_data.table)

    stat_file = 'compfitter.stat'
    # best_fit, chain, lnprob = \
    cProfile.run(
        "compfitter.fit_comp(data=data, plot_it=True,"
        "convergence_tol=2., burnin_steps=400, plot_dir='',"
        "save_dir='')",
        stat_file,
    )

    stat = pstats.Stats(stat_file)
    stat.sort_stats('cumtime')
    stat.print_stats(0.3)


import mne
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt

# read the epoch data
epo = np.load("./epo_noref.npy")
n_p, n_conds, n_chan, n_t = epo.shape
pids = range(n_p)

# define the times
t = np.linspace(-0.1, 0.7, n_t)

# compute the neural difference score
X = epo[:, (0, 2)].mean(1) - epo[:, (1, 3)].mean(1)

# read the behavioral data
behav = np.genfromtxt("valence_scores.csv", dtype=None, names=True,
                      delimiter=',')

# compute the behavioral difference score
neu = behav[behav['valence'] == 'neutral']['score']
neg = behav[behav['valence'] == 'negative']['score']
y = (neu - neg) / 48.

# setup the regression
svr = SVR(kernel="linear", C=10**-10)

# setup empty array of scores
R = np.zeros((n_p, n_t))

# loop through the times
for ti in range(n_t):

    # get the channel data
    x = X[:, :, ti]

    # loop through the participants
    for pi in pids:
        # get the training and testing indices
        ix_test = np.in1d(pids, pi)
        ix_train =  np.logical_not(ix_test)

        # get the training and testing values
        y_test = y[ix_test]
        y_train = y[ix_train]

        x_test = x[ix_test]
        x_train = x[ix_train]

        # fit the svm
        svr.fit(x_train, y_train)

        # score the svm
        y_pred = svr.predict(x_test)
        R[pi, ti] = (y_test - y_pred)**2

ax = plt.axes()
ax.plot(t, R.mean(0))
ax.fill_between(t, R.mean(0) - R.std(0) / np.sqrt(n_p),
                R.mean(0) + R.std(0) / np.sqrt(n_p), alpha=0.3)

plt.show()


import psutil
import time
import opentracing
import sys
import requests
import argparse
import logging

# log everything with no format, because these messages will be formatted
# and printed by the controller
logging.basicConfig(format='%(message)s', level=logging.DEBUG)

MEMORY_PERIOD = 1  # report memory use every 5 seconds
CONTROLLER_PORT = 8023
NUM_SATELLITES = 8
MAX_BUFFERED_SPANS = 10000
REPORTING_PERIOD = 200  # ms
SPANS_PER_LOOP = 6

def do_work(units):
    i = 1.12563
    for i in range(0, units):
        i *= i

def send_result(result):
    requests.get(f'http://localhost:{CONTROLLER_PORT}/result', params=result)

class Monitor:
    """ Special timer to measure process time and time spent as a result of
    this process' system calls.

    Records 2 * 10^-5 seconds when we immediately run start() then stop(), so
    tests should be at ms scale to dwarf this contribution.
    """
    def __init__(self):
        self.process = psutil.Process()

    def get_memory(self):
        """ Returns the size of process virtual memory """
        return self.process.memory_info()[0]

    def start(self):
        user, system, _, _ = self.process.cpu_times()
        self.start_cpu_time = user + system
        self.start_clock_time = time.time()
        self.get_cpu()

    def get_cpu(self):
        """ Gets CPU %, calculated since last call to split. """
        return self.process.cpu_percent(interval=None)

    def stop(self):
        user, system, _, _ = self.process.cpu_times()
        return (user + system - self.start_cpu_time,
                time.time() - self.start_clock_time)

def build_tracer(command, tracer_name, port):
    if command['Trace'] and tracer_name == "vanilla":
        logging.info("We're using the python tracer.")
        import lightstep
        return lightstep.Tracer(
            component_name='isaac_service',
            collector_port=port,
            collector_host='localhost',
            collector_encryption='none',
            use_http=True,
            access_token='developer',
            # these are much more aggressive than the defaults
            # but are common in production
            periodic_flush_seconds=REPORTING_PERIOD / 1000,
            max_span_records=MAX_BUFFERED_SPANS,
        )
    elif command['Trace'] and tracer_name == "cpp":
        logging.info("We're using the python-cpp tracer.")
        import lightstep_native
        return lightstep_native.Tracer(
            component_name='isaac_service',
            access_token='developer',
            use_stream_recorder=True,
            collector_plaintext=True,
            satellite_endpoints=[{'host': 'localhost', 'port': p}
                                 for p in range(port, port + NUM_SATELLITES)],
            max_buffered_spans=MAX_BUFFERED_SPANS,
            reporting_period=REPORTING_PERIOD,
        )

    logging.info("We're using a NoOp tracer.")
    return opentracing.Tracer()

def generate_spans(tracer, units_work, number_spans, scope=None):
    assert number_spans >= 1

    # since python-cpp tracer doesn't allow child_of=None
    child_of_kwargs = {'child_of': scope.span} if scope else {}

    with tracer.start_active_span(
            operation_name='make_some_request',
            **child_of_kwargs) as client_scope:

        client_scope.span.set_tag('http.url', 'http://somerequesturl.com')
        client_scope.span.set_tag('http.method', "POST")
        client_scope.span.set_tag('span.kind', 'client')
        do_work(units_work)
        number_spans -= 1
        if number_spans == 0:
            return

        with tracer.start_active_span(
                operation_name='handle_some_request') as server_scope:
            server_scope.span.set_tag('http.url', 'http://somerequesturl.com')
            server_scope.span.set_tag('span.kind', 'server')
            server_scope.span.log_kv({
                'event': 'cache_miss',
                'message': 'some cache missed :('
            })

            do_work(units_work)
            number_spans -= 1
            if number_spans == 0:
                return

            with tracer.start_active_span(
                    operation_name='database_write') as db_scope:
                db_scope.span.set_tag('db.user', 'test_user')
                db_scope.span.set_tag('db.type', 'sql')
                db_scope.span.set_tag(
                    'db_statement',
                    "UPDATE ls_employees SET email = 'isaac@lightstep.com' " +
                    "WHERE employeeNumber = 27;")

                # pretend that an error happened
                db_scope.span.set_tag('error', True)
                db_scope.span.log_kv({
                    'event': 'error',
                    'stack': """File \"example.py\", line 7, in <module>
                                caller()
                                File \"example.py\", line 5, in caller
                                callee()
                                File \"example.py\", line 2, in callee
                                raise Exception(\"Yikes\")"""})

                do_work(units_work)
                number_spans -= 1
                if number_spans == 0:
                    return

            generate_spans(tracer, units_work,
                           number_spans, scope=server_scope)

def perform_work(command, tracer_name, port):
    logging.info("About to run this test: {}".format(command))
    logging.info("Connecting to satellite on port {}".format(port))

    # if exit is set to true, end the program
    if command['Exit']:
        send_result({})
        logging.info("sent exit response, now exiting...")
        sys.exit()

    tracer = build_tracer(command, tracer_name, port)

    sleep_debt = 0
    spans_sent = 0

    last_memory_save = time.time()
    memory_list = []
    cpu_list = []

    monitor = Monitor()
    monitor.start()

    while spans_sent < command['Repeat']:
        spans_to_send = min(command['Repeat'] - spans_sent, SPANS_PER_LOOP)
        generate_spans(tracer, command['Work'], spans_to_send)
        spans_sent += spans_to_send
        sleep_debt += command['Sleep'] * spans_to_send

        if sleep_debt > command['SleepInterval']:
            sleep_debt -= command['SleepInterval']
            # 10^-9 nanoseconds / second
            time.sleep(command['SleepInterval'] * 10**-9)

        if time.time() > last_memory_save + MEMORY_PERIOD:
            memory_list.append(monitor.get_memory())
            # saves CPU percentage as fraction since last call
            cpu_list.append(monitor.get_cpu() / 100)
            last_memory_save = time.time()

    memory_list.append(monitor.get_memory())

    # don't include flush in time measurement
    if command['Trace'] and not command['NoFlush']:
        logging.info("Flushing spans.")
        tracer.flush()

    cpu_time, clock_time = monitor.stop()

    result = {
        'ProgramTime': cpu_time,
        'ClockTime': clock_time,
        'SpansSent': spans_sent,
        'MemoryList': memory_list,
        'CPUList': cpu_list,
    }

    logging.info("Sending result to controller:")
    logging.info(result)
    send_result(result)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Start a client to test a LightStep tracer.')

    parser.add_argument(
        'port',
        type=int,
        help='Which port to connect to the satellite on.')

    parser.add_argument(
        'tracer',
        type=str,
        choices=["vanilla", "cpp"],
        help='Which LightStep tracer to use.')

    args = parser.parse_args()

    while True:
        r = requests.get(f'http://localhost:{CONTROLLER_PORT}/control')
        perform_work(r.json(), args.tracer, args.port)


import nltk # refers to NATURAL LANGUAGE TOOLKIT
import warnings
import random

warnings.filterwarnings("ignore")

# nltk.download() # for downloading packages
# nltk.download('punkt') #first-time use only
# nltk.download('wordnet') #first-time use only

"""              small greeting function                """

GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up", "hey",)
GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]

# Checking for greetings
def greeting(sentence):
    """If user's input is a greeting, return a greeting response"""
    for word in sentence.split():
        if word.lower() in GREETING_INPUTS:
            return random.choice(GREETING_RESPONSES)

""" getres function to give the queried result from wiki
    there's use of little pre-text processing (you can learn online how to do that)
     i know it can be improved further , but yeah try another queries to see at least it is working"""

def getres(user_response):
    # split into words
    tokens = nltk.word_tokenize(user_response)
    # convert to lower case
    tokens = [w.lower() for w in tokens]
    # remove punctuation from each word
    import string
    table = str.maketrans('', '', string.punctuation)
    stripped = [w.translate(table) for w in tokens]
    # remove remaining tokens that are not alphabetic
    words = [word for word in stripped if word.isalpha()]
    # filter out stop words
    from nltk.corpus import stopwords
    stop_words = set(stopwords.words('english'))
    words = [w for w in words if not w in stop_words]
    try:
        import wikipedia
        document = wikipedia.summary(words, sentences=5)
        return document
    except Exception as e:
        print("type query precisely "+str(e))

flag = True
print("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye or to make "
      "automatic review just type 'review'")

while (flag == True):
    user_response = input("YOU:")
    user_response = user_response.lower()
    if (user_response != 'bye'):
        if (user_response == 'thanks' or user_response == 'thank you'):
            flag = False
            print("ROBO: You are welcome..")
        else:
            if (greeting(user_response) != None):
                print("ROBO: " + greeting(user_response))
            else:
                if(user_response=="review"):
                    import review
                    review.review_writer()
                else:
                    print("ROBO: ", end="")
                    getres(user_response)
                    print(getres(user_response))
    else:
        flag = False
        print("ROBO: Bye! take care..")


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('redheart', '0002_auto_20160606_2339'),
    ]

    operations = [
        migrations.RenameField(
            model_name='counter',
            old_name='LikeUser',
            new_name='username',
        ),
        migrations.RemoveField(
            model_name='userprofile',
            name='iconic_image',
        ),
        migrations.RemoveField(
            model_name='userprofile',
            name='like',
        ),
        migrations.AddField(
            model_name='counter',
            name='iconic_image',
            field=models.ImageField(upload_to=b'iconic_image', blank=True),
        ),
        migrations.AddField(
            model_name='counter',
            name='like',
            field=models.IntegerField(default=0),
        ),
    ]


import socket
import json
import threading
import time

def look_for_slave():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(('', 0))
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    while not slave_founded:
        diagnostics.debug("trying find slave on %s" % PORT)
        s.sendto(CONNECTION_REQUEST, ('<broadcast>', PORT))
        time.sleep(5)

def wait_for_slave():
    global slave_founded, SLAVE_IP

    while True:
        data, addr = udp.recvfrom(1024)

        if (data == CONNECTION_ACCEPTED):
            diagnostics.debug("slave founded")
            slave_founded = True
            SLAVE_IP = addr[0]
            break

    run()

def run():
    while True:
        update()
        time.sleep(0.015)

def update():
    statuses = getStatusForXboxControls([xbox1, xbox2])
    data = json.dumps(statuses)

    udp.sendto(data, (SLAVE_IP, PORT))

def getStatusForXboxControls(controls):
    return [getXboxStatus(control) for control in controls]

def getXboxStatus(xbox):
    status = {}

    status["a"] = xbox.a
    status["b"] = xbox.b
    status["x"] = xbox.x
    status["y"] = xbox.y

    status["rb"] = xbox.rightShoulder
    status["rt"] = xbox.rightTrigger
    status["lb"] = xbox.leftShoulder
    status["lt"] = xbox.leftTrigger

    status["up"] = xbox.up
    status["down"] = xbox.down
    status["right"] = xbox.right
    status["left"] = xbox.left

    status["lth"] = xbox.rightThumb
    status["rth"] = xbox.leftThumb

    status["rx"] = xbox.rightStickX
    status["ry"] = xbox.rightStickY
    status["lx"] = xbox.leftStickX
    status["ly"] = xbox.leftStickY

    status["back"] = xbox.back
    status["start"] = xbox.start

    return status

if starting:

    CONNECTION_REQUEST = "REMOTEPADCONNECTIONREQUEST"
    CONNECTION_ACCEPTED = "REMOTEPADCONNECTIONACCEPTED"
    MASTER_IP = socket.gethostbyname(socket.gethostname())
    SLAVE_IP = ""
    PORT = 6060

    xbox1 = xbox360[0]
    xbox2 = xbox360[1]
    slave_founded = False

    udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp.bind((MASTER_IP, PORT))

    t1 = threading.Thread(target=look_for_slave)
    t2 = threading.Thread(target=wait_for_slave)

    t1.setDaemon(True)
    t2.setDaemon(True)

    t1.start()
    t2.start()


from __future__ import absolute_import
import sys
sys.path.append('./')

import argparse
import os
import os.path as osp
import numpy as np
import math
import time
from PIL import Image, ImageFile

import torch
from torch import nn, optim
from torch.backends import cudnn
from torch.utils.data import DataLoader
from torchvision import transforms

from config import get_args
from lib import datasets, evaluation_metrics, models
from lib.models.model_builder import ModelBuilder
from lib.datasets.dataset import LmdbDataset, AlignCollate
from lib.loss import SequenceCrossEntropyLoss
from lib.trainers import Trainer
from lib.evaluators import Evaluator
from lib.utils.logging import Logger, TFLogger
from lib.utils.serialization import load_checkpoint, save_checkpoint
from lib.utils.osutils import make_symlink_if_not_exists
from lib.evaluation_metrics.metrics import get_str_list
from lib.utils.labelmaps import get_vocabulary, labels2strs

global_args = get_args(sys.argv[1:])

def image_process(img, imgH=32, imgW=100, keep_ratio=False, min_ratio=1):
  if keep_ratio:
    w, h = img.size
    ratio = w / float(h)
    imgW = int(np.floor(ratio * imgH))
    imgW = max(imgH * min_ratio, imgW)

  img = img.resize((imgW, imgH), Image.BILINEAR)
  img = transforms.ToTensor()(img)
  img.sub_(0.5).div_(0.5)

  return img

class DataInfo(object):
  """
  Save the info about the dataset.
  This a code snippet from dataset.py
  """
  def __init__(self, voc_type):
    super(DataInfo, self).__init__()
    self.voc_type = voc_type

    assert voc_type in ['LOWERCASE', 'ALLCASES', 'ALLCASES_SYMBOLS']
    self.EOS = 'EOS'
    self.PADDING = 'PADDING'
    self.UNKNOWN = 'UNKNOWN'
    self.voc = get_vocabulary(voc_type, EOS=self.EOS, PADDING=self.PADDING, UNKNOWN=self.UNKNOWN)
    self.char2id = dict(zip(self.voc, range(len(self.voc))))
    self.id2char = dict(zip(range(len(self.voc)), self.voc))

    self.rec_num_classes = len(self.voc)

def recognizer(img_path, gt_path, model, device, dataset_info,
               savedir="outputs/", only_price=False):
    gt_file = open(gt_path, "r")

    save_filename = os.path.basename(gt_path)
    save_path = os.path.join(savedir, save_filename)

    if not os.path.isdir(savedir):
      os.mkdir(savedir)

    fp = open(save_path, "w")

    bounding_boxes = [[int(coord) if coord.isnumeric() else coord
                       for coord in bbox.split('\n')[0].split(',', 8)]
                      for bbox in gt_file.readlines()]

    img = Image.open(img_path)
    img_width, img_height = img.width, img.height

    for bbox in bounding_boxes:
        label = bbox[8]

        if only_price and not type(label) == int and len(label) == 1:
            continue

        x1, y1 = bbox[0], bbox[1]
        x2, y2 = bbox[2], bbox[3]
        x3, y3 = bbox[4], bbox[5]
        x4, y4 = bbox[6], bbox[7]

        cropped_img = img.crop((x1, y3, x2, y1))

        cropped_img = image_process(cropped_img.convert('RGB'))

        with torch.no_grad():
            cropped_img = cropped_img.to(device)

        input_dict = {}
        input_dict['images'] = cropped_img.unsqueeze(0)

        rec_targets = torch.IntTensor(1, args.max_len).fill_(1)
        rec_targets[:, args.max_len - 1] = dataset_info.char2id[
          dataset_info.EOS]

        input_dict['rec_targets'] = rec_targets
        input_dict['rec_lengths'] = [args.max_len]

        output_dict = model(input_dict)
        pred_rec = output_dict['output']['pred_rec']
        pred_str, _ = get_str_list(pred_rec, input_dict['rec_targets'],
                                   dataset=dataset_info)

        pred_label = pred_str[0]
        print('Recognition result: {0}'.format(pred_label))

        txt_line = "{},{},{},{},{},{},{},{},{}\n".format(x1, y1, x2, y2,
                                                         x3, y3, x4, y4,
                                                         pred_label)
        fp.write(txt_line)
    fp.close()

def main(args):
  np.random.seed(args.seed)
  torch.manual_seed(args.seed)
  torch.cuda.manual_seed(args.seed)
  torch.cuda.manual_seed_all(args.seed)
  cudnn.benchmark = True
  torch.backends.cudnn.deterministic = True

  args.cuda = args.cuda and torch.cuda.is_available()
  if args.cuda:
    print('using cuda.')
    torch.set_default_tensor_type('torch.cuda.FloatTensor')
  else:
    torch.set_default_tensor_type('torch.FloatTensor')

  # Create data loaders
  if args.height is None or args.width is None:
    args.height, args.width = (32, 100)

  dataset_info = DataInfo(args.voc_type)

  # Create model
  model = ModelBuilder(arch=args.arch, rec_num_classes=dataset_info.rec_num_classes,
                       sDim=args.decoder_sdim, attDim=args.attDim, max_len_labels=args.max_len,
                       eos=dataset_info.char2id[dataset_info.EOS], STN_ON=args.STN_ON)

  # Load from checkpoint
  if args.resume:
    checkpoint = load_checkpoint(args.resume)
    model.load_state_dict(checkpoint['state_dict'])

  if args.cuda:
    device = torch.device("cuda")
    model = model.to(device)
    model = nn.DataParallel(model)

  # Evaluation
  model.eval()
  images_path = args.images_path
  box_path = args.box_path
  imgs = os.listdir(images_path)

  for img in imgs:
      image_path = os.path.join(images_path, img)

      print("Image path:", image_path)

      gt_name = img.replace('jpg', 'txt')
      gt_path = os.path.join(box_path, gt_name)

      recognizer(image_path, gt_path, model, device, dataset_info,
       savedir="outputs/", only_price=False)

if __name__ == '__main__':
  # parse the config
  args = get_args(sys.argv[1:])
  main(args)


import random
import json
import string

from solariat_bottle.tests.base import BaseCase, RestCase

from solariat_bottle.db.lpage import LandingPage

URL = 'http://www.solariat.com'

class LPageDbTest(BaseCase):
    def test_create_delete(self):
        lpage = LandingPage.objects.create_by_user(
            self.user, url=URL)
        self.assertEqual(
            LandingPage.objects.count(), 1)
        lpage.delete_by_user(self.user)
        self.assertEqual(
            LandingPage.objects.count(), 0)

class LPageRestTest(RestCase):

    def create(self, url=None):
        if url is None:
            url = URL
        return self.do_post('landingpages', version='v1.2', url = url)

    def test_create(self):
        " correct creation should return json with ok = True and UUID "
        resp = self.do_post('landingpages', version='v1.2', url = URL)
        self.assertEqual(resp['ok'], True)
        self.assertEqual(resp['item']['url'], URL)
        self.assertEqual(resp['item']['display_field'], None)

    def test_create_duplicate(self):
        """ create more than one landingpage with
        the same url should return json with ok = False

        """
        resp1 = self.create(URL)
        resp2 = self.create(URL)
        self.assertTrue(resp1['ok'])
        self.assertFalse(resp2['ok'])

    def test_bad_json(self):
        "raise error on bad formed json filter parameter"
        self.create("foo")
        resp = self.client.get(
            '/api/v1.2/landingpages?token=%s' % self.auth_token,
            data = "{'url':'baz}",
            content_type='application/json')
        data = json.loads(resp.data)
        self.assertFalse(data['ok'])

    def test_get(self):
        "should return 0 or 1 for specific url"
        self.create('foo')
        self.create('bar')

        resp = self.do_get('landingpages', version='v1.2', url='foo')
        self.assertTrue(resp['ok'])
        self.assertEqual(len(resp['list']), 1)

        resp = self.do_get('landingpages', version='v1.2', url='baz')
        self.assertEqual(len(resp['list']), 0)

    def test_get_specific(self):
        " get specific landingpage "

        urls_count = random.randint(5, 10)
        for i in xrange(urls_count):
            self.create(URL + '/' + str(i))

        url = URL + '/' + str(random.randint(0, urls_count - 1))
        resp = self.do_get('landingpages', version='v1.2', url=url)
        self.assertEqual(resp['ok'], True)
        self.assertEqual(len(resp['list']), 1)
        self.assertEqual(resp['list'][0]['url'], url)

    def test_get_all(self):
        " get all landingpages "

        urls_count = random.randint(5, 10)
        for i in xrange(urls_count):
            self.create(URL + '/' + str(i))

        resp  = self.do_get('landingpages', version='v1.2')
        self.assertEqual(resp['ok'], True)
        self.assertEqual(len(resp['list']), urls_count)

    def test_delete_uuid(self):
        " delete specific landingpage using UUID "

        resp = self.create(URL)
        lpage_uuid = resp['item']['id']
        resp = self.do_delete('landingpages/%s' % lpage_uuid, version='v1.2')
        self.assertTrue(resp['ok'])

        resp = self.do_delete('landingpages/%s' % lpage_uuid, version='v1.2')
        self.assertFalse(resp['ok'])

    def test_delete_url(self):
        " delete specific landingpage using url "

        resp = self.create(URL)
        resp = self.do_delete('landingpages', url=URL, version='v1.2')
        self.assertEqual(resp['ok'], True)
        self.assertEqual(resp['message'], '1 docs was deleted, 0 rejected')

        resp = self.do_delete('landingpages', url=URL, version='v1.2')
        self.assertEqual(resp['ok'], True)
        self.assertEqual(resp['message'], '0 docs was deleted, 0 rejected')

    def test_weighted_fields(self):
        """make sure that randomly generated weighted_fields
        restored back without change
        """

        weighted_fields = []
        for _ in xrange(random.randint(1,5)):
            name = ''.join((random.choice(
                        string.letters + string.digits) for _ in xrange(
                        random.randint(5,10)) ))
            value = ''.join((random.choice(
                        string.letters + string.digits) for _ in xrange(
                        random.randint(5,10)) ))
            weight = random.random()
            weighted_fields.append({"name": name,
                                    "value": value,
                                   "weight": weight })

        resp = self.do_post(
            'landingpages', version='v1.2', url=URL, weighted_fields=weighted_fields)
        self.assertEqual(resp['ok'], True)
        self.assertEqual(resp['item']['weighted_fields'], weighted_fields)

    def test_missed_weight(self):
        " make sure that missed weight restored back with 1.0 value "

        name = ''.join((
                random.choice(
                    string.letters + string.digits) for _ in xrange(
                    random.randint(5,10)) ))
        value = ''.join((
                random.choice(
                    string.letters + string.digits) for _ in xrange(
                    random.randint(5,10)) ))
        weighted_fields = [ { 'name': name,
                             'value': value } ]
        resp = self.do_post('landingpages', version='v1.2', url=URL, weighted_fields=weighted_fields)
        self.assertEqual(resp['ok'], True)
        self.assertEqual(resp['item']['weighted_fields'][0]['weight'], 1.0)

    def test_archived(self):
        " test archiving capabilities "

        archived = []

        n = random.randint(3, 6)
        for i in xrange(n):
            url = "%s%s" % (URL, i)
            resp = self.create(url)
            archived.append(resp['item']['id'])
            self.do_delete('landingpages', version='v1.2', url=url)

        self.create()

        self.assertEqual(LandingPage.objects.find().count(), 1)
        self.assertEqual(LandingPage.objects.coll.count(), n + 1)

        lp_archived = random.choice(archived)

        stored_id = LandingPage.objects.get(id=lp_archived,
                                            is_archived=True).id
        self.assertEqual(str(stored_id), lp_archived)

        self.assertRaises(LandingPage.DoesNotExist,
                          LandingPage.objects.get,
                          id=lp_archived)

    def test_mass_deletion(self):
        lpage1 = LandingPage.objects.create_by_user(self.user,
                                                   url='solariat.com')
        lpage2 = LandingPage.objects.create_by_user(self.user,
                                                   url='solariat1.com')
        LandingPage.objects.remove_by_user(self.user)
        self.assertTrue(LandingPage.objects.find_one(lpage1.id) is None)
        self.assertTrue(LandingPage.objects.find_one(lpage2.id) is None)


import networkx as nx
from parse import read_input_file, write_output_file
from utils import *
import sys
import glob
from os.path import basename, normpath

def solve(G, s):
    """
    Args:
        G: networkx.Graph
        s: stress_budget
    Returns:
        D: Dictionary mapping for student to breakout room r e.g. {0:2, 1:0, 2:1, 3:2}
        k: Number of breakout rooms
    """

    room_to_student = {}
    student_to_room = {}

    # Put people into their own breakout room
    for node in list(G.nodes):
        room_to_student[node] = [node]
        student_to_room[node] = node

    is_changed = 1
    while is_changed:
        is_changed = 0
        max_happiness = calculate_happiness(student_to_room, G)
        best_student = 0
        best_move = 0

        for student in list(G.nodes):
            curr_room = student_to_room[student]
            num_rooms = len(room_to_student)
            if len(room_to_student[student_to_room[student]]) == 1:
                num_rooms -= 1

            for new_room in room_to_student.keys():
                room_to_student[curr_room].remove(student)
                room_to_student[new_room].append(student)
                student_to_room[student] = new_room
                curr_happiness = calculate_happiness(student_to_room, G)

                new_room_stress = calculate_stress_for_room(room_to_student[new_room], G)
                stress_budget_room = s / num_rooms
                if new_room_stress > stress_budget_room:
                    curr_happiness = 0

                if curr_happiness > max_happiness:
                    max_happiness = curr_happiness
                    is_changed = 1
                    best_move = new_room
                    best_student = student

                room_to_student[new_room].remove(student)
                room_to_student[curr_room].append(student)
                student_to_room[student] = curr_room

        # Remove best student from current breakout room
        # Add best student to best breakout room
        # Change best student's breakout room to best breakout room

        if is_changed:
            room_to_student[student_to_room[best_student]].remove(best_student)
            room_to_student[best_move].append(best_student)
            student_to_room[best_student] = best_move

        rooms = list(room_to_student.keys())
        for r in rooms:
            if len(room_to_student[r]) == 0:
                room_to_student.pop(r)

    print("Currently at swap")
    #Check for swaps
    is_changed = 1
    while is_changed:
        is_changed = 0
        max_happiness = calculate_happiness(student_to_room, G)
        best_student = 0
        best_student2 = 0

        for student in list(G.nodes):
            num_rooms = len(room_to_student)
            for student2 in list(G.nodes):
                if student != student2:
                    student_old_room = student_to_room[student]
                    student2_old_room = student_to_room[student2]

                    room_to_student[student2_old_room].append(student)
                    #Remove student from student room
                    student_to_room[student] = student2_old_room
                    #Put student2 in student room
                    room_to_student[student_old_room].append(student2)
                    #Remove student2 from student2 room
                    student_to_room[student2] = student_old_room

                    # Make sure students are not in same breakout room
                    student_room_stress = calculate_stress_for_room(room_to_student[student2_old_room], G)
                    student2_room_stress = calculate_stress_for_room(room_to_student[student_old_room], G)

                    stress_budget_room = s / num_rooms
                    if student_room_stress < stress_budget_room or student2_room_stress < stress_budget_room:
                        #Put student in student room
                        room_to_student[student_old_room].append(student)
                        #Remove student from student2 room
                        student_to_room[student] = student_old_room
                        #Put student2 in student room
                        room_to_student[student2_old_room].append(student2)
                        #Remove student2 from student2 room
                        student_to_room[student2] = student2_old_room

                    else:
                        curr_happiness = calculate_happiness(student_to_room, G)
                        if curr_happiness > max_happiness:
                            max_happiness = curr_happiness
                            is_changed = 1
                            best_student = student
                            best_student2 = student2
                        #Put student in student room
                        room_to_student[student_old_room].append(student)
                        #Remove student from student2 room
                        student_to_room[student] = student_old_room
                        #Put student2 in student room
                        room_to_student[student2_old_room].append(student2)
                        student_to_room[student2] = student2_old_room

        if is_changed:
            student_old_room = student_to_room[best_student]
            student2_old_room = student_to_room[best_student2]
            room_to_student[student2_old_room].append(best_student)
            student_to_room[best_student] = student2_old_room
            room_to_student[student_old_room].append(best_student2)
            student_to_room[best_student2] = student_old_room

    index = 0
    output = {}
    for r in room_to_student.keys():
        output[index] = room_to_student[r]
        index += 1

    return convert_dictionary(output), len(output)

# Here's an example of how to run your solver.

# Usage: python3 solver.py test.in

# if __name__ == '__main__':
#     assert len(sys.argv) == 2
#     path = sys.argv[1]
#     G, s = read_input_file(path)
#     D, k = solve(G, s)
#     assert is_valid_solution(D, G, s, k)
#     print("Total Happiness: {}".format(calculate_happiness(D, G)))
#     write_output_file(D, 'out/test.out')

# For testing a folder of inputs to create a folder of outputs, you can use glob (need to import it)
if __name__ == '__main__':
    inputs = glob.glob('inputs/*')
    for input_path in inputs:
        output_path = 'outputs/' + basename(normpath(input_path))[:-3] + '.out'
        G, s = read_input_file(input_path, 100)
        D, k = solve(G, s)
        assert is_valid_solution(D, G, s, k)
        cost_t = calculate_happiness(D, G)
        write_output_file(D, output_path)


# -*- coding: utf-8 -*-
# Simple syslog logger

"""
@Time : 2018/11/27 17:28
@Author : Panjks-
@Description : Remote Syslog Output
"""

from __future__ import absolute_import, division

import logging
import logging.handlers
import json
import os

try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse
import requests

import cowrie.core.output
from cowrie.core.config import CONFIG

class Output(cowrie.core.output.Output):

    def __init__(self):
        self.enabled = CONFIG.getboolean('output_malshare', 'enabled')
        self.host = CONFIG.get('output_remotesyslog', 'host')
        self.port = CONFIG.get('output_remotesyslog', 'port')
        self.server = CONFIG.get('output_remotesyslog', 'server')
        cowrie.core.output.Output.__init__(self)

    def start(self):
        self.logger = logging.getLogger()
        fh = logging.handlers.SysLogHandler((self.host, int(self.port)), logging.handlers.SysLogHandler.LOG_AUTH)
        formatter = logging.Formatter('%(message)s')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)

    def stop(self):
        pass

    def write(self, logentry):
        for i in list(logentry.keys()):
            # remove twisted 15 legacy keys
            if i.startswith('log_'):
                del logentry[i]

        self.logger.error(json.dumps(logentry).rstrip('\t\r\n\0'))

        if logentry["eventid"] == "cowrie.session.file_download":
            print("Sending file to Server")
            p = urlparse(logentry["url"]).path
            if p == "":
                fileName = logentry["shasum"]
            else:
                b = os.path.basename(p)
                if b == "":
                    fileName = logentry["shasum"]
                else:
                    fileName = b

            self.postfile(logentry["outfile"], fileName)

        elif logentry["eventid"] == "cowrie.session.file_upload":
            print("Sending file to Server")
            self.postfile(logentry["outfile"], logentry["filename"])

    def postfile(self, artifact, fileName):
        """
        Send a file to Private server
        """
        if self.enabled:
            try:
                res = requests.post(
                    self.server,
                    files={fileName: open(artifact, "rb")}
                )
                if res and res.ok:
                    print("Submited to Server")
                else:
                    print("Server Request failed: {}".format(res.status_code))
            except Exception as e:
                print("Server Request failed: {}".format(e))
        return


#scraper for RotoWire Last 10 FanDuel PG Defense vs. Position DFS Stats

from bs4 import BeautifulSoup
import urllib2
import csv

url = "http://www.rotowire.com/daily/nba/defense-vspos.htm?statview=last10&pos=PF"

page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page, "html.parser")

rotowireFanduelDvPLast10PF = open('rotowireFanduelDvPLast10PF.csv', 'w')
rotowireFanduelDvPLast10PF.write("Team, Vs. Pos, Season, Last 5, Last 10, PTS, REB, AST, STL, BLK, 3PM, FG%, FT%, TO" + "\n")

for tr in soup.find_all('tr')[2:]:
    tds = tr.find_all('td')

    name = tds[0].text
    if name in ['Philadelphia 76ers']:
        name = 'PHI'
    if name in ['Minnesota Timberwolves']:
        name = 'MIN'
    if name in ['Washington Wizards']:
        name = 'WAS'
    if name in ['Cleveland Cavaliers']:
        name = 'CLE'
    if name in ['New Orleans Pelicans']:
        name = 'NOP'
    if name in ['Houston Rockets']:
        name = 'HOU'
    if name in ['Portland Trail Blazers']:
        name = 'POR'
    if name in ['Denver Nuggets']:
        name = 'DEN'
    if name in ['Detroit Pistons']:
        name = 'DET'
    if name in ['Dallas Mavericks']:
        name = 'DAL'
    if name in ['Los Angeles Lakers']:
        name = 'LAL'
    if name in ['Los Angeles Clippers']:
        name = 'LAC'
    if name in ['Miami Heat']:
        name = 'MIA'
    if name in ['San Antonio Spurs']:
        name = 'SAS'
    if name in ['Atlanta Hawks']:
        name = 'ATL'
    if name in ['Brooklyn Nets']:
        name = 'BKN'
    if name in ['Phoenix Suns']:
        name = 'PHO'
    if name in ['New York Knicks']:
        name = 'NYK'
    if name in ['Golden State Warriors']:
        name = 'GSW'
    if name in ['Memphis Grizzlies']:
        name = 'MEM'
    if name in ['Sacramento Kings']:
        name = 'SAC'
    if name in ['Boston Celtics']:
        name = 'BOS'
    if name in ['Milwaukee Bucks']:
        name = 'MIL'
    if name in ['Charlotte Hornets']:
        name = 'CHA'
    if name in ['Toronto Raptors']:
        name = 'TOR'
    if name in ['Indiana Pacers']:
        name = 'IND'
    if name in ['Orlando Magic']:
        name = 'ORL'
    if name in ['Utah Jazz']:
        name = 'UTA'
    if name in ['Chicago Bulls']:
        name = 'CHI'
    if name in ['Oklahoma City Thunder']:
        name = 'OKC'
    name = str(name.encode('ascii'))

    vsPos = tds[1].text
    vsPos = str(vsPos.encode('ascii'))

    season = tds[2].text
    season = str(season.encode('ascii'))

    last5 = tds[3].text
    last5 = str(last5.encode('utf-8'))

    last10 = tds[4].text
    last10 = str(last10.encode('utf-8'))

    pts = tds[5].text
    pts = str(pts.encode('utf-8'))

    reb = tds[6].text
    reb = str(reb.encode('utf-8'))

    ast = tds[7].text
    ast = str(ast.encode('utf-8'))

    stl = tds[8].text
    stl = str(stl.encode('utf-8'))

    blk = tds[9].text
    blk = str(blk.encode('utf-8'))

    threePM = tds[10].text
    threePM = str(threePM.encode('utf-8'))

    fgPercent = tds[11].text
    fgPercent = str(fgPercent.encode('utf-8'))

    ftPercent = tds[12].text
    ftPercent = str(ftPercent.encode('utf-8'))

    turnOver = tds[13].text
    turnOver = str(turnOver.encode('utf-8'))

    data = (name, vsPos, season, last5, last10, pts, reb, ast, stl, blk, threePM, fgPercent, ftPercent, turnOver)
    rotowireFanduelDvPLast10PF.write('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, \n' % data)

rotowireFanduelDvPLast10PF.close()

reader = csv.reader(open("rotowireFanduelDvPLast10PF.csv"))

row = 0

html = '
'

for row in reader:
    html += '
'
    for column in row:
            html += ''
            html += column
            html += '	'
    html += '
'

html += '
'


import sys, os
sys.path.append(os.pardir)  # 부모 디렉터리의 파일을 가져올 수 있도록 설정
import numpy as np
import matplotlib.pyplot as plt
from mnist import load_mnist
from common.multi_layer_net import MultiLayerNet
from common.util import shuffle_dataset
from common.trainer import Trainer

"""
MNIST 데이터셋으로 검증셋을 이용하여 하이퍼파라미터의 최적화 구현
"""

(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True)

# 결과를 빠르게 얻기 위해 훈련 데이터를 줄임
x_train = x_train[:500]
t_train = t_train[:500]

#20%로 검증 데이터 분할
validation_rate = 0.2
validation_num = int(x_train.shape[0] * validation_rate)
x_train, t_train = shuffle_dataset(x_train, t_train)  #데이터셋을 무작위로 섞어준다.

x_val = x_train[:validation_num]
t_val = t_train[:validation_num]

x_train = x_train[validation_num:] #슬라이싱으로 검증 데이터셋 이후부터 훈련 데이터셋으로 사용
t_train = t_train[validation_num:]

def __train(lr, weight_decay, epocs = 50):
    #네트워크 생성
    network = MultiLayerNet(input_size=784, hidden_size_list=[100, 100, 100, 100, 100, 100],
                            output_size= 10, weight_decay_lambda=weight_decay)

    #훈련 초기화
    trainer = Trainer(network,x_train,t_train,x_test,t_test,epocs,mini_batch_size=100,
                      optimizer='adam', optimizer_param={'lr':lr},verbose=False)

    #훈련 시작
    trainer.train()

    return trainer.test_acc_list, trainer.train_acc_list

#하이퍼 파라미터 무작위 탐색================================
optimization_trial = 100
results_val = {}
results_train = {}

for _ in range(optimization_trial):
    #탐색한 하이퍼 파라미터의 범위 지정========================
    weight_decay = 10 ** np.random.uniform(-8,4)
    lr = 10 ** np.random.uniform(-6,-2)
    #===================================================

    val_acc_list, train_acc_list = __train(lr,weight_decay)
    print("val acc:",str(val_acc_list[-1]),"| lr:",lr,", weight decay:",str(weight_decay))
    key = "lr:" + str(lr) + ", weight decay:" + str(weight_decay)
    results_val[key] = val_acc_list
    results_train[key] = train_acc_list

#그래프 그리기===============================================
print("=================Hyper-Parameter Optimization Result ===================")
graph_draw_num = 20
col_num = 5
row_num = int(np.ceil(graph_draw_num/ col_num))  #np.ceil은 올림 함수
i = 0

for key, val_acc_list in sorted(results_val.items(), key = lambda x:x[1][-1], reverse=True):
    print("Best-"+str(i+1)+"(val acc:"+str(val_acc_list[-1])+") | "+key)

    plt.subplot(row_num, col_num, i+1)
    plt.title("Best-"+str(i+1))
    plt.ylim(0.0,1.0)

    if i % 5:
        plt.yticks([])

    plt.xticks([])
    x = np.arange(len(val_acc_list))
    plt.plot(x, val_acc_list)
    plt.plot(x, results_train[key], "--")
    i += 1

    if i >= graph_draw_num:
        break

plt.show()


import speech_recognition as sr
import matplotlib.pyplot as plt
import numpy as np
import wave
import sys

def main():
    r = sr.Recognizer()

    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        print("Please say something")
        audio = r.listen(source)
        print("Recognizing Now .... ")
        # recognize speech using google
        try:
            r.recognize_bing()
            print("You have said \n" + r.recognize_google(audio, language='he'))
            print("Audio Recorded Successfully \n ")
        except Exception as e:
            print("Error :  " + str(e))
        # write audio
        with open("recorded.wav", "wb") as f:
            f.write(audio.get_wav_data())

    spf = wave.open("recorded.wav", "r")

    # Extract Raw Audio from Wav File
    signal = spf.readframes(-1)
    signal = np.fromstring(signal, "Int16")

    # If Stereo
    if spf.getnchannels() == 2:
        print("Just mono files")
        sys.exit(0)

    plt.figure(1)
    plt.title("Signal Wave...")
    plt.plot(signal)
    plt.show()

if __name__ == "__main__":
    main()


import datetime
import json
from decimal import Decimal

from sodasql.scan.group_value import GroupValue

class JsonHelper:

    @staticmethod
    def to_json(o):
        return json.dumps(o)

    @staticmethod
    def to_json_pretty(o):
        return json.dumps(o, indent=2)

    @staticmethod
    def to_jsonnable(o):
        if o is None \
                or isinstance(o, str) \
                or isinstance(o, int) \
                or isinstance(o, float) \
                or isinstance(o, bool):
            return o
        if isinstance(o, dict):
            for key, value in o.items():
                update = False
                if not isinstance(key, str):
                    del o[key]
                    key = str(key)
                    update = True
                jsonnable_value = JsonHelper.to_jsonnable(value)
                if value is not jsonnable_value:
                    value = jsonnable_value
                    update = True
                if update:
                    o[key] = value
            return o
        if isinstance(o, list):
            for i in range(len(o)):
                element = o[i]
                jsonnable_element = JsonHelper.to_jsonnable(element)
                if element is not jsonnable_element:
                    o[i] = jsonnable_element
            return o
        if isinstance(o, Decimal):
            return float(o)
        if isinstance(o, datetime.datetime):
            return o.isoformat()
        if isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        if isinstance(o, datetime.time):
            return o.strftime('%H:%M:%S')
        if isinstance(o, GroupValue):
            return o.to_json()
        raise RuntimeError(f"Don't know how to jsonize {o} ({type(o)})")


from typing import List, Tuple
from io import StringIO

def parse(puzzle) -> Tuple[int, List[int]]:
    """
    parse input text

    >>> parse(StringIO("123\\n1,2,x,3,x"))
    (123, [1, 2, 3])

    :param puzzle: file like object with input
    :return:
    """
    timestamp = int(puzzle.readline())
    bus_ids = [
        int(bus_id)
        for bus_id
        in puzzle.readline().split(',')
        if bus_id.isnumeric()
    ]
    return timestamp, bus_ids

def next_departure(timestamp: int, bus_ids: List[int]) -> Tuple[int, int]:
    """
    What is the ID of the earliest bus you can take to the airport
    multiplied by the number of minutes you'll need to wait for that bus?
         n*d        (n+1)*d
    ------|-----------|---------
               ^------+----^
               x      |   x+d
          | a  |   ?  |
    x: timestamp
    d: departure interval == bus id
    a: time since last departure: x % d
    ?: time to next departure: d - (x % d)
    """
    print('timestamp:', timestamp)
    print('bus id-s:', bus_ids)
    time_to_departures = [bus_id - (timestamp % bus_id) for bus_id in bus_ids]
    print('time to next departure:', time_to_departures)

    all_zero = [(timestamp + departure) % bus_id for bus_id, departure in zip(bus_ids, time_to_departures)]
    assert all(z == 0 for z in all_zero)

    bus_id, till_next_departure = min(zip(bus_ids, time_to_departures), key=lambda x: x[1])
    print('time to next departure', till_next_departure)
    print('bus', bus_id)
    return till_next_departure, bus_id

if __name__ == '__main__':
    import doctest
    doctest.testmod()

    with open('input.txt', 'rt') as puzzle:
        timestamp, bus_ids = parse(puzzle)

    time, bus_id = next_departure(timestamp, bus_ids)
    print('-'*10)
    print('departure time * bus id:', time * bus_id)


#!/usr/bin/env python3.5
"""
The MIT License

Copyright (c) 2015 Kyle Christensen

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from configparser import SafeConfigParser
from operator import itemgetter
import json
import os
import requests

def getUntappdActivity(cfg):
    """Returns a requests object full of Untappd API data"""
    try:
        return requests.get(getURL(cfg, 'checkin/recent')).text
    except ConnectionError:
        print('There was an error connecting to the Untappd API')

def getURL(cfg, method):
    """Returns an API url with credentials inserted"""
    return "https://api.untappd.com/v4/{}?" \
        "client_id={}&client_secret={}&access_token={}&min_id={}".format(
            method,
            cfg.get('untappd', 'id'),
            cfg.get('untappd', 'secret'),
            cfg.get('untappd', 'token'),
            cfg.get('untappd', 'lastseen'))

def loadConfig(cfg_file):
    """Returns a configparser object from the parsed config file"""
    if not os.path.exists(cfg_file):
        raise OSError('ERROR: Configuration file slappd.cfg does not exist')
    cfg = SafeConfigParser()
    cfg.read(cfg_file)
    return cfg

def notifySlack(token, text, icon, title=None, thumb=None):
    """Sends a Slack message via webhooks"""
    url = 'https://hooks.slack.com/services/' + token
    # If thumb is set, we're sending a badge notification
    if thumb is not None:
        payload = {
            'attachments': [
                {
                    'title': title,
                    'text': text,
                    'thumb_url': thumb
                }
            ],
            'icon_url': icon,
            'username': 'Untappd'
        }
    else:
        payload = {
            'icon_url': icon,
            'text': text,
            'username': 'Untappd'
        }
    try:
        requests.post(url, data=json.dumps(payload))
    except ConnectionError:
        print('There was an error connecting to the Slack API')

def main():
    """Where the magic happens"""
    cfg_file = os.path.dirname(os.path.realpath(__file__)) + '/slappd.cfg'
    cfg = loadConfig(cfg_file)
    data = json.loads(getUntappdActivity(cfg))
    text = ''

    if data['meta']['code'] == 200:
        checkins = data['response']['checkins']['items']
        for checkin in checkins:
            user = checkin['user']['user_name'].lower()
            # If this is one of our watched users, let's send a Slack message
            if user in cfg.get('untappd', 'users'):
                # If any users earned badges, let's send individual messages
                for badge in checkin['badges']['items']:
                    title = "<{0}/user/{1}|{2} {3}> earned the {4} badge!" \
                        .format(
                            'http://untappd.com',
                            checkin['user']['user_name'],
                            checkin['user']['first_name'],
                            checkin['user']['last_name'],
                            badge['badge_name'])
                    notifySlack(
                        cfg.get('slack', 'token'),
                        badge['badge_description'],
                        badge['badge_image']['sm'],
                        title,
                        badge['badge_image']['md'])

                # Lump all of the checkins together as one message
                text += ":beer: *<{0}/user/{1}|{2} {3}>* is " \
                    "drinking a *<{0}/b/{8}/{4}|{5}>* by " \
                    "*<{0}/w/{8}/{7}|{6}>* ({9}/5)\n".format(
                        'http://untappd.com',
                        checkin['user']['user_name'],
                        checkin['user']['first_name'],
                        checkin['user']['last_name'],
                        checkin['beer']['bid'],
                        checkin['beer']['beer_name'],
                        checkin['brewery']['brewery_name'],
                        checkin['brewery']['brewery_id'],
                        checkin['brewery']['brewery_slug'],
                        checkin['rating_score'])

                # If there's a check-in comment, include it
                if len(checkin['checkin_comment']):
                    text += "\n>\"{0}\"\n".format(checkin['checkin_comment'])

        # Send a message if there has been any check-in activity
        if len(text):
            notifySlack(
                cfg.get('slack', 'token'),
                text,
                checkin['beer']['beer_label'])

        # Find the id of the most recent checkin
        if data['response']['checkins']['count']:
            cfg.set(
                'untappd',
                'lastseen',
                str(max(data['response']['checkins']['items'],
                    key=itemgetter('checkin_id'))['checkin_id']))

            # Update the config file with the last checkin seen
            try:
                with open(cfg_file, 'w') as fd:
                    cfg.write(fd)
            except EnvironmentError:
                print('There was an error writing to the config file')
    else:
        print("Untappd API returned http code {}".format(data['meta']['code']))

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 19:47:25 2020

@author: chimochimo
"""

import numpy as np
from PIL import Image
import os, glob, random

photo_size = 75
x = []
y = []

def glob_images(path, label, max_photo):
    files = glob.glob(path + "/*.jpg")
    random.shuffle(files)
    for i, f in enumerate(files):
        if i >= max_photo: break

        img = Image.open(f)
        img = img.convert("RGB")
        img = img.resize((photo_size, photo_size))
        data = np.asarray(img)
        data = data / 256
        data = data.reshape(photo_size, photo_size, 3)
        x.append(data)
        y.append(label)

def make_dataset(max_photo, outfile):
    global x
    global y
    x = []
    y = []

    glob_images("./sakura-ok",0,max_photo)
    glob_images("./sunflower-ok",1,max_photo)
    glob_images("./rose-ok", 2, max_photo)
    x = np.array(x, dtype=np.float32)
    np.savez(outfile,x=x,y=y)
    print("saved:" + outfile)

make_dataset(100, "photo-min.npz")
make_dataset(300, "photo.npz")


# uncompyle6 version 3.7.4
# Python bytecode 3.5 (3350)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /home/trjg/code/venv/django-geo-db/lib/python3.5/site-packages/django_geo_db/migrations/0007_auto_20180310_0603.py
# Compiled at: 2018-03-10 20:33:06
# Size of source mod 2**32: 1893 bytes
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion, django_geo_db.models

class Migration(migrations.Migration):
    dependencies = [
     ('django_geo_db', '0006_auto_20180228_1147')]
    operations = [
     migrations.CreateModel(name='LocationBounds', fields=[
      (
       'location_bounds_id', models.AutoField(primary_key=True, serialize=False)),
      (
       'max_lat', models.DecimalField(decimal_places=6, max_digits=8)),
      (
       'min_lat', models.DecimalField(decimal_places=6, max_digits=8)),
      (
       'max_lon', models.DecimalField(decimal_places=6, max_digits=9)),
      (
       'min_lon', models.DecimalField(decimal_places=6, max_digits=9)),
      (
       'location', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='django_geo_db.Location'))]),
     migrations.CreateModel(name='LocationMap', fields=[
      (
       'location_map_id', models.AutoField(primary_key=True, serialize=False)),
      (
       'file', models.FileField(upload_to='')),
      (
       'location', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='django_geo_db.Location'))]),
     migrations.CreateModel(name='LocationMapType', fields=[
      (
       'location_map_type_id', models.AutoField(primary_key=True, serialize=False)),
      (
       'type', models.CharField(max_length=30))]),
     migrations.AddField(model_name='locationmap', name='type', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='django_geo_db.LocationMapType'))]


import os
import torch
import yaml
from datetime import datetime
import random
import numpy as np

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logging.basicConfig(level=logging.INFO)
cfg = yaml.safe_load(open('configs.yml', 'r', encoding='utf-8'))

def set_cfg(new_cfg):
    """
    change cfg file within run. a little shady.
    Args:
        new_cfg:

    Returns: None (cfg is changed for everyone).

    """
    global cfg
    cfg = new_cfg

current_time = datetime.now()
rnd_seed = cfg['misc']['random_seed']
if rnd_seed is not None:
    torch.manual_seed(rnd_seed)
    torch.cuda.manual_seed(rnd_seed)
    np.random.seed(rnd_seed)
    random.seed(rnd_seed)

def get_depth_dir():
    """

    Returns: path to depth folder

    """
    return os.path.join(cfg['dataset']['data_dir'], cfg['dataset']['depth_foldername'])

def get_img_dir():
    """

    Returns: path to img folder

    """
    return os.path.join(cfg['dataset']['data_dir'], cfg['dataset']['img_foldername'])

def get_test_dir():
    """
        Returns: path to test folder
    """
    return os.path.join(cfg['dataset']['data_dir'], cfg['dataset']['test_foldername'])

def get_dev():
    """
    Returns: device to be used for torch (preferably GPU).

    """
    if torch.cuda.is_available() and cfg['misc']['use_cuda']:
        return torch.device('cuda')
    else:
        return torch.device('cpu')

def get_folder_name():
    """

    Returns: folder name in which to save tensorboard run and model checkpoints.

    """
    cfg_checkpoint = cfg['checkpoint']
    use_saved = cfg_checkpoint['use_saved']
    if use_saved:
        folder_name = cfg_checkpoint['saved_path']
        if folder_name.endswith('.pt'):
            return '/'.join(folder_name.split('/')[:-1])
        else:
            return folder_name
    run_name = cfg_checkpoint['run_name']
    if run_name is None:
        run_name = input('enter run name: ')
        cfg_checkpoint['run_name'] = run_name
    return run_name

def save_checkpoint(epoch, net, optimizer, running_loss):
    """
    save a checkpoint of the network for future use.
    location is defined in configs.yml file.
    Args:
        epoch: int.
        net: network object (both weights and model object base is saved).
        optimizer:
        running_loss:

    Returns: None (checkpoint saved).

    """
    logger.info(f'\nsaving checkpoint at epoch {epoch}...')
    folder = get_folder_name()
    folder = os.path.join('../models', folder)
    filename = 'epoch_' + str(epoch).zfill(4) + '.pt'
    if not os.path.exists(folder):
        os.mkdir(folder)
    full_path = os.path.join(folder, filename)
    if os.path.exists(full_path):
        logger.warning(f'not saving {full_path} as it already exists.')
        return
    torch.save({
        'model': net,
        'optimizer': optimizer,
        'epoch': epoch,
        'loss': running_loss
    }, full_path)

def load_checkpoint(path=None):
    """
    load a saved checkpoint from the training process,
    be it for continued training or inference.
    location from which to load checkpoint is defined in configs.yml file.

    Args:
        path (string, optional): specify manual location of checkpoint.
                                 defaults to path in configs file.
    Returns: (net, optim, epoch, loss) where:
        net: weighted net
        optim: weighted optimizer
        epoch: updated epoch from checkpoint
        loss: current loss in checkpoint.

    """
    if path is None:
        path = os.path.join('..', 'models', cfg['checkpoint']['saved_path'])
    if not path.endswith('.pt'):
        # default to last trained model.
        path = os.path.join(path, max(os.listdir(path)))
    if not os.path.exists(path):
        raise FileNotFoundError
    logger.info(f'loading from {path}')
    checkpoint = torch.load(path)
    net = checkpoint['model']
    optim = checkpoint['optimizer']
    epoch = checkpoint['epoch']
    loss = checkpoint['loss']
    return net, optim, epoch, loss


from plotly import offline
from plotly.graph_objs import Scattergeo, Layout
import json

infile = open('US_fires_9_14.json', 'r')
#outfile = open('readable_eq_data.json', 'w')

# take raw file and convert that into a python dictionary
read_fires = json.load(infile)

# represent a list (the features)
brightness, lons, lats = [], [], []

# eq going through each earthquake which a each dictionary
for fire in read_fires:

    brightness_list = fire['brightness']
    if brightness_list > 450:

        lon = fire['longitude']
        lat = fire['latitude']

        lons.append(lon)
        lats.append(lat)
        brightness.append(brightness_list)
        # same thing, see first 5 elements of the list

data = [{
    'type': 'scattergeo',  # enhance size of dots on earth by mags
    'lon': lons,
    'lat': lats,
    'marker': {
        'size': [brightness_list/30 for brightness_list in brightness],
        'color': brightness,
        'colorscale':'viridis',
        'reversescale':True,
        'colorbar':{'title': 'Brightness'}
    }

}]

my_layout = Layout(title="US Fires - 9/14/2020 through 9/20/2020")

# combines figure data
fig = {'data': data, 'layout': my_layout}

# plot figure and give it this filename
offline.plot(fig, filename='US_fires_9_14.json.html')
# need magnitude to tell how big the earthquakes are


import pandas as pd
import numpy as np
from random import randint
import matplotlib.pyplot as plt

#code init
iterations = 50
ants = 15
twt = 240

#datastructure
graph = []
ph = []
num_node = 0
nodes = []

#param
alpha=0.5
beta=0.5
dens=0.25

#vehicals path
veh1 = []
veh2 = []
veh3 = []
all_st = {}

def read_data():
	global graph
	global ph
	global num_node
	global nodes

	#reading time matrix from csv file
	dt = pd.read_csv('ip3.csv')
	graph = dt.to_numpy()
	num_node = len(graph)
	temp = []

	#initiallization of
	for i in range(num_node):
		ph.append([1 for i in range(num_node)])

	#initiallization of all nodes
	nodes = [ i for i in range(num_node) ]

def start_ant(nvis,dpot):
	global graph
	global ph
	global num_node
	global nodes

	# init, cp(current position) is dpot.
	cp=dpot
	path = []
	path.append(cp)
	# This loop makes ant to visit each&every vertex. By the time visiting the vertex, it will remove the vertex from nvis(not visited list).
	while len(nvis)!=0:
		#count the probabilities of non visited vertex.
		probabilities = list(map(lambda x: ( ( ( (ph[cp][x])**alpha)*((1/graph[cp][x])**beta))  ) , nvis))
		probabilities = probabilities/np.sum(probabilities)

		# counting next vertex in the bases of heigest probability.
		cp=nvis[0]
		mm=probabilities[0]
		for i in range(len(probabilities)):
			if probabilities[i] >mm:
				mm=probabilities[i]
				cp=nvis[i]
		# appending next vertex in path and removing from the list of non visited vertex.
		path.append(cp)
		nvis.remove(cp)
	#returning the path of individual ant.
	return path

def update_feromone(dpot,best_solution,shortest_time):
	# for all the edge, decresing the level of feromone.
	for i in range(num_node):
		for j in range(num_node):
			ph[i][j] -= (1-dens)*ph[i][j]
			# if the feromone level become 0 then it will not appropriate for the probability count.
			# So, I've taken 0.0000000001 insted of 0.
			if ph[i][j]<=0:
				ph[i][j]=(10**(-10))

	# cp is current position
	# starting from dpot which is 0 by default.
	cp = dpot

	#end of the path is also dpot(0). so, i'm appending mnly.
	best_solution[1].append(dpot)
	#path = [1,2,3,4,0]
	# 0-1
	# 1-2
	# 2-3
	# 3-4
	# 4-0

	# taking each edges in best path and updating feromone level.
	for x in best_solution[1]:
		if cp != x:
			#Q=1,l=graph[cp][x]
			ph[cp][x] += 1/graph[cp][x] + (ants/6)*(1/shortest_time[0])
			ph[x][cp] = ph[cp][x]
			cp=x

def total_traveltime(path,dpot):
	# this function counts the summation of the path.
	x=dpot
	travel_time = 0
	for y in path:
		travel_time+=graph[x][y]
		x=y
	travel_time+=graph[x][dpot]
	return travel_time

def get_best_solution(solution):
	# this function returns path which has min length.
	bs=solution[0]
	for soln in solution:
		if bs[0]>soln[0]:
			bs=soln
	return bs

def opt_2(path):
	#making 2 path. temp_path is old path. "path" is the path where all the 2-opt changes gonna happen.
	temp_path = path.copy()

	#temp_path,path

	# path <- 2-opt

	# path = [2,3,4,5,2,3,0]
	# selecting rendomly node from the path and removing that node.
	rnd_node = np.random.choice(path[:-1])
	path.remove(rnd_node)

	#inserting the selected node randomaly.
	path.insert( randint(0, len(path[:-1])) ,rnd_node)

	#path = [ 2,5,3,4,2,3,0]
	# return temp_path
	#If the new path has less cost than old one, update the  path by returning new one.
	if total_traveltime(temp_path,0) > total_traveltime(path,0):
		return path
	else:
		return temp_path

def select_nodes(path):
	#1--3-4-5-6
	# 3 = 66
	# 1 = 50
	inds = []
	cp=0
	# path = 0-1-2 = 0-2
	# time(0,1) + time(1,2) - time(0,2)
	# ans = [ (-50,2) , ( -100 , 1 )  ]
	for i in range(0,len(path)-1):
		change = graph[path[cp]][path[i]]+graph[path[i]][ path[i+1] ]-graph[path[cp]][path[i+1]]
		inds.append( (-1*change, path[i] ) )
		cp=i
	inds.sort()
	#ans = [ (-100,1) , (-50,2) ]
	return inds

def start_spreading_ants(nvis,shortest_time,veh_type,itr,limit):
	global graph
	global ph
	global num_node
	global nodes

	global veh1
	global veh2
	global veh3
	global all_st

	#solution will store all the paths which are coverd by 13 ants.
	solution = []

	for i in range(ants):
		#nvis is list of not visited nodes.
		nnvis = nvis.copy()
		#selecting randome starting point.
		dpot = np.random.choice(nnvis)
		nnvis.remove(dpot)
		#ant will start from the mentioned dpot.
		path = start_ant(nnvis,dpot)
		if len(path)>2:
			path = opt_2(path)
		solution.append( (total_traveltime(path,0),path) )

	# "get_best_solution" will return shortest path coverd among all the ants.
	best_solution = get_best_solution(solution)

	# "opt_2" will apply 2-opt method on best solution.
	if( len(best_solution[1])>1 ):
		opt_best_solution = opt_2(best_solution[1])
		# upedating the best solution.
		#todo:
		best_solution = ( total_traveltime(opt_best_solution,0) , opt_best_solution )

	# print("best",best_solution)
	ID = 240-best_solution[0]
	# if the idle time is positive and pass the given condition then only we can apply idle time optimization
	if itr>limit and ID>0:
		if veh_type==2:
			from_veh_type = 1
			inds = []

			# if the idle time is greater then twt/4, then only vehicle can adopt the node from othervehivle
			# this is minimum cindition

			while twt/4 <= ID:
				# select node will return the list of node of from_veh_type_type
				# this list of node is sorted inorder to get the node which decrease the traveling time most
				inds = select_nodes(all_st[from_veh_type][1])
				if( len(inds)<=3 ):
					break
				# inds = [ (-100,1) , (-50,2) ]
				#lock is use to terminate the while loop. if the vehicle is not able to adopt any node from other vehicle
				lock = True

				for ind in inds:
					#ind = (-100,1)
					#slp = second last position
					#lp = last position
					# for exaample path : 1-2-3-4-5-6 then slp=5, lp=6
					slp = best_solution[1][-2]
					lp = best_solution[1][-1]

					#checking that after adding one node, the total time of the path is less then 240 or not
					if graph[slp][ind[1]]+graph[ind[1]][lp]-graph[slp][lp]+best_solution[0] < twt:
						#lock is false because we found one node which is adopted by the vehicle
						lock=False
						#removing and updating the node from the solution of from vehicle
						all_st[from_veh_type][1].remove(ind[1])
						all_st[from_veh_type]=(total_traveltime(all_st[from_veh_type][1],0),all_st[from_veh_type][1])

						#appending the new node in the vehicle's path, and updating the best solution of this vehicle.
						veh2.append(ind[1])
						all_st[2][1].remove(0)
						all_st[2][1].append(ind[1])
						all_st[2][1].append(0)
						all_st[2]=(total_traveltime(all_st[2][1],0) , all_st[2][1] )

						#after adding new node, updating the best solution.
						shortest_time=all_st[2]
						best_solution=all_st[2]
						veh1.remove(ind[1])
						# counting IDLE time again, if the idle time is more than twt/4, then again we will adopt one more node.
						ID = 240-best_solution[0]
						break
				# if vehicle not able to adopt any node then we will break the current while loop
				if lock:
					break
		elif veh_type==3:
			inds = []
			# checking basic condition for single node adoption.
			while twt/4 <=ID:
				#lock is use to terminate the while loop. if the vehicle is not able to adopt any node from other vehicle
				lock = True

				# vehicle 3 can adopt node for either vehicle1 or vehicle2
				# counting idle time for both vehicles,
				ID1 = 240 - all_st[1][0]
				ID2 = 240 - all_st[2][0]
				from_veh_type = -1

				#which ever vehicle has higher value we will adopt node from that vehicle.
				if ID1>ID2 and len(veh2)>3:
					from_veh_type=2
				elif ID1<ID2 and len(veh1)>3:
					from_veh_type=1
				else:
					break

				# selectiong node from selected vehicle
				# select node will return the list of node of from_veh_type_type
				# this list of node is sorted inorder to get the node which decrease the traveling time most
				inds = select_nodes(all_st[from_veh_type][1])

				#iterate through all the nodes and chech the conditions.
				for ind in inds:
					#slp = second last position
					#lp = last position
					# for exaample path : 1-2-3-4-5-6 then slp=5, lp=6
					slp = best_solution[1][-2]
					lp = best_solution[1][-1]

					#checking that after adding one node, the total time of the path is less then 240 or not
					if graph[slp][ind[1]]+graph[ind[1]][lp]-graph[slp][lp]+best_solution[0] < twt:
						#lock is false because we found one node which is adopted by the vehicle
						lock=False
						#removing and updating the node from the solution of from vehicle
						all_st[from_veh_type][1].remove(ind[1])
						all_st[from_veh_type]=(total_traveltime(all_st[from_veh_type][1],0),all_st[from_veh_type][1])

						#appending the new node in the vehicle's path, and updating the best solution of this vehicle.
						veh3.append(ind[1])
						all_st[3][1].remove(0)
						all_st[3][1].append(ind[1])
						all_st[3][1].append(0)
						all_st[3]=(total_traveltime(all_st[3][1],0) , all_st[3][1] )
						#after adding new node, updating the best solution.
						shortest_time=all_st[3]
						best_solution=all_st[3]
						#removing the node from from_veh_type_type vehicle
						if from_veh_type==1:
							if ind[1] in veh1:
								veh1.remove(ind[1])
						else:
							if ind[1] in veh2:
								veh2.remove(ind[1])
						# counting IDLE time again, if the idle time is more than twt/4, then again we will adopt one more node.
						ID = 240-best_solution[0]
						break
				# if vehicle not able to adopt any node then we will break the current while loop
				if lock:
					break

	#updating the shortest time
	if shortest_time[0] > best_solution[0]:
		shortest_time=best_solution

	#This will update the feromone level.
	update_feromone(0,best_solution,shortest_time)
	return shortest_time

def main():
	global alpha
	global beta
	global dens
	global iterations

	global veh1
	global veh2
	global veh3
	global all_st

	# # init the path of all vehicles
	# veh1 = [1, 4, 6, 9, 10, 12]
	# veh2 = [8,11,2,13,5]
	# veh3 = [3,7]

	#output graph datastructure = x,veh1,veh2,veh3

	#printing the value of parameters of the algo
	print("alpha:",alpha, " | beta:", beta, " | density",dens, " | Iterations: ",iterations, " | ants:",ants)

	# # code for n number of iteration
	# limit = randint(4,8)

	vehs_type1 = [[1,4,6,9,10,12],[55,92,20,33,18],[72,51,79,41,39],[98,16,17,76,56],[21,84,52,99,28],[15,93,27,73,24],[53,59,68,82,25,14],[50,38,75,91,97],[90,85,83,74,29],[70,64,54,46,66,81]]
	vehs_type2 = [[45,48,77,86],[8,11,13,2,5],[26,30,43,96],[31,40,58,62],[34,47,95,63],[36,49,60,65,67],[37,44,61],[69,71,78,80]]
	vehs_type3 = [[42,32,23],[19,100,89],[57,88,94],[87,22,35],[3,7]]

	for comb in range(0,10):
		"""
			0, (0,0,0)
			1, (1,1,1)
			.
			.
			.
			5, (5,5,0)
			.
			.
			.
			9, (9,1,4)
		"""
		veh1 = vehs_type1[ comb%10 ]
		veh2 = vehs_type2[ comb%8 ]
		veh3 = vehs_type3[ comb%5 ]
		limit = randint(4,8)
		plt.clf()
		output_graph = [ [] , [] , [] , [] ]

		# for n number of iterations, spreading ants in the graph.
		all_st[1] = (10**200,[])
		all_st[2] = (10**200,[])
		all_st[3] = (10**200,[])

		for itr in range(iterations):
			read_data()

			# iterations=itr

			for ii in range(itr):
				# this will start spreading ants in the graph.This will return shortest time of all the previous iterations
				all_st[1]= start_spreading_ants(veh1,all_st[1],1,ii,limit)
				all_st[1] = ( total_traveltime( all_st[1][1] , 0 ) , all_st[1][1] )

			for ii in range(itr):
				# this will start spreading ants in the graph.This will return shortest time of all the previous iterations
				all_st[2] = start_spreading_ants(veh2,all_st[2],2,ii,limit)
				all_st[2] = ( total_traveltime( all_st[2][1] , 0) , all_st[2][1] )

			for ii in range(itr):
				# this will start spreading ants in the graph.This will return shortest time of all the previous iterations
				all_st[3] = start_spreading_ants(veh3,all_st[3],3,ii,limit)
				all_st[3] = ( total_traveltime( all_st[3][1] , 0) , all_st[3][1] )

			#printing result, shortest time of all the vehicals.
			if itr!=0:
				print(itr,all_st)
				output_graph[0].append(itr)
				output_graph[1].append(all_st[1][0])
				output_graph[2].append(all_st[2][0])
				output_graph[3].append(all_st[3][0])

		plt.plot(output_graph[0] , output_graph[1], label="Vehicle 1"  )
		plt.plot(output_graph[0] , output_graph[2], label="Vehicle 2"  )
		plt.plot(output_graph[0] , output_graph[3], label="Vehicle 3"  )
		ttl = "Elist Combinations : " + str(comb+1)
		plt.title( ttl)
		plt.legend()
		plt.show()
		plt.close()

if __name__ == '__main__':
	main()


# -*- coding: utf-8 -*-
"""Module providing consultation appointment model"""
from lra.cos.interfaces import IConsultationAppointmentLocator, \
    IConsultationAppointmentGenerator
from sqlalchemy import Table, func
from sqlalchemy import schema as sqlalchemy_schema
from sqlalchemy import types as sqlalchemy_types
from z3c.saconfig import Session
from zope import schema
from zope.interface import Interface, implementer

from lra.cos import ORMBase
from lra.cos import _
from zope.sqlalchemy import register

metadata = ORMBase.metadata

class IConsultationAppointment(Interface):
    """ A consultation appointment """

    consultationAppointmentId = schema.Int(
        title=_(u"Consultation appointment identifier"),
    )

    consultationAppointmentCode = schema.TextLine(
        title=_(u"Consultation appointment code"),
    )

    consultationSlotCode = schema.TextLine(
        title=_(u"Consultation slot code"),
    )

    consultationAppointmentTimeStamp = schema.Datetime(
        title=_(u"Consultation appointment generated time stamp"),
    )

    privacy_notice = schema.Bool(
        title=_(u"Privacy notice accepted?"),
    )

    data_protection_notice = schema.Bool(
        title=_(u"Date protection notice accepted?"),
    )

    consultationAppointmentContactEmail = schema.TextLine(
        title=_(u"Consultation contact email"),
    )

    consultationAppointmentContactSalutation = schema.TextLine(
        title=_(u"Consultation contact salutation"),
    )

    consultationAppointmentContactFirstName = schema.TextLine(
        title=_(u"Consultation contact first name"),
    )

    consultationAppointmentContactLastName = schema.TextLine(
        title=_(u"Consultation contact last name"),
    )

    consultationAppointmentConstructionYear = schema.TextLine(
        title=_(u"Consultation appointment construction year"),
    )

    consultationAppointmentRequest = schema.Text(
        title=_(u"Consultation appointment request"),
    )

@implementer(IConsultationAppointment)
class ConsultationAppointment(ORMBase):
    """ Database-backed implementation of IConsultationAppointment """

    __tablename__ = 'consultation_appointment'

    consultationAppointmentId = sqlalchemy_schema.Column(
        sqlalchemy_types.Integer(),
        primary_key=True,
        autoincrement=True,
    )

    # Generated via secrets.token_hex
    consultationAppointmentCode = sqlalchemy_schema.Column(
        sqlalchemy_types.String(64),
        nullable=False,
    )

    # Generated via secrets.token_hex
    consultationSlotCode = sqlalchemy_schema.Column(
        sqlalchemy_types.String(64),
        nullable=False,
    )

    consultationAppointmentTimeStamp = sqlalchemy_schema.Column(
        sqlalchemy_types.DateTime(),
        nullable=False,
        server_default=func.now()
    )

    privacy_notice = sqlalchemy_schema.Column(
        sqlalchemy_types.Boolean(),
        nullable=False,
    )

    data_protection_notice = sqlalchemy_schema.Column(
        sqlalchemy_types.Boolean(),
        nullable=False,
    )

    consultationAppointmentContactEmail = sqlalchemy_schema.Column(
        sqlalchemy_types.String(120),
        nullable=False,
    )

    consultationAppointmentContactSalutation = sqlalchemy_schema.Column(
        sqlalchemy_types.String(120),
        nullable=False,
    )

    consultationAppointmentContactFirstName = sqlalchemy_schema.Column(
        sqlalchemy_types.String(120),
        nullable=False,
    )

    consultationAppointmentContactLastName = sqlalchemy_schema.Column(
        sqlalchemy_types.String(120),
        nullable=False,
    )

    consultationAppointmentConstructionYear = sqlalchemy_schema.Column(
        sqlalchemy_types.String(64),
        nullable=False,
    )

    consultationAppointmentRequest = sqlalchemy_schema.Column(
        sqlalchemy_types.Text(),
        nullable=False,
    )

#consultation_appointment = Table('consultation_appointment', metadata)

@implementer(IConsultationAppointmentLocator)
class ConsultationAppointmentLocator(object):
    """ Utility to locate available consultation slots """

    @staticmethod
    def available_appointments(from_date):
        """Return a list of all appointments for particular time slots
        on the specified dates.

        Returns a list of dictionaries with keys 'timeSlotCode', 'appointmentCode',
        and 'email'.
        """

        results = Session.query(ConsultationAppointment).filter(
            ConsultationAppointment.showTime.after(from_date)
        )

        appointments = [dict(appointment_id=row.consutationAppointmentId,
                      consultation_slot_code=row.consultationSlotCode,
                      appointment_code=row.consultationAppointmentCode,
                      appointment_email=row.consultationAppointmentContactEmail
                      )
                 for row in results]
        return appointments

@implementer(IConsultationAppointmentGenerator)
class ConsultationAppointmentGenerator(object):
    """ Utility to generate new consultation slots """

    def __call__(self, appointment_request):
        """Make a consultation appointment
        """

        # Make sure the time slot is still available
        # TODO: check for data validity
        session = Session()
        register(session)
        session().add(appointment_request)


from typing import Tuple
from datetime import datetime
import numpy as np
from .ecef import ecef2enu, geodetic2ecef, ecef2geodetic, enu2uvw
from .enu import geodetic2enu, aer2enu, enu2aer
from .eci import eci2ecef, ecef2eci

def ecef2aer(x: float, y: float, z: float,
             lat0: float, lon0: float, h0: float,
             ell=None, deg: bool=True) -> Tuple[float, float, float]:
    """
    Observer => Point

    input:
    -----
    x,y,z  [meters] target ECEF location                             [0,Infinity)
    lat0, lon0 (degrees/radians)  Observer coordinates on ellipsoid  [-90,90],[-180,180]
    h0     [meters]                observer altitude                 [0,Infinity)
    ell    reference ellipsoid
    deg    degrees input/output  (False: radians in/out)

    output: AER
    ------
    azimuth, elevation (degrees/radians)                             [0,360),[0,90]
    slant range [meters]                                             [0,Infinity)
    """
    xEast, yNorth, zUp = ecef2enu(x, y, z, lat0, lon0, h0, ell, deg=deg)

    return enu2aer(xEast, yNorth, zUp, deg=deg)

def geodetic2aer(lat: float, lon: float, h: float,
                 lat0: float, lon0: float, h0: float,
                 ell=None, deg: bool=True) -> Tuple[float, float, float]:
    """
    Observer => Point

    input:
    -----
    Target:   lat, lon, h (altitude, meters)
    Observer: lat0, lon0, h0 (altitude, meters)
    ell    reference ellipsoid
    deg    degrees input/output  (False: radians in/out)

    output: AER
    ------
    azimuth, elevation (degrees/radians)
    slant range [meters]
    """
    e, n, u = geodetic2enu(lat, lon, h, lat0, lon0, h0, ell, deg=deg)

    return enu2aer(e, n, u, deg=deg)

def aer2geodetic(az: float, el: float, srange: float,
                 lat0: float, lon0: float, h0: float,
                 deg: bool=True) -> Tuple[float, float, float]:
    """
    Input:
    -----
    az,el (degrees/radians)
    srange[meters]        [0, Infinity)

    Observer: lat0,lon0 [degrees]
              altitude h0 [meters]

    deg :   degrees input/output  (False: radians in/out)

    output:
    WGS84 lat,lon [degrees]  h0altitude above spheroid  [meters]

    """
    x, y, z = aer2ecef(az, el, srange, lat0, lon0, h0, deg=deg)

    return ecef2geodetic(x, y, z, deg=deg)

def eci2aer(eci: Tuple[float, float, float],
            lat0: float, lon0: float, h0: float,
            t: datetime,
            useastropy: bool=True) -> Tuple[float, float, float]:
    """
    Observer => Point

    input
    -----
    eci [meters] Nx3 target ECI location (x,y,z)                    [0,Infinity)
    lat0, lon0 (degrees/radians)  Observer coordinates on ellipsoid [-90,90],[-180,180]
    h0     [meters]                observer altitude                [0,Infinity)
    t  time (datetime.datetime)   time of obsevation (UTC)

    output: AER
    ------
    azimuth, elevation (degrees/radians)                             [0,360),[0,90]
    slant range [meters]                                             [0,Infinity)
    """
    ecef = np.atleast_2d(eci2ecef(eci, t, useastropy))

    return ecef2aer(ecef[:, 0], ecef[:, 1], ecef[:, 2], lat0, lon0, h0)

def aer2eci(az: float, el: float, srange: float,
            lat0: float, lon0: float, h0: float, t: datetime,
            ell=None, deg: bool=True,
            useastropy: bool=True) -> np.ndarray:
    """

    input
    -----
    azimuth, elevation (degrees/radians)                             [0,360),[0,90]
    slant range [meters]                                             [0,Infinity)
    Observer: lat0, lon0, h0 (altitude, meters)
    ell    reference ellipsoid
    deg    degrees input/output  (False: radians in/out)
    t  datetime.datetime of obseration

    output
    ------
    eci  x,y,z (meters)
    """
    x, y, z = aer2ecef(az, el, srange, lat0, lon0, h0, ell, deg)

    return ecef2eci(np.column_stack((x, y, z)), t, useastropy)

def aer2ecef(az: float, el: float, srange: float,
             lat0: float, lon0: float, alt0: float,
             ell=None, deg: bool=True) -> Tuple[float, float, float]:
    """
    convert target azimuth, elevation, range (meters) from observer at lat0,lon0,alt0 to ECEF coordinates.

     Input:
     -----
    azimuth, elevation (degrees/radians)                             [0,360),[0,90]
    slant range [meters]                                             [0,Infinity)
    Observer: lat0, lon0, h0 (altitude, meters)
    ell    reference ellipsoid
    deg    degrees input/output  (False: radians in/out)

     output: ECEF x,y,z  [meters]

    if you specify NaN for srange, return value z will be NaN
    """
    # Origin of the local system in geocentric coordinates.
    x0, y0, z0 = geodetic2ecef(lat0, lon0, alt0, ell, deg=deg)
    # Convert Local Spherical AER to ENU
    e1, n1, u1 = aer2enu(az, el, srange, deg=deg)
    # Rotating ENU to ECEF
    dx, dy, dz = enu2uvw(e1, n1, u1, lat0, lon0, deg=deg)
    # Origin + offset from origin equals position in ECEF
    return x0 + dx, y0 + dy, z0 + dz


# Created by: Tom Scherr (PragmaDx, Inc.)
# Created on: January 11, 2021

# Program overview
# This software accepts an image of a urinalysis strip in a testing housing.
# (Specifically: https://www.amazon.com/gp/product/B071XTRPPT/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1)
# The software identifies fiducial markers for image registration that are on the paper cover for the test. It performs
# perspective transformation to project the image onto a flat surface. Next, the software identifies test pads for each
# of the 11 biochemical assays on the urinalysis strip - these are based on relative location. It performs colorimetric
# analysis based on the individual reaction. The program returns a JSON object with the resulting concentration of each
# assay, along with any statistical analysis.

# + Imports
import json
import sys
from analyzeUrinalysisImage import analyzeUrinalysis, PrintException

if __name__ == '__main__':

    # + Parameters
    # - Operations
    webServer = False
    silencePlots = True
    silencePrints = True

    # + File prefixes
    dataPathPrefix = 'data_'

    # + Load file, depending on if running locally or on server
    if webServer:

        # + Sample Node code to call Python from server
        # var outputData = [];
        # const pyProg = spawn('python', ['functionalizedProjections.py', path/To/ImageOfUrinalysisTest.jpeg, uniqueFileName]);
        #
        # pyProg.stdout.on('data', function(data)
        # {
        # console.log('Pipe data from python script ...');
        # outputData.push(data);
        # });
        #
        # pyProg.on('close', (code) = > {
        #     console.log('child process close all stdio with code ${code}');
        # // send data to browser
        # console.log(outputData.join(""));
        # res.send(outputData.join(""));
        #
        # + Example call from PHP server:
        # // + Run Python Script
        # $commandToRunPyProg = '/usr/bin/python3'. ' ' . '/path/to/urinalysisReader.py' . ' ' . 'path/To/ImageOfUrinalysisTest.jpeg' . ' ' . uniqueFileName;
        # $escapedCommandToRunPyProg = escapeshellcmd($commandToRunPyProg);
        # $PyProgOutput = shell_exec($escapedCommandToRunPyProg);

        # + Web server file storage location:
        # TODO This will need to be modified according to server file path
        resultStoragePath = '/var/www/html/Basis/App/Temp/'
        # - Retrieve filename from Python argument on server
        queryImageFileName = sys.argv[1]
        tempFileName = sys.argv[2]

    else:
        # + Local/debug datafilename:
        resultStoragePath = './TempResults/'
        tempFileName = 'temp'

        # + Test images
        queryImageFileName = './Test Images/IMG_4556.jpg'
        queryImageFileName = './Test Images/IMG_4553.jpg'
        queryImageFileName = './Test Images/IMG_4563.jpg'
        queryImageFileName = './Test Images/IMG_4558.jpg'

    # + Initialize return dictionary for results
    returnResults = {}

    # + Using try loop to catch exceptions
    try:
        # + Run test analysis algorithm
        returnResults = analyzeUrinalysis(queryImageFileName, tempFileName, resultStoragePath, silencePrints, silencePlots)
        # + Set error flag as flag
        returnResults['imgProcErrorCode'] = 0

    except Exception as imgProcErr:
        # + Handling error found during image processing
        imgProcExceptionString = PrintException()

        # + Set error flag, exception thrown, and recommendation to retake photo in dictionary
        returnResults['imgProcErrorCode'] = -1
        returnResults['exceptionString'] = imgProcExceptionString
        returnResults['recommendation'] = 'There was an error processing your photo. Please try taking another photo.'

    dataFilename = resultStoragePath + dataPathPrefix + tempFileName + '.json'
    with open(dataFilename, 'w') as outfile:
        json.dump(returnResults, outfile)