from pygments.lexer import ExtendedRegexLexer, bygroups, words, include
from pygments.token import *

class CleanLexer(ExtendedRegexLexer):
    name = 'CleanLexer'
    aliases = ['Clean', 'clean']
    filenames = ['*.icl', '*.dcl']

    def __init__(self, *args, **kwargs):
        super(CleanLexer, self).__init__(*args, **kwargs)
        global stored_indent
        stored_indent = 0

    def check_class_not_import(lexer, match, ctx):
        if match.group(0) == 'import':
            yield match.start(), Keyword.Namespace, match.group(0)
            ctx.stack = ctx.stack[:-1] + ['fromimportfunc']
        else:
            yield match.start(), Name.Class, match.group(0)
        ctx.pos = match.end()

    def check_instance_class(lexer, match, ctx):
        if match.group(0) == 'instance' or match.group(0) == 'class':
            yield match.start(), Keyword, match.group(0)
        else:
            yield match.start(), Name.Function, match.group(0)
            ctx.stack = ctx.stack + ['fromimportfunctype']
        ctx.pos = match.end()

    def store_indent(lexer, match, ctx):
        global stored_indent
        # Tabs are four spaces:
        # https://svn.cs.ru.nl/repos/clean-platform/trunk/doc/STANDARDS.txt
        stored_indent = len(match.group(0).replace('\t','    '))
        ctx.pos = match.end()
        yield match.start(), Text, match.group(0)

    def check_indent1(lexer, match, ctx):
        global stored_indent
        indent = len(match.group(0)) - 1
        if indent > stored_indent:
            yield match.start(), Whitespace, match.group(0)
            ctx.pos = match.start() + indent + 1
        else:
            stored_indent = 0
            ctx.pos = match.start()
            ctx.stack = ctx.stack[:-1]
            yield match.start(), Whitespace, match.group(0)[1:]

    def check_indent2(lexer, match, ctx):
        global stored_indent
        indent = len(match.group(0)) - 1
        if indent > stored_indent:
            yield match.start(), Whitespace, match.group(0)
            ctx.pos = match.start() + indent + 1
        else:
            stored_indent = 0
            ctx.pos = match.start()
            ctx.stack = ctx.stack[:-2]
            yield match.start(), Whitespace, match.group(0)[1:]
            if match.group(0) == '\n\n':
                ctx.pos = ctx.pos + 1

    def check_indent3(lexer, match, ctx):
        global stored_indent
        indent = len(match.group(0)) - 1
        if indent > stored_indent:
            yield match.start(), Whitespace, match.group(0)
            ctx.pos = match.start() + indent + 1
        else:
            stored_indent = 0
            ctx.pos = match.start()
            ctx.stack = ctx.stack[:-3]
            yield match.start(), Whitespace, match.group(0)[1:]
            if match.group(0) == '\n\n':
                ctx.pos = ctx.pos + 1

    def skip(lexer, match, ctx):
        ctx.stack = ctx.stack[:-1]
        ctx.pos = match.end()
        yield match.start(), Comment, match.group(0)

    tokens = {
        'common': [
            (r';', Punctuation, '#pop'),
            (r'//', Comment, 'singlecomment')
        ],
        'root': [
            # Comments
            (r'//.*\n', Comment.Single),
            (r'(?s)/\*\*.*?\*/', Comment.Special),
            (r'(?s)/\*.*?\*/', Comment.Multi),

            # Modules, imports, etc.
            (r'\b((?:implementation|definition|system)\s+)?(module)(\s+)([\w`]+)',
                bygroups(Keyword.Namespace, Keyword.Namespace, Text, Name.Class)),
            (r'(?<=\n)import(?=\s)', Keyword.Namespace, 'import'),
            (r'(?<=\n)from(?=\s)', Keyword.Namespace, 'fromimport'),

            # Keywords
            # We cannot use (?s)^|(?<=\s) as prefix, so need to repeat this
            (words(('class','instance','where','with','let','let!','with','in',
                'case','of','infix','infixr','infixl','generic','derive',
                'otherwise', 'code', 'inline'),
                prefix=r'(?<=\s)', suffix=r'(?=\s)'), Keyword),
            (words(('class','instance','where','with','let','let!','with','in',
                'case','of','infix','infixr','infixl','generic','derive',
                'otherwise', 'code', 'inline'),
                prefix=r'(?s)^', suffix=r'(?=\s)'), Keyword),

            # Function definitions
            (r'(?=\{\|)', Whitespace, 'genericfunction'),
            (r'(?<=\n)(\s*)([\w`\$\(\)=\-<>~*\^\|\+&%]+)(\s+[\w])*(\s*)(::)',
                bygroups(store_indent, Name.Function, Keyword.Type, Whitespace, Punctuation),
                'functiondefargs'),

            # Type definitions
            (r'(?<=\n)([ \t]*)(::)', bygroups(store_indent, Punctuation), 'typedef'),

            # Literals
            (r'\'\\?.(?<!\\)\'', String.Char),
            (r'\'\\\d+\'', String.Char),
            (r'\'\\\\\'', String.Char), # (special case for '\\')
            (r'[\+\-~]?\s*?\d+\.\d+(E[+-~]?\d+)?\b', Number.Float),
            (r'[\+\-~]?\s*?0[0-7]\b', Number.Oct),
            (r'[\+\-~]?\s*?0x[0-9a-fA-F]\b', Number.Hex),
            (r'[\+\-~]?\s*?\d+\b', Number.Integer),
            (r'"', String.Double, 'doubleqstring'),
            (words(('True', 'False'), prefix=r'(?<=\s)', suffix=r'(?=\s)'), Literal),

            # Everything else is some name
            (r'([\w`\$%]+\.?)*[\w`\$%]+', Name),

            # Punctuation
            (r'[{}()\[\],:;\.#]', Punctuation),
            (r'[\+\-=!<>\|&~*\^/]', Operator),
            (r'\\\\', Operator),

            # Lambda expressions
            (r'\\.*?(->|\.|=)', Name.Function),

            # Whitespace
            (r'\s', Whitespace),

            include('common')
        ],
        'fromimport': [
            include('common'),
            (r'([\w`]+)', check_class_not_import),
            (r'\n', Whitespace, '#pop'),
            (r'\s', Whitespace)
        ],
        'fromimportfunc': [
            include('common'),
            (r'([\w`\$\(\)=\-<>~*\^\|\+&%]+)', check_instance_class),
            (r',', Punctuation),
            (r'\n', Whitespace, '#pop'),
            (r'\s', Whitespace)
        ],
        'fromimportfunctype': [
            include('common'),
            (r'[{(\[]', Punctuation, 'combtype'),
            (r',', Punctuation, '#pop'),
            (r':;\.#]', Punctuation),
            (r'\n', Whitespace, '#pop:2'),
            (r'\s', Whitespace),
            (r'.', Keyword.Type)
        ],
        'combtype': [
            include('common'),
            (r'[})\]]', Punctuation, '#pop'),
            (r'[{(\[]', Punctuation, '#pop'),
            (r',:;\.#]', Punctuation),
            (r'\s', Whitespace),
            (r'.', Keyword.Type)
        ],
        'import': [
            include('common'),
            (words(('from', 'import', 'as', 'qualified'),
                prefix='(?<=\s)', suffix='(?=\s)'), Keyword.Namespace),
            (r'[\w`]+', Name.Class),
            (r'\n', Whitespace, '#pop'),
            (r',', Punctuation),
            (r'\s', Whitespace)
        ],
        'singlecomment': [
            (r'(.)(?=\n)', skip),
            (r'.', Comment)
        ],
        'doubleqstring': [
            (r'[^\\\'"]+', String.Double),
            (r'"', String.Double, '#pop'),
            (r'\\.|\'', String.Double)
        ],
        'typedef': [
            include('common'),
            (r'[\w`]+', Keyword.Type),
            (r'[:=\|\(\),\[\]\{\}\!\*]', Punctuation),
            (r'->', Punctuation),
            (r'\n(?=[^\s\|])', Whitespace, '#pop'),
            (r'\s', Whitespace),
            (r'.', Keyword.Type)
        ],
        'genericfunction': [
            include('common'),
            (r'\{\|', Punctuation),
            (r'\|\}', Punctuation, '#pop'),
            (r',', Punctuation),
            (r'->', Punctuation),
            (r'(\s+of\s+)(\{)', bygroups(Keyword, Punctuation), 'genericftypes'),
            (r'\s', Whitespace),
            (r'[\w`]+', Keyword.Type),
            (r'[\*\(\)]', Punctuation)
        ],
        'genericftypes': [
            include('common'),
            (r'[\w`]+', Keyword.Type),
            (r',', Punctuation),
            (r'\s', Whitespace),
            (r'\}', Punctuation, '#pop')
        ],
        'functiondefargs': [
            include('common'),
            (r'\n(\s*)', check_indent1),
            (r'[!{}()\[\],:;\.#]', Punctuation),
            (r'->', Punctuation, 'functiondefres'),
            (r'^(?=\S)', Whitespace, '#pop'),
            (r'\S', Keyword.Type),
            (r'\s', Whitespace)
        ],
        'functiondefres': [
            include('common'),
            (r'\n(\s*)', check_indent2),
            (r'^(?=\S)', Whitespace, '#pop:2'),
            (r'[!{}()\[\],:;\.#]', Punctuation),
            (r'\|', Punctuation, 'functiondefclasses'),
            (r'\S', Keyword.Type),
            (r'\s', Whitespace)
        ],
        'functiondefclasses': [
            include('common'),
            (r'\n(\s*)', check_indent3),
            (r'^(?=\S)', Whitespace, '#pop:3'),
            (r'[,&]', Punctuation),
            (r'[\w`\$\(\)=\-<>~*\^\|\+&%]', Name.Function, 'functionname'),
            (r'\s', Whitespace)
        ],
        'functionname': [
            include('common'),
            (r'[\w`\$\(\)=\-<>~*\^\|\+&%]+', Name.Function),
            (r'(?=\{\|)', Punctuation, 'genericfunction'),
            (r'', Text, '#pop')
        ]
    }


# -*- encoding: utf-8 -*-
# ##########################################################################
#    Module Writen to OpenERP, Open Source Management Solution
#
#    Authors: Openpyme (<http://openpyme.mx>)
#
#
#    Coded by: Salvador Martínez (chavamm.83@gmail.com)
#              Miguel Angel Villafuerte Ojeda (mikeshot@gmail.com)
#              Luis Felipe Lores Caignet (luisfqba@gmail.com)
#              Agustín Cruz Lozano (agustin.cruz@openpyme.mx)
#
#    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/>.
#
##############################################################################
import logging
import xml.etree.ElementTree as ET
from openerp.osv import orm
from openerp.report import report_sxw
from .report_to_file import ReportToFile
from openerp.tools.translate import _
from collections import defaultdict

logger = logging.getLogger(__name__)

class journal_entries_parser(report_sxw.rml_parse):
    """
    Parser class to build the journal entries report in format xml.
    """
    def __init__(self, cr, uid, name, context=None):
        super(journal_entries_parser, self).__init__(
            cr, uid, name, context=context
        )
        self.localcontext.update({
            "cr": cr,
            "uid": uid,
            "actual_context": context,
        })

class JournalEntriesXml(ReportToFile):
    """
    Class to build the journal entries report in format xml based on company,
    period and target_move.
    """
    def __init__(
        self, name, table, rml=False, parser=False, header=True, store=False
    ):
        """
        Set default data for report
        """
        super(JournalEntriesXml, self).__init__(
            name, table, rml, parser, header, store
        )

    def _get_lst_account(self, cr, uid, account_id, context):
        account_obj = self.pool['account.account']
        actual_account = account_obj.browse(
            cr, uid, account_id, context=context
        )
        lst_account = []
        self._fill_list_account_with_child(lst_account, actual_account)
        return tuple(lst_account)

    def _fill_list_account_with_child(self, lst_account, account):
        # no more child
        lst_account.append(account.id)
        if not account.child_id:
            return
        for child in account.child_id:
            self._fill_list_account_with_child(lst_account, child)

    def get_trans_cta(self, cr, uid, account_id, context=None):
        """
        Get the account number of  transaction based on the account id
        account number of  transaction is the account code.
        """
        context = context or {}
        account_obj = self.pool.get('account.account').browse(
            cr, uid, account_id
        )
        if account_obj.sat_group_id:
            result = account_obj
        else:
            if not account_obj.parent_id:
                raise orm.except_orm(
                    _('Error'),
                    _('Not found Sat Code on account %s-%s. \n'
                      'Verify that the configuration of Account Sat_Group is'
                      ' correct!' % (account_obj.code, account_obj.name))
                )
            result = self.get_trans_cta(
                cr, uid, account_obj.parent_id.id, context=context
            )
        return result

    def get_journal_entry_type(self, cr, uid, ids, context, journal_id):
        """
        Get the type of account journal entry based on the account journal id
        """
        journal_obj = self.pool.get('account.journal')
        journal_entry_type = journal_obj.browse(
            cr, uid, journal_id, context=context
        ).type
        return journal_entry_type

    def check_journal_default_credit_debit_account_id(
        self, cr, uid, ids, context, journal_id, account_id
    ):
        """
        Checks if account_id is the default credit or debit account_id of
        account journal based on the account journal_id and account_id of
        account journal entry
        """
        journal_model = self.pool.get('account.journal')
        journal = journal_model.browse(
            cr, uid, [journal_id], context=context
        )[0]

        if (
            account_id == journal.default_debit_account_id.id or
            account_id == journal.default_credit_account_id.id
        ):
            return True
        return False

    def get_journal_entrie_type_xml(self, parser, entrie):
        """
        Get the SAT type of account journal entry based on journal_type and
        # the default account for journal_id
        """
        journal_entry_type_xml = 3
        for item_line in entrie:

            if self.check_journal_default_credit_debit_account_id(
                    parser.cr, parser.uid, parser.active_ids,
                    parser.actual_context, item_line.get('journal_id'),
                    item_line.get('account_id')
            ):
                journal_entry_type = self.get_journal_entry_type(
                    parser.cr, parser.uid, parser.active_ids,
                    parser.actual_context,
                    item_line.get('journal_id')
                )

                if (journal_entry_type in ['cash', 'bank']) and item_line.get(
                    'credit'
                ):
                    return 2
                elif (
                    journal_entry_type in ['cash', 'bank']) and item_line.get(
                    'debit'
                ):
                    return 1

        return journal_entry_type_xml

    def get_journal_entry_concept(self, cr, uid, ids, context, move_id):
        """
        Get the concept of account journal entry based on the account move id
        concept of account journal entry is the account.move ref.
        """
        move_obj = self.pool.get('account.move')
        concept = move_obj.browse(cr, uid, move_id).ref or "N/A"
        return concept

    def get_trans_currency(self, cr, uid, ids, context, currency_id):
        """
        Get the currency name of transaction based on the currency id
        """
        currency_obj = self.pool.get('res.currency')
        currency_name = currency_obj.browse(cr, uid, currency_id).name
        return currency_name

    def get_check_data(
        self, cr, uid, ids, context, move_id, journal_id, account_id,
        transaccion
    ):
        """
        Get the info of the check based on the move_id of journal entry
        """
        check_obj = self.pool.get('account.voucher')
        # Gets the default credit account ID for the journal
        journal = self.pool.get('account.journal').browse(
            cr, uid, journal_id
        )

        # If Payment Type Not is Check, then exit
        if journal.payment_type_id.code not in ['02']:
            return

        credit_acc_id = journal.default_credit_account_id.id

        # If the used account is not the default credit account
        # don't continue
        if account_id != credit_acc_id:
            return

        # Get the bank data asociated to the journal used
        # in the journal entry
        partner_bank_data = self.get_partner_bank_data(
            cr, uid, ids, context, journal_id
        )
        # Verify that exists bank account asociated to the journal
        if partner_bank_data:
            # Gets the info of the check data
            check_id = check_obj.search(cr, uid, [('move_id', '=', move_id)])
            check_data = check_obj.browse(cr, uid, check_id)

            # Process each check if any
            for check in check_data:
                check_number = check.check_number
                # Not all vouchers are checks, skip function if not check_done
                if not check.check_done:
                    continue

                check_date = check.date
                check_amount = check.amount
                partner_name = check.partner_id.name
                partner_vat = check.partner_id.vat_split

                # Adds the check info to the xml report
                bank_acc = partner_bank_data[0].acc_number
                bank_sat_code = partner_bank_data[0].bank.sat_code

                cheque = ET.SubElement(transaccion, 'PLZ:Cheque')
                cheque.set("Num", str(check_number))
                cheque.set("BanEmisNal", (bank_sat_code).encode(
                    'utf-8', 'ignore').decode('utf-8')
                )
                cheque.set("CtaOri", (bank_acc).encode(
                    'utf-8', 'ignore').decode('utf-8')
                )
                cheque.set("Fecha", str(check_date))
                cheque.set("Monto", str(check_amount))
                cheque.set("Benef", (partner_name).encode(
                    'utf-8', 'ignore').decode('utf-8')
                )
                cheque.set("RFC", (partner_vat).encode(
                    'utf-8', 'ignore').decode('utf-8')
                )
        return True

    def get_partner_bank_data(self, cr, uid, ids, context, journal_id):
        """
        Get the info of the bank account based on the journal_id of
        journal entry
        """
        bank_obj = self.pool.get('res.partner.bank')
        bank_id = bank_obj.search(cr, uid, [('journal_id', '=', journal_id)])
        bank_data = bank_obj.browse(cr, uid, bank_id, context=context)
        return bank_data

    def get_invoice_data(
        self, cr, uid, ids, context, acc_move_line, journal_entry_type_xml,
        transaccion
    ):
        """
        Get the info of the Invoice based on the move_id of journal entry
        """
        invoice_obj = self.pool.get('account.invoice')

        filters = []
        if (
            journal_entry_type_xml in [1, 2] and
            (acc_move_line.get('reconcile_id') or
             acc_move_line.get('reconcile_partial_id'))
        ):
            # if journal entry in Ingreso|Egreso
            reconcile_field = acc_move_line.get(
                'reconcile_id') and 'reconcile_id' or 'reconcile_partial_id'
            reconcile_value = acc_move_line.get(
                'reconcile_id') or acc_move_line.get('reconcile_partial_id')

            filters = [(reconcile_field, '=', reconcile_value),
                       ('journal_id', '!=', acc_move_line.get('journal_id'))]

            move_obj = self.pool.get('account.move.line')
            move_id = move_obj.search(cr, uid, filters)
            if move_id:
                move_data = move_obj.browse(cr, uid, move_id)

                for move in move_data:
                    filters = [
                        ('move_id', '=', move.move_id.id),
                        ('account_id', '=', acc_move_line.get('account_id'))
                    ]
            else:
                return False

        elif journal_entry_type_xml in [3]:
            filters = [('move_id', '=', acc_move_line.get('move_id')),
                       ('account_id', '=', acc_move_line.get('account_id'))]
        else:
            return False

        invoice_id = invoice_obj.search(cr, uid, filters)
        invoice_data = invoice_obj.browse(cr, uid, invoice_id)

        # Process each invoice if any
        for invoice in invoice_data:
            # Only add information about Comprobante
            # if there is an UUID at current invoice
            if invoice.cfdi_folio_fiscal:
                if not invoice.partner_id.vat_split:
                    raise orm.except_orm(
                        _('Error'),
                        _('Partner %s do not have a VAT number assigned')
                        % invoice.partner_id.name
                    )
                comprobante = ET.SubElement(transaccion, 'PLZ:CompNal')
                comprobante.set('MontoTotal', str(invoice.amount_total))
                comprobante.set('RFC', invoice.partner_id.vat_split)
                comprobante.set('UUID_CFDI', invoice.cfdi_folio_fiscal)
                if invoice.currency_id.name != 'MXN':
                    comprobante.set('Moneda', invoice.currency_id.name)
                    comprobante.set('TipCamb', str(invoice.rate))
        return True

    def get_transferencia_data(
        self, cr, uid, acc_move_line, journal_entry_type_xml,
        transaccion, context=None
    ):
        """
        Get the info of the Transferencia based on the move_id of journal entry
        """
        context = context or {}
        payment_obj = self.pool.get('account.voucher')
        # Gets the default credit account ID for the journal
        journal = self.pool.get('account.journal').browse(
            cr, uid, acc_move_line.get('journal_id'), context=context
        )

        # If Payment Type Not is Transfer, then exit
        if journal.payment_type_id.code not in ['03']:
            return

        credit_acc_id = journal.default_credit_account_id.id

        # If the used account is not the default credit account
        # don't continue
        if acc_move_line.get('account_id') != credit_acc_id:
            return

        payment_line_ids = payment_obj.search(
            cr, uid,
            [('move_id', '=', acc_move_line.get('move_id'))],
            context=context
        )
        payment_line_data = payment_obj.browse(
            cr, uid, payment_line_ids, context=context
        )

        # Process each payment line if any
        for payment_line in payment_line_data:
            transferencia = ET.SubElement(transaccion, 'PLZ:Transferencia')
            partnerBank = payment_line.partner_bank_id
            companyBank = payment_line.journal_id.res_partner_bank_id[0]
            partner = payment_line.partner_id

            # If dealing with income money
            rfc = partner.vat_split or 'N/A'
            if journal_entry_type_xml == 1:
                cta_orig = partnerBank.acc_number
                banco_orig = partnerBank.bank.sat_code
                cta_dest = companyBank.acc_number
                banco_dest = companyBank.bank.sat_code
                benef = companyBank.partner_id.name
            # If dealing with out money
            elif journal_entry_type_xml == 2:
                cta_orig = companyBank.acc_number
                banco_orig = companyBank.bank.sat_code
                cta_dest = partnerBank.acc_number
                banco_dest = partnerBank.bank.sat_code
                benef = partnerBank.partner_id.name

            transferencia.set('CtaOri', cta_orig)
            transferencia.set('BancoOriNal', banco_orig)
            transferencia.set('Monto', str(payment_line.amount))
            transferencia.set('CtaDest', cta_dest)
            transferencia.set('BancoDestNal', banco_dest)
            transferencia.set('Benef', benef)
            transferencia.set('RFC', rfc)
            transferencia.set('Fecha', payment_line.date)
        return

    def get_otr_metodo_pago(
        self, cr, uid, acc_move_line, journal_entry_type_xml,
        transaccion, context=None
    ):
        """
        Get the info of the otrMetodoPago based on the move_id of journal entry
        """
        context = context or {}
        payment_obj = self.pool.get('account.voucher')
        # Gets the default credit account ID for the journal
        journal = self.pool.get('account.journal').browse(
            cr, uid, acc_move_line.get('journal_id'), context=context
        )

        credit_acc_id = journal.default_credit_account_id.id

        # If the used account is not the default credit account
        # don't continue
        if acc_move_line.get('account_id') != credit_acc_id:
            return

        if not journal.payment_type_id:
            raise orm.except_orm(
                    _('Error'),
                    _('Journal %s do not have set a Payment Type')
                    % journal.name
                )

        # If Payment Type is Check or Transfer, then exit
        if journal.payment_type_id.code in ['02', '03']:
            return

        payment_line_ids = payment_obj.search(
            cr, uid,
            [('move_id', '=', acc_move_line.get('move_id'))],
            context=context
        )
        payment_line_data = payment_obj.browse(
            cr, uid, payment_line_ids, context=context
        )

        # Process each payment line if any
        for payment_line in payment_line_data:
            otrmetodopago = ET.SubElement(transaccion, 'PLZ:OtrMetodoPago')

            # MetPagoPol
            # Fecha
            # Benef
            # RFC
            # Monto
            # Moneda
            # TipCamb

            partnerBank = payment_line.partner_bank_id
            partner = payment_line.partner_id

            # If dealing with income money
            rfc = partner.vat_split or 'N/A'
            benef = partner.name

            otrmetodopago.set('MetPagoPol', str(journal.payment_type_id.code))
            otrmetodopago.set('Fecha', payment_line.date)
            otrmetodopago.set('Benef', benef)
            otrmetodopago.set('RFC', rfc)
            otrmetodopago.set('Monto', str(payment_line.amount))

            if payment_line.is_multi_currency:
                otrmetodopago.set('Moneda', str(payment_line.currency_id.name))
                otrmetodopago.set('TipCamb', str(payment_line.payment_rate))

        return

    def generate_report(self, parser, data, objects):
        """
        Build journal entries report in format xml based on company,
        period and target_move.
        """
        context = parser.actual_context
        import tempfile

        account_move_model = self.pool.get('account.move')

        Etree = ET.ElementTree()
        # #Begin of Sql query Section
        period_id = data["form"]["period_id"]
        target_move = data["form"]["target_move"]
        period_obj = self.pool['account.period']
        period = period_obj.browse(
            parser.cr, parser.uid, period_id,
            context=parser.actual_context
        )

        sql_select = """
        SELECT al.debit,al.credit,al.amount_currency,al.date,al.journal_id,
        al.ref,al.move_id,al.name,al.currency_id,al.account_id,
        al.reconcile_id, al.reconcile_partial_id
        FROM account_move_line al """
        sql_where = """
        WHERE al.period_id =  %(period_id)s
        AND al.state = 'valid'
        AND al.account_id in %(account_id)s """
        search_params = {
            'period_id': period_id,
            'account_id': self._get_lst_account(
                parser.cr, parser.uid, data['form']['account_id'],
                context=context
            )
        }
        sql_joins = ''
        sql_orderby = 'ORDER BY al.move_id'
        if target_move == 'posted':
            sql_joins = 'LEFT JOIN account_move am ON move_id = am.id '
            sql_where += """ AND am.state = %(target_move)s"""
            search_params.update({'target_move': target_move})
        query_sql = ' '.join((sql_select, sql_joins, sql_where, sql_orderby))
        parser.cr.execute(query_sql, search_params)
        lines = parser.cr.dictfetchall()
        # #End of Sql query Section
        if not lines:
            raise orm.except_orm(
                _('Error'),
                _('Not found Journal Entries for this Period.\n'
                  'Choose another Period!')
            )
        # if Journal Entries have lines will create the xml report
        # Create main journal entries node
        type_request = data["form"]["type_request"]
        order_num = data["form"]["order_num"]
        pro_num = data["form"]["pro_num"]
        from datetime import datetime
        time_period = datetime.strptime(period.date_start, "%Y-%m-%d")

        polizas = ET.Element('PLZ:Polizas')
        # namespace
        polizas.set("xsi:schemaLocation",
                    "www.sat.gob.mx/esquemas/ContabilidadE/1_1/PolizasPeriodo http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/PolizasPeriodo/PolizasPeriodo_1_1.xsd")
        polizas.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
        polizas.set("xmlns:PLZ", "www.sat.gob.mx/esquemas/ContabilidadE/1_1/PolizasPeriodo")

        polizas.set('Version', '1.1')
        polizas.set('RFC', parser.company.partner_id.vat_split)
        polizas.set('Mes', str(time_period.month).rjust(2, '0'))
        polizas.set('Anio', str(time_period.year))
        polizas.set('TipoSolicitud', type_request)
        if order_num:
            polizas.set('NumOrden', order_num)
        if pro_num:
            polizas.set('NumTramite', pro_num)
        Etree._setroot(polizas)

        # Groups of account move based on move id,
        # each group is one journal entries
        groups = defaultdict(list)
        for line in lines:
            groups[line.get('move_id')].append(line)
        for move_id in groups.keys():
            # Load account.move object for current move lines
            move = account_move_model.browse(
                parser.cr, parser.uid, move_id, context=context
            )
            cumul_debit = 0.0
            cumul_credit = 0.0
            poliza = ET.SubElement(polizas, 'PLZ:Poliza')

            # Check for SAT journal type using
            journal_entry_type_xml = self.get_journal_entrie_type_xml(
                parser, groups[move_id]
            )

            for item_line in groups[move_id]:
                # required fields on journal entry node
                cumul_debit += item_line.get('debit') or 0.0
                cumul_credit += item_line.get('credit') or 0.0
                journal_id = item_line.get('journal_id')
                # #Begin on transaction node
                trans_concept = item_line.get('name')
                acccta = self.get_trans_cta(
                    parser.cr, parser.uid,
                    item_line.get('account_id'), context=context
                )
                transaccion = ET.SubElement(poliza, 'PLZ:Transaccion')
                transaccion.set("NumCta", acccta.code)
                transaccion.set("DesCta", acccta.name)
                transaccion.set("Concepto", (trans_concept).encode(
                    'utf-8', 'ignore').decode('utf-8')
                )
                transaccion.set("Debe", str(item_line.get('debit')))
                transaccion.set("Haber", str(item_line.get('credit')))

                # Begin on journal entry node
                if journal_entry_type_xml in [2]:
                    # Get the check data related to the journal entry move
                    self.get_check_data(
                        parser.cr, parser.uid, parser.active_ids,
                        context, move_id, journal_id,
                        acccta.id, transaccion
                    )
                    # #End of Check section
                # # Begin for Invoice CFDI Section
                self.get_invoice_data(
                    parser.cr, parser.uid, parser.active_ids,
                    context, item_line, journal_entry_type_xml,
                    transaccion
                )
                # # End for Invoice CFDI Section

                # Get the Transferencia or otrMetodoPago data related for the Journal Entry move
                if journal_entry_type_xml in [1, 2]:
                    self.get_transferencia_data(
                        parser.cr, parser.uid,
                        item_line, journal_entry_type_xml,
                        transaccion, context=context,
                    )

                    self.get_otr_metodo_pago(
                        parser.cr, parser.uid,
                        item_line, journal_entry_type_xml,
                        transaccion, context=context,
                    )
                # # End of Transferencia Section
                # #End on transaction node
            journal_entry_concept = self.get_journal_entry_concept(
                parser.cr, parser.uid, parser.active_ids,
                context, move_id
            )

            concept_description = ("%s | $%s | $%s") % (
                (journal_entry_concept).encode(
                    'utf-8', 'ignore').decode(
                    'utf-8'), cumul_debit, cumul_credit
            )
            poliza.set("NumUnIdenPol", move.name)
            poliza.set("Concepto", concept_description)
            poliza.set("Fecha", move.date)
            # #End on journal entry node
        # Write data into temporal file
        with tempfile.NamedTemporaryFile(delete=False) as report:
            Etree.write(report.name, encoding='UTF-8')
            self.fname = report.name

        return

JournalEntriesXml(
    'report.journal.entries.xml',
    'account.account',
    parser=journal_entries_parser
)


# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.

from ctypes import c_double, c_int
from mpi4py import MPI
import numpy as np
import pickle
import sys
from lammps import lammps

__author__ = "Sarath Menon, Jan Janssen"
__copyright__ = (
    "Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH - "
    "Computational Materials Design (CM) Department"
)
__version__ = "1.0"
__maintainer__ = "Jan Janssen"
__email__ = "janssen@mpie.de"
__status__ = "production"
__date__ = "Feb 28, 2020"

# dict for extract atom methods
atom_properties = {
    "x": {"type": 3, "gtype": 1, "dim": 3},
    "mass": {"type": 2, "gtype": 1, "dim": 1},
    "id": {"type": 0, "gtype": 0, "dim": 1},
    "type": {"type": 0, "gtype": 0, "dim": 1},
    "mask": {"type": 0, "gtype": 0, "dim": 1},
    "v": {"type": 3, "gtype": 1, "dim": 3},
    "f": {"type": 3, "gtype": 1, "dim": 3},
    "molecule": {"type": 0, "gtype": 0, "dim": 1},
    "q": {"type": 2, "gtype": 1, "dim": 1},
    "mu": {"type": 3, "gtype": 1, "dim": 3},
    "omega": {"type": 3, "gtype": 1, "dim": 3},
    "angmom": {"type": 3, "gtype": 1, "dim": 3},
    "torque": {"type": 3, "gtype": 1, "dim": 3},
    "radius": {"type": 2, "gtype": 1, "dim": 1},
    "image": {"type": 2, "gtype": 0, "dim": 3},
    # we can add more quantities as needed
    # taken directly from atom.cpp -> extract()
}

# Lammps executable
args = ["-screen", "none"]
if len(sys.argv) > 1:
    args.extend(sys.argv[1:])
job = lammps(cmdargs=args)

def extract_compute(funct_args):
    # if MPI.COMM_WORLD.rank == 0:
    id = funct_args[0]
    style = funct_args[1]
    type = funct_args[2]
    length = funct_args[3]
    width = funct_args[4]
    filtered_args = [id, style, type]

    val = job.extract_compute(*filtered_args)

    # now process
    # length should be set
    data = []
    if style == 1:
        length = job.get_natoms()
    if type == 2:
        for i in range(length):
            dummy = []
            for j in range(width):
                dummy.append(val[i][j])
            data.append(np.array(dummy))
        data = np.array(data)
    elif type == 1:
        for i in range(length):
            data.append(val[i])
        data = np.array(data)
    else:
        data = val
    return data

def get_version(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.version()

def get_file(funct_args):
    job.file(*funct_args)
    return 1

def commands_list(funct_args):
    job.commands_list(*funct_args)
    return 1

def commands_string(funct_args):
    job.commands_string(*funct_args)
    return 1

def extract_setting(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.extract_setting(*funct_args)

def extract_global(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.extract_global(*funct_args)

def extract_box(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.extract_box(*funct_args)

def extract_atom(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        # extract atoms return an internal data type
        # this has to be reformatted
        name = str(funct_args[0])
        if not name in atom_properties.keys():
            return []

        # this block prevents error when trying to access values
        # that do not exist
        try:
            val = job.extract_atom(name, atom_properties[name]["type"])
        except ValueError:
            return []
        # this is per atom quantity - so get
        # number of atoms - first dimension
        natoms = job.get_natoms()
        # second dim is from dict
        dim = atom_properties[name]["dim"]
        data = []
        if dim > 1:
            for i in range(int(natoms)):
                dummy = [val[i][x] for x in range(dim)]
                data.append(dummy)
        else:
            data = [val[x] for x in range(int(natoms))]

        return np.array(data)

def extract_fix(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.extract_fix(*funct_args)

def extract_variable(funct_args):
    # in the args - if the third one,
    # which is the type is 1 - a lammps array is returned
    if MPI.COMM_WORLD.rank == 0:
        # if type is 1 - reformat file
        try:
            data = job.extract_variable(*funct_args)
        except ValueError:
            return []
        if funct_args[2] == 1:
            data = np.array(data)
        return data

def get_natoms(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.get_natoms()

def set_variable(funct_args):
    return job.set_variable(*funct_args)

def reset_box(funct_args):
    job.reset_box(*funct_args)
    return 1

def gather_atoms(funct_args):
    # extract atoms return an internal data type
    # this has to be reformatted
    name = str(funct_args[0])
    if name not in atom_properties.keys():
        return []

    # this block prevents error when trying to access values
    # that do not exist
    try:
        val = job.gather_atoms(
            name, atom_properties[name]["gtype"], atom_properties[name]["dim"]
        )
    except ValueError:
        return []
    # this is per atom quantity - so get
    # number of atoms - first dimension
    val = list(val)
    dim = atom_properties[name]["dim"]
    if dim > 1:
        data = [val[x : x + dim] for x in range(0, len(val), dim)]
    else:
        data = list(val)
    return np.array(data)

def gather_atoms_concat(funct_args):
    # extract atoms return an internal data type
    # this has to be reformatted
    name = str(funct_args[0])
    if not name in atom_properties.keys():
        return []

    # this block prevents error when trying to access values
    # that do not exist
    try:
        val = job.gather_atoms_concat(
            name, atom_properties[name]["gtype"], atom_properties[name]["dim"]
        )
    except ValueError:
        return []
    # this is per atom quantity - so get
    # number of atoms - first dimension
    val = list(val)
    dim = atom_properties[name]["dim"]
    if dim > 1:
        data = [val[x : x + dim] for x in range(0, len(val), dim)]
    else:
        data = list(val)
    return np.array(data)

def gather_atoms_subset(funct_args):
    # convert to ctypes
    name = str(funct_args[0])
    lenids = int(funct_args[1])
    ids = funct_args[2]

    # prep ids
    cids = (lenids * c_int)()
    for i in range(lenids):
        cids[i] = ids[i]

    if not name in atom_properties.keys():
        return []

    # this block prevents error when trying to access values
    # that do not exist
    try:
        val = job.gather_atoms_subset(
            name,
            atom_properties[name]["gtype"],
            atom_properties[name]["dim"],
            lenids,
            cids,
        )
    except ValueError:
        return []
    # this is per atom quantity - so get
    # number of atoms - first dimension
    val = list(val)
    dim = atom_properties[name]["dim"]
    if dim > 1:
        data = [val[x : x + dim] for x in range(0, len(val), dim)]
    else:
        data = list(val)
    return np.array(data)

def create_atoms(funct_args):
    # we have to process the input items
    # args are natoms, ids, type, x, v, image, shrinkexceed
    natoms = funct_args[0]
    ids = funct_args[1]
    type = funct_args[2]
    x = funct_args[3]
    v = funct_args[4]
    image = funct_args[5]
    shrinkexceed = funct_args[6]

    id_lmp = (c_int * natoms)()
    id_lmp[:] = ids

    type_lmp = (c_int * natoms)()
    type_lmp[:] = type

    image_lmp = (c_int * natoms)()
    image_lmp[:] = image

    args = [natoms, id_lmp, type_lmp, x, v, image_lmp, shrinkexceed]
    job.create_atoms(*args)
    return 1

def has_exceptions(funct_args):
    return job.has_exceptions

def has_gzip_support(funct_args):
    return job.has_gzip_support

def has_png_support(funct_args):
    return job.has_png_support

def has_jpeg_support(funct_args):
    return job.has_jpeg_support

def has_ffmpeg_support(funct_args):
    return job.has_ffmpeg_support

def installed_packages(funct_args):
    return job.installed_packages

def set_fix_external_callback(funct_args):
    job.set_fix_external_callback(*funct_args)

def get_neighlist(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.get_neighlist(*funct_args)

def find_pair_neighlist(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.find_pair_neighlist(*funct_args)

def find_fix_neighlist(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.find_fix_neighlist(*funct_args)

def find_compute_neighlist(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.find_compute_neighlist(*funct_args)

def get_neighlist_size(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.get_neighlist_size(*funct_args)

def get_neighlist_element_neighbors(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return job.get_neighlist_element_neighbors(*funct_args)

def get_thermo(funct_args):
    if MPI.COMM_WORLD.rank == 0:
        return np.array(job.get_thermo(*funct_args))

def scatter_atoms(funct_args):
    name = str(funct_args[0])
    py_vector = funct_args[1]
    # now see if its an integer or double type- but before flatten
    py_vector = np.array(py_vector).flatten()

    if atom_properties[name]["gtype"] == 0:
        c_vector = (len(py_vector) * c_int)(*py_vector)
    else:
        c_vector = (len(py_vector) * c_double)(*py_vector)

    job.scatter_atoms(
        name, atom_properties[name]["gtype"], atom_properties[name]["dim"], c_vector
    )
    return 1

def scatter_atoms_subset(funct_args):
    name = str(funct_args[0])
    lenids = int(funct_args[2])
    ids = funct_args[3]

    # prep ids
    cids = (lenids * c_int)()
    for i in range(lenids):
        cids[i] = ids[i]

    py_vector = funct_args[1]
    # now see if its an integer or double type- but before flatten
    py_vector = np.array(py_vector).flatten()

    if atom_properties[name]["gtype"] == 0:
        c_vector = (len(py_vector) * c_int)(*py_vector)
    else:
        c_vector = (len(py_vector) * c_double)(*py_vector)

    job.scatter_atoms_subset(
        name,
        atom_properties[name]["gtype"],
        atom_properties[name]["dim"],
        lenids,
        cids,
        c_vector,
    )
    return 1

def command(funct_args):
    job.command(funct_args)
    return 1

def select_cmd(argument):
    """
    Select a lammps command

    Args:
        argument (str): [close, extract_compute, get_thermo, scatter_atoms, command, gather_atoms]

    Returns:
        function: the selected function
    """
    switcher = {
        f.__name__: f
        for f in [
            extract_compute,
            get_version,
            get_file,
            commands_list,
            commands_string,
            extract_setting,
            extract_global,
            extract_box,
            extract_atom,
            extract_fix,
            extract_variable,
            get_natoms,
            set_variable,
            reset_box,
            gather_atoms_concat,
            gather_atoms_subset,
            scatter_atoms_subset,
            create_atoms,
            has_exceptions,
            has_gzip_support,
            has_png_support,
            has_jpeg_support,
            has_ffmpeg_support,
            installed_packages,
            set_fix_external_callback,
            get_neighlist,
            find_pair_neighlist,
            find_fix_neighlist,
            find_compute_neighlist,
            get_neighlist_size,
            get_neighlist_element_neighbors,
            get_thermo,
            scatter_atoms,
            command,
            gather_atoms,
        ]
    }
    return switcher.get(argument)

if __name__ == "__main__":
    while True:
        if MPI.COMM_WORLD.rank == 0:
            input_dict = pickle.load(sys.stdin.buffer)
            # with open('process.txt', 'a') as file:
            #     print('Input:', input_dict, file=file)
        else:
            input_dict = None
        input_dict = MPI.COMM_WORLD.bcast(input_dict, root=0)
        if input_dict["c"] == "close":
            job.close()
            break
        output = select_cmd(input_dict["c"])(input_dict["d"])
        if MPI.COMM_WORLD.rank == 0 and output is not None:
            # with open('process.txt', 'a') as file:
            #     print('Output:', output, file=file)
            pickle.dump(output, sys.stdout.buffer)
            sys.stdout.flush()


# -*- coding:utf-8 -*-
from lib.handlers.common.BaseHandler import WebBaseHandler
from lib.settings import *

class IndexDataHandler(WebBaseHandler):
    def GET(self):
        data = db.query('select * from anmielist where 1 order by id desc limit 0,8')
        animeList = [{
            "name"   : i.animename,
            "animeid": i.animeid,
            "episode": int(i.episode),
            "isnewer": int(i.isnew),
            "isover" : int(i.isover),
        } for i in data]

        return json.dumps({
            "status": 200,
            "message": "",
            "data": animeList
        })


import Tkinter as tk

root = tk.Tk()
root.title(u'window')

# window size
root.geometry('400x300')

def addList(text):
    ListBox1.insert(tk.END, text)
    print(bln.get())

def deleteSelectedList():
    ListBox1.delete(tk.ACTIVE)

bln = tk.BooleanVar()
bln.set(True)

chk = tk.Checkbutton(variable=bln, text='save')
chk.place(x=50, y=70)

# label
Static1 = tk.Label(text=u'test', foreground='#ff0000', background='#ffaacc')
Static1.pack()

Entry1 = tk.Entry()
Entry1.insert(tk.END, u'Input path')
Entry1.pack()

Button1 = tk.Button(text=u'Button', width=10, command=lambda: addList(Entry1.get()))
Button1.pack()

Button2 = tk.Button(text=u'Delete', width=10, command=lambda: deleteSelectedList())
Button2.pack()

ListBox1 = tk.Listbox()
ListBox1.pack()

root.mainloop()


import numpy as np
from physics_sim import PhysicsSim
from tasks.task import Task

class Takeoff(Task):
    """Takeoff (environment) that defines the goal of the agent to achieve some height and give feedback on performance"""
    def __init__(self, init_pose=None, init_velocities=None,
        init_angle_velocities=None, runtime=5., target_pos=None):
        """Initialize a Task object.
        Params
        ======
            init_pose: initial position of the quadcopter in (x,y,z) dimensions and the Euler angles
            init_velocities: initial velocity of the quadcopter in (x,y,z) dimensions
            init_angle_velocities: initial radians/second for each of the three Euler angles
            runtime: time limit for each episode
            target_pos: target/goal (x,y,z) position for the agent
        """
        super(Takeoff, self).__init__(init_pose, init_velocities, init_angle_velocities, runtime, target_pos)
        # Simulation
        self.sim = PhysicsSim(init_pose, init_velocities, init_angle_velocities, runtime)
        self.start_pos = self.sim.pose[:3]
        self.action_repeat = 3

        # state made of current position, velocity and angular velocity
        self.state_size = self.action_repeat * (6 + 3 + 3)
        self.action_low = 0
        self.action_high = 900
        self.action_size = 4
        self.runtime = runtime

        # Goal
        self.target_pos = target_pos if target_pos is not None else np.array([0., 0., 10.])

        self.penalties_obj = {}
        self.penalties = 0
        self.reward = 0

    def get_reward(self):
        """Uses current pose of sim to return reward."""
        # initialize
        reward = 0
        penalties = 0

        # penalty for distance from target
        residual_distances = self.sim.pose[:3]-self.target_pos[:3]
        pos_x_penalty = abs(residual_distances[0])**2
        pos_y_penalty = abs(residual_distances[1])**2
        pos_z_penalty = abs(residual_distances[2])**2
        self.penalties_obj['pos_x'] = round(pos_x_penalty,2)
        self.penalties_obj['pos_y'] = round(pos_y_penalty,2)
        self.penalties_obj['pos_z'] = round(pos_z_penalty,2)

        # penalty for euler angles, we want the takeoff to be stable
        euler_penalty = abs(self.sim.pose[3:6]).sum()
        self.penalties_obj['euler'] = round(euler_penalty,2)

        # distance to velocity relationship
        velo_x_penalty = self.sim.v[0]**2
        velo_y_penalty = self.sim.v[1]**2
        # velo_x_penalty += abs(abs(residual_distances[0]) + abs(self.sim.v[0]))
        # velo_y_penalty += abs(abs(residual_distances[1]) + abs(self.sim.v[1]))
        velo_z_penalty = abs(residual_distances[2] + self.sim.v[2])**2
        self.penalties_obj['v_x'] = round(velo_x_penalty, 2)
        self.penalties_obj['v_y'] = round(velo_y_penalty, 2)
        self.penalties_obj['v_z'] = round(velo_z_penalty, 2)

        #anguar velocity
        av_phi_penalties = abs(self.sim.pose[3] + self.sim.angular_v[0])**2
        av_theta_penalties = abs(self.sim.pose[4] + self.sim.angular_v[1])**2
        av_psi_penalties = abs(self.sim.pose[5] + self.sim.angular_v[2])**2 # change to 5
        self.penalties_obj['av_p'] = av_phi_penalties
        self.penalties_obj['av_t'] = av_theta_penalties
        self.penalties_obj['av_p'] = av_psi_penalties

        # factoring individual penalties
        pos_penalties = pos_x_penalty + pos_y_penalty + 10 * pos_z_penalty
        velo_penalties = velo_x_penalty + velo_y_penalty + velo_z_penalty
        angular_v_penalties = av_phi_penalties + av_theta_penalties + av_psi_penalties
        self.penalties_obj['pos'] = round(pos_penalties,2)
        self.penalties_obj['velo'] = round(velo_penalties,2)
        self.penalties_obj['av_all'] = round(angular_v_penalties,2)

        # adding penalties
        penalties += pos_penalties
        penalties += 100 * euler_penalty
        penalties += velo_penalties
        penalties += angular_v_penalties

        # behaviour near target
        distance = np.sqrt( (residual_distances**2).sum())
        if(self.sim.pose[2] >= self.target_pos[2]):
            # extra reward for flying near the target
            reward += 100
            penalties += pos_z_penalty * 2
            if distance < 5.:
                reward += 100

        self.penalties_obj['all'] = round(penalties,2)

        #summary calculation
        reward += 100 # base reward
        factored_penalties = penalties*0.0005 # factoring penalties
        reward = reward - factored_penalties
        self.penalties = factored_penalties
        self.reward = reward

        return reward


from Actions import Key, Text
from protocol import Integer, Dictation, RuleType
from requirements.Emacs import NotEmacs
from rules.ContextualRule import makeContextualRule

_mapping = {
    "find [<search_terms>]" : Key("c-f") + Text("%(search_terms)s"),
}

_extras = [
    Dictation("search_terms"),
]

CUAFindRule = makeContextualRule("CUAFind", _mapping, _extras, {},
                                 ruleType=RuleType.TERMINAL)
CUAFindRule.context.addRequirement(NotEmacs)

_mapping = {
    "copy"                : Key("c-c"),
    "cut"                 : Key("c-x"),
    "paste"               : Key("c-v"),
    "term paste"          : Key("s-insert"),
    "select all"          : Key("c-a"),
    "select per"          : Key("cs-left"),
    "select pro"          : Key("cs-right"),
    "select home"         : Key("s-home"),
    "select edge"         : Key("s-end"),
    "undo"                : Key("c-z"),
    "redo"                : Key("c-y"),
    "next form"           : Key("tab"),
    "previous form"       : Key("s-tab"),
    "axe"                 : Key("escape"),
    "find next [<n>]"     : Key("F3:%(n)d"),
    "find previous [<n>]" : Key("s-F3:%(n)d"),
    "leaf [<n>]"          : Key("pgdown:%(n)d"),
    "feel [<n>]"          : Key("pgup:%(n)d"),
    "home"                : Key("home"),
    "edge"                : Key("end"),
    "left [<n>]"          : Key("left:%(n)d"),
    "right [<n>]"         : Key("right:%(n)d"),
    "up [<n>]"            : Key("up:%(n)d"),
    "down [<n>]"          : Key("down:%(n)d"),
    "thump [<n>]"          : Key("delete:%(n)d"),
    "knock [<n>]"         : Key("backspace:%(n)d"),
    "slap [<n>]"          : Key("enter:%(n)d"),
    "num <big>"           : Text("%(big)d"),
    "per [<n>]"           : Key("c-left:%(n)d"),
    "pro [<n>]"           : Key("c-right:%(n)d"),
    "chip [<n>]"          : Key("c-backspace:%(n)d"),
    "pitch [<n>]"         : Key("c-delete:%(n)d"),
    "top side"            : Key("c-home"),
    "bottom"              : Key("c-end"),
    "save file"           : Key("c-s"),
    "open file"           : Key("c-o"),
    "new file"            : Key("c-n"),
}

_extras = [
    Integer("n", 3, 20),
    Integer("i", 3, 8),
    Integer("big", 0, 2**14),
]

_defaults = {
    "search_terms" : "",
    "n": 1,
    "i": 1,
}

CUARule = makeContextualRule("CUA", _mapping, _extras, _defaults)
CUARule.context.addRequirement(NotEmacs)


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

import re

class Solution1:
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        patt = re.compile('[-|+]{0,1}\d+')
        match = patt.match(str.strip())
        if match:
            match = int(match.group())
            if match <= -2147483648:
                return -2147483648
            if match >= 2147483647:
                return 2147483647
            return match
        return 0

class Solution:
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if len(str) == 0:
            return 0

        start = -1
        end = -1
        for i in range(len(str)):
            if start < 0 and str[i] != ' ':
                start = i
                continue
            if start >= 0 and (str[i] < '0' or str[i] > '9'):
                end = i
                break
            end = i + 1

        if end <= start:
            end = start + 1

        if (str[start] != '-' and str[start] != '+') and not (str[start] >= '0' and str[start] <= '9'):
            return 0
        if str[start:end] == '-' or str[start:end] == '+':
            return 0

        i = int(str[start: end])
        if i > 2 ** 31 - 1:
            i = 2 ** 31 - 1
        if i < -2 ** 31:
            i = -2**31
        return i

if __name__ == "__main__":
    str = " 987"
    # str = "9.11w1223"
    # str = "2147483648"
    # str = "3.145"
    # str = "-42"
    print(Solution.myAtoi(None, str))
    print(Solution1.myAtoi(None, str))


import time
import pytest
from page.periodical.sub3.periodical_cataloging_page import PeriodicalCatalogingPage
from utils.driver_utils import DriverUtils
from config.base_config import *

# 期刊-期刊编目 测试用例
class TestPeriodicalCataloging:

    @pytest.fixture(scope='function', autouse=True)
    def setup_class(self, drivers):
        self.page = PeriodicalCatalogingPage(drivers)

    def teardown_class(self):
        DriverUtils.back_ops()
        time.sleep(3)

    @pytest.mark.skip
    def test_select(self):
        """ 测试 查询 功能 """
        self.page.click_model("期刊")
        self.page.click_menu("期刊编目管理")
        self.page.click_sub_menu(3, "期刊编目")
        self.page.click_sub_menu_btn("查询")
        assert self.page.get_sub_menu_alert()


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

"""
Uso: preprocesar.py

Aplica los procesadores definidos en preprocesadores a cada
una de las páginas, para producir la prioridad con la que página
será (o no) incluída en la compilación.

"""

from __future__ import with_statement, unicode_literals, print_function

import os
import codecs
import config
import logging
import operator
import sys
import time

from collections import Counter
from os.path import join, abspath, dirname

from src.armado import to3dirs
from src.preproceso import preprocesadores
from src import utiles

logger = logging.getLogger(__name__)

LOG_SCORES_ACCUM = os.path.join(config.DIR_TEMP, 'page_scores_accum.txt')
LOG_SCORES_FINAL = os.path.join(config.DIR_TEMP, 'page_scores_final.txt')

class WikiArchivo(object):
    def __init__(self, cwd, last3dirs, nombre_archivo):
        self.ruta_relativa = join(last3dirs, nombre_archivo)
        self.url = nombre_archivo
        self._filename = join(cwd, nombre_archivo)
        self._html = None

    def get_html(self):
        """Devuelve el contenido del archivo, lo carga si no lo tenía."""
        if self._html is None:
            with open(self._filename, 'rb') as fh:
                self._html = fh.read()

        return self._html

    def set_html(self, data):
        """Setea el html."""
        self._html = data

    html = property(get_html, set_html)

    def guardar(self):
        """Guarda el archivo, crea los directorios si no están."""
        destino = join(config.DIR_PREPROCESADO, self.ruta_relativa)
        try:
            os.makedirs(dirname(destino))
        except os.error:
            # ya estaba
            pass

        with open(destino, 'wb') as fh:
            fh.write(self._html)

    def __str__(self):
        return "<WikiArchivo: %s>" % self.url.encode("utf8")

class WikiSitio(object):

    def __init__(self, root_dir):
        self.origen = unicode(abspath(root_dir))
        self.preprocesadores = [proc() for proc in preprocesadores.TODOS]
        self.prof_quant = Counter()
        self.prof_times = Counter()

    def process(self):
        """Process all pages under a root directory."""
        # let's see what was processed from before, and open the log file to keep adding
        if os.path.exists(config.LOG_PREPROCESADO):
            with codecs.open(config.LOG_PREPROCESADO, "rt", "utf8") as fh:
                processed_before_set = set(x.strip() for x in fh)
        else:
            processed_before_set = set()
        processed_before_log = codecs.open(config.LOG_PREPROCESADO, "at", "utf8")

        # get the total of directories to parse
        logger.info("Getting how many pages under root dir")
        total_pages = sum(len(filenames) for _, _, filenames in os.walk(self.origen))
        logger.info("Quantity of pages to process: %d", total_pages)

        # open the scores file to keep adding
        scores_log = codecs.open(LOG_SCORES_ACCUM, "at", "utf8")

        count_processed = count_new_ok = count_new_discarded = count_old_before = 0
        tl = utiles.TimingLogger(30, logger.debug)
        for cwd, _, filenames in os.walk(self.origen):
            parts_dir = cwd.split(os.path.sep)
            last3dirs = join(*parts_dir[-3:])

            if len(last3dirs) != 5:  # ej: u"M/a/n"
                # we're not in a leaf, we shouldn't have any files
                if filenames:
                    logger.warning("We have content in a non-leaf directory: %s %s",
                                   last3dirs, filenames)
                continue

            for page_path in filenames:
                count_processed += 1
                tl.log("Processing %s (%d/%d)", last3dirs, count_processed, total_pages)

                if " " in page_path:
                    logger.warning("Have names with spaces! %s %s", last3dirs, page_path)

                # check if the page was processed or discarded before
                if page_path in processed_before_set:
                    count_old_before += 1
                    continue

                wikipage = WikiArchivo(cwd, last3dirs, page_path)

                this_total_score = 0
                other_pages_scores = []
                for procesador in self.preprocesadores:
                    tini = time.time()
                    try:
                        (this_score, other_scores) = procesador(wikipage)
                    except:
                        logger.error("Processor %s crashed on page %r", procesador, page_path)
                        raise
                    self.prof_times[procesador] += time.time() - tini
                    self.prof_quant[procesador] += 1

                    # keep the score for other pages (check before to avoid a bogus function call)
                    if other_scores:
                        other_pages_scores.extend(other_scores)

                    if this_score is None:
                        # the processor indicated to discard this page
                        count_new_discarded += 1
                        break

                    # keep the score for this page
                    this_total_score += this_score

                else:
                    # all processors done, page not discarded
                    count_new_ok += 1
                    wikipage.guardar()

                    # save the real page score
                    scores_log.write("{}|R|{:d}\n".format(
                        to3dirs.to_pagina(page_path), this_total_score))

                    # save the extra pages score (that may exist or not in the dump)
                    for extra_page, extra_score in other_pages_scores:
                        scores_log.write("{}|E|{:d}\n".format(extra_page, extra_score))

                # with score or discarded, log it as processed
                processed_before_log.write(page_path + "\n")

        # all processing done for all the pages
        logger.info("Processed pages: %d new ok, %d discarded, %d already processed before",
                    count_new_ok, count_new_discarded, count_old_before)
        scores_log.close()
        processed_before_log.close()
        for procesador in self.preprocesadores:
            procesador.close()
            logger.debug("Preprocessor %17s usage stats: %s", procesador.nombre, procesador.stats)

    def commit(self):
        """Commit all the processing done, adjusting some logs."""
        colsep = config.SEPARADOR_COLUMNAS

        # load the score files and compress it
        all_scores = Counter()
        real_pages = set()
        with codecs.open(LOG_SCORES_ACCUM, "rt", "utf8") as fh:
            for line in fh:
                page, status, score = line.strip().split(colsep)
                all_scores[page] += int(score)
                if status == 'R':
                    real_pages.add(page)

        # load the redirects
        redirects = {}
        with codecs.open(config.LOG_REDIRECTS, "r", "utf-8") as fh:
            for linea in fh:
                r_from, r_to = linea.strip().split(colsep)
                redirects[r_from] = r_to

        # transfer score
        transferred_scores = Counter()
        for page, score in all_scores.items():
            if page not in redirects:
                transferred_scores[page] += score
                continue

            # dereference the redirect, avoiding a possible loop; note that intermediate
            # pages have not score (see processor)
            loop_guard = []
            while page in redirects:
                page = redirects[page]
                if page in loop_guard:
                    logger.warning("Redirect loop found: %s", loop_guard, page)
                    break
                loop_guard.append(page)

            # add the original score to the dereferenced page
            transferred_scores[page] += score

        # store the scores again, but only for the real pages (there is no point in storing
        # scores for pages that were not included in the dump)
        with codecs.open(LOG_SCORES_FINAL, "wt", "utf8") as fh:
            for page in real_pages:
                fh.write("{}|{:d}\n".format(page, transferred_scores[page]))

class PagesSelector(object):
    """Select the htmls that will be included in this version."""

    def __init__(self):
        self._calculated = False
        self._top_pages = None

        # used from outside to decided regenerate index, blocks, etc
        self._same_info_through_runs = None

    @property
    def top_pages(self):
        """The list of top pages."""
        if not self._calculated:
            raise ValueError("You need to first 'calculate' everything.")
        return self._top_pages

    @property
    def same_info_through_runs(self):
        """The top HTMLs for this run is the same of the previous one."""
        if not self._calculated:
            raise ValueError("You need to first 'calculate' everything.")
        return self._same_info_through_runs

    def calculate(self):
        """Calculate the HTMLs with more score and store both lists."""
        self._calculated = True

        # read the preprocessed file
        all_pages = []
        colsep = config.SEPARADOR_COLUMNAS
        with codecs.open(LOG_SCORES_FINAL, 'rt', encoding='utf8') as fh:
            for line in fh:
                page, score = line.strip().split(colsep)
                dir3, fname = to3dirs.get_path_file(page)
                all_pages.append((dir3, fname, int(score)))

        # order by score, and get top N
        all_pages.sort(key=operator.itemgetter(2), reverse=True)
        page_limit = config.imageconf['page_limit']
        self._top_pages = all_pages[:page_limit]

        # get all items after N that still has the same score that last one
        last_score = self._top_pages[-1][2]
        for more_info in all_pages[page_limit:]:
            if more_info[2] == last_score:
                self._top_pages.append(more_info)

        separator = config.SEPARADOR_COLUMNAS
        if os.path.exists(config.PAG_ELEGIDAS):
            # previous run for this info! same content?
            with codecs.open(config.PAG_ELEGIDAS, "rt", "utf8") as fh:
                old_stuff = []
                for linea in fh:
                    dir3, arch, score = linea.strip().split(separator)
                    old_stuff.append((dir3, arch, int(score)))
                if sorted(old_stuff) == sorted(self._top_pages):
                    self._same_info_through_runs = True

        if not self._same_info_through_runs:
            # previous info not there, or different: write to disk
            with codecs.open(config.PAG_ELEGIDAS, "wt", "utf8") as fh:
                for dir3, fname, score in self._top_pages:
                    info = (dir3, fname, str(score))
                    fh.write(separator.join(info) + "\n")

pages_selector = PagesSelector()

def run(root_dir):
    if os.path.exists(LOG_SCORES_FINAL):
        logger.info("Skipping the whole processing stage as the final scores log was found.")
        return

    wikisitio = WikiSitio(root_dir)
    wikisitio.process()
    wikisitio.commit()

def profiled_run(root_dir):
    # import cProfile

    tini = time.time()
    wikisitio = WikiSitio(root_dir)

    # uncomment the following if you want to profile just ONE preprocessor (fix which one)
    wikisitio.preprocesadores = [preprocesadores.HTMLCleaner()]

    # select here to run the profiled process or not
    # cProfile.runctx("wikisitio.process()", globals(), locals(), "/tmp/procesar.stat")
    wikisitio.process()

    wikisitio.commit()
    tend = time.time()
    print("Whole process", tend - tini)
    print("In processors", sum(wikisitio.prof_times.values()))
    for proc in wikisitio.prof_times:
        quant = wikisitio.prof_quant[proc]
        total = wikisitio.prof_times[proc]
        print("         proc ", proc, quant, total, total / quant)
    print("Full stats (if profile run) saved in /tmp/procesar.stat")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: preprocesar.py root_dir")
        exit()
    if os.path.exists(config.LOG_PREPROCESADO):
        print("ERROR: The PREPROCESADO file is there, it will make some articles to be skipped:",
              config.LOG_PREPROCESADO)
        exit()

    # fix config for a needed variable
    config.langconf = dict(include=[])

    profiled_run(sys.argv[1])


from flask import Blueprint, render_template, request, abort #pylint: disable=import-error
from .forms import RegisterForm

frontend = Blueprint("frontend", __name__)

@frontend.route("/")
def index():
    return render_template("index.html")

@frontend.route("/register", methods=["GET", "POST"])
def register():
    form = RegisterForm()
    if request.method == "POST":
        if not form.validate_on_submit():
            abort(400)

        # Validate and add stuff to database
        return render_template("index.html")

    return render_template("register.html", form=form)


# 병합 정렬
# 입력: 리스트 a
# 출력: 없음(입력으로 주어진 a가 정렬됨)

def merge_sort(a):
	n = len(a)

	if n <= 1:		# 종료 조건
		return

	mid = n // 2
	g1 = a[:mid]
	g2 = a[mid:]
	merge_sort(g1)
	merge_sort(g2)

	i1 = 0
	i2 = 0
	ia = 0

	while i1 < len(g1) and i2 < len(g2):
		if g1[i1] < g2[i2]:
			a[ia] = g1[i1]
			i1 += 1
			ia += 1
		else:
			a[ia] = g2[i2]
			i2 += 1
			ia += 1

	while i1 < len(g1):
		a[ia] = g1[i1]
		i1 += 1
		ia += 1

	while i2 < len(g2):
		a[ia] = g2[i2]
		i2 += 1
		ia += 1

d = [6, 8, 3, 9, 10, 1, 2, 4, 7, 5]
merge_sort(d)
print(d)


"""
Given an array of ints, return True if the array
contains a 2 next to a 2 somewhere.

has22([1, 2, 2]) → True
has22([1, 2, 1, 2]) → False
has22([2, 1, 2]) → False"""
def has22(nums):
  if len(nums) < 2:
    return False
  else:
    for i in range(len(nums)):
      print (nums[i])
      print (nums[i+1])
      if (nums[i] == 2 and nums[i+1] == 2):
        return True
    return False
print (has22([1, 2, 2]))


# -*- coding: utf-8 -*-
import random
import string

from django.db import models
# from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy as _

class Trade(models.Model):
    """Model to represent Trade object.

    A Trade has the following fields:
    - id: string with the format 'TR\w{7}'
    - sell_currency: string
    - sell_amount: string
    - buy_currency:
    - buy_amount:
    - rate: decimal
    - date_booked: related to 3 hashtags at most
    """

    # Currencies available in the api.
    CURRENCY_TYPE = (
        ('AUD', _('Australian dollar')),
        ('BGN', _('Bulgarian lev')),
        ('BRL', _('Brazilian real')),
        ('CAD', _('Canadian dollar')),
        ('CHF', _('Swiss franc')),
        ('CNY', _('Chinese yuan')),
        ('CZK', _('Czech koruna')),
        ('DKK', _('Danish krone')),
        ('EUR', _('Euro')),
        ('GBP', _('Pound sterling')),
        ('HKD', _('Hong Kong dollar')),
        ('HRK', _('Croatian kuna')),
        ('HUF', _('Hungarian forint')),
        ('IDR', _('Indonesian rupiah')),
        ('ILS', _('Israeli new shekel')),
        ('INR', _('Indian rupee')),
        ('JPY', _('Japanese yen')),
        ('KRW', _('South Korean won')),
        ('MXN', _('Mexican peso')),
        ('MYR', _('Malaysian ringgit')),
        ('NOK', _('Norwegian krone')),
        ('NZD', _('New Zealand dollar')),
        ('PHP', _('Philippine peso')),
        ('PLN', _('Polish zloty')),
        ('RON', _('Romanian leu')),
        ('RUB', _('Russian ruble')),
        ('SEK', _('Swedish krona')),
        ('SGD', _('Singapore dollar')),
        ('THB', _('Thai baht')),
        ('TRY', _('Turkish lira')),
        ('USD', _('United States dollar')),
        ('ZAR', _('South African rand')),
    )

    ID_PREFIX = "TR"
    ID_MAX_LENGTH = 9

    # Please note that `max_length` has no effect for sqlite database
    id = models.CharField(primary_key=True, max_length=ID_MAX_LENGTH, editable=False)
    sell_currency = models.CharField(_('Sell currency'), choices=CURRENCY_TYPE, blank=False, null=False, max_length=3)
    sell_amount = models.FloatField(_('Sell amount'), blank=False, null=False)
    buy_currency = models.CharField(_('Buy currency'), choices=CURRENCY_TYPE, blank=False, null=False, max_length=3)
    # This value is calculated with sell_amount and rate.
    #  It is stored to not calculate every time the object is requested
    buy_amount = models.FloatField(_('Buy amount'), blank=False, null=False)
    rate = models.FloatField(_('Rate'), blank=False, null=False)
    date_booked = models.DateTimeField(_('Date booked'), blank=False, null=False, auto_now=True)

    def __str__(self):
        return self.id

    def save(self, *args, **kwargs):
        # If not pk, then the instance doesn't exist in database yet. Generate corresponding id then.
        if not self.pk:
            self.id = self._gen_custom_id()

        super(Trade, self).save(*args, **kwargs)

    @classmethod
    def _gen_custom_id(cls):
        """Generates a string with format 'TR\w{7}' for Trade id.

        :return: String with format 'TR\w{7}'
        :rtype: str
        """
        new_id = None
        max_aphnum_len = cls.ID_MAX_LENGTH - len(cls.ID_PREFIX)

        while new_id is None:
            random_aphnum = ''.join(random.choice(string.digits + string.ascii_uppercase)
                                    for _ in range(max_aphnum_len))
            new_id = "{}{}".format(cls.ID_PREFIX, random_aphnum)

            if cls.objects.filter(id=new_id).exists():
                new_id = None

        return new_id


from numpy import *
import math
import xlrd
import numpy as np
import openpyxl
import datetime
def norm_pdf_multivariate(x, mu, sigma):
    size = len(x)
    if size == len(mu) and (size, size) == sigma.shape:
        det = linalg.det(sigma)
        if det == 0:
            raise NameError("The covariance matrix can't be singular")

        norm_const = 1.0/ (math.pow((2*pi),float(size)/2) * math.pow(det,1.0/2) )
        x_mu = matrix(x - mu)
        inv = sigma.I
        result = math.pow(math.e, -0.5 * (x_mu * inv * x_mu.T))
        return norm_const * result
    else:
        raise NameError("The dimensions of the input don't match")

#读取清洗后的数据
datasigma = [];datatimeYes = []
dataabnormal = [];datatimeNo = []
data_xsls = xlrd.open_workbook("./data/14A17Process.xlsx") #打开此地址下的exl文档
#data_xsls = xlrd.open_workbook("13ANew.xls")
sheet_name = data_xsls.sheets()[0]
count_nrows = sheet_name.nrows
for i in range(1,count_nrows,5):
    if i < 3000 or (i>250000 and i<300000) or(i>380000 and i<490000) or (i > 760000 and i< 820000):
    #if i < 3000 or (i>50000 and i<100000) or (i > 330000 and i< 360000) or (i>850000 and i<990000):
        pass
    else:
        b = []
        for j in range(9):
            b.append(sheet_name.cell_value(i,j+1))
        datasigma.append(b)
        a = xlrd.xldate_as_tuple(sheet_name.cell_value(i,0),0)
        datatimeYes.append(datetime.datetime(*a))
for i in range(1,count_nrows):
    if (i>397000 and i<400200) :
        b = []
        for j in range(9):
            b.append(sheet_name.cell_value(i,j+1))
        dataabnormal.append(b)
        a = xlrd.xldate_as_tuple(sheet_name.cell_value(i,0),0)
        datatimeNo.append(datetime.datetime(*a))

#生成均值和协方差矩阵
sigma = matrix(cov(array(datasigma).T))
mean = []
for i in range(9):
    l = len(datasigma)
    mean.append(sum(datasigma[j][i]for j in range(l))/l)
mu = array(mean)

Y = []
for i in range(len(datasigma)):
    a = norm_pdf_multivariate(datasigma[i], mu, sigma)*pow(10,7)
    Y.append(a)

xls=openpyxl.Workbook()
sheet = xls.active
pos = 0
for i in range(len(Y)):
    if Y[i] < 0.5:
        for j in range(9):
            sheet.cell(i+2-pos,j+2,datasigma[i][j])
        sheet.cell(i+2-pos,1,datatimeYes[i])
    else:
        pos+=1
xls.save('./data/14A17normalN.xlsx')

Y = []
for i in range(len(dataabnormal)):
    a = norm_pdf_multivariate(dataabnormal[i], mu, sigma)*pow(10,7)
    Y.append(a)

xls=openpyxl.Workbook()
sheet = xls.active
pos = 0
for i in range(len(Y)):
    if Y[i] < 0.5:
        for j in range(9):
            sheet.cell(i+2-pos,j+2,dataabnormal[i][j])
        sheet.cell(i+2-pos,1,datatimeNo[i])
    else:
        pos+=1
xls.save('./data/14A17abnormalN.xlsx')


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

"""TODO: High-level file comment."""

import sys

def main(argv):
    pass

if __name__ == '__main__':
    main(sys.argv)
import logging
import random
import db_helpers as helpers
import time

import config
import pyfcm

if config.FIREBASE_APIKEY:
  fcm = pyfcm.FCMNotification(api_key=config.FIREBASE_APIKEY)

def HandleNotification(game_state, queued_notification_id, queued_notification):
  """Helper function to propogate a notification."""

  if 'playerId' in queued_notification and queued_notification['playerId'] is not None:
    public_player_ids = [queued_notification['playerId']]
  elif 'groupId' in queued_notification:
    public_player_ids = game_state.get('/groups/%s' % queued_notification['groupId'], 'players')
    if public_player_ids is None:
      public_player_ids = []
    else:
      public_player_ids = sorted(public_player_ids)
  else:
    logging.error('Queued notification %s does not have a playerId or a groupId!' % (
        queued_notification_id))
    return

  device_tokens = []

  for index, public_player_id in enumerate(public_player_ids):
    notification_id = queued_notification_id.replace('queuedNotification-', 'notification-', 1) + '-' + str(index)
    notification = {
      'queuedNotificationId': queued_notification_id,
      'message': queued_notification['message'],
      'previewMessage': queued_notification['previewMessage'],
      'destination': queued_notification['destination'],
      'time': int(time.time() * 1000),
      'icon': queued_notification['icon'] if 'icon' in queued_notification else None,
    }
    private_player_id = helpers.GetPrivatePlayerId(game_state, public_player_id)
    game_state.put('/privatePlayers/%s/notifications' % private_player_id,
                  notification_id, notification)

    if queued_notification['mobile']:
      user_id = game_state.get('/publicPlayers/%s' % public_player_id, 'userId')
      user = game_state.get('/users', user_id)
      if 'deviceToken' in user:
        device_tokens.add(user['deviceToken'])
  if len(device_tokens) == 0:
    return
  if config.FIREBASE_APIKEY:
    fcm.notify_multiple_devices(registration_ids=list(device_tokens),
                                data_message=notification)

def ExecuteNotifications(request, game_state):
  """Send the notifications.

  This method will execute queued notifications and send them to apps and add
  them to the player specific notification database URLs.

  Changes 'sent' from False to True once it's sent.

  We iterate over the entire set of notifications in existence currently. Soon,
  we'll iterate over all notifications in the given game id.
  """

  current_time = int(time.time() * 1000)
  while True:
    updates = False
    queued_notifications = game_state.get('/queuedNotifications', None)
    if queued_notifications is None:
      return
    for queued_notification_id, queued_notification in queued_notifications.iteritems():
      send_time = queued_notification['sendTime'] if 'sendTime' in queued_notification else None
      sent = queued_notification['sent']
      if not sent and (send_time is None or send_time < current_time):
        updates = True
        HandleNotification(game_state, queued_notification_id, queued_notification)
        game_state.patch('/queuedNotifications/%s' % queued_notification_id, {'sent': True})
    if not updates:
      return


from tensorflow.keras.models import load_model
import tensorflow as tf
import os
import math
import os.path as osp
import tensorflow.keras.backend as K
from tensorflow.python.framework import graph_util, graph_io

def cosloss(y_true, y_pred):
    y_true = tf.Print(y_true, ['y_true: ', y_true])
    y_pred2 = y_pred * 2. * math.pi
    y_pred2 = tf.Print(y_pred2, ['y_pred: ', y_pred2])
    loss = K.mean(2. * (1. - tf.cos(0.5 * (y_pred2 - y_true))))
    loss = tf.Print(loss, ['my loss: ', loss])
    return loss

def freeze_graph(graph, session, output):
    with graph.as_default():
        graphdef_inf = tf.graph_util.remove_training_nodes(graph.as_graph_def())
        graphdef_frozen = tf.graph_util.convert_variables_to_constants(session, graphdef_inf, output)
        graph_io.write_graph(graphdef_frozen, ".", "frozen_model.pb", as_text=False)

os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"

# 路径参数
h5_dir = '/home/ubuntu/cs/table_derection_tf2/use_cos_loss/saved_model_bnwrong'
h5_file = 'model_51.hdf5'
h5_file_path = osp.join(h5_dir, h5_file)

# 重要的环境配置，在图中有BN这种层时非常重要，设置为推理模式
K.clear_session()
K.set_learning_phase(0)  # this line most important
session = K.get_session()

# 加载模型
h5_model = load_model(h5_file_path,  custom_objects={'cosloss': cosloss})

'''
g_list = tf.global_variables()
bn_moving_vars = [g for g in g_list if 'moving_mean' in g.name]
bn_moving_vars += [g for g in g_list if 'moving_variance' in g.name]
print(bn_moving_vars)
'''

# 打印输出输出结点，在load pb时用到
INPUT_NODE = h5_model.inputs[0].op.name
OUTPUT_NODE = [out.op.name for out in h5_model.outputs]
print('输入结点名称：', INPUT_NODE)
print('输出结点名称：', OUTPUT_NODE)

# 生成pb
freeze_graph(session.graph, session, [out.op.name for out in h5_model.outputs])

print('h5 cvt pb finished!!!')


# coding:utf-8
import os
import random
from . import tech
from .forms import tech_form
from ..tech_models import Tech,Review
from datetime import datetime
from bson.objectid import ObjectId
from flask import render_template, redirect, request, url_for, flash, make_response, Response

@tech.route('/')
def tech_index():
    r = Tech.objects()
    techs = r.all()
    scategorys= set([ k.subCategory for k in r])
    return render_template('technology/index.html', techs=techs,categorys=scategorys)

@tech.route('/add', methods=['GET', 'POST'])
def add_tech():
    form = tech_form()
    if request.method == 'POST' and form.validate():
        tech = Tech(title=form.title.data, content=form.content.data,subCategory=form.subCategory.data,tags=form.tags.data.strip().split())
        result = tech.save()
        return make_response(str(result))
        # return redirect(url_for('.tech_index'))
    else:
        flash('support markdown format')
        return render_template('technology/add.html', form=form)

@tech.route('/<string:pk>')
def get_tech(pk):
    scategorys= set([ k.subCategory for k in Tech.objects()])
    t = list(Tech.objects(pk=pk))[0]

    return render_template('technology/tech.html', tech=t,categorys=scategorys)

@tech.route('/category/<string:category>')
def tech_category(category):
    r = Tech.objects(subCategory=category)
    techs = r.all()
    scategorys= set([ k.subCategory for k in Tech.objects()])
    return render_template('technology/index.html', techs=techs,categorys=scategorys)

@tech.route('/tags/<string:tag>')
def tech_tag(tag):
    r = Tech.objects()
    techs = r.filter(tags=tag)
    alltags= set([ j for k in Tech.objects() for j in k.tags ])
    return render_template('technology/tag.html', techs=techs,tags=alltags)

@tech.route('/like',methods=['POST'])
def tech_like():
    values = request.values
    pk = values.get('pk')
    num = values.get('num')
    t = list(Tech.objects(pk=pk))[0]
    t.like+=int(num)
    r=t.save()
    return make_response(str(r))

@tech.route('/unlike',methods=['POST'])
def tech_unlike():
    values = request.values
    pk = values.get('pk')
    num = values.get('num')
    t = list(Tech.objects(pk=pk))[0]
    t.unlike+=int(num)
    r=t.save()
    return make_response(str(r))

@tech.route('/search/tag',methods=['GET'])
def tech_search_tag():
    values = request.values
    kd = values.get('key')
    techs = Tech.objects.filter(tags__contains=kd)

    alltags= set([ j for k in Tech.objects() for j in k.tags ])

    flash(u'共找到%d篇 标签 为%s的文章' %(len(techs),kd))

    return render_template('technology/tag.html', techs=techs,tags=alltags)

@tech.route('/search/category',methods=['GET'])
def tech_search_category():
    values = request.values
    kd = values.get('key')
    techs = Tech.objects.filter(subCategory__contains=kd)

    scategorys= set([ k.subCategory for k in Tech.objects()])

    message = u'共找到%d篇 分类 为%s的文章' %(len(techs),kd)
    flash(message)

    return render_template('technology/index.html', techs=techs,categorys=scategorys)


# coding: utf-8

# Archivo: ultrasonico.py

# Importar las funciones necesarias de los módulos RPi,
# y time.
import RPi.GPIO as GPIO
import time

# Pin GPIO donde está conectado el activador (entrada) del
# sensor HC-SR04.
TRIG = 23

# Pin GPIO donde está conectado el eco (salida) del sensor
# HC-SR04.
ECHO = 24

# list to store values and compute the mean
raw_values = []

# MAX_DISTANCE = 50 #setting max distance (to avoid weird jumps)
MEAN_RANGE = 10 #size of values over which to compute the range

# Indicar que se usa el esquema de numeración de pines
# de BCM (Broadcom SOC channel), es decir los números de
# pines GPIO (General-Purpose Input/Output).
GPIO.setmode(GPIO.BCM)

# Establecer que TRIG es un canal de salida.
GPIO.setup(TRIG, GPIO.OUT)

# Establecer que ECHO es un canal de entrada.
GPIO.setup(ECHO, GPIO.IN)

print("Medición de distancias en progreso")

try:
    # Ciclo infinito.
    # Para terminar el programa se debe presionar Ctrl-C.
    while True:

        # Apagar el pin activador y permitir un par de
        # segundos para que se estabilice.
        GPIO.output(TRIG, GPIO.LOW)
        print("Esperando a que el sensor se estabilice")
        time.sleep(2)

        # Prender el pin activador por 10 microsegundos
        # y después volverlo a apagar.
        GPIO.output(TRIG, GPIO.HIGH)
        time.sleep(0.00001)
        GPIO.output(TRIG, GPIO.LOW)

        # En este momento el sensor envía 8 pulsos
        # ultrasónicos de 40kHz y coloca su salida ECHO
        # en HIGH. Se debe detectar este evento e iniciar
        # la medición del tiempo.
        print("Iniciando eco")
        while True:
            pulso_inicio = time.time()
            if GPIO.input(ECHO) == GPIO.HIGH:
                break

        # La salida ECHO se mantendrá en HIGH hasta recibir
        # el eco reflejado por el obstáculo. En ese momento
        # el sensor pondrá ECHO en LOW y se debe terminar
        # la medición del tiempo.
        while True:
            pulso_fin = time.time()
            if GPIO.input(ECHO) == GPIO.LOW:
                break

        # La medición del tiempo es en segundos.
        duracion = pulso_fin - pulso_inicio

        # Calcular la distancia usando la velocidad del
        # sonido y considerando que la duración incluye
        # la ida y vuelta.
        distancia = (34300 * duracion) / 2

        # Imprimir resultado.
        print ("Distancia: %.2f cm" % distancia)

        # Add to list
        raw_values.append(distancia)

        if len(raw_values)==MEAN_RANGE:
        	acc_distance = sum(raw_values)/len(raw_values)
        	print("Mean distance: "+ str(acc_distance))
        	raw_values = []

finally:
    # Reiniciar todos los canales de GPIO.
    GPIO.cleanup()


# -*- coding: utf-8 -*-
"""
C2017-38
"""
import scrapy
from carbuisness.items import fangshopitem
import time
from scrapy.conf import settings
from scrapy.mail import MailSender
import logging
import json
import re
import random
import hashlib
from hashlib import md5

website='fang_shop'

class CarSpider(scrapy.Spider):

    name=website

    def __init__(self,**kwargs):
        super(CarSpider,self).__init__(**kwargs)
        self.mailer=MailSender.from_settings(settings)
        self.counts=0
        self.carnum=800000

        settings.set('CrawlCar_Num',self.carnum,priority='cmdline')
        settings.set('MONGODB_DB','carbusiness',priority='cmdline')
        settings.set('MONGODB_COLLECTION',website,priority='cmdline')

    def start_requests(self):
        city_list=['','.sh','.gz','.tj','.cq','.cd','.suzhou','.wuhan','.xian','.dg','.km','.hz','.jn','.wuxi','.zz','.nc','.qd','.sjz','.nanjing','.dl','.hkproperty']
        for temp in city_list:
            url="http://shop"+temp+".fang.com/zu/house/"
            yield scrapy.Request(url,callback=self.parse)

    def parse(self, response):
        x = response.xpath('//div[@class="qxName"]/a')
        for i in range(1,len(x)-1):
            urlbase=x[i].xpath('@href').extract_first()
            url=response.urljoin(urlbase)
            yield scrapy.Request(url,callback=self.middle1_parse, dont_filter=True)

    def middle1_parse(self,response):
        x = response.xpath('//div[@class="houseList"]/dl')
        for temp in x:
            urlbase = temp.xpath('dd/p[@class="title"]/a/@href').extract_first()
            url=response.urljoin(urlbase)
            yield scrapy.Request(url,callback=self.parse_info, dont_filter=True)
        next_page=response.xpath(u'//a[contains(text(),"下一页")]/@href').extract_first()
        if next_page:
            url=response.urljoin(next_page)
            yield scrapy.Request(url,callback=self.middle1_parse, dont_filter=True)

    def parse_info(self,response):
        item=fangshopitem()
        item['url'] = response.url
        item['website'] = website
        item['grabtime'] = time.strftime('%Y-%m-%d %X', time.localtime())
        item['status'] = response.url
        item['shortdesc']=response.xpath('//div[@class="title"]/h1/text()').extract_first().strip() \
            if response.xpath('//div[@class="title"]/h1/text()').extract_first() else "-"                   # 标题描述
        item['houseid']=response.xpath(u'//span[contains(text(),"房源编号")]/text()').re('\d+')[0] \
            if response.xpath(u'//span[contains(text(),"房源编号")]/text()').re('\d+') else "-"             # 房源编号
        item['posttime']=response.xpath('//p[@class="gray9"]/text()[3]').re(u'发布时间：(.*)\(')[0] \
            if response.xpath('//p[@class="gray9"]/text()[3]').re(u'发布时间：(.*)\(') else "-"              # 发布时间
        item['price']=response.xpath('//span[@class="red20b"]/text()').extract_first() \
            if response.xpath('//span[@class="red20b"]/text()').extract_first() else "-"                        # 价格
        item['paystyle']=response.xpath('//dt[@class="gray6 zongjia1"]/text()[3]').re(u'支付方式：(.*)\)')[0] \
            if response.xpath('//dt[@class="gray6 zongjia1"]/text()[3]').re(u'支付方式：(.*)\)') else "-"    # 支付方式
        item['area']=response.xpath(u'//dt[contains(text(),"建筑面积：")]/strong/text()').extract_first() \
            if response.xpath(u'//dt[contains(text(),"建筑面积：")]/strong/text()').extract_first() else "-"     # 建筑面积
        item['phone']=response.xpath('//div[@class="phone_top"]/span/label/text()').extract_first() \
            if response.xpath('//div[@class="phone_top"]/span/label/text()').extract_first() else "-"               # 电话
        item['shopname']=response.xpath(u'//span[contains(text(),"楼盘名称：")]/../text()[2]').extract_first().strip() \
            if response.xpath(u'//span[contains(text(),"楼盘名称：")]/../text()[2]').extract_first() else "-"        # 楼盘名称
        item['address']=response.xpath(u'//span[contains(text(),"楼盘地址：")]/../text()[1]').extract_first() \
            if response.xpath(u'//span[contains(text(),"楼盘地址：")]/../text()[1]').extract_first() else "-"        # 楼盘地址
        item['propertycost']=response.xpath(u'//span[contains(text(),"物业费：")]/../text()[1]').extract_first() \
            if response.xpath(u'//span[contains(text(),"物业费：")]/../text()[1]').extract_first() else "-"             # 物业费
        item['sfb']=response.xpath(u'//span[contains(text(),"适合经营：")]/../span[2]/text()').extract_first() \
            if response.xpath(u'//span[contains(text(),"适合经营：")]/../span[2]/text()').extract_first() else "-"       # 适合经营
        item['type']=response.xpath('//div[@class="inforTxt"]/dl[2]/dd[3]/text()[2]').extract_first() \
            if response.xpath('//div[@class="inforTxt"]/dl[2]/dd[3]/text()[2]').extract_first() else "-"                    # 房屋类型
        item['uniprice']=response.xpath(u'//span[contains(text(),"元/平米·天")]/../span/text()').extract_first().strip() \
            if response.xpath(u'//span[contains(text(),"元/平米·天")]/../span/text()').extract_first() else "-"         # 租金
        yield item


with open("hightemp.txt") as f:
    line=f.readlines()
    d={}
    for l in line:
        l1=l.split("\t")
        k=l1[0]
        if k in d:
            d[k]+=1
        else:
            d[k]=1
ans=sorted(d.items(), key=lambda x:x[1])
ans.reverse()
[print(ans[i]) for i in range(len(ans))]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from app.database.db_base import DBBase, execute_sql

class MusicDB(DBBase):
    @classmethod
    def add_music(cls, music_id, style, t):
        sql = "INSERT INTO musics (music_id, style, type) VALUES ('%d','%s', %s)" % (music_id, style, t)
        execute_sql(sql, 'insert')

    @classmethod
    def get_music_id_by_random(cls, style, t):
        sql = "SELECT music_id FROM musics WHERE style = '%s' AND type = '%s' ORDER BY RANDOM() limit 1" % (style, t)
        results = execute_sql(sql, 'select')
        return results

    @classmethod
    def get_all_styles(cls):
        sql = "SELECT style FROM musics GROUP BY style"
        results = execute_sql(sql, 'select')
        return results


#!/usr/bin/env python
import sys
import os
import itk
import numpy as np
import glob

outputDir = sys.argv[1]
IdentitySpacing = sys.argv[2]
for patientDirectory in glob.glob(outputDir +'/3D*'):
    print(patientDirectory.rsplit('/')[-1])

    patientPath =  patientDirectory+"/patient.nii"
    liverPath =  patientDirectory+ "/liver.nii"
    venousPath =  patientDirectory+ "/venacava.nii"
    portalPath =  patientDirectory+ "/portal.nii"

    if not os.path.exists( patientDirectory):
        os.makedirs(patientDirectory)

    patientOutPath = patientDirectory+"/patientIso.nii"
    liverOutPath = patientDirectory+ "/liverMaskIso.nii"
    vesselsOutPath = patientDirectory+ "/vesselsIso.nii"
    maskedLiverOutPath = patientDirectory+"/maskedLiverIso.nii"
    bifurcationsOutPath = patientDirectory+"/bifurcationsMaskIso.nii"
    dilatedVesselsMask = patientDirectory + "/dilatedVesselsMaskIso.nii"

    print(patientOutPath)
    print(vesselsOutPath)
    print(liverOutPath)
    print(bifurcationsOutPath)
    print(dilatedVesselsMask)

    # calling external program
    # missing outputs
    commandLine = "./MakeIso " + patientPath + " " + liverPath + " " + venousPath + " " + portalPath + " "
    commandLine += patientOutPath + " " + liverOutPath + " " + vesselsOutPath + " " + dilatedVesselsMask + " " + maskedLiverOutPath  + " " + IdentitySpacing

    print(commandLine)
    os.system(commandLine)

    commandLine = "./MakeIrcadBifurcationGT " + vesselsOutPath + " " + liverOutPath  + " " + bifurcationsOutPath

    #print(commandLine)
    os.system(commandLine)

    bifurcationInPath = patientDirectory+"/bifurcationsMaskIso.nii"
    liverInPath = patientDirectory+ "/liverMaskIso.nii"
    bifurcationsOutPath = "/DATA/ircad_iso/"+patientDirectory.split("/")[3]+"/bifurcationsMaskIso.nii"
    commandLine = "./isoFromUnit " + bifurcationInPath + " " + liverInPath + " " + bifurcationsOutPath

    #print(commandLine)
    os.system(commandLine)


# URLs configuration file for python setup
from django.urls import path
from . import views

urlpatterns = [
    path('before-you-begin', views.beforeyoubegin, name='beforeyoubegin'),
    path('what-to-expect', views.whattoexpect, name='whattoexpect'),
    path('tutorial', views.install_gitbash, name='tutorial'),
    path('did-you-complete', views.didyoucomplete, name='didyoucomplete'),
    path('once-you-complete', views.onceyoucomplete, name='onceyoucomplete'),
]