# Game in which the player must make it through a 'normal' Magnet school day

class Character(object):
    """character template"""
    def __init__(self, name):
        self.name = name
        self.gp = 100 #gp stands for "grade points"
        self.sp = 100 #sp stands for "self-esteem points"

    def bang_head_against_wall(self):
        """deducts 5 points from sp"""
        self.sp -= 5
        print(input('''You lost 5 self-esteem points.

[ENTER]'''))

    def powerschool(self):
        """Displays how many self-esteem/grade points the player has"""
        print(input(f'''You have {you.sp}/100 self-esteem points.
You have {you.gp}/100 grade points.

[ENTER]'''))

you = Character("you") #How the player is referred to the entire game

def end_game():
    """checks if player's sp/gp is less than or equal to zero"""
    if you.sp <= 0 or you.gp <= 0:
        print(input('''Magnet is too much for you.

You go back to your home district.

[ENTER]''')) #displayed if amounts are negative
        print("\033[H\033[J")
        print(input('Press [ENTER] to try again'))
        choice_1() #player can restart game

# Game introduction
print(input('''Welcome to Magnet: The Game!

It's an A day. Can you make it all the way to 2:50?

To continue, press [ENTER]''')) # press ENTER to advance

# Choice_1: Has two options
# If the player inputs anything other than 'a' or 'b', the question will repeat itself
def choice_1():
    you.sp = 100 #resets sp value to 100 if the player plays the game multiple times
    you.gp = 100 #resets gp value to 100 if the player plays the game multiple times
    print("\033[H\033[J") #used throughout to clear the screen
    choice = ""
    while choice != "a" and choice != "b":
        choice = input('''The lovely smell of bus fumes at 7:55 AM fills the air. You know you’re a slow walker.
Do you cut across the grass like a barbarian, or walk along the pathway?
 a  I’m a barbarian
 b  Walk along pathway

Type a or b: ''')

    if choice is "a":
        print("\033[H\033[J")
        print(input('''You cut across the grass and trip on a rock. Good. You deserve it.

[ENTER]'''))
        choice_2() #leads to choice_2

    if choice is "b":
        print("\033[H\033[J")
        print(input('''You walk the entire length of the pavement, taking in your surroundings.

The sun illuminates the sky. A flock of geese fly by. The gnome in the window of the magnet senior lounge waves “hi.”

[ENTER] '''))
        print("\033[H\033[J")
        print(input('''You’re so lost in the moment that you trip over a student who stopped to tie his shoelaces in the middle of the path.

You break your nose.

Minus 10 self-esteem points.

[ENTER]'''))
        you.sp -= 10 #subtracts 10 sp
        choice_2() # leads to choice_2

#Choice_2: Has two options
def choice_2():
    print("\033[H\033[J")
    choice = ""
    while choice != "a" and choice !="b":
        print(input('''You approach the front doors of Magnet. Someone holds the door open for you. You give them a pat on the back.

[ENTER]'''))
        print("\033[H\033[J")
        choice = input('''You go to swipe in, but realize your lanyard isn’t hanging around your neck.

Do you wear a temporary ID or not?

 a  Wear temporary ID
 b  Don't wear temporary ID

 Type a or b: ''')

    if choice is "a":
        print("\033[H\033[J")
        print(input('''You wear your temporary ID. Three freshmen walk by and make fun of you.

Minus 10 self-esteem points.

[ENTER]'''))
        you.sp -= 10 #subtracts 10 sp
        print("\033[H\033[J")
        print(input('''You see Betia waving to you from down the hallway

[ENTER]'''))
        print("\033[H\033[J")
        print(input('''Betia: Hey! Did you know if you check Powerschool you can see how many self-esteem points and grade points you have?!?

[ENTER]'''))
        print(input('''You: What?

[ENTER]'''))
        print(input('''Betia: What?

[ENTER]'''))
        print(input('''Betia: *Barrel-rolls away*

[ENTER]'''))
        print("\033[H\033[J")
        print(input(''' You continue on to your locker on the second floor

[ENTER]'''))
        choice_3() #leads to choice_3

    if choice is "b": #GAME END
        print("\033[H\033[J")
        print(input('''You take the green sticker, rip it in half and stomp on it.

[ENTER]'''))
        print("\033[H\033[J")
        print(input('''Mr. Rafalowski sees the whole thing and lets out a disapproving sigh.

[ENTER]'''))
        print("\033[H\033[J")
        print(input('''You try to tape the pieces back together, but in doing so, you lose all your dignity.

Minus 100 self-esteem points.

[ENTER]'''))
        you.sp -= 100 #subtracts 100 sp
        end_game() #game will end

#Choice_3: Has three choices
def choice_3():
    print("\033[H\033[J")
    choice = ""
    while choice != "a" and choice != "b" and choice != "c":
        choice = input('''Do you remember your locker combination?

 a  10-14-35
 b  Nope
 c  Check powerschool

Type a, b, or c: ''')
        if choice is "a":
            print("\033[H\033[J")
            print(input('''You remembered correctly!

Plus 5 self-esteem points.

[ENTER]'''))
            you.sp += 5 #plus 5 sp
            print("\033[H\033[J")
            print(input('''You open up your locker only to find a void of empty space.
Oh that's right, you don’t use your locker anyway.

[ENTER]'''))
            print("\033[H\033[J")
            print(input('''...
It's 7:59! You have one minute to get to class.

[ENTER]'''))
            print("\033[H\033[J")
            print(input('''You hurry over to English.
Once you get there, you see Ms. Arnold passing out tests.

You sit down and open up a textbook for some last-minute studying, but when you open it, you find what looks like the answer key stuck in the pages!

[ENTER]'''))

            choice_4() #leads to choice_4
        if choice is "b": #GAME END
            print("\033[H\033[J")
            print(input('''You don’t remember, so you try every possible combination of numbers sequentially.

[ENTER]'''))
            print(input('''Life goes on.

[ENTER]'''))
            print(input('''You finally get the correct combination, but everyone has graduated high school already.

Minus 100 self-esteem points.

[ENTER]'''))
            you.sp -= 100 #subtracts 100 sp
            end_game() #game will end
        if choice is "c":
            print("\033[H\033[J")
            you.powerschool() #checks powerschool
            choice_3() #back to choice_3

#Choice_4: Has 3 choices
def choice_4():
    print("\033[H\033[J")
    choice = ""
    while choice != "a" and choice != "b" and choice != "c":
        choice = input('''Do you cheat and use the answer key?

 a  Yes
 b  No
 c  powerschool

Type a, b, or c: ''')
        if choice is "a":
            print("\033[H\033[J")
            print(input('''You hide the key underneath your desk and copy down the answers exactly...

    1. C, 2. C, 3. C, 4. C, 5. C...

[ENTER]'''))
            print(input('''But the questions were all "True or False."

Minus 50 grade points.

[ENTER]'''))
            you.gp -= 50 #subtract 50 gp
            print("\033[H\033[J")
            print(input('''BELL BELL BELL

You leave English. It's been a stressful morning.

[ENTER]'''))
            choice_5() #leads to choice_5
        if choice is "b":
            print("\033[H\033[J")
            print(input('''You remember the academic honesty policy that you signed at the beginning of the year and choose not to cheat.

But you didn't study anyway.

Minus 20 grade points.

[ENTER]'''))
            you.gp -= 20 #subtracts 20 gp
            print("\033[H\033[J")
            print(input('''BELL BELL BELL

You leave English. It's been a stressful morning.

[ENTER]'''))
            choice_5() #leads to choice_5

        if choice is "c":
            print("\033[H\033[J")
            you.powerschool() #checks powerschool
            choice_4() #leads to choice_4

#Choice 5: three options
def choice_5():
    end_game() #possible game end, depending on how many times player repeats
    print("\033[H\033[J")
    choice = ""
    while choice != "a" and choice != "b" and choice != "c":
        choice = input('''**You’ve learned a new coping mechanism!**

[bang_head_against_wall]

Use now?

 a  Yes
 b  No

Type a or b: ''')
        if choice is "a":
            print("\033[H\033[J")
            you.bang_head_against_wall() #subtracts 5 sp
            choice_6() #leads to choice_6

        if choice is "b":
            print("\033[H\033[J")
            print(input('''You make it to your ¾ class– Tech.

Before you can sit down and open up your chromebook, you hear the fire alarm!
The clock is flashing FIRE FIRE FIRE. You walk over to the doorway.

[ENTER]'''))
            choice_7() #leads to choice_7

#Choice_6: three options
def choice_6():
    end_game() #possible game end, depending on how many times player repeats
    print("\033[H\033[J")
    choice = ""
    while choice != "a" and choice != "b" and choice != "c":
        choice = input('''Repeat?

 a  Bang head against wall again
 b  Have a little self-respect
 c  Powerschool

Type a, b, or c: ''')
        if choice is "a":
            print("\033[H\033[J")
            you.bang_head_against_wall() #subtracts 5 sp
            choice_6() #leads to choice_6
        if choice is "b":
            print("\033[H\033[J")
            print(input('''You make it to your ¾ class– Tech.

Before you can sit down and open up your chromebook, you hear the fire alarm!
The clock is flashing FiRE FiRE FiRE. You walk over to the doorway.

[ENTER]'''))
            choice_7() #leads to choice_7
        if choice is "c":
            print("\033[H\033[J")
            you.powerschool() #checks powerschool
            choice_6() #back to choice_6

#Choice 7: three options
def choice_7():
    print("\033[H\033[J")
    choice = ""
    while choice != "a" and choice != "b" and choice != "c":
        choice = input("""Do you know how to make it out of the building?

 a  left, forward, left
 b  right, forward, left
 c  right, right, right
 d  Powerschool

Type a, b, c, or d: """)

        if choice is "a":
            print("\033[H\033[J")
            print(input('''Good thing Magnet’s floorplan is essentially a circle. You do a lap around the first floor and then join the class outside under the AIT bridge.

[ENTER]'''))
            print("\033[H\033[J")

            print(input('''Safely outside, you stand in a line with your classmates.

You take a look around. It’s been 2 and half hours since you’ve been outside and the expanse of the wilderness inspires you.

You realize you could do anything at this moment.

Self-esteem? Grades? What’s the point?

[ENTER]'''))
            choice_8() #leads to choice_8
        if choice is "b":
            print("\033[H\033[J")

            print(input('''You push your fellow classmates down and make a break for the exit.

[ENTER]'''))
            print("\033[H\033[J")

            print(input('''Safely outside, you stand in a line with your classmates.

You take a look around. It’s been 2 and half hours since you’ve been outside and the expanse of the wilderness inspires you.

You realize you could do anything at this moment.

Self-esteem? Grades? What’s the point?

[ENTER]'''))
            choice_8() #leads to choice_8
        if choice is "c":
            print("\033[H\033[J")
            print(input('''You panic and walk in a circle. You are blocking the exit to the classroom.

Ms. Gerstein is forced to drag your body outside so that the rest of the class can get through.

Minus 10 self-esteem points.

[ENTER]'''))
            you.sp -= 10 #subtracts 10 sp
            print("\033[H\033[J")
            print(input('''Safely outside, you stand in a line with your classmates.

You take a look around. It’s been 2 and half hours since you’ve been outside and the expanse of the wilderness inspires you.

You realize you could do anything at this moment.

Self-esteem? Grades? What’s the point?

[ENTER]'''))
            choice_8() #leads to choice_8

        if choice is "d":
            print("\033[H\033[J")
            print('You check your grades in this time of crisis.')
            you.powerschool() #checks powerschool
            choice_7() #leads to choice_7

#Choice 8: three options
def choice_8():
    print("\033[H\033[J")
    choice = ""
    while choice != "a" and choice != "b" and choice != "c":
        choice = input('''The world is your oyster.

 a  Run
 b  Cry
 c  Powerschool
 d  Bang head against wall

Type a, b, c, or d: ''')
        if choice is "a": #WINNING GAME END
            print("\033[H\033[J")
            print(input('''You rip off your temporary ID and toss it into the wind. You run north.

Everyone calls out after you, but you don't listen. You feel the cool air of Scotch Plains filling your lungs as you continue to sprint away in a single direction.

Your self-esteem points and grade points max out. You are elevated to a higher level of existence.

YOU WIN

Press [ENTER] to play again'''))
            choice_1() #goes back to start

        if choice is "b": #LOSING GAME END
            print("\033[H\033[J")
            print(input('''A single tear glides down your cheek.

Everything is just so beautiful.

Life is so overwhelming. Suddenly, Janessa slaps you across the face and shouts, "Get a grip, man!!"

But you don't want to.

Minus 476 self-esteem points.
Minus 298 grade points.

THE END

Press [ENTER] to play again'''))
            choice_1() #goes back to choice_1

        if choice is "c": #won't access powerschool
            print("\033[H\033[J")
            print(input('''[Powerschool is closed]

[ENTER]'''))
            choice_8() #back to choice_8
        if choice is "d": #possible game end
            print("\033[H\033[J")
            you.bang_head_against_wall()
            end_game()
            choice_8() #back to choice_8

choice_1() #starts the game


"""
Copyright 2018 Fluence Labs Limited

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.
"""
from project.VMDescriptor import VMDescriptor
from project.TestDescriptor import TestDescriptor
from os.path import join

# launch count of interpreter-based VMs
interpreter_launches_count = 3

# launch count of compiler-based VMs
compiler_launches_count = 11

# export function name that should be called from each Wasm module
test_export_function_name = "main"

vm_descriptors = {
    "wavm"   : VMDescriptor(join("build_", "bin", "wavm-run"),
                            "{wasm_file_path} -f {function_name}", True),

    "life"   : VMDescriptor(join("life"), "-entry {function_name} {wasm_file_path}", False),

    "wasmi"  : VMDescriptor(join("target", "release", "examples", "invoke"),
                            "{wasm_file_path} {function_name}", False),

    "wasmer" : VMDescriptor(join("target", "release", "wasmer"), "run {wasm_file_path}", True),

    "wagon"  : VMDescriptor(join("cmd", "wasm-run"), "wasm_run {wasm_file_path}", False),

    "asmble" : VMDescriptor(join("asmble", "bin", "asmble"),
                            "invoke -in {wasm_file_path} {function_name} -defmaxmempages 20000", True)
}


#Exercise 4 CH3 (Zelle 2017, Python Programming: An Introduction to Computer Science)

# A program to determine the distance to a lightning strike
import math

def main():

    print("This program determines the distance to a lightning strike.")

    time = int(input("Enter the time elapsed between flash and sound of thunder in in seconds: "))

    distance = 1100*time
    distance_miles = distance / 5280
    print("The distance to the lightning strike is:", distance_miles, "miles.")

main()


import logging

import requests

from pajbot.models.command import Command
from pajbot.modules import BaseModule
from pajbot.modules import ModuleSetting

log = logging.getLogger(__name__)

class PNSLModule(BaseModule):

    ID = __name__.split(".")[-1]
    NAME = "Run P&SL lists"
    DESCRIPTION = "Run P&SL lists through the !runpnsl command"
    CATEGORY = "Moderation"
    SETTINGS = [
        ModuleSetting(
            key="level",
            label="Level required to use the command",
            type="number",
            required=True,
            placeholder="",
            default=750,
            constraints={"min_value": 500, "max_value": 2000},
        ),
        ModuleSetting(
            key="per_chunk",
            label="How many lines to process per chunk",
            type="number",
            required=True,
            placeholder="",
            default=30,
            constraints={"min_value": 1, "max_value": 500},
        ),
        ModuleSetting(
            key="chunk_delay",
            label="Delay between chunks (in seconds)",
            type="number",
            required=True,
            placeholder="",
            default=30,
            constraints={"min_value": 5, "max_value": 60},
        ),
    ]

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

        self.pnsl_token = None

        if bot:
            if "pnsl" in bot.config:
                self.pnsl_token = bot.config["pnsl"].get("token", None)

    def run_pnsl(self, bot, source, message, event, args):
        base_url = "https://bot.tetyys.com/api/v1/BotLists"

        if not self.pnsl_token:
            bot.whisper(source, f"Missing P&SL token in config.ini. talk to @{bot.admin} BabyRage")
            return False

        guid = message.replace("https://bot.tetyys.com/BotList/", "")

        headers = {"Authorization": f"Bearer {self.pnsl_token}"}

        res = requests.get(base_url + "/" + guid, headers=headers)

        if not res.ok:
            error_data = res.json()
            bot.whisper(source, f"Something went wrong with the P&SL request: {error_data['errors']['Guid'][0]}")
            return False

        privmsg_list = res.text.splitlines()

        log.info(f"[P&SL] User {source.name} running list {guid} with {len(privmsg_list)} entries")

        bot.privmsg_arr_chunked(
            privmsg_list, per_chunk=self.settings["per_chunk"], chunk_delay=self.settings["chunk_delay"]
        )

    def load_commands(self, **options):
        self.commands["runpnsl"] = Command.raw_command(
            self.run_pnsl,
            delay_all=20,
            delay_user=20,
            level=self.settings["level"],
            description="Run a P&SL list",
            command="runpnsl",
        )
        self.commands["pnslrun"] = self.commands["runpnsl"]


class Solution:
    """
    @param nums: a rotated sorted array
    @return: the minimum number in the array
    """
    def findMin(self, nums):
        # write your code here
        if nums is None or len(nums) == 0:
          return -1

        start, end = 0, len(nums)-1
        last = nums[-1]
        while start+1 < end:
          mid = (start+end) // 2
          if nums[mid] <= last:
            end = mid
          else:
            start = mid

        return min(nums[start], nums[end])

def main():
  nums = [4,5,6,7,0,1,2]
  sol = Solution()
  print(sol.findMin(nums))

main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' writes nodes csv to nodes sql table '''

import sqlite3
import csv
from pprint import pprint
# modified from code posted to Udacity forums

sqlite_file = 'osm.db'    # name of the sqlite database file

# Connect to the database
conn = sqlite3.connect(sqlite_file)
# Get a cursor object
cur = conn.cursor()
cur.execute('''DROP TABLE IF EXISTS nodes''')
conn.commit()
# Create the table, specifying the column names and data types:
cur.execute('''
    CREATE TABLE nodes (
        id INTEGER PRIMARY KEY NOT NULL,
        lat REAL,
        lon REAL,
        user TEXT,
        uid INTEGER,
        version INTEGER,
        changeset INTEGER,
        timestamp TEXT
        );
    ''')
# commit the changes
conn.commit()
# Read in the csv file as a dictionary, format the
# data as a list of tuples:
with open('nodes.csv','rb') as fin:
    dr = csv.DictReader(fin) # comma is default delimiter
    to_db = [(i['id'].decode("utf-8"), i['lat'].decode("utf-8"),i['lon'].decode("utf-8"), i['user'].decode("utf-8"), i['uid'].decode("utf-8"), i['version'].decode("utf-8"), i['changeset'].decode("utf-8"), i['timestamp'].decode("utf-8")) for i in dr]
# insert the formatted data
cur.executemany("INSERT INTO nodes(id, lat, lon, user, uid, version, changeset, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?);", to_db)
# commit the changes
conn.commit()
cur.execute('SELECT * FROM nodes')
all_rows = cur.fetchall()
print('1):')
pprint(all_rows)
conn.close()


from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.core.validators import MaxValueValidator, MinValueValidator
from utils.models import BaseUtilityModel

class Rating(BaseUtilityModel):
    user = models.ForeignKey(
        'auth.User',
        related_name='rating_user'
    )
    content_type = models.ForeignKey(
        ContentType,
        db_index=True
    )
    object_id = models.IntegerField(
        db_index=True
    )
    content_object = GenericForeignKey(
        'content_type',
        'object_id'
    )
    date_rated = models.DateField(
        blank=True,
        null=True
    )
    rating_text = models.TextField(
        blank=True,
        null=True
    )
    rating = models.IntegerField(
        blank=True,
        validators=[MaxValueValidator(100),
                    MinValueValidator(1)]
    )

    class Meta:
        verbose_name = 'rating'
        verbose_name_plural = 'ratings'
        unique_together = ('user', 'object_id',)

    def __str__(self):
        return 'rating: %s | %s' % (self.rating, self.rating_text[0:20])


# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Module: l10n_hr_obrt
#    Author: Stjepan Lovasic
#    mail:   stjepan.lovasic@gmail.com
#    Copyright (C) 2013- Datacom d.o.o Zagreb
#    Contributions:
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from osv import fields, osv, orm
import time
from tools.translate import _
from lxml import etree

class obrt_kpr(osv.Model):
    _name='obrt.kpr'
    _description='Knjiga prometa'

    def _sum_cash_checks(self, cr, uid, ids, field_name, field_values, context=None):
        if len(ids) == 0 :
            return False
        res={}
        for kpr in self.browse(cr, uid, ids):
            res[kpr.id] = kpr.gotovina + kpr.cekovi
        return res

    def _get_last_used_pj(self, cr, uid, context=None):
        #fields_ = fields_view_get(self, cr, uid)
        cr.execute("SELECT MAX(id) FROM obrt_kpr")
        last_pj = cr.fetchone()[0]
        if last_pj is None:
            last_pj = self.pool.get('obrt.pj').search(cr, uid, [])[0]
        else :
            last_pj = self.read(cr, uid, last_pj, ['pj_id'])['pj_id'][0]
        #pj=self.read(cr, uid, last_pr, ['pj_id'])
        #return pj['pj_id'][0]
        #B: skratio i vratio kao default
        return last_pj

    _columns = {
                'rbr':fields.integer('Red. broj'),
                'date':fields.date('Nadnevak',required=1),
                'temeljnica':fields.char('Broj temeljnice', size=64),
                'name':fields.char('Opis isprava o primicima u gotovini', size=64),
                'gotovina':fields.float('Iznos naplacen u gotovini',(16,2)),
                'cekovi':fields.float('Iznos naplacen u cekovima',(16,2)),
                'ukupno':fields.function( _sum_cash_checks, type="float", obj="obrt.kpr", method=True, store=True, string='Ukupno naplacen iznos'),
                'pj_id':fields.many2one('obrt.pj','Poslovna jedinica', required=1, ondelete='restrict'),
                }

    _order = 'date asc'

    '''
    _defaults = {
                 'pj_id': _get_last_used_pj
                 }
    '''

    """
    def fields_view_get(cr, uid, view_id=None, view_type='form', context=None, toolbar = False, submenu=False):
        if context is None:
            context={}
        res = super(obrt_kpr,self).fields_view_get(cr, uid, view_id, view_type, context, toolbar, submenu)
        if context.get('type', False):
            doc=etree.XML(res['arch'])

        return res
    """

    def create(self, cr, uid, vals, context=None):
        if context is None:
            context = {}

        cr.execute("SELECT MAX(rbr) FROM obrt_kpr WHERE pj_id = " + str(vals['pj_id']))
        rbr = cr.fetchone()
        if rbr[0] is None:
            vals['rbr'] = 1
        else:
            vals['rbr'] = rbr[0] + 1

        return super(obrt_kpr, self).create(cr, uid, vals, context=context)

    def assert_check(self, ids):
        assert len(ids) == 1, "Dozvoljen jedan zapis!"
        return True

    def _check_closed_period(self, cr, uid, ids, context=None):
        self.assert_check(ids)
        period_obj = self.pool.get('obrt.period')
        closed_period_ids = period_obj.search(cr, uid, [('closed','=',True)])

        check = self.browse(cr, uid, ids[0], context=context)
        for period in period_obj.browse(cr, uid, closed_period_ids):
            if period.date_end > check.date :
                return False
        return True

    def _check_last_date(self, cr, uid, ids, context=None):
        self.assert_check(ids)
        check = self.browse(cr, uid, ids[0], context=context)
        cr.execute("SELECT MAX(date) from obrt_kpr where pj_id = " + str(check.pj_id.id))
        cur_date = cr.fetchone()[0]

        return (check.date >= cur_date) or False

    def _check_sum(self, cr, uid, ids, context=None):
        self.assert_check(ids)
        check_sum = self.browse(cr, uid, ids[0], context)
        return check_sum.cekovi or check_sum.gotovina or False

    _constraints = [
                    (_check_closed_period,'Period za unešeni datum je zatvoren za unose.',['date']),
                    (_check_last_date,'Zapisi za pojedinu poslovnicu moraju biti kronoloski poredani,\n postoji zapis iz datuma kasnije od upisanog.',['date','pj_id']),
                    (_check_sum,'Promet ne može imati iznos 0!',['cekovi','gotovina'])
                    ]


# -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 06:57:05 2020

@author: anavr
"""

import matplotlib.pyplot as plt
import pyComtrade
import numpy as np
from scipy import signal, fftpack
from tkinter import *
from tkinter import filedialog
from inspect import *

# app
#funcion para cargar

global comtradeObj
comtradeObj = pyComtrade.ComtradeRecord()

#------------------ FUNCIONES DEL PROGRAMA -------------------------------
# Para abrir archivo cfg
def abrir_cfg():

    global ar

    ar=filedialog.askopenfilename(title="Abrir cfg")#,filetypes=(("Archivos COMTRADE .cfg y .dat",".")))

    #fs=
    messagebox.showinfo("Se cargó el archivo .cfg de la siguiente dirección:\n", ar)

# Para abrir archivo dat
def abrir_dat():

    global dat

    dat=filedialog.askopenfilename(title="Abrir cfg")#,filetypes=(("Archivos COMTRADE .cfg y .dat",".")))

    #fs=
    messagebox.showinfo("Se cargó el archivo .dat de la siguiente dirección:\n", dat)

# Carga las entradas del programa
def cargar():
    global e1,e2,e3,e4,e5, ratio_V, ratio_C
    e1=en1.get()
    e2=en2.get()
    e3=en3.get()
    e4=en4.get()
    e5=en5.get()

    if e1 == "Seleccionar":
        messagebox.showerror("Error","Debe seleccionar la frecuencia de muestro del relé")
    else:
        e1 = int(e1)

    if e2=="" and e3=="":
        messagebox.showerror("Error","Debe ingresar la relación de transformación de voltaje")
    elif e2=="":
        messagebox.showerror("Error","Debe ingresar la relación de transformación del lado primario de voltaje")
    elif e3=="":
        messagebox.showerror("Error","Debe ingresar la relación de transformación del lado secundario de voltaje")
    else:
        e2 = int(e2)
        e3 = int(e3)

    if e4=="" and e5=="":
        messagebox.showerror("Error","Debe ingresar la relación de transformación de corriente")
    elif e4=="":
        messagebox.showerror("Error","Debe ingresar la relación de transformación del lado primario de corriente")
    elif e5=="":
        messagebox.showerror("Error","Debe ingresar la relación de transformación del lado secundario de corriente")
    else:
        e4 = int(e4)
        e5 = int(e5)

    if side.get() == 0:
        messagebox.showerror("Error","Debe seleccionar el lado del transformador que desea visualizar")
    elif side.get()==1:
        ratio_V = e2/e3
        ratio_C = e4/e5
    elif side.get()==2:
        ratio_V = 1
        ratio_C = 1

    DFP()

# Funciones para cada etapa
# ETAPA DE SUBMUESTREO
def subsampling(time,data,fs_comtrade,fk,fs_user_cycle):
    # time is the vector of time
    # data is the vector with the signal
    # fs_comtrade is the sample rate from the comtrade file
    # fk is the frequency of the system
    # fs_user_cycle is the sample rate given by user
    N1 = fs_user_cycle
    fs_cycle = fs_comtrade/fk
    N=np.int(fs_cycle)
    N_tot = np.int(len(data)/fs_cycle)
    new_data = [0]
    new_time = [0]
    for i in np.arange(N_tot):
        xi=data[i*N:i*N+N]
        ti=time[i*N:i*N+N]
        new_data[i*N1:i*N1+N1] = signal.resample(xi, N1)
        new_time[i*N1:i*N1+N1] = np.linspace(ti[0], ti[-1], N1, endpoint=False)

    return (new_time,new_data)

# ETAPA DE DIGITALIZACION
def quantizer(data, quantizing_bits):
    # data is the vector with the signal
    # quantizing_bits is the number of bits for the converter
    # Quantizer - S&H and ADC
    quantizing_levels   = 2 ** quantizing_bits
    quantizing_step     = (np.max(data)-np.min(data)) / quantizing_levels
    quantizing_signal   = np.round (data / quantizing_step) * quantizing_step;

    return quantizing_signal

#ETAPA DE DFT
def DFT(time, data, fk, fs_user_cycle):
    # time is the vector of time
    # data is the vector with the signal
    # fk is the frequency of the system
    # fs_user_cycle is the sample rate given by user

    N=np.int(fs_user_cycle)
    N_tot = len(data)-N
    Xc = [0]*N_tot
    Xs = [0]*N_tot
    t = [0]*N_tot

    for i in np.arange(N_tot):
        xi=data[i:i+N]
        t[i]=time[i]
        Xc_sum = 0
        Xs_sum = 0
        for k in np.arange(N):
            Xc_temp=xi[k]*np.cos(2*np.pi*k/(N))
            Xc_sum=Xc_sum+Xc_temp
            Xs_temp=xi[k]*np.sin(2*np.pi*k/(N))
            Xs_sum=Xs_sum+Xs_temp

        Xc[i]= 2/(N*np.sqrt(2))*Xc_sum
        Xs[i]= 2/(N*np.sqrt(2))* Xs_sum

    return t, Xc, Xs

# Realiza todo el proceso de DSP
def DFP():
    # Definición de variables globales para resultados
    global time, voltages, currents, time_sub, V_sub, C_sub, dig_V_sub, dig_C_sub, t, X_V, X_C, Y_V, Y_C, Xc_V, Xs_V, Xc_C, Xs_C, fs_user_cycle

    comtradeObj.read(ar,dat)
    N = comtradeObj['endsamp'][-1]
    #sampling_freq=comtradeObj['samp'][-1]
    fs_comtrade=comtradeObj['samp'][-1]
    fk = comtradeObj['line_freq']
    time = comtradeObj.get_timestamps()
    voltages = np.empty(([len(time),3]))
    currents = np.empty(([len(time),3]))
    # Reading voltaje and currents
    voltages[:,0] = comtradeObj['A'][16]['values']
    voltages[:,1] = comtradeObj['A'][17]['values']
    voltages[:,2] = comtradeObj['A'][18]['values']

    currents[:,0] = comtradeObj['A'][0]['values']
    currents[:,1] = comtradeObj['A'][1]['values']
    currents[:,2] = comtradeObj['A'][2]['values']
    for i in np.arange(6):
        if i<3:
            # voltages[:,i] = comtradeObj['A'][i]['values']
            for j in np.arange(len(voltages[:,i])):
                voltages[j,i]= voltages[j,i] * ratio_V
        else:
            # currents[:,i-3] = comtradeObj['A'][i]['values']
            for j in np.arange(len(currents[:,i-3])):
                currents[j,i-3]= currents[j,i-3] * ratio_C

    # Submuestreo
    fs_user_cycle = e1 # ESTA DATO VIENE DE LA INTERFAZ
    N_tot = np.int(N*fk/fs_comtrade)*fs_user_cycle
    V_sub = np.empty(([N_tot,3]))
    C_sub = np.empty(([N_tot,3]))
    time_sub = np.empty(([N_tot,6]))
    for i in np.arange(6):
        if i<3:
            time_sub[:,i], V_sub[:,i] = subsampling(time,voltages[:,i],fs_comtrade,fk,fs_user_cycle)
        else:
            time_sub[:,i], C_sub[:,i-3] = subsampling(time,currents[:,i-3],fs_comtrade,fk,fs_user_cycle)

    # Digitalización
    quantizing_bits_V = 12 # Valor típico: 12 (Voltaje)
    quantizing_bits_C = 16 # Valor típico: 16 (Corriente)
    dig_V_sub = np.empty(([N_tot,3]))
    dig_C_sub = np.empty(([N_tot,3]))
    for i in np.arange(6):
        if i<3:
            dig_V_sub[:,i] = quantizer(V_sub[:,i], quantizing_bits_V)
        else:
            dig_C_sub[:,i-3] = quantizer(C_sub[:,i-3], quantizing_bits_C)

    # DFT
    N_tot_DTF = np.int(N_tot-fs_user_cycle)
    Xc_V = np.empty(([N_tot_DTF,3]))
    Xs_V = np.empty(([N_tot_DTF,3]))
    Xc_C = np.empty(([N_tot_DTF,3]))
    Xs_C = np.empty(([N_tot_DTF,3]))
    X_V = np.empty(([N_tot_DTF,3]))
    Y_V = np.empty(([N_tot_DTF,3]))
    X_C = np.empty(([N_tot_DTF,3]))
    Y_C = np.empty(([N_tot_DTF,3]))
    t = np.empty(([N_tot_DTF,6]))
    for i in np.arange(6):
        if i<3:
            t[:,i], Xc_V[:,i], Xs_V[:,i] = DFT(time_sub[:,i], dig_V_sub[:,i], fk, fs_user_cycle)
            X_V[:,i] = np.sqrt(np.power(Xc_V[:,i],2)+np.power(Xs_V[:,i],2))
            ajus = np.pi
            if Xc_V[-1,i]>0 and Xs_V[-1,i]<0:
                ajus = 2*np.pi
            elif Xc_V[-1,i]>0 and Xs_V[-1,i]>0:
                ajus = 0
            Y_V[:,i] = (np.arctan(Xs_V[:,i]/Xc_V[:,i])+ajus)*180/np.pi
        else:
            t[:,i], Xc_C[:,i-3], Xs_C[:,i-3] = DFT(time_sub[:,i], dig_C_sub[:,i-3], fk, fs_user_cycle)
            X_C[:,i-3] = np.sqrt(np.power(Xc_C[:,i-3],2)+np.power(Xs_C[:,i-3],2))
            ajus = np.pi
            if Xc_C[-1,i-3]>0 and Xs_C[-1,i-3]<0:
                ajus = 2*np.pi
            elif Xc_C[-1,i-3]>0 and Xs_C[-1,i-3]>0:
                ajus = 0
            Y_C[:,i-3] = (np.arctan(Xs_C[:,i-3]/Xc_C[:,i-3])+ajus)*180/np.pi

# ------------------------- Funciones para los Botones --------------------
def seniales_COMTRADE():
    f, axarr = plt.subplots(1, 2, figsize =(16, 4))
    f.suptitle('Lectura del archivo COMTRADE', y=1, fontsize=16)

    axarr[0].plot(time, voltages[:,0], 'b-', label='Phase A')
    axarr[0].plot(time, voltages[:,1], 'r-', label='Phase B')
    axarr[0].plot(time, voltages[:,2], 'g-', label='Phase C')
    axarr[0].set_xlabel('Time [sec]')
    axarr[0].set_ylabel('Voltage [V]')
    axarr[0].grid()
    axarr[0].legend()

    axarr[1].plot(time, currents[:,0], 'b-', label='Phase A')
    axarr[1].plot(time, currents[:,1], 'r-', label='Phase B')
    axarr[1].plot(time, currents[:,2], 'g-', label='Phase C')
    axarr[1].set_xlabel('Time [sec]')
    axarr[1].set_ylabel('Current [A]')
    axarr[1].grid()
    axarr[1].legend()
    plt.show()

def submuestreo_boton():
    # PLOTING -----------------------------------------------------------------
    f, axarr = plt.subplots(3, 2, figsize =(16, 10))
    f.suptitle('Submuestreo de las señales', y=0.92, fontsize=16)

    # Plot Voltages
    axarr[0,0].plot(time, voltages[:,0], 'b-', label='Phase A')
    axarr[0,0].plot( time_sub[:,0], V_sub[:,0], 'co-', label='Phase A resampled')
    axarr[1,0].plot(time, voltages[:,1], 'r-', label='Phase B')
    axarr[1,0].plot( time_sub[:,1], V_sub[:,1], 'mo-', label='Phase B resampled')
    axarr[2,0].plot(time, voltages[:,1], 'g-', label='Phase C')
    axarr[2,0].plot( time_sub[:,2], V_sub[:,2], 'yo-', label='Phase C resampled')

    # Plot Currents
    axarr[0,1].plot(time, currents[:,0], 'b-', label='Phase A')
    axarr[0,1].plot( time_sub[:,3], C_sub[:,0], 'co-', label='Phase A resampled')
    axarr[1,1].plot(time, currents[:,1], 'r-', label='Phase B')
    axarr[1,1].plot( time_sub[:,4], C_sub[:,1], 'mo-', label='Phase B resampled')
    axarr[2,1].plot(time, currents[:,2], 'g-', label='Phase C')
    axarr[2,1].plot( time_sub[:,5], C_sub[:,2], 'yo-', label='Phase C resampled')

    for i in np.arange(3):
        axarr[i,0].set_xlabel('Time [sec]')
        axarr[i,0].set_ylabel('Voltage [V]')
        axarr[i,0].grid()
        axarr[i,0].legend()
        axarr[i,1].set_xlabel('Time [sec]')
        axarr[i,1].set_ylabel('Current [A]')
        axarr[i,1].grid()
        axarr[i,1].legend()
    plt.show()

def digitalizacion_boton():
    # PLOTING -----------------------------------------------------------------
    f, axarr = plt.subplots(3, 2, figsize =(16, 10))
    f.suptitle('Digitalización de la señal', y=0.92, fontsize=16)

    # Plot Voltages
    axarr[0,0].plot(time_sub[:,0][0:fs_user_cycle*3], V_sub[:,0][0:fs_user_cycle*3], 'b-', label='Phase A')
    axarr[0,0].plot( time_sub[:,0][0:fs_user_cycle*3], dig_V_sub[:,0][0:fs_user_cycle*3], 'c-', label='Phase A digital')
    axarr[1,0].plot(time_sub[:,1][0:fs_user_cycle*3], V_sub[:,1][0:fs_user_cycle*3], 'r-', label='Phase B')
    axarr[1,0].plot( time_sub[:,1][0:fs_user_cycle*3], dig_V_sub[:,1][0:fs_user_cycle*3], 'm-', label='Phase B digital')
    axarr[2,0].plot(time_sub[:,2][0:fs_user_cycle*3], V_sub[:,2][0:fs_user_cycle*3], 'g-', label='Phase C')
    axarr[2,0].plot( time_sub[:,2][0:fs_user_cycle*3], dig_V_sub[:,2][0:fs_user_cycle*3], 'y-', label='Phase C digital')

    # Plot Currents
    axarr[0,1].plot(time_sub[:,3][0:fs_user_cycle*3], C_sub[:,0][0:fs_user_cycle*3], 'b-', label='Phase A')
    axarr[0,1].plot( time_sub[:,3][0:fs_user_cycle*3], dig_C_sub[:,0][0:fs_user_cycle*3], 'c-', label='Phase A digital')
    axarr[1,1].plot(time_sub[:,4][0:fs_user_cycle*3], C_sub[:,1][0:fs_user_cycle*3], 'r-', label='Phase B')
    axarr[1,1].plot( time_sub[:,4][0:fs_user_cycle*3], dig_C_sub[:,1][0:fs_user_cycle*3], 'm-', label='Phase B digital')
    axarr[2,1].plot(time_sub[:,5][0:fs_user_cycle*3], C_sub[:,2][0:fs_user_cycle*3], 'g-', label='Phase C')
    axarr[2,1].plot( time_sub[:,5][0:fs_user_cycle*3], dig_C_sub[:,2][0:fs_user_cycle*3], 'y-', label='Phase C digital')

    for i in np.arange(3):
        axarr[i,0].set_xlabel('Time [sec]')
        axarr[i,0].set_ylabel('Voltage [V]')
        axarr[i,0].grid()
        axarr[i,0].legend()
        axarr[i,1].set_xlabel('Time [sec]')
        axarr[i,1].set_ylabel('Current [A]')
        axarr[i,1].grid()
        axarr[i,1].legend()

    plt.show()

def DFT_boton():
    # PLOTING -----------------------------------------------------------------
    f, axarr = plt.subplots(3, 2, figsize =(16, 10))
    f.suptitle('DFT En Magnitud', y=0.92, fontsize=16)

    # Plot Voltages
    #axarr[0,0].plot(time_sub[:,0], V_sub[:,0], 'b-', label='Phase A')
    axarr[0,0].plot( t[:,0], X_V[:,0], 'c-', label='Phase A FFT(mag)')
    #axarr[1,0].plot(time_sub[:,1], V_sub[:,1], 'r-', label='Phase B')
    axarr[1,0].plot( t[:,1], X_V[:,1], 'm-', label='Phase B FFT(mag)')
    #axarr[2,0].plot(time_sub[:,2], V_sub[:,2], label='Phase C')
    axarr[2,0].plot( t[:,2], X_V[:,2], 'y-', label='Phase C FFT(mag)')

    # Plot Currents
    #axarr[0,1].plot(time_sub[:,3], C_sub[:,0], 'b-', label='Phase A')
    axarr[0,1].plot( t[:,3], X_C[:,0], 'c-', label='Phase A FFT(mag)')
    #axarr[1,1].plot(time_sub[:,4], C_sub[:,1], 'r-', label='Phase B')
    axarr[1,1].plot( t[:,4], X_C[:,1], 'm-', label='Phase B FFT(mag)')
    #axarr[2,1].plot(time_sub[:,5], C_sub[:,2], 'g-', label='Phase C')
    axarr[2,1].plot( t[:,5], X_C[:,2], 'y-', label='Phase C FFT(mag)')

    for i in np.arange(3):
        axarr[i,0].set_xlabel('Time [sec]')
        axarr[i,0].set_ylabel('Voltage [V]')
        axarr[i,0].grid()
        axarr[i,0].legend()
        axarr[i,1].set_xlabel('Time [sec]')
        axarr[i,1].set_ylabel('Current [A]')
        axarr[i,1].grid()
        axarr[i,1].legend()

    plt.show()

    # Ploting angle
    f, axarr = plt.subplots(3, 2, figsize =(16, 10))
    f.suptitle('DFT En Fase', y=0.92, fontsize=16)

    # Plot Voltages
    #axarr[0,0].plot(time_sub[:,0], V_sub[:,0], 'b-', label='Phase A')
    axarr[0,0].plot( t[:,0], Y_V[:,0], 'c-', label='Phase A FFT[ang(rad)]')
    #axarr[1,0].plot(time_sub[:,1], V_sub[:,1], 'r-', label='Phase B')
    axarr[1,0].plot( t[:,1], Y_V[:,1], 'm-', label='Phase B FFT[ang(rad)]')
    #axarr[2,0].plot(time_sub[:,2], V_sub[:,2], label='Phase C')
    axarr[2,0].plot( t[:,2], Y_V[:,2], 'y-', label='Phase C FFT[ang(rad)]')

    # Plot Currents
    #axarr[0,1].plot(time_sub[:,3], C_sub[:,0], 'b-', label='Phase A')
    axarr[0,1].plot( t[:,3], Y_C[:,0], 'c-', label='Phase A FFT[ang(rad)]')
    #axarr[1,1].plot(time_sub[:,4], C_sub[:,1], 'r-', label='Phase B')
    axarr[1,1].plot( t[:,4], Y_C[:,1], 'm-', label='Phase B FFT[ang(rad)]')
    #axarr[2,1].plot(time_sub[:,5], C_sub[:,2], 'g-', label='Phase C')
    axarr[2,1].plot( t[:,5], Y_C[:,2], 'y-', label='Phase C FFT[ang(rad)]')

    for i in np.arange(3):
        axarr[i,0].set_xlabel('Time [sec]')
        axarr[i,0].set_ylabel('Angle (°)')
        axarr[i,0].grid()
        axarr[i,0].legend()
        axarr[i,1].set_xlabel('Time [sec]')
        axarr[i,1].set_ylabel('Angle (°)')
        axarr[i,1].grid()
        axarr[i,1].legend()
    plt.show()

def fasores_boton():
    # Creando la figura
    fig, ax = plt.subplots(1, 2, figsize =(16, 6))
    fig.suptitle('Diagrama fasorial de Voltaje y Corriente', y=0.95, fontsize=16)

    lim_axis_V = np.max([np.float(X_V[-1:,0]), np.float(X_V[-1:,1]),np.float(X_V[-1:,2])])
    lim_axis_C = np.max([np.float(X_C[-1:,0]), np.float(X_C[-1:,1]),np.float(X_C[-1:,2])])
    # Creando el punto de origen para los vectores
    x_pos = [0, 0,0]
    y_pos = [0, 0,0]

    ax[0].quiver(x_pos, y_pos, Xc_V[-1,0], Xs_V[-1,0], angles='xy', scale_units = 'xy', scale=1, color=['b'], label='Fase A')
    ax[0].quiver(x_pos, y_pos, Xc_V[-1,1], Xs_V[-1,1], angles='xy', scale_units = 'xy', scale=1, color=['r'], label='Fase B')
    ax[0].quiver(x_pos, y_pos, Xc_V[-1,2], Xs_V[-1,2], angles='xy', scale_units = 'xy', scale=1, color=['g'], label='Fase C')
    ax[0].axis([-1.2*lim_axis_V, 1.2*lim_axis_V, -1.2*lim_axis_V, 1.2*lim_axis_V])
    ax[0].set_title('Voltaje [V]')
    ax[0].legend() #<-- Se nombran las leyendas
    ax[0].grid(b=True, which='major') #<-- plot grid lines

    ax[1].quiver(x_pos, y_pos, Xc_C[-1,0], Xs_C[-1,0], angles='xy', scale_units = 'xy', scale=1, color=['b'], label='Fase A')
    ax[1].quiver(x_pos, y_pos, Xc_C[-1,1], Xs_C[-1,1], angles='xy', scale_units = 'xy', scale=1, color=['r'], label='Fase B')
    ax[1].quiver(x_pos, y_pos, Xc_C[-1,2], Xs_C[-1,2], angles='xy', scale_units = 'xy', scale=1, color=['g'], label='Fase C')
    ax[1].axis([-1.2*lim_axis_C, 1.2*lim_axis_C, -1.2*lim_axis_C, 1.2*lim_axis_C])
    ax[1].set_title('Corriente [A]')
    ax[1].legend() #<-- Se nombran las leyendas
    ax[1].grid(b=True, which='major') #<-- plot grid lines
    plt.show()

    # Mostrando las fases en la interfaz
    label_fas0.grid(row=3,column=0)
    label_fas1.config(text=['Voltaje fase A:', "{:.2f}".format(np.double(X_V[-1:,0])), 'V', "{:.2f}".format(np.double(Y_V[-1:,0])),'°'])
    label_fas1.grid(row=4,column=0)
    label_fas2.config(text=['Voltaje fase B:', "{:.2f}".format(np.double(X_V[-1:,1])), 'V', "{:.2f}".format(np.double(Y_V[-1:,1])),'°'])
    label_fas2.grid(row=5,column=0)
    label_fas3.config(text=['Voltaje fase C:', "{:.2f}".format(np.double(X_V[-1:,2])), 'V', "{:.2f}".format(np.double(Y_V[-1:,1])),'°'])
    label_fas3.grid(row=6,column=0)
    label_fas4.config(text=['Corriente fase A:', "{:.2f}".format(np.double(X_C[-1:,0])), 'A', "{:.2f}".format(np.double(Y_C[-1:,0])),'°'])
    label_fas4.grid(row=7,column=0)
    label_fas5.config(text=['Corriente fase B:', "{:.2f}".format(np.double(X_C[-1:,1])), 'A', "{:.2f}".format(np.double(Y_C[-1:,1])),'°'])
    label_fas5.grid(row=8,column=0)
    label_fas6.config(text=['Corriente fase C:', "{:.2f}".format(np.double(X_C[-1:,2])), 'A', "{:.2f}".format(np.double(Y_C[-1:,2])),'°'])
    label_fas6.grid(row=9,column=0)
#------------------------------------------------------------------
# MAIN
raiz=Tk()
raiz.title("Modulo DSP para relés")
    #raiz.geometry("650x380")
x_frame = 720
y_frame = 500
raiz.geometry("{width}x{height}".format(width=x_frame, height=y_frame))
raiz.resizable(True, True)
# mifr= Frame()
# mifr.pack(side=TOP, fill=BOTH, expand=Y)
# #mifr.config()
# mifr.config(width="650",height="380")
# mifr.config(cursor="star")
bmenu=Menu(raiz)
raiz.config(menu=bmenu)

#-------------------------------- FRAME 1 -------------------------------
frame1 = LabelFrame(raiz, text="Entradas",height= y_frame,width =x_frame,padx=5, labelanchor=N)
frame1.config(cursor="star")
frame1.pack(expand = 'no', fill = 'both')

x_frame11 = 350
frame11 = LabelFrame(frame1, text="Selección del archivo COMTRADE",fg="red",height= 100,width =x_frame11,padx=15)
frame11.grid(column=0, row=0, padx=10, pady=10)
label11 = Label(frame11, text = 'Instrucciones: Se deben seleccionar los archivos .cfg y .dat')
label11.place(x = 0, y = 5)

BotonAbrircfg = Button(frame11,text="Abrir .cfg",command=abrir_cfg)
BotonAbrircfg.place(x = x_frame11/6, y = 30)
BotonAbrirdat = Button(frame11,text="Abrir .dat",command=abrir_dat)
BotonAbrirdat.place(x = 3*x_frame11/6, y = 30)

x_frame12 = 250
frame12 = LabelFrame(frame1, text="Selección de parámetros de entrada",fg="red",height= 200,width =x_frame12,padx=15)
frame12.grid(column=1, row=0, columnspan=1, rowspan=2, padx=10, pady=10)

t1=Label(frame12,text="Seleccione la frecuencia \nde muestro del relé",fg="green")
t1.grid(row=0,column=0,sticky="w",pady="20")
en1=StringVar()
d=OptionMenu(frame12, en1, "4","8","16","32","64")
d.grid(row=0,column=1,sticky="w",padx="20",pady="20")
en1.set("Seleccionar")

frame121 = LabelFrame(frame12, text="Relación de transformadores de instrumentación",fg="Blue",height= 200,width =x_frame12,padx=15)
frame121.grid(column=0, row=1, columnspan=2, rowspan=1, padx=10, pady=10)

# Relación de transformadores de instrumentación voltaje le falta dividir entre prim y secundario
t2=Label(frame121,text="Relacion de Voltaje")
t2.grid(row=0,column=0,sticky="w")
en2=Entry(frame121, width=7)
en2.grid(row=0,column=1)
t3=Label(frame121,text=":")
t3.grid(row=0,column=2)
en3=Entry(frame121, width=7)
en3.grid(row=0,column=3)

# Relación de transformadores de instrumentación corriente le falta dividir entre prim y secundario
t21=Label(frame121,text="Relacion de Corriente")
t21.grid(row=1,column=0,sticky="w")
en4=Entry(frame121, width=7)
en4.grid(row=1,column=1)
t31=Label(frame121,text=":")
t31.grid(row=1,column=2)
en5=Entry(frame121, width=7)
en5.grid(row=1,column=3)

b1=Button(frame12,text="cargar valores",command=cargar)
b1.grid(row=2,column=0,columnspan=2, rowspan=1)

x_frame13 = 350
frame13 = LabelFrame(frame1, text="Visualización en el transformador",fg="red",height= 100,width =x_frame13,padx=15)
frame13.grid(column=0, row=1, padx=10, pady=0)
label13 = Label(frame13, text = 'Seleccione el lado que desea ver la señal del transformador')
label13.place(x = 0, y = 5)

side = IntVar()
rad_trafo1 = Radiobutton(frame13,text="Primario", variable = side, value=1)
rad_trafo1.place(x = x_frame13/6, y = 30)
rad_trafo2 = Radiobutton(frame13,text="Secundario", variable = side, value=2)
rad_trafo2.place(x = 3*x_frame13/6, y = 30)

#-------------------------------- FRAME 2 -------------------------------
frame2 = LabelFrame(raiz, text="Resultados del procesamiento",height= y_frame,width =x_frame,padx=5, labelanchor=N)
frame2.config(cursor="star")
frame2.pack(expand = 'no', fill = 'both')

x_frame21 = 350
frame21 = LabelFrame(frame2, text="Detalle por etapa",fg="red",height= 100,width =x_frame21,padx=15)
frame21.grid(column=0, row=0, padx=10, pady=10)
label21 = Label(frame21, text = 'Seleccione la etapa que desea detallar')
label21.grid(row=0,column=0,columnspan=3)

bi=Button(frame21,text="Señales de entrada",command=seniales_COMTRADE)#carga los archivos
bi.grid(row=1,column=0)
b2=Button(frame21,text="Submuestreo",command=submuestreo_boton)
b2.grid(row=1,column=1)
#etapa de mostrar señal digitalizada
b3=Button(frame21,text="Digitalizacion",command=digitalizacion_boton)
b3.grid(row=1,column=2)
#etapa de ventaneo
b3=Button(frame21,text="DFT",command=DFT_boton)
b3.grid(row=2,column=1)

x_frame22 = 250
frame22 = LabelFrame(frame2, text="Señal Procesada",fg="red",height= 100,width =x_frame22,padx=15)
frame22.grid(column=1, row=0, padx=10, pady=10)
label22 = Label(frame22, text = 'En este módulo se muestran las señales resultantes')
label22.grid(row=0,column=0)

b3=Button(frame22,text="Fasores",command=fasores_boton)
b3.grid(row=1,column=0)

label_fas0 = Label(frame22, text = 'Los fasores resultantes en rms son:')
label_fas0.grid_forget()
label_fas1 = Label(frame22, text = 'Aqui se mostrara el fasor 1',fg="blue")
label_fas1.grid_forget()
label_fas2 = Label(frame22, text = 'Aqui se mostrara el fasor 2',fg="red")
label_fas2.grid_forget()
label_fas3 = Label(frame22, text = 'Aqui se mostrara el fasor 3',fg="green")
label_fas3.grid_forget()
label_fas4 = Label(frame22, text = 'Aqui se mostrara el fasor 1',fg="blue")
label_fas4.grid_forget()
label_fas5 = Label(frame22, text = 'Aqui se mostrara el fasor 2',fg="red")
label_fas5.grid_forget()
label_fas6 = Label(frame22, text = 'Aqui se mostrara el fasor 3',fg="green")
label_fas6.grid_forget()

barchiv=Menu(bmenu,tearoff=0)
bhelp=Menu(bmenu,tearoff=0)
barchiv.add_command(label="Abrir archivo ")#carga los archivos
barchiv.add_command(label="Guardar")
bmenu.add_cascade(label="Archivo",menu=barchiv)
#help

bhelp.add_command(label="Descripción")
bmenu.add_cascade(label="Ayuda",menu=bhelp)

raiz.mainloop()


r"""
Download resources used for various purposes.

Usage:
    python download_resources.py \
        --game_num 5961 \
        --data_root path/to/folder/containing/all/game/data/ \
        --purpose calibration
"""

import argparse
import os

from src.util import s3_util

def download_spotlight_resources(game_num, local_game_folder):
    """
    Download resources used for running spotlight.

    Args:
        game_num            Game number
        local_game_folder   Path to folder containing game resources
    """
    s3_util.download_calibration_folder(game_num, local_game_folder)
    s3_util.download_color_classification_folder(game_num, local_game_folder)
    s3_util.download_object_detector_folder_no_videos(
        game_num, local_game_folder)
    s3_util.download_object_tracker_folder(game_num, local_game_folder)
    s3_util.download_results_folder(game_num, local_game_folder)
    s3_util.download_spotlight_folder(game_num, local_game_folder)
    s3_util.download_stitch_folder_no_videos(game_num, local_game_folder)

def download_calibration_resources(game_num, local_game_folder):
    """
    Download resources used for calibration.

    Args:
        game_num            Game number
        local_game_folder   Path to folder containing game resources
    """
    s3_util.download_calibration_folder(game_num, local_game_folder)
    s3_util.download_results_folder(game_num, local_game_folder)
    s3_util.download_stitch_folder_no_videos(game_num, local_game_folder)

if __name__ == "__main__":

    ap = argparse.ArgumentParser()
    ap.add_argument(
        "--game_num", required=True, type=int,
        help="Game number to use")
    ap.add_argument(
        "--data_root", required=True, type=str,
        help="Folder containing game data")
    ap.add_argument(
        "--purpose", required=True, type=str,
        choices=["calibration", "spotlight"])
    args = vars(ap.parse_args())
    game_num = args["game_num"]
    data_root = args["data_root"]
    purpose = args["purpose"]

    assert os.path.isdir(data_root)

    local_game_folder = os.path.join(data_root, "game_{0}".format(game_num))

    if purpose == "calibration":
        download_calibration_resources(game_num, local_game_folder)
    elif purpose == "spotlight":
        download_spotlight_resources(game_num, local_game_folder)


# -*- coding: utf-8 -*-
"""
This script contains functions for loading and analysis of burrito data
"""

import numpy as np
import scipy as sp
import pandas as pd

def load_burritos(filename='burrito_current.csv',
                  delete_unreliable = True):
    # Load all data
    df = pd.read_csv(filename)
    df.Location = df.Location.str.lower()

    # Delete unreliable ratings
    if delete_unreliable:

        # Binarize unreliable
        df.Unreliable = df.Unreliable.map({'x':1,'X':1,1:1})
        df.Unreliable = df.Unreliable.fillna(0)

        # Select only reliable ratings from dataframe
        import pandasql
        q = """
        SELECT
        *
        FROM
        df
        WHERE
        unreliable == 0
        """
        df = pandasql.sqldf(q.lower(), locals())

    return df


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('microdevices', '0003'),
    ]

    operations = [
        migrations.AddField(
            model_name='organmodel',
            name='model_image',
            field=models.ImageField(null=True, upload_to=b'models', blank=True),
        ),
    ]


'''
请实现一个函数，用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样，那么它是对称的。

例如，二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof
'''
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        # 迭代 BFS
        queue = [root.left, root.right]
        while queue:
            node1 = queue.pop(0)
            node2 = queue.pop(0)
            if not node1 and not node2:
                continue
            if not node1 or not node2 or node1.val != node2.val:
                return False
            queue.append(node1.left)
            queue.append(node2.right)
            queue.append(node1.right)
            queue.append(node2.left)
        return True

        #递归
        # def helper(node1, node2):
        #     if not node1 and not node2:
        #         return True
        #     if not node1 or not node2 or node1.val != node2.val:
        #         return False
        #     l = helper(node1.left, node2.right)
        #     r = helper(node1.right, node2.left)
        #     return l and r
        # return helper(root.left, root.right)


import argparse
from PIL import Image

from vietocr.tool.predictor import Predictor
from vietocr.tool.config import Cfg
import sys
sys.path.insert(0, './')
from char import character
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--img', required=True, help='foo help')
    parser.add_argument('--config', required=True, help='foo help')

    args = parser.parse_args()
    config_base = Cfg.load_config_from_file("config/base.yml")
    config = Cfg.load_config_from_file(args.config)
    config_base.update(config)
    config = config_base

    config['vocab'] = character

    detector = Predictor(config)

    img = Image.open(args.img)
    s = detector.predict(img)

    print(s)

if __name__ == '__main__':
    main()


# pip install beautifulsoup4
# pip install lxml

from bs4 import BeautifulSoup

with open("sample.html", "r") as html_file:
    content = html_file.read()
    soup = BeautifulSoup(content, 'lxml')
    course_cards = soup.findAll("div", class_="card")
    for course in course_cards:
        course_name = course.h5.text
        course_price = course.a.text.split()[-1]
        print(f"{course_name} costs {course_price}")

# headers = {"User-Agent": "Mozilla/5.0"}
# content is bytes, text is text - content is better
# find, find_all
# select_one, select
# # id
# . class
# tag
# find and .get("attr")

# bs4.element
# bs4.element.ResultSet

# str.ljust(30)

# string="xx"

# find_parents
# find_parent
# .get_text(strip=True)

# ul
# ol
# li

# table
# tr
# th/td

# div section span input a p

# find_next_sibling/s
# find_previous_sibling/s

# find_next()
# find_all_next()

# find_previous()
# find_all_previous()


# coding: UTF-8

import numpy as np
import cv2
from matplotlib import pyplot as plt

#img = cv2.imread('simple.jpg',0)
img = cv2.imread('simple2.jpg',0)

#まずデフォルト値でFASTオブジェクトを作る
fast = cv2.FastFeatureDetector_create()

# キーポイントを求めて描画する
kp = fast.detect(img,None)
img2 = cv2.drawKeypoints(img, kp,None,color=(255,0,0))

# デフォルトのパラメタをすべて表示
print("Threshold: ", fast.getThreshold())   #閾値の設定
print("nonmaxSuppression: ", fast.getNonmaxSuppression()) #最大値抑制を適用するか
print("neighborhood: ", fast.getType())     #周辺領域の選択
print("Total Keypoints with nonmaxSuppression: ", len(kp))

#cv2.imwrite('fast_true.png',img2)
cv2.imwrite('fast_true2.png',img2)

# nonmaxSuppressionを停止
fast.setNonmaxSuppression(0)
kp = fast.detect(img,None)

print("Total Keypoints without nonmaxSuppression: ", len(kp))

img3 = cv2.drawKeypoints(img, kp,None,color=(255,0,0))

#cv2.imwrite('fast_false.png',img3)
cv2.imwrite('fast_false2.png',img3)


"""empty message

Revision ID: 40bc44aaf9dd
Revises: 201626a58dfd
Create Date: 2017-01-02 18:22:33.100981

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '40bc44aaf9dd'
down_revision = '201626a58dfd'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('last_message',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('fb_uid', sa.Integer(), nullable=True),
    sa.Column('last_user_message', sa.Unicode(), nullable=True),
    sa.Column('last_bot_response', sa.Unicode(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('last_message')
    # ### end Alembic commands ###


# the main class, which runs off the other classes handling everything (Vars.py, Rooms.py)

from Vars import *
from Rooms import *

eg.msgbox("Welcome to TextExplore.", title, ok_button="Continue")
eg.msgbox("A simple game by xPythonier.", title, ok_button="Continue")

start_choices = ["Play", "Credits", "Exit"]

def Main():
    choice = eg.indexbox("Please, choose an option.", "Main Menu", start_choices)

    if choice == 0:
        roomOne()

    if choice == 1:
        Credits()
        Main()

    if choice == 2:
        end_choices = ["Yes", "No"]
        end = eg.indexbox("Are you sure?", "End Game", end_choices)
        if end == 0:
            eg.sys.exit()
        if end == 1:
            Main()

Main()


import socket
import threading
import os
import sys
import tkinter as tk
from tkinter import simpledialog
#import PyQt5
#from PyQt5 import QtCore, QtGui, QtWidgets
#from PyQt5.QWidgets import QApplication, QMainWindow

import emoji

#number of users in chatroom
numUsers = 0

##############
# Server
##############

class Server(threading.Thread):
    def __init__(self, host, port):
        #holds the connections of server to client
        self.connections = []
        self.host = "127.0.0.1"
        self.port = 1060
        super().__init__()

    def run(self):
        #attempt to connect socket and port
        serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        serverSock.bind(("127.0.0.1", 1060))
        serverSock.listen(1)
        #announce in terminal what we are listening on
        print('Connected on:', serverSock.getsockname())
        #attempt to connect user(s) to server
        while True:
            sc, sockname = serverSock.accept()
            print('user connects from {} to {}'.format(
                sc.getpeername(), sc.getsockname()))
            #new thread
            server_socket = ServerSocket(sc, sockname, self)
            server_socket.start()
            # Add thread to  connections
            self.connections.append(server_socket)
            print('Server gets messages from user from:', sc.getpeername())

    def messageSend(self, message, source):
        #sends all other users usernames message
        for connection in self.connections:
            if connection.sockname != source:
                connection.send(message)

    def remove_connection(self, connection):
        #remove connnnection from server socket
        self.connections.remove(connection)

class ServerSocket(threading.Thread):
    #support socket connection
    def __init__(self, sc, sockname, server):
        self.sc = sc
        self.sockname = sockname
        self.server = server
        super().__init__()

    def run(self):
        #return user message
        while True:
            message = self.sc.recv(1024).decode('ascii')
            if message:
                #send users message
                self.server.messageSend(message, self.sockname)
            else:
                self.sc.close()
                #server.remove_connection(self)
                return

    def send(self, message):
        #Send user message to server.
        self.sc.sendall(message.encode('ascii'))

##############
# Client
##############

class Send(threading.Thread):
    def __init__(self, socket, name):
        self.socket = socket
        self.username = name
        super().__init__()

class ClientRecieve(threading.Thread):
    #get threads from server
    def __init__(self, socket, name):
        super().__init__()
        self.socket = socket
        self.username = name
        self.messages = None

    def run(self):
        #gets messages from server and displays on GUI
        message = self.socket.recv(1024).decode('ascii')
        print("line 104: " + message)
        #check message is valid
        if message:
            if self.messages:
                self.messages.insert(tk.END, (message))
                print("line 109: " + message)
        else:
            print("ISSUE")

#GUI support for client and server

class ChatroomGUI:
    #get ports/hosts
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.username = None
        self.messages = None

    #Starting up the client server connection
    def start(self):
        #Connect host and port
        print("Connecting to " + str(self.host) + ":" + str(self.port))
        self.socket.connect((self.host, self.port))
        print(emoji.emojize("Success! :thumbs_up:"))

        #Get name from user
        self.username = simpledialog.askstring(
            "Input", "What is your name?", parent=tk.Tk())

        #threads
        send = Send(self.socket, self.username)
        receive = ClientRecieve(self.socket, self.username)
        #start thread connections
        send.start()
        receive.start()

        #announce that another user joined chatroom
        self.socket.sendall("{} has joined. Say hi!".format(
            self.username).encode("ascii"))
        print("\rNote: you can leave the chatroom by typing 'q'!\n")
        return receive

    def send(self, msgTextBox):
        #message from user written in textbox in GUI
        message = msgTextBox.get()
        #remove message from textbox after user hits send
        msgTextBox.delete(0, tk.END)
        #place message (if valid, meaning there is a message) in gui box
        print("156 message: " + message)
        if len(message) > 0:
            self.messages.insert(tk.END, "{}: {}".format(
                self.username, (message)))

        # quit classroom: user must type "q"
        if message == "q":
            #send to socket that user is leaving chat
            self.socket.sendall("{} has left the chat.".format(
                self.username).encode("ascii"))
            #close socket
            self.socket.close()
            os._exit(0)
        else:
            self.socket.sendall("{}: {}".format(
                self.username, (message)).encode("ascii"))

def main(host, port):
    #GUI of program
    client = ChatroomGUI(host, port)
    receive = client.start()

    #Create window for gui
    window = tk.Tk()

    #dimensions of window
    window.geometry("300x200")

    #Title
    window.title("Socket Server Chatroom")

    #Box of TEXT messages
    MsgBox = tk.Frame(master=window)
    messages = tk.Listbox(master=MsgBox)
    messages.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
    client.messages = messages
    receive.messages = messages
    MsgBox.grid(row=0, column=3)

    #Textbox for input
    colOne = tk.Frame(master=window)
    #accept single-line text strings from a user.
    msgTextBox = tk.Entry(master=colOne)
    msgTextBox.pack(side=tk.RIGHT, expand=True)
    #input of text message
    msgTextBox.bind("<Return>", lambda x: client.send(msgTextBox))
    colOne.grid(row=6, column=3)

    #Send button
    sendMsgButton = tk.Button(
        master=window,
        text="Send",
        width=8,
        command=lambda: client.send(msgTextBox)
    )
    sendMsgButton.grid(row=6, column=1)

    #deploy
    window.mainloop()

#start up program
if __name__ == '__main__':

    #get input from user(s)

    hosting = simpledialog.askstring(
        "Input", "Create Host connection? (yes/no)", parent=tk.Tk())
    #start up server on socket 127.0.0.1 and port 1060
    if (hosting == "yes" or hosting == "Yes" or hosting == "y"):
         (Server("127.0.0.1", int(1060))).start()

    socketValue = simpledialog.askstring(
        "Input", "Type socket value:", parent=tk.Tk())
    portValue = simpledialog.askstring(
        "Input", "Type port value:", parent=tk.Tk())
    #start main with users given socket and port values
    #main((socketValue), int(portValue))
    main("127.0.0.1", int(1060))


from django.shortcuts import render
from .models import Product, Category
from django.db.models import Q
from django.core.paginator import Paginator, InvalidPage, PageNotAnInteger, EmptyPage
from .forms import walleSearchForm
from haystack import forms
from haystack.query import SearchQuerySet

def index(request):
    clo_list = Product.objects.all()
    clo_list = get_page(request, clo_list)
    categories = Category.objects.filter(parent=None)
    search_from = walleSearchForm()
    return render(request, 'store/index.html', locals())

def get_page(request, clo_list):
    pagintor = Paginator(clo_list, 4)
    try:
        page = int(request.GET.get('page',1))
        clo_list = pagintor.page(page)
    except (EmptyPage, InvalidPage,Paginator):
        clo_list = pagintor.page(1)
    return clo_list

def product_detail(request, id):
    try:
        clo = Product.objects.get(pk=id)
    except Product.DoesNotExist:
        return render(request, 'store/error.html', {'error': '商品不存在'})
    return render(request, 'store/single_product.html', locals())

def category(request, id):
    try:
        cat = Category.objects.get(pk=id)
    except Category.DoesNotExist:
        return render(request, 'store/error.html', {'error': '分类不存在'})

    clo_list = Product.active_objects.filter(category=cat)
    clo_list= get_page(request,clo_list)
    categories = Category.objects.filter(parent=None)
    return render(request, 'store/index.html', locals())

def search(request):
    categories = Category.objects.filter(parent=None)
    search_from = walleSearchForm(request.GET)

    if search_from.is_valid():
        keyword = search_from.cleaned_data['keyword']
        query = SearchQuerySet()
        sqs = query.auto_query(keyword)
        clo_list = []
        for s in sqs:
            clo = Product.objects.get(pk=s.pk)
            if clo:
                clo_list.append(clo)
        clo_list = get_page(request,clo_list)

    return render(request, 'store/index.html', locals())


def quicksort(left, right):
	pivot = array[left]
	pivot_index = left
	i = left
	j = right
	if(left == right):
		return
	while(left < right):
		while(array[right] > pivot and right > left):
			right -= 1
		if(right > left):
			array[left] = array[right]
			array[right] = pivot
			pivot_index = right
		else:
			break
		while(array[left] < pivot and left < right):
			left += 1
		if(left < right):
			array[right] = array[left]
			array[left] = pivot
			pivot_index = left
		else:
			break
	quicksort(i, pivot_index)
	quicksort(pivot_index + 1, j)

array = [9, 4,2,1,3,8,5,7,6,10]
quicksort(0, len(array) -1)
print(array)


import FWCore.ParameterSet.Config as cms

process = cms.Process("prodCommissioningZmumuEnrichedPATtuple")

# import of standard configurations for RECOnstruction
# of electrons, muons and tau-jets with non-standard isolation cones
process.load('Configuration/StandardSequences/Services_cff')
process.load('FWCore/MessageService/MessageLogger_cfi')
process.MessageLogger.cerr.FwkReport.reportEvery = 100
#process.MessageLogger.cerr.threshold = cms.untracked.string('INFO')
#process.MessageLogger.suppressInfo = cms.untracked.vstring()
process.MessageLogger.suppressWarning = cms.untracked.vstring("PATTriggerProducer",)
process.load('Configuration/StandardSequences/GeometryIdeal_cff')
process.load('Configuration/StandardSequences/MagneticField_cff')
process.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff')

#--------------------------------------------------------------------------------
process.source = cms.Source("PoolSource",
    fileNames = cms.untracked.vstring(
        #'file:/data2/friis/CMSSW_4_2_X/skims/06-27-MatthewsZTTEvents/crab_0_110627_082505/ZTTCands_merged_v1.root'
        'file:/data1/veelken/CMSSW_4_2_x/skims/skim_data_SingleMu_Run2011A_PromptReco_v4_chunk_93_5651.root'
    ),
    skipEvents = cms.untracked.uint32(0)
)

process.maxEvents = cms.untracked.PSet(
    input = cms.untracked.int32(-1)
)

#--------------------------------------------------------------------------------
# define configuration parameter default values

##isMC = True # use for MC
isMC = False # use for Data
##HLTprocessName = "HLT" # use for 2011 Data
HLTprocessName = "HLT" # use for Summer'11 MC
pfCandidateCollection = "particleFlow" # pile-up removal disabled
##pfCandidateCollection = "pfNoPileUp" # pile-up removal enabled
applyEventSelection = True
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
# define "hooks" for replacing configuration parameters
# in case running jobs on the CERN batch system/grid
#
#__isMC = #isMC#
#__HLTprocessName = #HLTprocessName#
#__pfCandidateCollection = #pfCandidateCollection#
#__applyEventSelection = #applyEventSelection#
#
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
# define GlobalTag to be used for event reconstruction
if isMC:
    process.GlobalTag.globaltag = cms.string('START52_V9::All')
else:
    process.GlobalTag.globaltag = cms.string('GR_R_52_V7::All')
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
# define skimming criteria
# (in order to be able to produce Tau Ntuple directly from unskimmed Monte Carlo/datasets;
#  HLT muon trigger passed && two global muons passing VBTF selection && within Z mass-window
#                          && either CaloJet or PFJet of Pt > 10 GeV within |eta| < 2.5)
process.load('TauAnalysis.TauIdEfficiency.filterZmumuEnriched_cfi')
if isMC:
    process.dataQualityFilters.remove(process.hltPhysicsDeclared)
    process.dataQualityFilters.remove(process.dcsstatus)
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
#
# produce collections of objects needed as input for PAT-tuple production
# (e.g. rerun reco::Tau identification algorithms with latest tags)
#
from TauAnalysis.TauIdEfficiency.tools.configurePrePatProduction import configurePrePatProduction

configurePrePatProduction(process, pfCandidateCollection = pfCandidateCollection, isMC = isMC)
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
#
# produce PAT objects
#
from TauAnalysis.TauIdEfficiency.tools.configurePatTupleProduction import configurePatTupleProduction

# "clean" CaloTau/PFTau collections
# (i.e. remove CaloTaus/PFTaus overlapping with muons)
process.load("PhysicsTools.PatAlgos.cleaningLayer1.tauCleaner_cfi")

# remove jets outside kinematic range Pt > 10 GeV && |eta| < 2.5 from Tau Ntuple
# (in order to speed-up plotting macros)
patCaloTauCleanerPrototype = process.cleanPatTaus.clone(
    preselection = cms.string(''),
    checkOverlaps = cms.PSet(
        muons = cms.PSet(
           src                 = cms.InputTag("patMuonsWithinAcc"),
           algorithm           = cms.string("byDeltaR"),
           preselection        = cms.string("isGlobalMuon"),
           deltaR              = cms.double(0.7),
           checkRecoComponents = cms.bool(False),
           pairCut             = cms.string(""),
           requireNoOverlaps   = cms.bool(True)
        )
    ),
    finalCut = cms.string(
        'caloTauTagInfoRef().jetRef().pt() > 8.0 & abs(caloTauTagInfoRef().jetRef().eta()) < 2.5'
    )
)

patPFTauCleanerPrototype = patCaloTauCleanerPrototype.clone(
    finalCut = cms.string(
        'pfJetRef().pt() > 8.0 & abs(pfJetRef().eta()) < 2.5'
    )
)

retVal = configurePatTupleProduction(
    process,
    patPFTauCleanerPrototype = patPFTauCleanerPrototype,
    patCaloTauCleanerPrototype = patCaloTauCleanerPrototype,
    hltProcess = HLTprocessName,
    isMC = isMC
)

# add event counter for Mauro's "self baby-sitting" technology
process.totalEventsProcessed = cms.EDProducer("EventCountProducer")
process.eventCounterPath = cms.Path(process.totalEventsProcessed)
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
#
# produce Ntuple
#
process.load("TauAnalysis.TauIdEfficiency.ntupleConfigVertex_cfi")
process.load("TauAnalysis.TauIdEfficiency.ntupleConfigGenPhaseSpaceEventInfo_cfi")
process.load("TauAnalysis.TauIdEfficiency.ntupleConfigGenPileUpEventInfo_cfi")

process.ntupleProducer = cms.EDProducer("ObjValEDNtupleProducer",

    ntupleName = cms.string("tauIdEffNtuple"),

    sources = cms.PSet(
        # number of reconstructed primary event vertices
        # with sum(trackPt) exceeding different thresholds
        vertexMultiplicity = process.vertexMultiplicity_template,
    )
)

if isMC:
    setattr(process.ntupleProducer.sources, "genPhaseSpaceEventInfo", process.genPhaseSpaceEventInfo_template)
    setattr(process.ntupleProducer.sources, "genPileUpEventInfo", process.genPileUpEventInfo_template)
    # add reweighting factors to be applied to Monte Carlo simulated events
    # in order to match vertex multiplicity distribution in Data
    setattr(process.ntupleProducer.sources, "vertexMultReweight", process.vertexMultReweight_template)
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
#
# update InputTags for HLT trigger result object
# in case running on reprocessed Monte Carlo samples
#
if HLTprocessName != "HLT":
    process.hltMu.selector.src = cms.InputTag('TriggerResults::' + HLTprocessName)
    process.patTrigger.processName = HLTprocessName
    process.patTriggerEvent.processName = HLTprocessName
    process.patCaloTausTriggerEvent.processName = cms.string(HLTprocessName)
    process.patPFTausTriggerEventFixedCone.processName = cms.string(HLTprocessName)
    process.patPFTausTriggerEventShrinkingCone.processName = cms.string(HLTprocessName)
    process.patPFTausTriggerEventHPS.processName = cms.string(HLTprocessName)
    process.patPFTausTriggerEventHPSpTaNC.processName = cms.string(HLTprocessName)
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
#
# Save PAT-tuple
#
process.patTupleOutputModule = cms.OutputModule("PoolOutputModule",
    cms.PSet(
        outputCommands = cms.untracked.vstring(
            'drop *',
            'keep EventAux_*_*_*',
            'keep LumiSummary_*_*_*',
            'keep edmMergeableCounter_*_*_*',
            ##'keep *_%s_*_*' % retVal['caloTauCollection'],
            ##'keep *_%s_*_*' % retVal['pfTauCollectionFixedCone'],
            ##'keep *_%s_*_*' % retVal['pfTauCollectionShrinkingCone'],
            'keep *_%s_*_*' % retVal['pfTauCollectionHPS'],
            'keep *_%s_*_*' % retVal['pfTauCollectionHPSpTaNC'],
            'keep *_goodIsoMuons_*_*',
            'keep *_goldenZmumuCandidatesGe2IsoMuons_*_*',
            'keep *_selectedPatMuonsVBTFid_*_*',
            'keep *_offlinePrimaryVertices_*_*',
            'keep *_selectedPrimaryVertexPosition_*_*',
            'keep *_selectedPrimaryVertexHighestPtTrackSum_*_*',
            'keep *_offlinePrimaryVerticesWithBS_*_*',
            'keep *_patPFMet_*_*',
            ##'keep *_patMETs_*_*',
            'keep *_patJetsAK5PFnotOverlappingWithLeptonsForMEtUncertainty_*_*',
            'keep patJets_patJetsAK5PF_*_*',
            ##'keep patJets_patJetsAK5Calo_*_*',
            'keep *_*ntupleProducer*_*_*'
        )
    ),
    process.zMuMuEnrichedEventSelection, # comment-out to disable filtering of events written to PAT-tuple
    fileName = cms.untracked.string("tauCommissioningZmumuEnrichedPATtuple.root")
)

from PhysicsTools.PatAlgos.patEventContent_cff import patTriggerEventContent
process.patTupleOutputModule.outputCommands.extend(patTriggerEventContent)

if isMC:
    process.patTupleOutputModule.outputCommands.extend(
        cms.untracked.vstring(
            'keep *_smearedPatJetsAK5PF_*_*',
            'keep *_vertexMultiplicityReweight3dRunA_*_*',
            'keep *_vertexMultiplicityReweight3dRunB_*_*',
            'keep *_vertexMultiplicityVsRhoPFNeutralReweight_*_*',
            'keep *_addPileupInfo_*_*',
            'keep *_genPhaseSpaceEventInfo_*_*',
            'keep *_genParticles_*_*'
        )
    )
#--------------------------------------------------------------------------------

process.printEventContent = cms.EDAnalyzer("EventContentAnalyzer")

process.p = cms.Path(
    process.prePatProductionSequence
   + process.patTupleProductionSequence
   + process.ntupleProducer
   ##+ process.printEventContent
)

process.options = cms.untracked.PSet(
    wantSummary = cms.untracked.bool(True)
)

process.o = cms.EndPath(process.patTupleOutputModule)

# define order in which different paths are run
if applyEventSelection:
    process.schedule = cms.Schedule(
        process.eventCounterPath,
        process.p,
        ##process.diMuonCaloTauSkimPath,
        process.diMuonPFTauSkimPath,
        process.o
    )
else:
    delattr(process.patTupleOutputModule, "SelectEvents")
    process.schedule = cms.Schedule(
        process.eventCounterPath,
        process.p,
        process.o
    )

processDumpFile = open('produceCommissioningZmumuEnrichedPATTuple.dump' , 'w')
print >> processDumpFile, process.dumpPython()


from inspect import stack
from pathlib import Path

def abs_path_str_from_rel_to_this_file( path : str ) :
    caller_frame = stack()[1]
    caller_file_path = caller_frame.filename
    caller_directory = Path( caller_file_path ).parent
    full_path = caller_directory / path
    abs_path = full_path.resolve()
    abs_path_str = abs_path.as_posix()
    return abs_path_str


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 18:08:07 2019

@author: skgpc
"""
import pandas as pd
import numpy as np
from itertools import chain
#%%
from features_stats import get_all_tokens
from features_stats import get_words
from features_stats import get_punct
from features_stats import average_word_length
from features_stats import average_sent_length
from features_stats import check_sarcsymbol
from features_stats import count_uppercase
from features_stats import get_verb_lemmas
from features_stats import get_punct_average
from features_stats import get_sentiment
from features_stats import get_indiv_punct
from features_stats import relative_count_wordtypes
from features_stats import get_entities
#%%
def get_average_features(dictionary):
    """Take dictionary, extract specific features (see below for full list) and
    return summary as a dataframe:
    (1) Average Word Count
    (2) Average Sentence Count
    (3) Punctuation Richness
    (4) Sarcasm Symbol
    (5) Upper-case Words
    (6) Verb Lemmas
    (7) Sentiment Classification"""

    #Get all tokens
    tokens = get_all_tokens(dictionary)

    #Get list of ONLY words (no punct)
    word_list = get_words(tokens)

    #Get list of ONLY punct (no words)
    punct_list = get_punct(tokens)

    #Create df for total, full returns for irony
    total_train= pd.DataFrame({'Ironic Comment Parsed':tokens})
    total_train["Tokens"] = word_list
    total_train["Punctuation"] = punct_list
    total_train.head()

    #(1) AVERAGE WORD LENGTH
    average_word_leng = []
    for comment in word_list:
        average_word_leng.append(average_word_length(comment))

    #Create DataFrame for Summary of Irony STATS
    summary= pd.DataFrame({"Average Word Length": average_word_leng})

    #(2) AVERAGE SENTENCE LENGTH
    average_sent_leng = []
    for x in tokens:
        average_sent_leng.append(average_sent_length(x))

    #Add to Summary of Irony STATS df
    summary["Average Sentence Length"] = average_sent_leng
    summary.head()

    #(3) AVERAGE NUMBER OF SARCASM SYMBOL (/s)
    sarcfunc = []
    for x in tokens:
        sarcfunc.append(check_sarcsymbol(x))

    sarcsymb_list = []
    for l in sarcfunc:
        if len(l) >= 1:
            sarcsymb_list.append(l)
        else:
            sarcsymb_list.append([0])

    #Remove list layer
    sarcsymb_list = list(chain.from_iterable(sarcsymb_list))

    #Add result to Ironic Summary DF
    summary["Sarcasm Symbol (/s)"] = sarcsymb_list

    #(4) AVERAGE NUMBER OF UPPER CASE WORDS (total)
    uppercase_list = []
    for b in tokens:
        uppercase_list.append((count_uppercase(b)))

    #Remove list layer
    uppercase_list = list(chain.from_iterable(uppercase_list))

    #Add result to Ironic Summary DF
    summary["Uppercase Average"] = uppercase_list
    summary.head()

    #(5) AVERAGE PUNCTUATION RICHNESS
    punct_avg = get_punct_average(punct_list, tokens)

    #Add result to Ironic Summary DF
    summary["Punctuation Richness"] = punct_avg
    summary.head()

    #(6) AVERAGE NUMBER OF LEMMAS
    lemma_list = []
    for doc in tokens:
        lemma_list.append(get_verb_lemmas(doc))

    summary["Verb Lemma Average"] = lemma_list
    summary.head()

    #(7) SENTIMENT CLASSIFICATION
    #1 = positive, -1 = negative

    sentiment = get_sentiment(dictionary)

    summary["Sentiment Classification"] = sentiment

    #replace NAN values
    summary = summary.replace(np.nan, 0)
    return summary

#%%
def get_indivpunct(dictionary):
    """Take dictionary, extract punctuation marks and return summary as a
    dataframe"""

    #Get all tokens
    tokens = get_all_tokens(dictionary)

    average_indivpunc_list = []
    for x in tokens:
        average_indivpunc_list.append(get_indiv_punct(x))

    #Create Summary DF for each individual Punctuation Mark
    summary_indivpunct = pd.DataFrame(average_indivpunc_list)
    summary_indivpunct = summary_indivpunct.replace(np.nan, 0)

    return summary_indivpunct
#%%
def get_pos(dictionary):

    #Get all tokens
    tokens = get_all_tokens(dictionary)

    average_pos_list = []
    for comment in tokens:
        average_pos_list.append(relative_count_wordtypes(comment))

    #Create Summary DF for POS
    summary_pos = pd.DataFrame(average_pos_list)

    #replace NAN values
    summary_pos = summary_pos.replace(np.nan, 0)

    return summary_pos
#%%
def get_NER(dictionary):

    #Get all tokens
    tokens = get_all_tokens(dictionary)

    #(2.10) AVERAGE FOR ALL NAMED ENTITIES
    named_entity_list = []
    for comment in tokens:
        named_entity_list.append(get_entities(comment))

    #Create Summary DF for all Named Entities
    summary_namedentity = pd.DataFrame(named_entity_list)

    #replace NAN values
    summary_namedentity = summary_namedentity.replace(np.nan, 0)

    return summary_namedentity


A = [1,2,1,1,1,2,2,2]
B = [2,1,2,2,2,2,2,2]
C=list(zip(A,B))
flag=0
a=A[0]
ansA=[1,0]
b=B[0]
ansB=[0,1]
for i in range(1,len(A)):
    if a not in C[i]:
        flag+=1
        ansA=[99999,99999]
        break
    if C[i][0]==a and C[i][1]==a:
        continue
    if C[i][0]==a:
        ansA[0]+=1
    else:
        ansA[1]+=1
for i in range(1,len(A)):
    if b not in C[i]:
        flag+=1
        ansB = [99999, 99999]
        break
    if C[i][0]==b and C[i][1]==b:
        continue
    if C[i][0]==b:
        ansB[0]+=1
    else:
        ansB[1]+=1
if flag==2:
    print("-1")
else:
    print(min(min(ansA),min(ansB)))


# -*- mode: python; coding: utf-8 -*-
# Copyright 2014 Peter Williams <peter@newton.cx> and collaborators.
# Licensed under the MIT License.

"""pwkit.cli.astrotool - the 'astrotool' program."""

from __future__ import absolute_import, division, print_function, unicode_literals

__all__ = [b'commandline']

import math, numpy as np, os, sys

from .. import PKError
from ..astutil import *
from ..cgs import *
from . import *

class UsageError (PKError):
    pass

def fparse (text):
    try:
        # note: totally reckless about globals/locals passed, etc.
        # nice to have * from astutil and cgs available.
        v = eval (text)
    except Exception as e:
        die ('cannot evaluate "%s": %s (%s)', text, str (e), e.__class__.__name__)

    try:
        f = float (v)
    except Exception as e:
        die ('evaluted "%s", but could not floatify result %r: %s (%s)', text, v,
             str (e), e.__class__.__name__)

    return f

def fmt (v):
    f1 = '%.4g' % v
    f2 = '%.3e' % v

    if f1 == f2:
        reprs = [f1]
    else:
        reprs = [f1, f2]

    if v > 0:
        reprs.append ('10**(%.2f)' % log10 (v))

    return ' = '.join (reprs)

# The commands.

def cmd_abs2app (args):
    if len (args) != 2:
        raise UsageError ('abs2app expected exactly 2 arguments')

    absmag = fparse (args[0])
    dist = fparse (args[1])
    appmag = absmag + 5 * (log10 (dist) - 1)
    print (fmt (appmag))
cmd_abs2app.argspec = '<absmag [mag]> <dist [pc]>'
cmd_abs2app.summary = 'Convert absolute to apparent magnitude.'

def cmd_app2abs (args):
    if len (args) != 2:
        raise UsageError ('app2abs expected exactly 2 arguments')

    appmag = fparse (args[0])
    dist = fparse (args[1])
    absmag = appmag - 5 * (log10 (dist) - 1)
    print (fmt (absmag))
cmd_app2abs.argspec = '<appmag [mag]> <dist [pc]>'
cmd_app2abs.summary = 'Convert apparent to absolute magnitude.'

def cmd_c2m (args):
    """c2m  - calendar to MJD[TAI]"""

    if len (args) not in (3, 6):
        raise UsageError ('c2m expected exactly 3 or 6 arguments')

    try:
        import precastro
    except ImportError:
        die ('need the "precastro" module')

    year = int (args[0])
    month = int (args[1])

    if len (args) == 3:
        day = float (args[2])
        iday = int (math.floor (day))
        fday = day - iday
    else:
        iday = int (args[2])
        hour = int (args[3])
        minute = int (args[4])
        second = float (args[5])
        fday = (hour + minute / 60. + second / 3600.) / 24

    t = precastro.Time ().fromfdcal (year, month, iday, fday, 'TAI')
    print ('%.4f' % t.asMJD ())
cmd_c2m.argspec = '<year> <month> <frac.day> [hour] [min] [sec]'
cmd_c2m.summary = 'Convert a calendar date to MJD[TAI].'

def cmd_calc (args):
    if not len (args):
        raise UsageError ('calc expected arguments')

    print (fmt (fparse (' '.join (args))))
cmd_calc.argspec = '{expr...}'
cmd_calc.summary = 'Evaluate and print an expression.'

def cmd_csep (args):
    if len (args) != 4:
        raise UsageError ('csep expected 4 arguments')

    try:
        lat1 = parsedeglat (args[1])
        lon1 = parsehours (args[0])
        lat2 = parsedeglat (args[3])
        lon2 = parsehours (args[2])
    except Exception as e:
        die (e)

    print ('degree:', fmt (sphdist (lat1, lon1, lat2, lon2) * R2D))
    print ('arcsec:', fmt (sphdist (lat1, lon1, lat2, lon2) * R2A))
cmd_csep.argspec = '<RA 1> <dec 1> <RA 2> <dec 2>'
cmd_csep.summary = 'Print separation between two positions; args in sexagesimal.'

def cmd_d2sh (args):
    if not len (args):
        raise UsageError ('d2sh expected arguments')

    deglon = fparse (' '.join (args))
    print (fmthours (deglon * D2R))
cmd_d2sh.argspec = '{expr}'
cmd_d2sh.summary = 'Convert decimal degrees to sexagesimal hours (RA).'

def cmd_d2sl (args):
    if not len (args):
        raise UsageError ('d2sl expected arguments')

    deglat = fparse (' '.join (args))
    print (fmtdeglat (deglat * D2R))
cmd_d2sl.argspec = '{expr}'
cmd_d2sl.summary = 'Convert decimal degrees to a sexagesimal latitude (declination).'

def cmd_ephem (args):
    # This is obviously not going to be super high accuracy.

    if len (args) != 2:
        raise UsageError ('ephem expected exactly 2 arguments')

    try:
        import precastro
    except ImportError:
        die ('need the "precastro" module')

    try:
        obj = precastro.EphemObject (args[0])
    except Exception as e:
        die (e)

    mjd = fparse (args[1])
    print (fmtradec (*obj.astropos (mjd + 2400000.5)))
cmd_ephem.argspec = '<name> <mjd>'
cmd_ephem.summary = 'Compute position of ephemeris object at a given time.'

def cmd_flux2lum (args):
    if len (args) != 2:
        raise UsageError ('flux2lum expected exactly 2 arguments')

    flux = fparse (args[0])
    dist = fparse (args[1])
    lum = flux * 4 * pi * (dist * cmperpc)**2
    print (fmt (lum))
cmd_flux2lum.argspec = '<flux [cgs]> <dist [pc]>'
cmd_flux2lum.summary = 'Compute luminosity from flux and distance.'

def cmd_lum2flux (args):
    if len (args) != 2:
        raise UsageError ('lum2flux expected exactly 2 arguments')

    lum = fparse (args[0])
    dist = fparse (args[1])
    flux = lum / (4 * pi * (dist * cmperpc)**2)
    print (fmt (flux))
cmd_lum2flux.argspec = '<lum [cgs]> <dist [pc]>'
cmd_lum2flux.summary = 'Compute flux from luminosity and distance.'

def cmd_m2c (args):
    if len (args) != 1:
        raise UsageError ('m2c expected exactly 1 argument')

    try:
        import precastro
    except ImportError:
        die ('need the "precastro" module')

    mjd = float (args[0])
    t = precastro.Time ().fromMJD (mjd, 'TAI')
    print (t.fmtcalendar ())
cmd_m2c.argspec = '<MJD>'
cmd_m2c.summary = 'Convert MJD[TAI] to a calendar date.'

def cmd_sastrom (args):
    verbose = pop_option ('v', args)

    if len (args) != 2:
        raise UsageError ('simbadastrom expected 2 arguments')

    ident = args[0]
    mjd = float (args[1])

    info = AstrometryInfo ()
    info.fill_from_simbad (ident, debug=verbose)
    p = info.predict (mjd)
    print ('%s at %.3f:' % (ident, mjd))
    print ()
    info.print_prediction (p)
cmd_sastrom.argspec = '[-v] <source name> <MJD>'
cmd_sastrom.summary = 'Compute source location using Simbad data.'

def cmd_sesame (args):
    if not len (args):
        raise UsageError ('sesame expected an argument')

    try:
        import precastro
    except ImportError:
        die ('need the "precastro" module')

    src = ' '.join (args)
    obj = precastro.SiderealObject ()

    try:
        obj.fromsesame (src)
    except Exception as e:
        die ('couldn\'t look up "%s": %s (%s)', src, e, e.__class__.__name__)

    print (obj.describe ())
cmd_sesame.argspec = '{source name}'
cmd_sesame.summary = 'Print source information from Sesame.'

def cmd_senscale (args):
    if len (args) != 3:
        raise UsageError ('senscale expected 3 arguments')

    s1 = fparse (args[0])
    t1 = fparse (args[1])
    t2 = fparse (args[2])
    s2 = s1 * np.sqrt (t1 / t2)
    print (fmt (s2))
cmd_senscale.argspec = '<sens 1> <time 1> <time 2>'
cmd_senscale.summary = 'Scale a sensitivity to a different integration time.'

def cmd_sh2d (args):
    if len (args) != 1:
        raise UsageError ('sh2d expected 1 argument')

    try:
        rarad = parsehours (args[0])
    except Exception as e:
        die ('couldn\'t parse "%s" as sexagesimal hours: %s (%s)',
             args[0], e, e.__class__.__name__)

    print ('%.8f' % (rarad * R2D))
cmd_sh2d.argspec = '<sexagesimal hours>'
cmd_sh2d.summary = 'Convert sexagesimal hours to decimal degrees.'
cmd_sh2d.moredocs = """The argument should look like "12:20:14.6"."""

def cmd_sl2d (args):
    if len (args) != 1:
        raise UsageError ('sl2d expected 1 argument')

    try:
        decrad = parsedeglat (args[0])
    except Exception as e:
        die ('couldn\'t parse "%s" as sexagesimal latitude in degrees: %s (%s)',
             args[0], e, e.__class__.__name__)

    print ('%.8f' % (decrad * R2D))
cmd_sl2d.argspec = '<sexagesimal latitude in degrees>'
cmd_sl2d.summary = 'Convert sexagesimal latitude (ie, declination) to decimal degrees.'
cmd_sl2d.moredocs = """The argument should look like "47:20:14.6". The leading sign is optional."""

def cmd_ssep (args):
    if len (args) != 2:
        raise UsageError ('ssep expected 2 arguments')

    try:
        import precastro
    except ImportError:
        die ('need the "precastro" module')

    try:
        obj1 = precastro.SiderealObject ().fromsesame (args[0])
    except Exception as e:
        die ('couldn\'t look up "%s": %s (%s)', args[0], e, e.__class__.__name__)

    try:
        obj2 = precastro.SiderealObject ().fromsesame (args[1])
    except Exception as e:
        die ('couldn\'t look up "%s": %s (%s)', args[1], e, e.__class__.__name__)

    print ('degree:', fmt (sphdist (obj1.dec, obj1.ra, obj2.dec, obj2.ra) * R2D))
    print ('arcsec:', fmt (sphdist (obj1.dec, obj1.ra, obj2.dec, obj2.ra) * R2A))
cmd_ssep.argspec = '<source name> <source name>'
cmd_ssep.summary = 'Print separation between two sources identified by name.'

# The driver.

def _fullusage ():
    usagestr = """astrotool <command> [arguments...]

This is a tool that does quick astronomical calculations that I find myself
performing frequently.

Subcommands are:

"""

    g = globals ()
    cnames = sorted (n for n in g.iterkeys () if n.startswith ('cmd_'))

    for cname in cnames:
        usagestr += '  astrotool %-8s - %s\n' % (cname[4:], g[cname].summary)

    usagestr += """
Most commands will give help if run with no arguments."""

    return usagestr

usagestr = _fullusage ()

def commandline (argv=None):
    if argv is None:
        argv = sys.argv
        unicode_stdio ()

    check_usage (usagestr, argv, usageifnoargs='long')

    if len (argv) < 2:
        wrong_usage (usagestr, 'need to specify a command')

    cmdname = argv[1]
    func = globals ().get ('cmd_' + cmdname)

    if func is None:
        wrong_usage (usagestr, 'no such command "%s"', cmdname)

    args = argv[2:]
    if not len (args) and not hasattr (func, 'no_args_is_ok'):
        print ('usage: astrotool', cmdname, func.argspec)
        print ()
        print (func.summary)
        if hasattr (func, 'moredocs'):
            print ()
            print (func.moredocs)
        return

    try:
        func (args)
    except UsageError as e:
        print ('error:', e, '\n\nusage: astrotool', cmdname, func.argspec,
               file=sys.stderr)


import dmx
import sys
import ImageFile

fp = open(sys.argv[1], "rb");
p = ImageFile.Parser();

while 1:
	s = fp.read(1024);
	if not s:
		break
	p.feed(s);

im = p.close();

panel = dmx.getDefaultPanel()

h = len(panel.lights)
w = len(panel.lights[0])

im.thumbnail([w,h])

sz = im.size;

offx = (h- sz[0])/2
offy = (w - sz[1])/2
for row in panel.lights:
	for pixel in row:
		cp =  (pixel.col -offx)
		rp = sz[1] - (pixel.row -offy)
		if cp >= 0 and cp < sz[0] and rp >= 0 and rp < sz[1] :
			npix = im.getpixel((cp,rp))
			panel.lights[pixel.row][pixel.col].setrgb(npix[0]/255.,npix[1]/255.,npix[2]/255.)

panel.outputAndWait(30)