from django.db import models
from django.utils.translation import gettext_lazy as _
from simple_history.models import HistoricalRecords

READER = 'Lectura en voz alta'
MUSICIAN = 'Interpretación musical'
SOUND_ENGINEER = 'Ingeniería de sonido'
PRODUCTION = 'Producción'
DIRECTION = 'Dirección'
POST_PRODUCTION = 'Post-producción'
AUX = 'Auxiliar de sonido'
CONTRIBUTOR = 'Contribuidor'
PUBLISHER = 'Publicador'
COMPOSER = 'Composición'
TRANSLATOR = 'Traducción'

ENTITY_WORK_ROLE = (
    (COMPOSER, COMPOSER),
    (READER, READER),
    (MUSICIAN, MUSICIAN),
    (SOUND_ENGINEER, SOUND_ENGINEER),
    (PRODUCTION, PRODUCTION),
    (DIRECTION, DIRECTION),
    (POST_PRODUCTION, POST_PRODUCTION),
    (AUX, AUX),
    (CONTRIBUTOR, CONTRIBUTOR),
    (PUBLISHER, PUBLISHER),
    (TRANSLATOR, PUBLISHER),
)

class EntityToWorkRel(models.Model):
    from_entity = models.ForeignKey('Entity', verbose_name=_('From entity'), on_delete=models.CASCADE,
                                    db_column='from_entity', related_name='ew_from_model')
    to_work = models.ForeignKey('Work', verbose_name=_('To recording'), on_delete=models.CASCADE,
                                db_column='to_work', related_name='ew_to_model')

    relationship = models.CharField(max_length=256, verbose_name=_('Role'), choices=ENTITY_WORK_ROLE, default=READER)
    instrument = models.CharField(max_length=256, verbose_name=_('Instrument'), blank=True, null=True)

    # Arbitrary additional information
    commentary = models.TextField(verbose_name=_('Additional commentary'), blank=True, null=True)
    history = HistoricalRecords()

    class Meta:
        managed = True
        db_table = 'poet_entity_to_work_rel'
        verbose_name = _('Entity to recording relationship')


from django.conf.urls import patterns, include, url
from django.contrib import admin
from calc import views

urlpatterns = [
    url(r'(-?\d+)([+])(\d+)', views.suma, name="suma"),
    url(r'(-?\d+)([-])(\d+)', views.resta, name="resta"),
    url(r'(-?\d+)([*])(\d+)', views.mult, name="mult"),
    url(r'(-?\d+)([/])(\d+)', views.div, name="div"),
    url(r'(.*)', views.error, name="error")
]


import pickle
import datetime

import THESIS2019.utils.to_lexicon as lex
from THESIS2019.utils.base_words import *

# import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
# import matplotlib.pyplot as plt
from collections import defaultdict

import dit
from dit.divergences import jensen_shannon_divergence
import THESIS2019.utils.get_articles as get

# get the topic distribution for a document set (corpus)
def total_topic_distribution(model, corpus):
    dist = defaultdict(lambda:0)
    for doc in corpus:
        topics = model[doc]
        for topic,prob in topics:
            dist[topic] += prob
    # normalize
    s = sum(dist.values())
    for d in dist:
        dist[d] /= s
    return dist

def to_js_distro(distro):
    ids, probs = list(distro.keys()), list(distro.values())
    js_distro = dit.ScalarDistribution(ids, probs)
    return js_distro

def compare_topic_distributions(distros):
	js_distros = []
	for distro in distros:
		js_distros.append(to_js_distro(distro))
	return jensen_shannon_divergence(js_distros)

def graph_distribution(dist):
    x, y = dist.keys(), dist.values()
    plt.bar(x, y, alpha=0.5)
    plt.xlabel('Topic number')
    plt.ylabel('Proportion in document set')
    plt.title('Topic distribution')

    plt.show()

if __name__ == '__main__':
	# path = "/Users/ninawang/Thesis/remote/THESIS2019/example_data/NYT-OPINION2012-2013-processed/"
	# start = datetime.datetime(2012, 6, 1)
	# end = datetime.datetime(2013, 7, 1)
	# articles = lex.get_articles_from_filepath(path,start,end)

	# # notebook to find consistency over time of topic models using LDA

	datapath = "/Users/ninawang/Thesis/remote/THESIS2019/example_data_1000/"
	outlets = ['BREITBART','NATIONALREVIEW','FOX',
			'WASHINGTONEXAMINER','REUTERS','NPR',
			'NYT', 'MSN','CNN','SLATE']
	articles = get.get_articles_outlets(datapath,outlets,2012,filter_date=False)
	for outlet, article in articles.items():
		print("%s has %d articles" %(outlet, len(article)))

	arts, dictionary, corpus, model = lex.LDA(articles, LEFT_WORDS+RIGHT_WORDS,num_topics=30,load=False)

	# SAVE
	with open("all_model2012.pkl","wb") as f:
		pickle.dump(model, f)
	with open("all_articles2012.pkl","wb") as f:
		pickle.dump(arts, f)
	with open("all_dictionary2012.pkl","wb") as f:
		pickle.dump(dictionary, f)
	with open("all_corpus2012.pkl","wb") as f:
		pickle.dump(corpus, f)

	# LOAD
	# path = "/Users/ninawang/Thesis/remote/THESIS2019/Jupyter Notebooks/"
	# with open(path+"prelim_model2012.pkl","rb") as f:
	# 	model = pickle.load(f)
	# with open(path+"prelim_dictionary2012.pkl","rb") as f:
	# 	dictionary = pickle.load(f)
	# with open(path+"prelim_articles2012.pkl","rb") as f:
	# 	articles = pickle.load(f)
	# with open(path+"prelim_corpus2012.pkl","rb") as f:
	# 	corpus = pickle.load(f)

	# arts = {"2012":[],"2013":[]}
	# for i,article in enumerate(articles):
	# 	if article.date_publish is not None:
	# 		arts[str(article.date_publish.year)].append(corpus[i])

	# dist2012 = total_topic_distribution(model, arts["2012"])
	# dist2013 = total_topic_distribution(model, arts["2013"])

	# jsd = compare_topic_distributions(dist2012, dist2013)
	# print("JS Divergence of topic: %f"%(jsd))


from model import SbertModel
from pytorch_lightning import Trainer
from data import SbertDataModule
import hparams
from pytorch_lightning import loggers as pl_loggers

'''
How sbert_sub is trained.
For approximately 3000 steps, the discriminator is trained without the generator. This is because the generator is
initialized in a good position while the discriminator is not. Done by adjusting the frequency to 1, 0 in model.py
After this, the model trains as normal. Saving every epoch is suggested. On epoch end swords validation scores are saved
'''

model = SbertModel(alpha=hparams.ALPHA)
# model = SbertModel.load_from_checkpoint('sbert_sub.ckpt')
model.alpha = hparams.ALPHA

summary_data = SbertDataModule('data', batch_size=hparams.BATCH_SIZE)

tb_logger = pl_loggers.TensorBoardLogger('logs/')

trainer = Trainer(
    gpus=[1],
    accelerator='dp',
    auto_select_gpus=True,
    max_epochs=hparams.MAX_EPOCHS,
    deterministic=True,
    logger=tb_logger,
)

trainer.fit(model, summary_data)
# trainer.save_checkpoint("sbert_sub.ckpt")


### This is the main code file f my telescope control software.

# Thanks to:
# https://git.nexlab.net/astronomy/skylived/tree/bd59190026d9d95b39983f8a0106a7e17023aee8/DecraDB/xephemdb
# https://github.com/Alex-Broughton/StarAtlas
# I'll do proper credits eventually.

import sys # for updatable print for status messages

# Raspberry Pi GPIO access
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# Global variables
import config
from config import *

# Welcome message
print ("\n\x1b[1;37;42m ====== DIY GoTo Telesope Control ===== " + TColors.normal + " \n")

from load_observers import *
#config.observers = gather_observers(config.observers_file)
#config.observer, config.observer_name = set_observer(config.observer_name)

from load_landmarks import *
#config.landmarks = gather_landmarks(config.landmarks_file)

from backup_location import * # CRITICAL: before set_functions
from set_functions import * # CRITICAL: after backup_location

from ephem_wrapper import * # here: for printing names of stars

#from move_function import * # not directly
#from move_1_step import * # not directly
#from move_1_deg import * # not directly

# Operating modes
from track_mode import *
from go_to_mode import *
from manual_drive_mode import *
from scan_sky_mode import *

##################

def do_nothing(): pass # passthrough nethtod for menu

def quit_nicely():
	GPIO.cleanup()
	print (TColors.italic + "\nGood riddance!\n" + TColors.normal)

def show_options():
	print (TColors.bold + "\nAvailable options:" + TColors.normal)
	print (TColors.orange_on_black + "0:" + TColors.normal + " Quit nicely")
	print (TColors.orange_on_black + "1-4:" + TColors.blue_on_black + " Operating modes: " + TColors.normal + "track " + TColors.orange_on_black + "(1)" + TColors.normal + ", move " + TColors.orange_on_black + "(2)" + TColors.normal + ", manual drive " + TColors.orange_on_black + "(3)" + TColors.normal + " , scan sky area " + TColors.orange_on_black + "(4)" + TColors.normal)
	print (TColors.orange_on_black + "5-9:" + TColors.blue_on_black + " Set: " + TColors.normal + "speed " + TColors.orange_on_black + "(5)" + TColors.normal + ", microstepping " + TColors.orange_on_black + "(6)" + TColors.normal + ", track refresh interval " + TColors.orange_on_black + "(7)" + TColors.normal + ", observer " + TColors.orange_on_black + "(8)" + TColors.normal + ", current coordinates " + TColors.orange_on_black + "(9)" + TColors.normal)
	print (TColors.orange_on_black + "10:" + TColors.normal + " Recover last recoded coordinates")
	print (TColors.orange_on_black + "18 19 20:" + TColors.blue_on_black + " Print: " + TColors.normal + "observer " + TColors.orange_on_black + "(18)" + TColors.normal + ", current coordinates " + TColors.orange_on_black + "(19)" + TColors.normal + ", status " + TColors.orange_on_black + "(20)" + TColors.normal)
	print (TColors.orange_on_black + "21-23:" + TColors.blue_on_black + " Print: " + TColors.normal + "named stars " + TColors.orange_on_black + "(21)" + TColors.normal + ", all available stars in YBS " + TColors.orange_on_black + "(22)" + TColors.normal + ", landmakrs " + TColors.orange_on_black + "(23)" + TColors.normal)
	print (TColors.orange_on_black + "31:" + TColors.normal + " Make fake star")

def switch_main(option):
	switcher = {
		0: quit_nicely,

		1: track,
		2: go_to_location,
		3: manual_drive,
		4: scan_sky,

		5: set_speed,
		6: set_microstepping,
		7: set_track_refresh_interval,
		8: set_observer,
		9: set_location,
		10: recover_last_location,

		18: print_observer,
		19: print_location,
		20: print_status,

		21: print_named_stars,
		22: print_available_stars,
		23: print_landmarks,

		31: make_fake_star,

		99: show_options, # hidden
		100: do_nothing # hidden
	}
	func = switcher.get(option, show_options)
	func()

################

def main():

	#sys.stdout.write("\r")
	sys.stdout.write(TColors.italic + "Loading observers ... " + TColors.normal)
	sys.stdout.flush()
	config.observers = gather_observers(config.observers_file)
	config.observer, config.observer_name = set_observer(config.observer_name)

	sys.stdout.write("\r")
	sys.stdout.write(TColors.italic + "Loading landmarks ... " + TColors.normal)
	sys.stdout.flush()
	config.landmarks = gather_landmarks(config.landmarks_file)

	sys.stdout.write("\r")
	sys.stdout.write(TColors.italic + "Loading celestial bodies into ephem ... " + TColors.normal)
	sys.stdout.flush()

	# named stars from YBS
	#ephem_wrapper.list_of_named_stars = open("named_stars.txt", "r").readlines()
	#ephem_wrapper.list_of_named_stars = [star[:-1].lower() for star in list_of_named_stars]

	# named stars in an other catalog
	#ephem_wrapper.list_of_stars_YBS = open("YBS2.txt", "r").readlines()
	#ephem_wrapper.list_of_stars_YBS = [star[:-1].lower() for star in list_of_stars_YBS]

	sys.stdout.write("\r")
	sys.stdout.write("                                                                          \n")
	sys.stdout.flush()

	#print("\n")
	recover_last_location()
	config.fake_star = make_fake_star(0, 0) # defined in config.py as None

	# main loop:
	option = 100 # default, do_nothing()
	while option != 0:
		switch_main(int(option)) # first tine: do_nothing()
		print('\n')

		# next step
		show_options()
		try:
			option = input(TColors.italic + "What is my purpose? " + TColors.normal).strip()
		except KeyboardInterrupt as err: # accept Ctrl+c
			print(TColors.red_on_black + "  [ keybord interrupt ... ]  " + TColors.normal)
			quit_nicely()
			return()

		if not option.isnumeric():
			print("Please choose one of the listed options! ")
			option = 100 # do_nothing()
			#continue
		option = int(option)

	#GPIO.cleanup()
	quit_nicely()
	return(0)

#print("before if")
if __name__ == '__main__':
	main()

#GPIO.cleanup()
#quit_nicely()


# Copyright 2014 Wind River, Inc.
# Copyright 2012 Nebula, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
#
# Copyright (c) 2013-2017 Wind River Systems, Inc.
#

from django.core.urlresolvers import NoReverseMatch
from django.core.urlresolvers import reverse
from django.utils import html
from django.utils import safestring
from django.utils.translation import string_concat
from django.utils.translation import ugettext_lazy as _  # noqa
from django.utils.translation import ungettext_lazy

from horizon import exceptions
from horizon import tables

from openstack_dashboard import api
from openstack_dashboard.api import nova
from openstack_dashboard.dashboards.project.volumes.tables \
    import get_attachment_name
from openstack_dashboard.usage import quotas

from starlingx_dashboard.api import nova as stx_nova

DELETABLE_STATES = ("available", "error")

class DeleteServerGroup(tables.DeleteAction):
    @staticmethod
    def action_present(count):
        return ungettext_lazy(
            u"Delete Server Group",
            u"Delete Server Groups",
            count
        )

    @staticmethod
    def action_past(count):
        return ungettext_lazy(
            u"Deleted Server Group",
            u"Deleted Server Groups",
            count
        )

    def delete(self, request, obj_id):
        obj = self.table.get_object_by_id(obj_id)
        name = self.table.get_object_display(obj)

        try:
            stx_nova.server_group_delete(request, obj_id)
        except Exception:
            msg = _('Unable to delete group "%s" because it is not empty. '
                    'Either delete the member instances'
                    ' or remove them from the group.')
            exceptions.check_message(["group", "not", "empty."], msg % name)
            raise

    # maybe do a precheck to see if the group is empty first?
    def allowed(self, request, server_group=None):
        return True

class CreateServerGroup(tables.LinkAction):
    name = "create"
    verbose_name = _("Create Server Group")
    url = "horizon:admin:server_groups:create"
    classes = ("ajax-modal", "btn-create")
    icon = "plus"

    def allowed(self, request, volume=None):
        usages = quotas.tenant_quota_usages(request)
        if usages['server_groups']['available'] <= 0:
            if "disabled" not in self.classes:
                self.classes = [c for c in self.classes] + ['disabled']
                self.verbose_name = string_concat(self.verbose_name, ' ',
                                                  _("(Quota exceeded)"))
        else:
            self.verbose_name = _("Create Server Group")
            classes = [c for c in self.classes if c != "disabled"]
            self.classes = classes
        return True

class EditAttachments(tables.LinkAction):
    name = "attachments"
    verbose_name = _("Edit Attachments")
    url = "horizon:admin:server_groups:attach"
    classes = ("ajax-modal", "btn-edit")

    def allowed(self, request, server_group=None):
        return True  # volume.status in ("available", "in-use")

class CreateSnapshot(tables.LinkAction):
    name = "snapshots"
    verbose_name = _("Create Snapshot")
    url = "horizon:admin:server_groups:create_snapshot"
    classes = ("ajax-modal", "btn-camera")

    def allowed(self, request, server_group=None):
        return True  # server_group.status == "available"

class UpdateRow(tables.Row):
    ajax = True

    def get_data(self, request, server_group_id):
        server_group = stx_nova.server_group_get(request, server_group_id)
        if not server_group.name:
            server_group.name = server_group_id

        return server_group

def get_policies(server_group):
    policies = ', '.join(server_group.policies)
    return policies

def get_metadata(server_group):
    metadata_items = ['{}:{}'.format(x, y) for x, y in
                      server_group.metadata.items()]
    metadata = ', '.join(metadata_items)
    return metadata

def get_member_name(request, server_id):
    try:
        server = api.nova.server_get(request, server_id)
        name = server.name
    except Exception:
        name = None
        exceptions.handle(request, _("Unable to retrieve "
                                     "member information."))
    # try and get a URL
    try:
        url = reverse("horizon:admin:instances:detail", args=(server_id,))
        instance = '%s' % (url, html.escape(name))
    except NoReverseMatch:
        instance = name
    return instance

class ProjectNameColumn(tables.Column):
    """Customized column class

    Customized column class that does complex processing on the
    server group.
    """

    def get_raw_data(self, server_group):
        request = self.table.request
        project_id = getattr(server_group, 'project_id', None)
        try:
            tenant = api.keystone.tenant_get(request,
                                             project_id,
                                             admin=True)

            project_name = getattr(tenant, "name", None)
        except Exception:
            project_name = "(not found)"

        return project_name

class MemberColumn(tables.Column):
    """Customized column class

    Customized column class that does complex processing on the instances
    in a server group.  This was substantially copied
    from the volume equivalent.
    """

    def get_raw_data(self, server_group):
        request = self.table.request
        link = _('%(name)s (%(id)s)')
        members = []
        for member in server_group.members:
            member_id = member
            name = get_member_name(request, member)
            vals = {"name": name, "id": member_id}
            members.append(link % vals)
        return safestring.mark_safe(", ".join(members))

def get_server_group_type(server_group):
    return server_group.volume_type if server_group.volume_type != "None" \
        else None

class ServerGroupsFilterAction(tables.FilterAction):
    def filter(self, table, server_groups, filter_string):
        """Naive case-insensitive search."""
        q = filter_string.lower()
        return [group for group in server_groups
                if q in group.display_name.lower()]

class ServerGroupsTable(tables.DataTable):
    projectname = ProjectNameColumn("project_name",
                                    verbose_name=_("Project"))
    name = tables.Column("name",
                         verbose_name=_("Group Name"),
                         link="horizon:admin:server_groups:detail")
    policies = tables.Column(get_policies,
                             verbose_name=_("Policies"))
    members = MemberColumn("members",
                           verbose_name=_("Members"))
    metadata = tables.Column(get_metadata,
                             verbose_name=_("Metadata"))

    class Meta(object):
        name = "server_groups"
        verbose_name = _("Server Groups")
        row_class = UpdateRow
        table_actions = (
            CreateServerGroup, DeleteServerGroup, ServerGroupsFilterAction)
        row_actions = (DeleteServerGroup,)

    def get_object_display(self, obj):
        return obj.name

class DetachServerGroup(tables.BatchAction):
    name = "detach"
    action_type = 'danger'

    @staticmethod
    def action_present(count):
        return ungettext_lazy(
            u"Detach Server Group",
            u"Detached Server Groups",
            count
        )

    @staticmethod
    def action_past(count):
        return ungettext_lazy(
            u"Detaching Server Group",
            u"Detaching Server Groups",
            count
        )

    def action(self, request, obj_id):
        attachment = self.table.get_object_by_id(obj_id)
        api.nova.instance_server_group_detach(request,
                                              attachment.get('server_id',
                                                             None),
                                              obj_id)

    def get_success_url(self, request):
        return reverse('horizon:admin:server_groups:index')

class AttachedInstanceColumn(tables.Column):
    """Customized column class

    Customized column class that does complex processing on the attachments
    for a server group.
    """

    def get_raw_data(self, attachment):
        request = self.table.request
        return safestring.mark_safe(get_attachment_name(request, attachment,
                                                        True))

class AttachmentsTable(tables.DataTable):
    instance = AttachedInstanceColumn(get_member_name,
                                      verbose_name=_("Instance"))
    device = tables.Column("device",
                           verbose_name=_("Device"))

    def get_object_id(self, obj):
        return obj['id']

    def get_object_display(self, attachment):
        instance_name = get_attachment_name(self.request, attachment, True)
        vals = {"dev": attachment['device'],
                "instance_name": html.strip_tags(instance_name)}
        return _("%(dev)s on instance %(instance_name)s") % vals

    def get_object_by_id(self, obj_id):
        for obj in self.data:
            if self.get_object_id(obj) == obj_id:
                return obj
        raise ValueError('No match found for the id "%s".' % obj_id)

    class Meta(object):
        name = "attachments"
        verbose_name = _("Attachments")
        table_actions = (DetachServerGroup,)
        row_actions = (DetachServerGroup,)


from kubernetes import client,config
from packtivity.asyncbackends import PacktivityProxyBase
from packtivity.syncbackends import packconfig, build_job, publish
from packtivity.statecontexts import load_state
from packtivity import prepublish_default
import logging
import uuid
import os

log = logging.getLogger(__name__)

class KubeProxy(PacktivityProxyBase):
    def __init__(self, job_id, spec, pars, state):
        self.job_id = job_id
        self.spec = spec
        self.pars = pars
        self.state = state

    def proxyname(self):
        return 'KubeProxy'

    def details(self):
        return {
            'job_id': self.job_id,
            'spec': self.spec,
            'pars':self.pars,
            'state':self.state.json()
        }

    @classmethod
    def fromJSON(cls,data):
        return cls(
            data['proxydetails']['job_id'],
            data['proxydetails']['spec'],
            data['proxydetails']['pars'],
            load_state(data['proxydetails']['state'])
        )

class KubeBackend(object):
    def __init__(self,kubeconfigloc = None):
        config.load_kube_config(kubeconfigloc or os.path.join(os.environ['HOME'],'.kube/config'))
        self.config = packconfig()

    def prepublish(self, spec, parameters, state):
        return None

    def submit(self, spec, parameters, state, metadata = None):
        job = build_job(spec['process'], parameters, self.config)

        image   = spec['environment']['image']
        tag     = spec['environment']['imagetag']

        interpreter = 'sh' if 'command' in job else job['interpreter']
        script = job['command'] if 'command' in job else job['script']
        jobspec = job_spec(interpreter, script, image, tag, state)

        jobid = jobspec['metadata']['name']

        thejob = client.V1Job(
            api_version = jobspec['apiVersion'],
            kind = jobspec['kind'],
            metadata = jobspec['metadata'],
            spec = jobspec['spec']
        )

        log.info(thejob)
        client.BatchV1Api().create_namespaced_job('default',thejob)

        log.info('submitted job: %s', jobid)
        return KubeProxy(
            job_id = jobid,
            spec = spec,
            pars = parameters,
            state = state
        )

    def result(self, resultproxy):
        return prepublish_default(
            resultproxy.spec,resultproxy.pars, resultproxy.state
        )

    def ready(self, resultproxy):
        jobstatus = client.BatchV1Api().read_namespaced_job(resultproxy.job_id,'default').status
        return jobstatus.failed or jobstatus.succeeded

    def successful(self, resultproxy):
        jobstatus = client.BatchV1Api().read_namespaced_job(resultproxy.job_id,'default').status
        return jobstatus.succeeded

    def fail_info(self, resultproxy):
        pass

def state_binds(state):
    container_mounts = []
    volumes = []

    log.info('mountspec: %s', state.mountspec)

    for i,path in enumerate(state.readwrite + state.readonly):
        container_mounts.append({
            "name": "cephfs",
            "mountPath": path,
            "subPath": path.lstrip('/')
        })

    volumes.append({
        "name": "cephfs".format(i),
    })
    volumes[0].update(state.mountspec)
    return container_mounts, volumes

def job_spec(interpreter,script,image,imagetag,state):
    wrapped_script = '''cat << EOF | {interpreter}\n{script}\nEOF'''.format(
        interpreter = interpreter,
        script = script)

    job_uuid = str(uuid.uuid4())

    container_mounts, volumes = state_binds(state)

    spec = {
      "apiVersion": "batch/v1",
      "kind": "Job",
      "spec": {
        "template": {
          "spec": {
            "restartPolicy": "Never",
            "containers": [
              {
                "image": ':'.join([image,imagetag]),
                "command": [
                  "sh",
                  "-c",
                  wrapped_script
                ],
                "volumeMounts": container_mounts,
                "name": job_uuid
              }
            ],
            "volumes": volumes
          },
          "metadata": {
            "name": job_uuid
          }
        }
      },
      "metadata": {
        "name": job_uuid
      }
    }
    return spec


import json
import boto3

codecommit_client = boto3.client('codecommit')
codepipeline_client = boto3.client('codepipeline')

non_essential_files = [
    "readme.md",
    "emr-master/views/layouts/main.handlebars",
]

def lambda_handler(event, context):
    print(event)
    old_commit_id = event["detail"]["oldCommitId"]
    new_commit_id = event["detail"]["commitId"]

    codecommit_response = codecommit_client.get_differences(
        repositoryName="EMR-REPO",
        beforeCommitSpecifier=str(old_commit_id),
        afterCommitSpecifier=str(new_commit_id)
    )

    print(codecommit_response["differences"])

    changes = len(codecommit_response["differences"])
    non_essential_changes = 0

    for difference in codecommit_response["differences"]:
        try:
            file_name = difference["afterBlob"]["path"].lower()

            if file_name in non_essential_files:
                non_essential_changes += 1

        except:
            pass

    if changes != non_essential_changes:
        print("PERFORMING TESTS")
        response = codepipeline_client.start_pipeline_execution(name='EMR-PIPELINE-TESTS')
    else:
        print("SKIPPING TESTS")
        response = codepipeline_client.start_pipeline_execution(name='EMR-PIPELINE-SKIP-TESTS')


import time,sys,os
from flask import Flask, request
from twilio.twiml.voice_response import VoiceResponse, Gather
from directline import DirectLineAPI as DL
from utils.twilio import buildTwilioResponse

app = Flask(__name__)
converations = {}

@app.route("/", methods=['GET'])
def index():
    return "Twilio-Docker-Bot"

@app.route("/answer", methods=['GET', 'POST'])
def answer_call():
    caller = request.form.get('Caller')
    bot = DL(caller);
    converations[caller] = bot
    return str(buildTwilioResponse("Hello! welcome to NTT service desk. How may I help?"))

@app.route("/gather", methods=['POST'])
def gather():
    user_speech = request.form.get('SpeechResult',None)
    input_digits = request.form.get('Digits', None)
    data = input_digits if input_digits else user_speech
    caller = request.form.get('Caller')
    bot = converations[caller]
    bot._lastAccessed = time.time()
    bot.send(data)
    print(str(time.time()) + ' - ' + caller + ': ' + data)
    return str(buildTwilioResponse(text=None, waitForResponse=True));

@app.route("/gather/dtmf", methods=['POST'])
def gather_dtmf():
    pass

@app.route("/realtimevoice", methods=['get'])
def realTimeVoice():
    print(request.values);
    return str(request.values)

@app.route('/wait/<ntry>', methods=['POST'])
def waitForBotRespsonse(ntry=1):
    caller = request.form.get('Caller')
    bot = converations[caller]
    if (int(ntry)>7):
        return str(buildTwilioResponse('Sorry I could not reply from the application', hangUp=True))
    msg = bot.get()
    bot._lastAccessed = time.time()
    loop = time.time()
    if not msg:
        while time.time() - loop <= 10:
            try:
                msg=bot.get()
                if msg:
                    break
                time.sleep(.5)
            except Exception as e:
                print(str(e))
                pass
    bot._lastAccessed = time.time()
    if not msg:
        resp = VoiceResponse()
        url = '/wait/' + str(int(ntry)+1)
        resp.redirect(url, method='POST');
        return str(resp)
    else:
        return str(buildTwilioResponse(msg.get('msgs'), msg.get('endOfConversation'), msg.get('waitForResponse'),
                    msg.get('routeToMainMenu'), hangUp=msg.get('hangUp'), dtmf=msg.get('dtmf')))

if __name__ == "__main__":
    app.run('0.0.0.0', port=80,debug=True)


import discord
from discord.ext import commands
import random

class Channels(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print(f"{self.__class__.__name__} Cog has been loaded\n-----")

    @commands.command(aliases=['cs'])
    @commands.bot_has_guild_permissions(manage_channels=True)
    async def channelstats(self, ctx):
        """
        Sends a nice fancy embed with some channel stats
        !channelstats
        """
        channel = ctx.channel
        embed = discord.Embed(title=f"Stats for **{channel.name}**", description=f"{'Category: {}'.format(channel.category.name) if channel.category else 'This channel is not in a category'}", color=random.choice(self.bot.color_list))
        embed.add_field(name="Channel Guild", value=ctx.guild.name, inline=False)
        embed.add_field(name="Channel Id", value=channel.id, inline=False)
        embed.add_field(name="Channel Topic", value=f"{channel.topic if channel.topic else 'No topic.'}", inline=False)
        embed.add_field(name="Channel Position", value=channel.position, inline=False)
        embed.add_field(name="Channel Slowmode Delay", value=channel.slowmode_delay, inline=False)
        embed.add_field(name="Channel is nsfw?", value=channel.is_nsfw(), inline=False)
        embed.add_field(name="Channel is news?", value=channel.is_news(), inline=False)
        embed.add_field(name="Channel Creation Time", value=channel.created_at, inline=False)
        embed.add_field(name="Channel Permissions Synced", value=channel.permissions_synced, inline=False)
        embed.add_field(name="Channel Hash", value=hash(channel), inline=False)

        await ctx.send(embed=embed)

def setup(bot):
    bot.add_cog(Channels(bot))


import numpy as np
import matplotlib.pyplot as plt

def kernel(x, i):
    return x**i

# データの読み込み
tmp = np.load("samples.npz")
x, y = tmp["arr_0"], tmp["arr_1"]

# sinカーブの描画
x_min, x_max = 0, 10
xx = np.linspace(x_min, x_max, 100)
tt = np.sin(xx)

# 計画行列の作成
p = x.shape[0]
ones = np.ones(p)
phi = np.c_[ones, kernel(x,1), kernel(x,2), kernel(x,3), kernel(x,4), kernel(x,5)]

# パラメータの計算

# tmp = [i*0.1 for i in range(100)]# +
tmp = [10**i for i in range(10, 50)]
for lambda_ in tmp:
    A = np.dot(phi.T, phi)
    I = np.eye(A.shape[0])
    w = np.dot(np.dot(np.linalg.inv(A+ lambda_ * I) , phi.T), y)
    w0, w1, w2, w3, w4, w5 = w

    xxx = np.linspace(0, 10, 100)
    yyy = w0 + w1 * kernel(xxx, 1) + w2 * kernel(xxx, 2) + w3 * kernel(xxx, 3) + w4 * kernel(xxx, 4) + w5 * kernel(xxx,5)
    plt.plot(xxx, yyy, color="red")
    plt.scatter(x, y, color="blue", marker="x")
    plt.plot(xx, tt, color="green")
    plt.title("lambda={}".format(lambda_))
    plt.xlim([0, 8])
    plt.ylim([-2, +2])

    plt.savefig("./img4/fitting_polynomial_{}_lambda_{}".format(p, str(lambda_).replace(".","_")))
    plt.close()
#    plt.show()


# lifted from https://deepctr-torch.readthedocs.io/en/latest/Quick-Start.html for quick testing
import pandas as pd
import torch

from sklearn.metrics import log_loss, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, MinMaxScaler

from deepctr_torch.inputs import SparseFeat, DenseFeat, get_feature_names
from deepctr_torch.models import DeepFM
data = pd.read_csv('data/criteo_sample.txt')

sparse_features = ['C' + str(i) for i in range(1, 27)]
dense_features = ['I' + str(i) for i in range(1, 14)]

# filling in empty fields
data[sparse_features] = data[sparse_features].fillna('-1', )
data[dense_features] = data[dense_features].fillna(0, )
target = ['label']

# simple pre-processing
for feat in sparse_features:
    lbe = LabelEncoder()
    data[feat] = lbe.fit_transform(data[feat])

fixlen_feature_columns = [SparseFeat(feat, vocabulary_size=data[feat].nunique(),embedding_dim=4)
                       for i,feat in enumerate(sparse_features)] + [DenseFeat(feat, 1,)
                      for feat in dense_features]

mms = MinMaxScaler(feature_range=(0, 1))
data[dense_features] = mms.fit_transform(data[dense_features])

dnn_feature_columns = fixlen_feature_columns
linear_feature_columns = fixlen_feature_columns

feature_names = get_feature_names(linear_feature_columns + dnn_feature_columns)

train, test = train_test_split(data, test_size=0.2)

train_model_input = {name:train[name] for name in feature_names}

test_model_input = {name:test[name] for name in feature_names}

device = 'cpu'
use_cuda = True
if use_cuda and torch.cuda.is_available():
    print('cuda ready...')
    device = 'cuda:0'
model = DeepFM(linear_feature_columns,dnn_feature_columns,task='binary',device=device)
model.compile("adam", "binary_crossentropy",
              metrics=['binary_crossentropy'], )

history = model.fit(train_model_input,train[target].values,batch_size=256,epochs=10,verbose=2,validation_split=0.2)
pred_ans = model.predict(test_model_input, batch_size=256)

print("")
print("test LogLoss", round(log_loss(test[target].values, pred_ans), 4))
print("test AUC", round(roc_auc_score(test[target].values, pred_ans), 4))


'''
Name of file:  Relationship
Author: Jun Yang, Yingxin Liang, Yan Pan, Puxing Zhao, Shaoqing Zhang
Purpose: This module is to scrape data of hero relationship via json data
Module imports it: main
'''
import json
import requests

def Relationship():
    #define the header for the user request
    headers = {
        'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
    }

    url = 'https://graphics.straitstimes.com/STI/STIMEDIA/Interactives/2018/04/marvel-cinematic-universe-whos-who-interactive/data/marvel-data.json'
    response = requests.get(url=url, headers=headers) #get the response from the website
    result = json.loads(response.text)

    num = 0
    names = []
    item = {0: 'friend', 1: 'enemy', 2: 'creation', 3: 'family', 4: 'work', 5: 'love'} #create dictionary for analysis

    #Collect the data based on json data
    #Use key to locate the value
    for i in result['relationship']:
        #extract data by using the key
        subject = result['relationship'][i]['id']
        object = result['relationship'][i]['target_id']

        #create the name list of all characters
        if subject not in names:
            names.append(subject)
        if object not in names:
            names.append(object)

        #create a file to store all relationship for all characters
        relation = int(result['relationship'][i]['relationship'])
        with open('relation_message.csv', 'a+') as f:
            f.write(subject + ',' + object + ',' + item[relation] + '\n')

    #create a file to store ID and character names
    for j in names:
        num += 1
        with open('names_message.csv', 'a+') as f:
            f.write(j + ',' + str(num) + '\n')

    #create a file to store id, name,status and species for all characters
    for k in result['characters']:
        id = result['characters'][k]['id']
        name = result['characters'][k]['name']
        status = result['characters'][k]['status']
        species = result['characters'][k]['species']
        with open('message.csv', 'a+') as f:
            f.write(id + ',' + name + ',' + status + ',' + species + '\n')

    print("The data has been stored in the files.")


from PDP import PDP
from JinEnv import JinEnv
from casadi import *
import math
import scipy.io as sio
import numpy as np
import time

# --------------------------- load environment ----------------------------------------
uav = JinEnv.Quadrotor()
uav.initDyn(c=0.01)
uav.initCost(wthrust=0.1)

# --------------------------- load demos data ----------------------------------------
data = sio.loadmat('../quadrotor/data/uav_demos.mat')
trajectories = data['trajectories']
true_parameter = data['true_parameter']
dt = data['dt']

# reorganize data into numpy-preferred
n_demo = trajectories.shape[1]
n_state = trajectories[0, 0]['state_traj_opt'][0, 0].shape[1]
n_control = trajectories[0, 0]['control_traj_opt'][0, 0].shape[1]

state_trajs = []
control_trajs = []
costate_trajs = []
for i in range(n_demo):
    state_traj = trajectories[0, i]['state_traj_opt'][0, 0]
    state_trajs += [state_traj]
    control_traj = trajectories[0, i]['control_traj_opt'][0, 0]
    control_trajs += [control_traj]
    costate_traj = trajectories[0, i]['costate_traj_opt'][0, 0]
    costate_trajs += [costate_traj]

# ---------------------------------------- define the KKT loss function -----------------------
# first establish a pdp object, because there are some utilities in pdp which can be used to define KKT loss
uavoc = PDP.OCSys()
uavoc.setAuxvarVariable(vertcat(uav.dyn_auxvar, uav.cost_auxvar))
uavoc.setControlVariable(uav.U)
uavoc.setStateVariable(uav.X)
dyn = uav.X + dt * uav.f
uavoc.setDyn(dyn)
uavoc.setPathCost(uav.path_cost)
uavoc.setFinalCost(uav.final_cost)
uavoc.diffPMP()
lqr_solver = PDP.LQR()

# define loss function, which is the norm of KKT residual, please find the related work for more details
KKT_loss = 0
parameter_theta = uavoc.auxvar
parameter_theta_guess = true_parameter.flatten().tolist()
parameter_lambda = []
parameter_lambda_guess = []  # in fact, this will store the true value of lambda (costates)
for i in range(n_demo):
    state_traj = state_trajs[i]
    control_traj = control_trajs[i]
    costates_traj = costate_trajs[i]
    horizon = control_traj.shape[0]
    # define costate variable
    LAM = SX.sym('lambda_1' + str(i), n_state)
    parameter_lambda += [LAM]
    parameter_lambda_guess += costates_traj[0, :].flatten().tolist()
    for t in range(0, horizon - 1):
        x_curr = state_traj[t + 1, :]
        u_curr = control_traj[t + 1, :]
        # define unknown costate
        LAM_next = SX.sym('lambda_' + str(t + 2) + str(i), n_state)
        parameter_lambda += [LAM_next]
        parameter_lambda_guess += costates_traj[t + 1, :].flatten().tolist()
        # compute the current loss
        loss_curr_1 = dot(LAM - uavoc.dHx_fn(x_curr, u_curr, LAM_next, parameter_theta),
                          LAM - uavoc.dHx_fn(x_curr, u_curr, LAM_next, parameter_theta))
        loss_curr_2 = dot(uavoc.dHu_fn(x_curr, u_curr, LAM_next, parameter_theta),
                          uavoc.dHu_fn(x_curr, u_curr, LAM_next, parameter_theta))
        KKT_loss = KKT_loss + loss_curr_1 + loss_curr_2
        # update
        LAM = LAM_next
    # final cost term
    KKT_loss = KKT_loss + dot(LAM - uavoc.dhx_fn(state_traj[-1, :], parameter_theta),
                              LAM - uavoc.dhx_fn(state_traj[-1, :], parameter_theta))

#  define KKT loss function
parameter_lambda = vcat(parameter_lambda)
parameter = vertcat(parameter_theta, parameter_lambda)
parameter_guess = parameter_theta_guess + parameter_lambda_guess
KKT_loss_fn = Function('loss_fn', [parameter], [KKT_loss])
grad_KKT_loss_fn = Function('grad_loss_fn', [parameter], [jacobian(KKT_loss, parameter)])

# ------------------------ inverse KKT: learn both the theta and costate (lambda) --------------------------

lr = 1e-7  # learning rate
for j in range(10):  # loop for trials
    start_time = time.time()
    traj_loss_trace, theta_trace, kkt_loss_trace = [], [], []

    sigma = 0.08
    initial_parameter = np.array(parameter_guess) # note we use the true parameter to initilize because otherwise the method is not working well.
    initial_parameter = initial_parameter + sigma * np.random.randn(np.size(initial_parameter)) - sigma / 2
    current_parameter = initial_parameter

    for k in range(int(2e4)):  # loop for iteration
        # update for parameter
        dp = grad_KKT_loss_fn(current_parameter).full().flatten()
        current_parameter = current_parameter - lr * dp
        current_theta = current_parameter[0:parameter_theta.numel()]
        theta_trace += [current_theta]  # only take theta
        kkt_loss = KKT_loss_fn(current_parameter).full().flatten().item()
        kkt_loss_trace += [kkt_loss]

        # solve the trajectory loss
        current_loss = 0
        for i in range(n_demo):
            # take out the demos i
            demo_state_traj = state_trajs[i]
            demo_control_traj = control_trajs[i]
            initial_state = demo_state_traj[0, :]
            horizon = demo_control_traj.shape[0]
            #  current trajectory based on current theta guess
            current_traj = uavoc.ocSolver(initial_state, horizon, current_theta)
            current_state_traj = current_traj['state_traj_opt']
            current_control_traj = current_traj['control_traj_opt']
            dldx_traj = current_state_traj - demo_state_traj
            dldu_traj = current_control_traj - demo_control_traj
            current_loss = current_loss + numpy.linalg.norm(dldx_traj) ** 2 + numpy.linalg.norm(dldu_traj) ** 2
        traj_loss_trace += [current_loss / n_demo]

        # print and terminal check
        if k % 1 == 0:
            print('trial:', j, 'iter:',k, ' loss: ', traj_loss_trace[-1])

    # save
    save_data = {'trail_no': j,
                 'loss_trace': traj_loss_trace,
                 'kkt_loss_trace': kkt_loss_trace,
                 'learning_rate': lr,
                 'parameter_trace': theta_trace,
                 'time_passed': time.time() - start_time}
    sio.savemat('./data/KKT_results_trial_' + str(j) + '.mat', {'results': save_data})


from logic import *
from rule import Rule
from input_generator import *
from supervisor import acgreedy

#Original table
data = [('New Yorks',      'NY'),
        ('New York',       'NY'),
        ('San Francisco',  'SF'),
        ('San Francisco',  'SF'),
        ('San Jose',       'SJ'),
        ('New York',       'NY'),
        ('San Francisco',  'SFO'),
        ('Berkeley City',  'Bk'),
        ('San Mateo',      'SMO'),
        ('Albany',         'AB'),
        ('San Mateo',      'SM')]

print("Original Table:")
print(data)
print("\n")

input_gen = InputGenerator(data)
data = input_gen.generate()

print("New Table:")
print(data)
print("\n")

#you need unique keys for all entries
d = {i : v for i,v in enumerate(data)}

#some property you want the db to satisfy
#E.g., one to one map between cities and codes
rule = Rule(lambda s,t: iff(eq(s,t,0), eq(s,t,1)))

#get state-action list
print("\n")
print(acgreedy(rule, d)[0])

#E.g., all codes must be len 2
rule = Rule(lambda s: len(s[1]) == 2)
print("\n")
print(acgreedy(rule, d)[0])
print("\n")


"""
Created on 01:54, June. 4th, 2021
Author: fassial
Filename: expr1.py
Description:
    Changes in spatial patterning (Ω), temporal patterning (cv) and
    cross correlation patterning (cor) as a function of weight (g_w)
    and spikelet (g_k) of the GJ network.
"""
import gc
import numpy as np
import brainpy as bp
from copy import deepcopy
# local dep
import os
import sys
sys.path.append(os.path.join("..", ".."))
import model
import stimulus
import utils

# macro
DIR_ROOT = os.getcwd()
DIR_FIGS = os.path.join(DIR_ROOT, "figs")
if not os.path.exists(DIR_FIGS): os.mkdir(DIR_FIGS)
DIR_OUTPUTS = os.path.join(DIR_ROOT, "outputs")
if not os.path.exists(DIR_OUTPUTS): os.mkdir(DIR_OUTPUTS)
DIR_OUTPUTS_STIM = os.path.join(DIR_OUTPUTS, "stimulus")
if not os.path.exists(DIR_OUTPUTS_STIM): os.mkdir(DIR_OUTPUTS_STIM)
DIR_OUTPUTS_SPIKE = os.path.join(DIR_OUTPUTS, "spike")
if not os.path.exists(DIR_OUTPUTS_SPIKE): os.mkdir(DIR_OUTPUTS_SPIKE)

## default params
# default stim_params
default_stim_params = {
    "white": stimulus.stim_params(
        name = "white",
        height = 50,
        width = 50,
        duration = 300,
        others = {
            "noise": 0.,
        }
    ),
    "black": stimulus.stim_params(
        name = "black",
        height = 50,
        width = 50,
        duration = 300,
        others = {
            "noise": 0.,
        }
    ),
    "normal": stimulus.stim_params(
        name = "normal",
        height = 50,
        width = 50,
        duration = 300,
        others = {
            "freqs": np.full((50, 50), 20., dtype = np.float32),
            "noise": 0.,
        }
    ),
    "frate_increase": stimulus.stim_params(
        name = "frate_increase",
        height = 50,
        width = 50,
        duration = 300,
        others = {
            "freqs": np.full((50, 50), 20., dtype = np.float32),
            "factor": 4.,    # (1,16)
            "ratio": .2,
            "noise": 0.,
        }
    ),
}
# default net_params
default_net_params = {
    "neurons": {
        ## neurons params
        # shape params
        "size": (50, 50),
        # dynamic params
        "V_init": "gaussian",
        "tau": 5.,
        "t_refractory": 1.,
        "noise": .2,
    },
    "GJ": {
        # gap junction
        "weight": .5,
        "k_spikelet": .1,
        "conn": bp.connect.GridEight(include_self = False),
    },
}

def expr(gj_w, gj_k, run_params, dt = 0.01):
    print("processing expr(" +\
        str(gj_w) + "," + str(gj_k) + ")..."
    )

    # init seed
    np.random.seed(0)

    # init expr_curr & stim
    expr_curr = run_params["expr_curr"]
    stim = run_params["stim"]

    ## prepare expr
    # init net_params
    net_params = deepcopy(default_net_params)
    net_params["GJ"]["weight"] = gj_w; net_params["GJ"]["k_spikelet"] = gj_k; print(net_params)

    ## exec expr
    # inst GJ2DNet
    net = model.GJ2DNet(net_params = net_params, run_params = {
        "inputs": stim,
        "dt": dt,
        "duration": default_stim_params[expr_curr].duration,
    })
    # net run
    net.run(report = True)
    # show net.mon
    net_monitors = net.get_monitors()
    net.show(img_fname = os.path.join(DIR_FIGS,
        expr_curr + "-" +\
        str(gj_w) + "-" + str(gj_k) + ".png"
    ))
    net.save(spike_fname = os.path.join(DIR_OUTPUTS_SPIKE,
        expr_curr + "-" +\
        str(gj_w) + "-" + str(gj_k) + ".csv"
    ))

    ## compute statistic-values
    # compute cor
    cor = bp.measure.cross_correlation(
        spikes = net_monitors.spike,
        bin = 10,
        dt = dt
    )
    # compute omega & cv
    spike = net_monitors.spike.T; print(spike.shape)
    omega = utils.get_omega(
        spike = spike,
        bin = 100,
        dt = dt,
        N = 100
    )
    cv = np.mean(utils.get_cv(
        spike = spike,
        dt = dt
    ))

    # rm vars
    del(net_params); del(net); del(net_monitors); del(spike); gc.collect()

    return (omega, cv, cor)

def main(dt = 0.01):
    # init omegas & cvs & cors
    omegas = []; cvs = []; cors = []

    # init gj_ws & gj_ks
    gj_ws = [.05, .1, .15, .2, .25, .3, .35, .4, .45, .5]
    gj_ks = [.05, .1, .15, .2, .25, .3, .35, .4, .45, .5]

    ## init backend
    bp.backend.set(dt = dt)
    bp.backend.set(backend = "numba")
    ## init expr_curr
    expr_curr = "white"
    ## get stim
    # get stim_fname
    stim_fname = os.path.join(
        DIR_OUTPUTS_STIM,
        expr_curr + "-" + str(default_stim_params[expr_curr].duration) + ".csv"
    )
    # get stim
    if os.path.exists(stim_fname):
        # load stim
        stim = np.loadtxt(
            fname = stim_fname,
            delimiter = ","
        )
    else:
        # get stim
        stim, _ = stimulus.stimulus.get(
            stim_params = default_stim_params[expr_curr]
        )
        # save stim
        np.savetxt(fname = stim_fname, X = stim, delimiter = ",")
    # rescale stim
    stim *= .9; print(stim.shape)

    # set omegas & cvs & cors
    for gj_w in gj_ws:
        omega = []; cv = []; cor = []
        for gj_k in gj_ks:
            res = expr(
                gj_w = gj_w,
                gj_k = gj_k,
                run_params = {
                    "expr_curr": expr_curr,
                    "stim": stim,
                },
                dt = dt
            ); omega.append(res[0]); cv.append(res[1]); cor.append(res[2])
        omegas.append(omega); cvs.append(cv); cors.append(cor)
    omegas = np.array(omegas); cvs = np.array(cvs); cors = np.array(cors)

    # save omegas & cvs & cors
    np.savetxt(
        fname = os.path.join(DIR_OUTPUTS, "omegas.csv"),
        X = omegas,
        delimiter = ","
    )
    np.savetxt(
        fname = os.path.join(DIR_OUTPUTS, "cvs.csv"),
        X = cvs,
        delimiter = ","
    )
    np.savetxt(
        fname = os.path.join(DIR_OUTPUTS, "cors.csv"),
        X = cors,
        delimiter = ","
    )

if __name__ == "__main__":
    main()


#coding:utf8
'''

1、从raw AndroidManifest.xml文件或APK文件中获取暴露组件
2、从raw AndroidManifest.xml文件或APK文件中获取明文AndroidManifest.xml

'''
# 加密zip ChilkatZip

import bytecode

from axmlprinter import AXMLPrinter
from bytecode import SV

import zipfile, StringIO
from struct import pack, unpack
from xml.dom import minidom

class APKCook:
    def __init__(self, filename, single=False, text=False):

        self.filename = filename
        self.xml = {}
        self.package = ""
        self.androidversion = {}
        self.raw_manifest = ""

        fd = open(filename, "rb")
        self.__raw = fd.read()
        fd.close()

        if single:
            self.raw_manifest = self.__raw
        else:
            self.zip = zipfile.ZipFile(StringIO.StringIO(self.__raw))
            for i in self.zip.namelist():
                if i == "AndroidManifest.xml":
                    self.raw_manifest = self.zip.read(i)
        if text:
            self.xml = minidom.parseString(self.raw_manifest)
        else:
            self.xml = minidom.parseString(AXMLPrinter(self.raw_manifest).getBuff())

        self.package = self.xml.documentElement.getAttribute("package")
        self.androidversion["Code"] = self.xml.documentElement.getAttribute("android:versionCode")
        self.androidversion["Name"] = self.xml.documentElement.getAttribute("android:versionName")

    def get_package(self):
        return self.package

    def get_androidversion_code(self):
        return self.androidversion["Code"]

    def get_androidversion_name(self):
        return self.androidversion["Name"]

    def get_permission(self):
        out = []
        for item in self.xml.getElementsByTagName("permission"):
            name = item.getAttribute("android:name")
            pl = item.getAttribute("android:protectionLevel")
            if pl == "0x00000000":
                name += "@normal"
            elif pl == "0x00000001":
                name += "@dangerous"
            elif pl == "0x00000002":
                name += "@signature"
            elif pl == "0x00000003":
                name += "@signatureOrSystem"

            out.append(name)

        return out;

    def get_element(self, tag_name, attribute):
        for item in self.xml.getElementsByTagName(tag_name):
            value = item.getAttribute(attribute)

            if len(value) > 0:
                return value
        return None

    def get_min_sdk_version(self):
        return self.get_element("uses-sdk", "android:minSdkVersion")

    def get_target_sdk_version(self):
        return self.get_element("uses-sdk", "android:targetSdkVersion")

    def get_activities(self):
        out = []
        for item in self.xml.getElementsByTagName("activity"):
            exported = item.getAttribute("android:exported")
            name = ""
            if exported == "true":
                name = item.getAttribute("android:name")
            elif exported != "false":
                #未设置exported属性，则检查是否有intent-filter
                if len(item.getElementsByTagName("intent-filter")) > 0:
                    name = item.getAttribute("android:name")

            #未开启
            if item.getAttribute("android:enabled") == "false":
                if name != "":
                    name = "!disabled!"+name

            #要求权限
            if item.getAttribute("android:permission") != "":
                if name != "":
                    name += "@"+item.getAttribute("android:permission")

            if name != "":
                out.append(name)

        for item in self.xml.getElementsByTagName("activity-alias"):
            exported = item.getAttribute("android:exported")
            name = ""
            if exported == "true":
                name = item.getAttribute("android:name")
            elif exported != "false":
                #未设置exported属性，则检查是否有intent-filter
                if len(item.getElementsByTagName("intent-filter")) > 0:
                    name = item.getAttribute("android:name")

            #未开启
            if item.getAttribute("android:enabled") == "false":
                if name != "":
                    name = "!disabled!"+name

            #要求权限
            if item.getAttribute("android:permission") != "":
                if name != "":
                    name += "@"+item.getAttribute("android:permission")

            if name != "":
                out.append(name)

        return out

    def get_services(self):
        out = []
        for item in self.xml.getElementsByTagName("service"):
            exported = item.getAttribute("android:exported")
            name = ""
            if exported == "true":
                name = item.getAttribute("android:name")
            elif exported != "false":
                #未设置exported属性，则检查是否有intent-filter
                if len(item.getElementsByTagName("intent-filter")) > 0:
                    name = item.getAttribute("android:name")

            #未开启
            if item.getAttribute("android:enabled") == "false":
                if name != "":
                    name = "!disabled!"+name

            #要求权限
            if item.getAttribute("android:permission") != "":
                if name != "":
                    name += "@"+item.getAttribute("android:permission")

            if name != "":
                out.append(name)

        return out

    def get_receivers(self):
        out = []
        for item in self.xml.getElementsByTagName("receiver"):
            exported = item.getAttribute("android:exported")
            name = ""
            if exported == "true":
                name = item.getAttribute("android:name")
            elif exported != "false":
                #未设置exported属性，则检查是否有intent-filter
                if len(item.getElementsByTagName("intent-filter")) > 0:
                    name = item.getAttribute("android:name")

            #未开启
            if item.getAttribute("android:enabled") == "false":
                if name != "":
                    name = "!disabled!"+name

            #要求权限
            if item.getAttribute("android:permission") != "":
                if name != "":
                    name += "@"+item.getAttribute("android:permission")

            if name != "":
                out.append(name)

        return out

    def get_providers(self):
        out = []
        for item in self.xml.getElementsByTagName("provider"):
            exported = item.getAttribute("android:exported")
            name = ""
            if exported == "true":
                name = item.getAttribute("android:name")
            elif exported != "false":
                #未设置exported属性，则检查是否有intent-filter
                if len(item.getElementsByTagName("intent-filter")) > 0:
                    name = item.getAttribute("android:name")
            #####新增####临时访问权限
            elif item.getAttribute("android:grantUriPermissions") == "true":
                name = item.getAttribute("android:name")

            #未开启
            if item.getAttribute("android:enabled") == "false":
                if name != "":
                    name = "!disabled!"+name

            #要求权限
            if item.getAttribute("android:permission") != "":
                if name != "":
                    name += "@"+item.getAttribute("android:permission")

            if name != "":
                out.append(name)

        return out

    def show(self):
        print ("===暴露组件===(注意调用权限，动态recevier未检测)")
        print ("Package: "+self.get_package())
        print ("VersionName: "+self.androidversion["Name"]+" VersionCode: "+self.androidversion["Code"])
        print ("Min_sdk: "+self.get_min_sdk_version()+" Target_sdk: "+self.get_target_sdk_version())
        print ("==Activity:\n"+"\n".join(self.get_activities()))
        print ("==Service:\n"+"\n".join(self.get_services()))
        print ("==Receive:\n"+"\n".join(self.get_receivers()))
        print ("==Provider:\n"+"\n".join(self.get_providers()))
        print ("==Permission:\n"+"\n".join(self.get_permission()))

    def output(self):
        print(AXMLPrinter(self.raw_manifest).getBuff())

if __name__ == "__main__":
    apkcook = APKCook('../../oemapp/thememanager.apk')
    apkcook.show()

    # apkcook = APKCook('AndroidManifest.xml' ,True)
    # apkcook.show()


"""
Some d3 trajectory plots (with networkx)
"""

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

from util import RandomColor

import matplotlib as mpl
# mpl.rcParams["savefig.dpi"] = 50

def simple_nx_trajectory(frame, node_size=10, figsize=50, show=True, newfig=True, ax=None):
    """
    Construct a networkx graph from the trajectory and plot it using matplotlib (not d3)

    :param frame: Trajectory
    :return: figure
    """

    # First construct the graph; each node is connected only the next one
    G = nx.Graph()
    n = len(frame)
    for i in range(n-1):
        G.add_edge(i, i+1)

    # generate plot
    if newfig:
        plt.figure(figsize=(figsize, figsize))

    if ax is None:
        ax = plt.gca()

    nx.draw(G, pos=frame[list(frame.geo_cols)].values, node_size=node_size, node_color=np.random.rand(3,1), ax=ax)

    if show:
        plt.show()

def simple_d3_trajectory(frame):
    pass

def simple_nx_segmented_trajectory(frame, ax=None):

    # First construct the graph; each node is connected only the next one
    G = nx.Graph()
    n = len(frame)
    for i in range(n - 1):
        G.add_edge(i, i + 1)

    if ax is None:
        ax = plt.gca()

    # Draw nodes and edges seperately
    pos = frame[list(frame.geo_cols)].values
    node_sizes = (frame["DBSCAN_n"].values > 500) * 10

    color = RandomColor.sample_map()

    nx.draw_networkx_nodes(G, pos, node_color='r', node_size=node_sizes, linewidths=0, ax=ax)
    nx.draw_networkx_edges(G, pos, edge_color=color, ax=ax, alpha=.6)

def nx_trajectory(frame, ax=None, node_sizes=10, static_node_size=20, cmap='jet'):

    # First construct the graph; each node is connected only the next one
    G = nx.Graph()
    n = len(frame)
    for i in range(n - 1):
        G.add_edge(i, i + 1)

    if ax is None:
        ax = plt.gca()

    # Draw nodes and edges seperately
    pos = frame[list(frame.geo_cols)].values

    if node_sizes is None:
        node_sizes = (frame["DBSCAN_n"].values > 500) * static_node_size

    # color = RandomColor.sample_map(cmap=plt.cm.get_cmap(cmap))
    color = RandomColor.sample_rgb()

    nx.draw_networkx_nodes(G, pos, node_color=color, node_size=node_sizes, linewidths=0, ax=ax)
    nx.draw_networkx_edges(G, pos, edge_color=color, ax=ax, alpha=.85)

def intensity_map(frames, nbins=200, figsize=20):
    plt.figure(figsize=(figsize, figsize), facecolor='black')
    plt.axis('off')

    pos = np.vstack((frame[list(frame.geo_cols)].values for frame in frames))
    hist, xedges, yedges = np.histogram2d(pos[:, 0], pos[:, 1], bins=nbins)

    plt.imshow(hist, extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], cmap=plt.get_cmap('hot'), norm=LogNorm())
    plt.savefig("C:\\temp\\heat.png", facecolor="black")
    plt.savefig("C:\\temp\\heat.pdf", facecolor="black")


# -*- coding:utf-8 -*-
"""
"""
__author__ = "Cliff.wang"
import configparser
import logging
import os, sys

class Settings():

    def __init__(self):
        # 获取编程环境下的代码路径
        self.path = os.path.abspath(os.path.dirname(__file__))
        # 获取打包后的可执行文件路径
        # self.path = os.path.dirname(sys.executable)

        self.logger = self._getLogger()

        config = configparser.ConfigParser()
        confFile = os.path.join(os.path.dirname(self.path), "srv.conf")
        if not os.path.exists(confFile):
            confFile = os.path.join(self.path, "srv.conf")
        config.read(confFile, encoding="utf-8")

        # 数据库服务器
        self.serverHost = config.get("dbServer", "host")         # 服务端地址
        if self.serverHost[-1:] == "/":
            self.serverHost = self.serverHost[:-1]
        self.serverUser = config.get("dbServer", "user")         # 服务端用户名
        self.serverPwd = config.get("dbServer", "password")      # 服务端密码
        self.serverDb = config.get("dbServer", "database")       # 服务端数据库名

        # web服务器
        self.webHost = config.get("webServer", "host")          # web服务器
        self.webPort = config.getint("webServer", "port")          # web端口

        # 业务控制
        self.vipClass = config.get("business", "vipclass")          # 默认会员类别
        self.branchNo = config.get("business", "branchNo")          # 默认会员类别
        self.rptTitle = config.get("business", "rptTitle")          # 报表数据标题

    def _getLogger(self):
        logger = logging.getLogger("[DataInterCatering]")
        handler = logging.FileHandler(os.path.join(self.path, "service.log"))
        formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.setLevel(logging.INFO)

        return logger

if __name__ == "__main__":
    sett = Settings(r"E:\AI\Python\proDataInter\dataInterKingdee\config")
    i = 1
    i += 1


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

from rest_framework import serializers

from admin_app.places.models import Place
from .core import ContentSerializer
from .fields import LocationField
from .payments import PaymentSerializer
from .serializers import JoinSerializer
from .serializers import RateSerializer
from .serializers import ContactsSerializer
from .schedule.common import ScheduleSerializer

class PlacePricesSerializer(JoinSerializer):
    # 'from' is using for import
    from_ = serializers.FloatField(source='price_from')
    till = serializers.FloatField(source='price_till')

    class Meta:
        model = Place
        fields = ('from_', 'till')

class LocationSerializer(JoinSerializer):
    city = serializers.StringRelatedField()
    location = LocationField()
    metro_ids = serializers.PrimaryKeyRelatedField(
        source='metro', many=True, read_only='True'
    )

    class Meta:
        model = Place
        fields = ('city', 'address', 'location', 'metro_ids')

class WorkTimeSerializer(JoinSerializer):
    from_ = serializers.TimeField(source='w_time_from')
    till = serializers.TimeField(source='w_time_till')

    class Meta:
        model = Place
        fields = ('from_', 'till', 'timetable')

class PlaceViewNameScheduleSerializer(ScheduleSerializer):

    class Meta(ScheduleSerializer.Meta):
        alternative = {
            'params': {
                'source': '*',
                'read_only': True,
                'view_name': 'place-schedule',
                'lookup_field': 'slug',
            }
        }

class PlaceSerializer(ContentSerializer):
    location = LocationSerializer()
    work_time = WorkTimeSerializer()
    contacts = ContactsSerializer(model=Place)
    rate = RateSerializer(model=Place)
    prices = PlacePricesSerializer()
    payment = PaymentSerializer()
    schedule = PlaceViewNameScheduleSerializer(source='sessions', many=True)

    class Meta:
        model = Place
        fields = ContentSerializer.Meta.fields + (
            'location',
            'work_time',
            'contacts',
            'rate',
            'prices',
            'payment',
            'schedule',
        )
        alternative = {
            'params': {
                'read_only': True,
                'lookup_field': 'slug',
                'view_name': 'place-detail',
            }
        }


#!/usr/bin/env python
from constants import STATE
import os
import sqlite3

scriptdir = os.path.dirname(os.path.realpath(__file__))
conn = sqlite3.connect(scriptdir + '/../blm.sqlite')

ignored = set()
for i in open('ignored.txt').readlines():
    ignored.add(i.strip())

reviewed = set()
for i in open('to-review.txt').readlines():
    reviewed.add(i.strip())

query = '''
SELECT imageid FROM Plat_Image WHERE sheet_nr = 1 AND back_of_plat = 'N' AND dm_id > ?
'''

start = 398000
c = conn.cursor()
c.execute(query, (start,))
ids = [str(x[0]) for x in c.fetchall() if str(x[0]).startswith(STATE)]
diff = set(ids) - ignored - reviewed

diff = set([x[0:15] for x in diff])

import platchooser
platchooser.show(sorted(diff))


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

"""Created on Fri Apr 26 12:10:35 2019@author: milroa1"""

"""

    A frame is a widget that displays just as a simple rectangle. Frames are primarily used as a container for other widgets,
             which are under the control of a geometry manager such as grid.

    A label is a widget that displays text or images, typically that the user will just view but not otherwise interact with.
            Labels are used for such things as identifying controls or other parts of the user interface, providing textual feedback or results, etc.

    A button, unlike a frame or label, is very much designed for the user to interact with, and in particular, press to perform some action.
             Like labels, they can display text or images, but also have a whole range of new options used to control their behavior.

            A checkbutton is like a regular button, except that not only can the user press it, which will invoke a command callback,
                    but it also holds a binary value of some kind (i.e. a toggle). Checkbuttons are used all the time when a user is asked to choose between e.g. two different values for an option.

            A radiobutton lets you choose between one of a number of mutually exclusive choices; unlike a checkbutton, it is not
                    limited to just two choices. Radiobuttons are always used together in a set, and are a good option when the number of choices is fairly small,

            An entry presents the user with a single line text field that they can use to type in a string value. These can be just
                    about anything: their name, a city, a password, social security number, and so on.

            A combobox combines an entry with a list of choices available to the user. This lets them either choose from a set of values
                    you've provided (e.g. typical settings), but also put in their own value (e.g. for less common cases you don't want to include in the list).

A text widget provides users with an area so that they can enter multiple lines of text. Text widgets are part of the classic Tk widgets, not the themed Tk widgets.
A scrollbar helps the user to see all parts of another widget, whose content is typically much larger than what can be shown in the available screen space.
A progressbar widget provides a way to give feedback to the user about the progress of a lengthy operation.
A spinbox widget allows users to choose numbers (or in fact, items from an arbitrary list).

A treeview widget can display and allow browsing through a hierarchy of items, and can show one or more attributes of each item as columns to the right of the tree.

#######################################################################################################################################################################
frame = ttk.Frame(parent)
frame['padding'] = (5,10)
frame['borderwidth'] = 2
frame['relief'] = 'sunken'

label = ttk.Label(parent, text='Full name:')
resultsContents = StringVar()
label['textvariable'] = resultsContents
resultsContents.set('New value to display')
image = PhotoImage(file='myimage.gif')
label['image'] = image

button = ttk.Button(parent, text='Okay', command=submitForm)
button.state(['disabled'])            # set the disabled flag, disabling the button
button.state(['!disabled'])

check = ttk.Checkbutton(parent, text='Use Metric',
	    command=metricChanged, variable=measureSystem,
	    onvalue='metric', offvalue='imperial')

phone = StringVar()
home = ttk.Radiobutton(parent, text='Home', variable=phone, value='home')
office = ttk.Radiobutton(parent, text='Office', variable=phone, value='office')
cell = ttk.Radiobutton(parent, text='Mobile', variable=phone, value='cell')

username = StringVar()
name = ttk.Entry(parent, textvariable=username)

countryvar = StringVar()
country = ttk.Combobox(parent, textvariable=countryvar)

country.bind('<<ComboboxSelected>>', function)
country['values'] = ('USA', 'Canada', 'Australia')
"""

#https://tkdocs.com/tutorial/grid.html
#%%################################################################################################################################################################

import tkinter as tk
from tkinter import Label,Frame,Button,Entry,Checkbutton,Menu,Canvas,PhotoImage
from tkinter import BOTTOM,LEFT,X,Y,E,TOP,SUNKEN,W
from PIL import ImageTk, Image
from tkinter import filedialog
import os

def tk_img(filepath):
    if filepath.endswith(".jpg") or filepath.endswith(".png"):
        return ImageTk.PhotoImage(Image.open(filepath))
    return PhotoImage(filepath)# gifs I think work with this

def printbutton(*args):
    """    frame.bind("<Button-1>", printbutton("left"))    """
    def print_temp(event):
        print(*args)
    return print_temp

#%%############################################################################################
##################################################################################
# Most Basic 0

window = tk.Tk() # create window

window.mainloop()#keep window open

##################################################################################
## Baisc Window 1

window = tk.Tk()
window.title("Example 1")

label = Label(window, text="This is label")
label.pack()# just packs text it in there
window.mainloop() # puts it inf loop so window continously displays
##################################################################################
##  Window 2

window = tk.Tk() # create window
window.title("Example 2")

topframe = Frame(window)
topframe.pack()
bottomframe = Frame(window)
bottomframe.pack(side=BOTTOM)
buttons={}
for i, clr in enumerate(["red","red","red","purple"]):
    buttons[i] =  Button(topframe if clr =="purple" else bottomframe, text=f"Button-{i}", fg=clr)

for i,b in buttons.items():
    if i<3:
       b.pack(side=LEFT)
    else:
       b.pack(side=BOTTOM)

window.mainloop()#keep window open
##################################################################################
## Basic Window 3

window = tk.Tk() # create window
window.title("Example 3")

one =Label(window, text="One", bg="red",fg="white")
one.pack()
two =Label(window, text="Two", bg="green",fg="black")
two.pack(fill=X)
three =Label(window, text="Three", bg="blue",fg="white")
three.pack(side=LEFT,fill=Y)
window.mainloop()
##################################################################################
## Basic Window 4

window = tk.Tk() # create window
window.title("Example 4")

label_1 = Label(window,text="Name")
label_2 = Label(window,text="Password")
entry_1 = Entry(window)
entry_2 = Entry(window)

label_1.grid(row=0,sticky=E)
label_2.grid(row=1,sticky=E)

entry_1.grid(row=0,column=1)
entry_2.grid(row=1,column=1)

c_button = Checkbutton(window,text="Keep me logged in ")
c_button.grid(columnspan=2)

window.mainloop()
##################################################################################
# binding fuction

window = tk.Tk() # create window
window.title("Example 5")
def printdog(event):
    print("Dog!!")

button_1 = Button(window, text="bbbuton", )
button_1.bind("<Button-1>",printdog)#left mouse button
button_1.pack()
window.mainloop()

##################################################################################

def leftclick(event):
    print("Left")
def rightclick(event):
    print("Right")

window = tk.Tk()
window.title("Example 6")
frame = Frame(window, width=300, height=250)
frame.bind("<Button-1>", leftclick)
frame.bind("<Button-3>",printbutton("Right")) # custom code at top written for this
frame.pack()

window.mainloop()

##################################################################################

class BuckysBall:
    def __init__(self,master):
        frame = Frame(master)
        frame.pack()

        self.printbutton = Button(frame, text = "Print-Message", command=self.printMessage)
        self.printbutton.pack(side=LEFT)

        self.quitButton = Button(frame, text="Quit", command=frame.quit) # quit wasnt working
        self.quitButton.pack(side=LEFT)

    def printMessage(self):
        print("WOW this worked")
window = tk.Tk()
b = BuckysBall(window)
window.mainloop()

##################################################################################

# Maybe below would be better sytax
#with tkwindow() as window:
#    with Menu(window) as menu:
#        window.config(menu=menu)
#        with Menu(menu, tearoff=0) as submenu:# this gets ride of the "----" at top
#            menu.add_cascade(label="File",menu=submenu)
#            submenu.add_command(label="New Project",command=donothing)
#            submenu.add_command(label="2nd one",command=donothing)
#            submenu.add_separator()
#            submenu.add_command(label="Exit",command=donothing)
#        with Menu(menu) as editmenu:# this gets ride of the "----" at top
#            menu.add_cascade(label="Other",menu=editmenu)
#            editmenu.add_command(label="Redo",command=donothing)
#    with Frame(window, bg="blue",pack={"side":TOP,"fill":X}) as toolbar:
#        insertButt = Button(toolbar,text="Insert Image",command=donothing,pack={"side":LEFT, "padx":2,"pady":2} )
#        printButt  = Button(toolbar,text="Insert Image",command=donothing,pack={"side":LEFT, "padx":2,"pady":2} )
#
#

def donothing():
    print("ok ok I wont")

window = tk.Tk()

menu = Menu(window)
window.config(menu=menu)
submenu = Menu(menu, tearoff=0)# this gets ride of the "----" at top
menu.add_cascade(label="File",menu=submenu)
submenu.add_command(label="New Project",command=donothing)
submenu.add_command(label="2nd one",command=donothing)
submenu.add_separator()
submenu.add_command(label="Exit",command=donothing)

editmenu= Menu(menu)
menu.add_cascade(label="Other",menu=editmenu)
editmenu.add_command(label="Redo",command=donothing)

toolbar = Frame(window, bg="blue")

insertButt = Button(toolbar,text="Insert Image",command=donothing)
insertButt.pack(side=LEFT, padx=2,pady=2)
printButt = Button(toolbar,text="Print",command=donothing)
printButt.pack(side=LEFT, padx=2,pady=2)
toolbar.pack(side=TOP,fill=X)

##status bar at the bottom
status = Label(window,text="Blank",bd=1,relief=SUNKEN, anchor=W)
status.pack(side=BOTTOM,fill=X)

window.mainloop()

##################################################################################

# message boxs

import tkinter.messagebox as msgbox
window = tk.Tk()
#tk.messagebox.showinfo("WIINDOW TITLE","DOGS AND CATS")
msgbox.showinfo("info name","This is a Test")
ans = msgbox.askquestion("Q1","WHAT IS A COW")
if ans =="yes":
    print("cowcowo cow")

window.mainloop()

##################################################################################

window = tk.Tk()

canvas = Canvas(window,width=200,height=100)
canvas.pack()
blackline = canvas.create_line( 0,  0,200,50)
redline   = canvas.create_line( 0,100,200,50,fill="red")
greenbox  = canvas.create_rectangle(25,25,120,60,fill="green")
canvas.delete(redline)
window.mainloop()
##################################################################################

path = r"C:\Users\milroa1\Downloads\New2_7\_106598514_gettyimages-175035140.jpg"
path = r"C:\Users\milroa1\Downloads\DKL.png"

#This creates the main window of an application
window = tk.Tk()

img = tk_img(path)
label_img = tk.Label(window, image = img)
label_img.pack(side = "bottom", fill = "both", expand = "yes")

window.mainloop()

##################################################################################

def ImgGallery(*args):
    class imgbutton:
        def __init__(self,parent,files):
            self.files,self.count = files, 0
            self.nfiles = len(self.files)
            self.img = tk_img(self.files[self.count])
            self.label_img = tk.Label(parent, image = self.img)

            self.label_img.bind("<Button-1>", self.shift_image( -1))
            self.label_img.bind("<Button-3>", self.shift_image( +1))
            self.label_img.bind("<Left>"    , self.shift_image( -1)) # "<KeyPress>"
            self.label_img.bind("<Right>"   , self.shift_image( +1)) # "<KeyPress>"
            self.label_img.bind("<Up>"      , self.shift_image(+10))
            self.label_img.bind("<Down>"    , self.shift_image(-10))
            self.label_img.bind("<p>"       , self.printfilepath)

            self.label_img.focus_force()#focus_set()
            self.label_img.pack(side="bottom", fill="both", expand="yes")
        def printfilepath(self,*args):
            print(self.files[self.count])

        def shift_image(self,shift):
            def mover(args):
                self.count =(self.count+shift) % self.nfiles
                self.draw_img()
            return mover

        def draw_img(self):
            self.img = tk_img(self.files[self.count])
            self.label_img.configure(image=self.img)
            self.label_img.image = self.img

    window = tk.Tk()
    if len(args)==0:
       folder = filedialog.askdirectory()
    else:
       folder = args[0]
    files = [folder+"/"+f for f in os.listdir(folder)  if (os.path.isfile(folder+"/"+f) and (f.endswith(".jpg") or f.endswith(".png")))]
    frame = Frame(window, width=300, height =20).place(x=700, y=0)
    imgbutton(frame, files)
    window.mainloop()

ImgGallery()

#%%
################################################
## Dynamic Content

counter = 0
def counter_label(label):
  counter = 0
  def count():
    global counter
    counter += 1
    label.config(text=str(counter))
    label.after(1000, count)
  count()

root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="dark green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()
#####################################################

window = tk.Tk()
window.title("Example 6")
frame = Frame(window, width=300, height=250)
frame.bind("<Button-1>", printbutton("left"))
frame.bind("<Button-3>", printbutton("right"))
frame.pack()

window.mainloop()

window = tk.Tk() # create window

window.mainloop()#keep window open

## Baisc Window 1
window = tk.Tk()
window.title("Example 1")

label = Label(window, text="This is label")
label.pack()# just packs text it in there
window.mainloop() # puts it inf loop so window continously displays

##  Window 2
window = tk.Tk() # create window
window.title("Example 2")

topframe = Frame(window)
topframe.pack()
bottomframe = Frame(window)
bottomframe.pack(side=BOTTOM)
buttons={}
for i, clr in enumerate(["red","red","red","purple"]):
    buttons[i] =  Button(topframe if clr =="purple" else bottomframe, text=f"Button-{i}", fg=clr)

b[0].pack(side=LEFT)
b[1].pack(side=LEFT)
b[2].pack(side=LEFT)
b[3].pack(side=BOTTOM)

window.mainloop()#keep window open

## Basic Window 3
##################################################################################
window = tk.Tk() # create window
window.title("Example 3")

one =Label(window, text="One", bg="red",fg="white")
one.bind("<Button-3>")
one.pack()
two =Label(window, text="Two", bg="green",fg="black")
two.pack(fill=X)
three =Label(window, text="Three", bg="blue",fg="white")
three.pack(side=LEFT,fill=Y)
window.mainloop()
##################################################################################

## Basic Window 4
window = tk.Tk() # create window
window.title("Example 4")

label_1 = Label(window,text="Name")
label_2 = Label(window,text="Password")
entry_1 = Entry(window)
entry_2 = Entry(window)

label_1.grid(row=0,sticky=E)
label_2.grid(row=1,sticky=E)

entry_1.grid(row=0,column=1)
entry_2.grid(row=1,column=1)

c_button = Checkbutton(window,text="Keep me logged in ")
c_button.grid(columnspan=2)

window.mainloop()

##################################################################################

from tkinter import *
from tkinter import ttk

def calculate(*args):
    try:
        value = float(feet.get())
        meters.set(round((0.3048 * float(value) ),6))
    except ValueError:
        pass

root = Tk()
root.title("Feet to Meters")

mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

feet, meters   = StringVar() , StringVar()

feet_entry = ttk.Entry(mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))

ttk.Label( mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W)

ttk.Label(mainframe, text="feet"            ).grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, text="meters"          ).grid(column=3, row=2, sticky=W)

for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=5)

feet_entry.focus()
root.bind('<Return>', calculate)

root.mainloop()

#%%%%%%%%%%%%%

########################################################################
expand_top_left_box = True

from tkinter import *
from tkinter import ttk

root = Tk()

content = ttk.Frame(root, padding=(3,3,12,12))
frame = ttk.Frame(content, borderwidth=5, relief="sunken", width=200, height=100)
namelbl = ttk.Label(content, text="Name")
name = ttk.Entry(content)

onevar   = BooleanVar()
twovar   = BooleanVar()
threevar = BooleanVar()

onevar.set(True)
twovar.set(False)
threevar.set(True)

one = ttk.Checkbutton(content, text="One", variable=onevar, onvalue=True)
two = ttk.Checkbutton(content, text="Two", variable=twovar, onvalue=True)
three = ttk.Checkbutton(content, text="Three", variable=threevar, onvalue=True)
ok = ttk.Button(content, text="Okay")
cancel = ttk.Button(content, text="Cancel")

content.grid(column=0, row=0, sticky=(N, S, E, W))
frame.grid(  column=0, row=0, columnspan=3, rowspan=2, sticky=(N, S, E, W))
namelbl.grid(column=3, row=0, columnspan=2, sticky=(N, W), padx=5)
name.grid(   column=3, row=1, columnspan=2, sticky=(N, E, W), pady=5, padx=5)
one.grid(    column=0, row=3)
two.grid(    column=1, row=3)
three.grid(  column=2, row=3)
ok.grid(     column=3, row=3)
cancel.grid( column=4, row=3)

if expand_top_left_box:
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)
    content.columnconfigure(0, weight=3)
    content.columnconfigure(1, weight=3)
    content.columnconfigure(2, weight=3)
    content.columnconfigure(3, weight=1)
    content.columnconfigure(4, weight=1)
    content.rowconfigure(1, weight=1)

root.mainloop()
#######################################################################
#                    Dynamic Buttons
#######################################################################

import tkinter as tk
from tkinter import font  as tkfont

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One", command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page", command=lambda: controller.show_frame("StartPage"))
        button.pack()

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

##############################################################################################################

from tkinter import *

def raise_frame(frame):
    frame.tkraise()

root = Tk()

f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)

for frame in (f1, f2, f3, f4):
    frame.grid(row=0, column=0, sticky='news')

Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()

Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()

Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')

Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()

raise_frame(f1)
root.mainloop()
##############################################################################################################

from tkinter import *

def raise_frame(frame):
    frame.tkraise()

root = Tk()

f1 = Frame(root)
f2 = Frame(root)

for frame in (f1, f2):
    frame.grid(row=0, column=0, sticky='news')

Label(f1, text='FRAME 1').pack()
Button(f1, text='Add extra button', command=lambda:raise_frame(f2)).pack()

Label(f2, text='FRAME 1').pack()
Button(f2, text='Add extra button', command=lambda:raise_frame(f1)).pack()
Button(f2, text='Nothing').pack()

raise_frame(f1)
root.mainloop()

###################################################
#  Dynamic Buttons Class add button
###################################################
from tkinter import *
def raise_frame(frame):
    frame.tkraise()

class GUI_Dynamic_Buttons:
    def __init__(self,root,extra_button=False):
        self.root = root
        self.extra_button = extra_button
        #create a frame and display
        self.create_frame()

    def create_frame(self):
       # create a frame(based on settings) and display
       self.frame = Frame(self.root)
       self.frame.grid(row=0, column=0, sticky='news')
       Label(self.frame, text='FRAME Dynamic Buttons').pack()
       # button to change settings and call this function(so redraw frame)
       Button(self.frame, text='Add extra button', command= self.switch_button_over).pack()

       if self.extra_button:
           Button(self.frame, text='Nothing').pack()
       #draw_frame
       raise_frame(self.frame)

    def switch_button_over(self,*args):
       self.extra_button = not(self.extra_button)
       self.create_frame()

root = Tk()
f1 = GUI_Dynamic_Buttons(root)
root.mainloop()

###################################################
#  Dynamic Buttons Fake Pages
###################################################

from tkinter import *
def raise_frame(frame):
    frame.tkraise()
# create settings
# create a frame from settings
# create a button in the frame
# this button calls on a function that changes settings are recreates frame
# rais frame

class GUI_Dynamic_Buttons:
    def __init__(self,root,pages=5):
        self.root = root
        self.page      = 1
        self.last_page = pages
        #create a frame and display
        self.create_frame()

    def next_page(self,*args):
        next_page = (((self.page)%self.last_page)+1)
        if "string" in args:
            return next_page
        self.page = next_page
        self.create_frame()

    def create_frame(self):
       # create a frame(based on settings) and display
       self.frame = Frame(self.root)
       self.frame.grid(row=0, column=0, sticky='news')
       Label(self.frame, text=f'Page {self.page}').pack()
       next_page_no = self.next_page("string")
       # button to change settings and call this function(so redraw frame)
       Button(self.frame, text=f'Next Page {next_page_no}', command= self.next_page).pack()
       if self.page==3:
           Button(self.frame, text='Nothing').pack()
       #draw_frame
       raise_frame(self.frame)

root = Tk()
f1 = GUI_Dynamic_Buttons(root)
root.mainloop()
######################################################################################################

window = tk.Tk()

class snake:
    def __init__(self):
        self.speed=1
        self.food =0
        self.length=7
        self.location=(4,4)
        self.up=1
        self.down=1
        self.space=[[0 for i in range(15)] for i in range(15)]

canvas = Canvas(window,width=150,height=150)
canvas.pack()

greenbox  = canvas.create_rectangle(25,25,120,60,fill="black")
window.mainloop()

import tkinter as tk
import random

# Создаем окно
root = tk.Tk()
# Устанавливаем название окна
root.title("PythonicWay Snake")

# Запускаем окно
root.mainloop()

# ширина экрана
WIDTH = 800
# высота экрана
HEIGHT = 600
# Размер сегмента змейки
SEG_SIZE = 20
# Переменная отвечающая за состояние игры
IN_GAME = True

# создаем экземпляр класса Canvas (его мы еще будем использовать) и заливаем все зеленым цветом
c = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="#003300")
c.grid()
# Наводим фокус на Canvas, чтобы мы могли ловить нажатия клавиш
c.focus_set()

#%%%
# sendex

from tkinter import *
class Window(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.master = master
        self.init_window()
    def init_window(self):
        self.master.title("GUI")
        self.pack(fill=BOTH,expand=1)
        quitButton = Button(self, text="QUIT-ME")
        quitButton.place(x=0,y=0)

root = Tk()
root.geometry("200x300")

app = Window(root)
root.mainloop()


import sqlite3

connectionObject = sqlite3.connect("../db/FallDatabase.db")
cursorObject = connectionObject.cursor()

createTable_fall = "CREATE TABLE IF NOT EXISTS fall(fall_id int, stadt_id int, anklage varchar, verurteilt int, urteil varchar, schlagwoerter varchar)"
cursorObject.execute(createTable_fall)

createTable_fall_infos = "CREATE TABLE IF NOT EXISTS fall_infos(fall_id int, protokoll varchar, anklage varchar, urteil varchar)"
cursorObject.execute(createTable_fall_infos)

createTable_namen = "CREATE TABLE IF NOT EXISTS namen(fall_id int, klaeger varchar, angeklagter varchar, richter varchar)"
cursorObject.execute(createTable_namen)

createTable_gesetzbuecher = "CREATE TABLE IF NOT EXISTS gesetzbuecher(buch_id int, paragraphen int, absatz varchar, inhalt varchar)"
cursorObject.execute(createTable_gesetzbuecher)

# Insert EOD stats into the reports table

# insertValues = "INSERT INTO temperature values(1,40.1)"

# cursorObject.execute(insertValues)

# insertValues = "INSERT INTO temperature values(2,65.4)"

# cursorObject.execute(insertValues)

# Select from the temperature table

queryTable_fall = "SELECT * from fall"
queryResults_fall = cursorObject.execute(queryTable_fall)

queryTable_fall_infos = "SELECT * from fall_infos"
queryResults_fall_infos = cursorObject.execute(queryTable_fall_infos)

queryTable_namen = "SELECT * from namen"
queryResults_namen = cursorObject.execute(queryTable_namen)

queryTable_gesetzbuecher = "SELECT * from gesetzbuecher"
queryResults_gesetzbuecher = cursorObject.execute(queryTable_gesetzbuecher)

# Print the Temperature records

for result in queryResults_fall:
    print(result)

for result in queryResults_fall_infos:
    print(result)

for result in queryResults_namen:
    print(result)

for result in queryResults_gesetzbuecher:
    print(result)

print('Datenbank wurde erstellt...')

connectionObject.close()