# survey result count function
def survey_result_count():

    with open("survey-results.txt", "r") as survey_results_output:
        survey_results = survey_results_output.readlines()

    yes_count = 0
    no_count = 0
    maybe_count = 0

    for item in survey_results:
        # count yes
        if item == 'Yes\n' or item == 'Yes':
            yes_count += 1
        # count no
        elif item == 'No\n' or item == 'No':
            no_count += 1
        # count maybe
        elif item == 'Maybe\n' or item == 'Maybe':
            maybe_count += 1

    print(f"Survey Results: Yes({yes_count}), No({no_count}), Maybe({maybe_count})")

# survey result count function
def age_data_count():

    with open("age-data.txt", "r") as age_data_output:
        age_data = age_data_output.readlines()

    under_18 = 0
    from_18_to_35 = 0
    from_36_to_65 = 0
    above_65 = 0
    for item in age_data:
        item = int(item)
        # count under 18
        if item < 18:
            under_18 += 1
        # count 18 to 35
        elif 18 <= item <= 35:
            from_18_to_35 += 1
        # count 36 to 65
        elif 36 <= item <= 65:
            from_36_to_65 += 1
        # count above 65
        else:
            above_65 += 1

    print(f"Age Results: under 18({under_18}), 18-35({from_18_to_35}), 36-65({from_36_to_65}), above 65({above_65})")

# survey result count function
def number_data_count():

    with open("number-data.txt", "r") as number_data_output:
        number_data = number_data_output.readlines()

    odd_count = 0
    even_count = 0

    for item in number_data:
        item = int(item)
        # count even
        if (item % 2) == 0:
            even_count += 1
        # count odd
        else:
            odd_count += 1

    print(f"Number Results: Even({even_count}), Odd({odd_count})")

# run function
survey_result_count()
age_data_count()
number_data_count()


import time
from functools import wraps

def measure_it(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # measure execution time for method
        s = time.time()
        res = func(*args, **kwargs)
        print("{} -> took {} seconds".format(func.__name__, time.time() - s))
        return res

    return wrapper


from django.urls import re_path
from django.views.generic import TemplateView

from . import views
from quartet_masterdata.routers import router

urlpatterns = [
    re_path(
        "^location-by-identifier/(?P<identifier>[[\w\s\W]{1,150})/$",
        view=views.LocationByIdentifierView.as_view(),
        name="location-by-identifier",
    ),
    re_path(
        "^entry-geohistory-by-epc/(?P<epc>[[\w\s\W]{1,150})/$",
        view=views.EntryGeoHistoryView.as_view(),
        name="entry-geohistory-by-epc",
    ),
    re_path(
        "^get-company-prefix-length/(?P<barcode>[[\w\s\W]{1,18})/$",
        view=views.GetCompanyPrefixLength.as_view(),
        name="get-company-prefix-length",
    ),
]
urlpatterns += router.urls


from project_app.views import *
from django.urls import path
from django.urls import path, include
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'login',UserViewSet,basename="login")
router.register(r'projects',ProjectViewSet,basename="project")
router.register(r'lists',ListViewSet,basename="list")
router.register(r'cards',CardViewSet,basename="card")
router.register(r'comments',CommentViewSet,basename="comment")
urlpatterns = router.urls
urlpatterns = [
    path('', include(router.urls)),
    path('get_oauth_token/', new_token),
    path('send_token_request/', login_redirect),
    path('logout_user/', logout_user),
    path('projects/create/',create_project),
    path('create_list/',create_list),
    path('create_card/',create_card),
    path('create_comment/',create_comment),
    path('create_project/',create_project),
    path('add_members/<int:project_id>/', addMember, name='add_members'),
    path('get_project_by_name/', get_project_by_name, name='get_project_by_name'),
    path('users/disable/', UserViewSet.as_view({'post': 'disable_user'}), name='disable-user'),
    path('users/change_user_role/', UserViewSet.as_view({'post': 'change_user_role'}), name='change_user_role'),

]


import json
from flask import Response, Blueprint
from flask_jwt_extended import jwt_required, get_jwt_identity
from util.db import db

XXX_bp = Blueprint('XXX', __name__)

@XXX_bp.route('/', methods=['GET'])
@jwt_required()
def func():
    try:
        output = {}
        response = {}

        output['success'] = True
        output['response'] = response

    except Exception as e:
        output['success'] = False
        output['error_message'] = 'Internal Server Error'
        return Response(json.dumps(output), mimetype='application/json', status=500)
    return Response(json.dumps(output), mimetype='application/json', status=200)


import array
arr=[]
count=[]
n= int(input("Enter size of array "))
for x in range(n):
    count.append(0)
    x=int(input("Enter The arry: "))
    arr.append(x)
print("Array elemet remov duplicate")
for x in range(n):
    count[arr[x]]=count[arr[x]]+1
    if count[arr[x]]==1:
        print(arr[x])


from ventures_tree import Link, find_venture

links = [
    Link("Root", "Hellofresh UK"),
    Link("Root", "Hellofresh US"),
    Link("Hellofresh UK", "account1"),
    Link("Hellofresh UK", "account2"),
    Link("Hellofresh US", "account3"),
    Link("account3", "account4"),
    Link("account4", "account5"),
    Link("account5", "account6"),
]

if __name__ == "__main__":
    print(find_venture(links, "account5"))
    print(find_venture(links, "account2"))


from te import tvm
from te.platform.cce_params import VEC
from te.platform.cce_params import AIC
from te.platform.cce_params import ASCEND_910
from te.platform.cce_params import ASCEND_910AIC
from te.platform.cce_params import HI3796CV300ESAIC
from te.platform.cce_params import HI3796CV300CSAIC
from te.platform.cce_params import ASCEND_610
from te.platform.cce_params import ASCEND_620
from te.platform.cce_conf import api_check_support
from .tik_expr import Expr
from ..api.tik_scalar import Scalar
from .. import debug
from .tik_util import type_convert
from ..api.tik_ir_builder import TikIRBuilder
from .tik_params import MAX_ATOMIC_ADD_MODE, ATOMIC_ADD_MODE_SHIFT_POS,\
    MAX_SMALL_CHANNEL_MODE, SMALL_CHANNEL_ENABLE_SHIFT_POS, FP2INT_SHIFT_POS, \
    MAX_SYSTEM_CACHE_MODE, SYSTEM_CACHE_MODE_SHIFT_POS, MAX_FP2INT_MODE, \
    MAX_TWO_BITS_VALUE, MAX_ONE_BIT_VALUE, ATOMIC_ADD_MASK, \
    SMALL_CHANNEL_MASK, SYSTEM_CACHE_MASK, FP2INT_MASK, ONE_IR, \
    INSTR_DTYPE_SUPPORT_STATEMENT
from .tik_check_util import TikCheckUtil
from .tik_source_info import source_info_decorator
from ..common.tik_get_soc_name import get_soc_name
from ..common.tik_get_soc_name import get_soc_core_type
_MAX_OVERFLOW_STATUS = 2

class TikSysControlApi(TikIRBuilder):
    """
    Proposal Operation Api
    """
    def __init__(self):
        super(TikSysControlApi, self).__init__()

    def _mov_ctrl_spr_to_scalar(self):
        """mov all bits of CTRL register to scalar

        Parameters
        ----------
        Returns
        -------
        ctrl : CTRL register
        """
        # disable it because calls subclass method
        ctrl = self.Scalar_(dtype="uint64")  # pylint: disable=E1101
        with self.new_scope():
            self.emit(
                tvm.call_extern(ctrl.dtype, "reg_set", ctrl.get(),
                                tvm.call_extern(ctrl.dtype, "get_ctrl")),
                ONE_IR)
        return ctrl

    @source_info_decorator()
    @debug.get_ctrl_bits(ATOMIC_ADD_MODE_SHIFT_POS,
                         ATOMIC_ADD_MODE_SHIFT_POS + 2)
    def mov_atomic_add_to_scalar(self, scalar):
        """mov the atomic_add bits of CTRL register to scalar

        Parameters
        ----------
        scalar : destination scalar operation

        Returns
        -------
        scalar : scalar with the atomic_add bits
        """
        TikCheckUtil.check_equality(
            get_soc_name(), ASCEND_910,
            "this api doesn't support version: %s" % get_soc_name())
        TikCheckUtil.check_type_match(
            scalar, Scalar, "input scalar should be Scalar")
        TikCheckUtil.check_equality(
            scalar.dtype, "uint64", "scalar must be uint64")
        ctrl = self._mov_ctrl_spr_to_scalar()
        ctrl.set_as(ctrl & (MAX_TWO_BITS_VALUE << ATOMIC_ADD_MODE_SHIFT_POS))
        ctrl.set_as(ctrl >> ATOMIC_ADD_MODE_SHIFT_POS)
        scalar.set_as(ctrl)
        return scalar

    @source_info_decorator()
    @debug.get_ctrl_bits(SMALL_CHANNEL_ENABLE_SHIFT_POS)
    def mov_small_channel_to_scalar(self, scalar):
        """mov the small_channel bits of CTRL register to scalar

        Parameters
        ----------
        scalar : destination scalar operation

        Returns
        -------
        scalar : scalar with the small_channel bits
        """
        TikCheckUtil.check_equality(
            get_soc_name(), ASCEND_910,
            "this api doesn't support version: %s" % get_soc_name())
        TikCheckUtil.check_type_match(
            scalar, Scalar, "input scalar should be Scalar")
        TikCheckUtil.check_equality(
            scalar.dtype, "uint64", "scalar must be uint64")
        ctrl = self._mov_ctrl_spr_to_scalar()
        ctrl.set_as(ctrl & (MAX_ONE_BIT_VALUE <<
                            SMALL_CHANNEL_ENABLE_SHIFT_POS))
        ctrl.set_as(ctrl >> SMALL_CHANNEL_ENABLE_SHIFT_POS)
        scalar.set_as(ctrl)
        return scalar

    @source_info_decorator()
    @debug.get_ctrl_bits(SYSTEM_CACHE_MODE_SHIFT_POS,
                         SYSTEM_CACHE_MODE_SHIFT_POS + 2)
    def mov_system_cache_to_scalar(self, scalar):
        """mov the system_cache bits of CTRL register to scalar

        Parameters
        ----------
        scalar : destination scalar operation

        Returns
        -------
        scalar : scalar with the system_cache bits
        """
        TikCheckUtil.check_equality(
            get_soc_name(), ASCEND_910,
            "this api doesn't support version: %s" % get_soc_name())
        TikCheckUtil.check_type_match(
            scalar, Scalar, "input scalar should be Scalar")
        TikCheckUtil.check_equality(
            scalar.dtype, "uint64", "scalar must be uint64")
        ctrl = self._mov_ctrl_spr_to_scalar()
        ctrl.set_as(ctrl & (MAX_TWO_BITS_VALUE <<
                            SYSTEM_CACHE_MODE_SHIFT_POS))
        ctrl.set_as(ctrl >> SYSTEM_CACHE_MODE_SHIFT_POS)
        scalar.set_as(ctrl)
        return scalar

    @source_info_decorator()
    @debug.get_ctrl_bits(FP2INT_SHIFT_POS)
    def mov_fp2int_mode_to_scalar(self, scalar):
        """mov the fp2int_mode bits of CTRL register to scalar

        Parameters
        ----------
        scalar : destination scalar operation

        Returns
        -------
        scalar : scalar with the fp2int_mode bits
        """
        TikCheckUtil.check_equality(
            get_soc_name(), ASCEND_910,
            "this api doesn't support version: %s" % get_soc_name())
        TikCheckUtil.check_type_match(
            scalar, Scalar, "input scalar should be Scalar")
        TikCheckUtil.check_equality(
            scalar.dtype, "uint64", "scalar must be uint64")
        ctrl = self._mov_ctrl_spr_to_scalar()
        ctrl.set_as(ctrl & (MAX_ONE_BIT_VALUE << FP2INT_SHIFT_POS))
        ctrl.set_as(ctrl >> FP2INT_SHIFT_POS)
        scalar.set_as(ctrl)
        return scalar

    @source_info_decorator()
    @debug.set_ctrl_bits(ATOMIC_ADD_MODE_SHIFT_POS,
                         ATOMIC_ADD_MODE_SHIFT_POS + 2)
    def set_atomic_add(self, mode):
        """set mode to the atomic_add bits of CTRL register

        Parameters
        ----------
        mode : atomic add mode, 0 - disable, 1 - float32, 2 - float16

        Returns
        -------
        None
        """
        arch_version_mode = {ASCEND_910: (0, 1),
                             ASCEND_610: (0, 1, 2, 3),
                             ASCEND_620: (0, 1, 2, 3)}
        TikCheckUtil.check_type_match(
            mode, (int, Scalar), "mode should be int or Scalar")
        TikCheckUtil.check_equality(api_check_support("tik." +
                                                      "set_atomic_add",
                                                      ""), True,
                                    INSTR_DTYPE_SUPPORT_STATEMENT.
                                    format("", "set_atomic_add"))
        if isinstance(mode, int):
            TikCheckUtil.check_in_range(
                mode, arch_version_mode[get_soc_name()],
                "mode should be in the range of %s, input mode: %s" % (
                    arch_version_mode[get_soc_name()], mode))
        if isinstance(mode, Scalar):
            TikCheckUtil.check_equality(
                mode.dtype, "uint64",
                "scalar_mode should be a scalar of uint64")
        ctrl = self._mov_ctrl_spr_to_scalar()
        ctrl.set_as(ctrl & ATOMIC_ADD_MASK)
        ctrl.set_as(ctrl | (mode << ATOMIC_ADD_MODE_SHIFT_POS))

        with self.new_scope():
            self.emit(tvm.call_extern("uint64", "set_ctrl", ctrl.get()),
                      ONE_IR)

    @source_info_decorator()
    @debug.set_ctrl_bits(SMALL_CHANNEL_ENABLE_SHIFT_POS)
    def set_small_channel(self, enable):
        """set enable mode to the small_channel bit of CTRL register

        Parameters
        ----------
        enable : small_channel mode, 0 - disable, 1 - enable

        Returns
        -------
        None
        """
        TikCheckUtil.check_type_match(
            enable, (int, Scalar), "enable should be int or Scalar")
        TikCheckUtil.check_equality(
            get_soc_name(), ASCEND_910,
            "this api doesn't support version: %s" % get_soc_name())
        if isinstance(enable, int):
            TikCheckUtil.check_in_range(enable, range(MAX_SMALL_CHANNEL_MODE),
                                        "enable should be 0 or 1")
        if isinstance(enable, Scalar):
            TikCheckUtil.check_equality(
                enable.dtype, "uint64",
                "scalar_enable should be a scalar of uint64")
        ctrl = self._mov_ctrl_spr_to_scalar()
        ctrl.set_as(ctrl & SMALL_CHANNEL_MASK)
        ctrl.set_as(ctrl | (enable << SMALL_CHANNEL_ENABLE_SHIFT_POS))
        with self.new_scope():
            self.emit(tvm.call_extern("uint64", "set_ctrl", ctrl.get()),
                      ONE_IR)

    @source_info_decorator()
    @debug.set_ctrl_bits(SYSTEM_CACHE_MODE_SHIFT_POS,
                         SYSTEM_CACHE_MODE_SHIFT_POS + 2)
    def set_system_cache(self, mode):
        """set mode to the system_cache bits of CTRL register

        Parameters
        ----------
        mode : system_cache mode, 0 - Normalread, 1 - ReadLast,
               2 - ReadInvalid, 3 - NotNeedWriteBack

        Returns
        -------
        None
        """
        TikCheckUtil.check_equality(
            get_soc_name(), ASCEND_910,
            "this api doesn't support version: %s" % get_soc_name())
        TikCheckUtil.check_type_match(
            mode, (int, Scalar), "mode should be int or Scalar")
        if isinstance(mode, int):
            TikCheckUtil.check_in_range(
                mode, range(MAX_SYSTEM_CACHE_MODE),
                "mode should be in the range of [0, 3]")
        if isinstance(mode, Scalar):
            TikCheckUtil.check_equality(
                mode.dtype, "uint64",
                "scalar_mode should be a scalar of uint64")
        ctrl = self._mov_ctrl_spr_to_scalar()
        ctrl.set_as(ctrl & SYSTEM_CACHE_MASK)
        ctrl.set_as(ctrl | (mode << SYSTEM_CACHE_MODE_SHIFT_POS))
        with self.new_scope():
            self.emit(tvm.call_extern("uint64", "set_ctrl", ctrl.get()),
                      ONE_IR)

    @source_info_decorator()
    @debug.set_ctrl_bits(FP2INT_SHIFT_POS)
    def set_fp2int_mode(self, mode):
        """set mode to the fp2int_mode bit of CTRL register

        Parameters
        ----------
        mode : fp2int_mode mode, 0 - Saturated, 1 - Truncted

        Returns
        -------
        None
        """
        TikCheckUtil.check_equality(
            get_soc_name(), ASCEND_910,
            "this api doesn't support version: %s" % get_soc_name())
        TikCheckUtil.check_type_match(
            mode, (int, Scalar), "mode should be int or Scalar")
        if isinstance(mode, int):
            TikCheckUtil.check_in_range(
                mode, range(MAX_FP2INT_MODE), "mode should be 0 or 1")
        if isinstance(mode, Scalar):
            TikCheckUtil.check_equality(
                mode.dtype, "uint64",
                "scalar_mode should be a scalar of uint64")
        ctrl = self._mov_ctrl_spr_to_scalar()
        ctrl.set_as(ctrl & FP2INT_MASK)
        ctrl.set_as(ctrl | (mode << FP2INT_SHIFT_POS))
        with self.new_scope():
            self.emit(tvm.call_extern("uint64", "set_ctrl", ctrl.get()),
                      ONE_IR)

    @source_info_decorator()
    def instr_preload(self, icache_base_addr, instr_num):
        """
            instr_num must be multiple of 128/4=32
        """
        # disable it because pylint can't recognize symbols from back-end
        arch_version_str = get_soc_name() + get_soc_core_type()
        TikCheckUtil.check_in_range(
            arch_version_str, [ASCEND_910AIC, AIC, VEC, HI3796CV300ESAIC,
                               HI3796CV300CSAIC],
            "%s doesn't support instr_preload." % (arch_version_str))
        TikCheckUtil.check_type_match(
            instr_num, (int, Scalar, Expr),
            "instr_num should be int, Scalar or Expr")
        from .tik_params import INSTR_UNIT, CACHE_LINE_SIZE
        if isinstance(instr_num, int):
            TikCheckUtil.check_equality(instr_num % INSTR_UNIT, 0,
                                        "instr_num must be multiple of 32.")
        with self.new_scope():
            with self.context.freeze():  # pylint: disable=E1101
                icache_addr = self.Scalar_("uint64")  # pylint: disable=E1101
                with self.for_range_(0, instr_num // INSTR_UNIT) as i:
                    icache_addr.set_as(icache_base_addr + i*CACHE_LINE_SIZE)
                    self.emit(
                        tvm.call_extern("uint64", "preload",
                                        icache_addr.get()), ONE_IR)

    @source_info_decorator()
    def get_overflow_status(self, status):
        """get overflow status stored in scalar buffer

        Parameters
        ----------
        status : destination scalar operation

        Returns
        -------
        None
        """
        TikCheckUtil.check_equality(
            get_soc_name(), ASCEND_910,
            "this api doesn't support version: %s" % get_soc_name())
        TikCheckUtil.check_type_match(
            status, Scalar, "variable should be Scalar, invalid type "
                            "for status: {}".format(type(status)))
        TikCheckUtil.check_equality(
            status.dtype, "uint64",
            "variable should be a Scalar of uint64, invalid "
            "dtype for status: {}".format(status.dtype))
        with self.new_scope():
            # overflow status is stored on scalar buffer, the address is 0x40000
            self.emit(
                tvm.call_extern("uint64_t", "reg_set",
                                status.get(),
                                tvm.call_pure_intrin(
                                    "uint64", "tvm_cce_string_print",
                                    "*(uint64_t *) 0x40000")),
                ONE_IR)

    @source_info_decorator()
    def set_overflow_status(self, value):
        """set overflow status to scalar buffer

        Parameters
        ----------
        value : overflow status

        Returns
        -------
        None
        """
        TikCheckUtil.check_equality(
            get_soc_name(), ASCEND_910,
            "this api doesn't support version: %s" % get_soc_name())
        TikCheckUtil.check_type_match(
            value, int, "value should be Int, "
                        "invalid type: {}".format(type(value)))
        TikCheckUtil.check_in_range(
            value, range(_MAX_OVERFLOW_STATUS),
            "value should be 0 or 1, invalid value: {}".format(value))
        with self.new_scope():
            self.emit(
                tvm.call_extern("uint64_t", "set_overflow",
                                type_convert(Expr(value, dtype="uint64"))),
                ONE_IR)


#
# @lc app=leetcode.cn id=36 lang=python3
#
# [36] 有效的数独
#

# @lc code=start
from collections import defaultdict
class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        m = len(board)
        n = len(board[0])
        col_dict=defaultdict(set)
        row_dict=defaultdict(set)
        region_dict=defaultdict(set)
        for i in range(m):
            for j in range(n):
                value = board[i][j]
                if value=='.':
                    continue
                if value not in col_dict:
                    col_dict[value].add(i)
                else:
                    if i in col_dict[value]:
                        return False
                    else:
                        col_dict[value].add(i)
                if value not in row_dict:
                    row_dict[value].add(j)
                else:
                    if j in row_dict[value]:
                        return False
                    else:
                        row_dict[value].add(j)
                region_idx = (i//3)*3+j//3
                if value not in region_dict:
                    region_dict[value].add(region_idx)
                else:
                    if region_idx in region_dict[value]:
                        return False
                    else:
                        region_dict[value].add(region_idx)
        return True

# @lc code=end


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

import datetime
from datetime import datetime
import pytz
from odoo import models,fields
from datetime import datetime, timedelta
from time import mktime

class as_invoices_emit_excel(models.AbstractModel):
    _name = 'report.l10n_cl_tichile_reports.invoices_emit_report_xls.xlsx'
    _inherit = 'report.report_xlsx.abstract'

    def generate_xlsx_report(self, workbook, data, lines):

        consulta = ("""
            SELECT
            to_char(((ai.fecha_boliviana AT TIME ZONE 'UTC' AT TIME ZONE 'BOT')::timestamp),'DD/MM/YYYY') AS fecha_nota,
                    """)
        moduleObj = self.env['ir.module.module'].sudo().search([("name","=","as_sales"),("state","=","installed")])
        if data['form']['as_tipo']=='ventas':
            if moduleObj:
                consulta += "so.as_numeracion_interna AS numero_nota,"
            else:
                consulta += "so.name AS numero_nota,"
        else:
            consulta += "ai.name AS numero_nota,"
        if data['form']['as_tipo']=='ventas':
            consulta += ("""
                ai.id,
                ai.as_nit AS nit_cliente,
                ai.as_razon_social AS nombre_cliente,
                ewqc.numero_autorizacion AS numero_autorizacion,
                ai.control_code AS codigo_control,
            CASE
                WHEN rc.NAME = 'BOB'
                OR rc.symbol = 'Bs.' THEN
                ROUND( ai.amount_total, 4 ) ELSE ai.amount_total
                END AS importe_neto_venta,
                ROUND( ai.amount_total, 4 ) AS importe_neto_factura,
                ai.invoice_number AS numero_factura,
                to_char((( ai.fecha_boliviana AT TIME ZONE'UTC' AT TIME ZONE'BOT' ) :: TIMESTAMP ), 'DD/MM/YYYY' ) AS fecha_factura,
                asesor.NAME AS nombre_asesor,
                ROUND( ai.amount_total, 4 ) AS impote_bruto_fact,
                ROUND( ai.amount_total, 4 ) AS total_descuento_fact,
                ai.fecha_boliviana AS fecha_factura2,
                fp.name AS tipo_venta
            FROM
                account_invoice ai
                JOIN sale_order so ON so.NAME = ai.origin
                JOIN res_partner AS cliente ON cliente.ID = so.partner_id
                JOIN res_users AS usuario ON usuario.ID = so.user_id
                JOIN res_partner AS asesor ON asesor.ID = usuario.partner_id
                JOIN qr_code AS ewqc ON ewqc.ID = ai.qr_code_id
                JOIN product_pricelist pp ON pp.ID = so.pricelist_id
                JOIN res_currency rc ON rc.ID = pp.currency_id
                JOIN as_metodo_pago_ventas fp ON fp.id = so.as_forma_pago_id
            WHERE
                ai.TYPE = 'out_invoice'
                AND ai.STATE NOT IN ( 'draft', 'cancel' )
                AND ai.order_status = 'valida'
                AND ai.invoice_number != 0
                AND ai.type = 'out_invoice'
            """)
        elif data['form']['as_tipo']=='pos':
            consulta += ("""
                ai.id,
                ai.as_nit AS nit_cliente,
                ai.as_razon_social AS nombre_cliente,
                ewqc.numero_autorizacion AS numero_autorizacion,
                ai.control_code AS codigo_control,
            CASE
                WHEN rc.NAME = 'BOB'
                OR rc.symbol = 'Bs.' THEN
                ROUND( ai.amount_total, 4 ) ELSE ai.amount_total
                END AS importe_neto_venta,
                ROUND( ai.amount_total, 4 ) AS importe_neto_factura,
                ai.invoice_number AS numero_factura,
                to_char((( ai.fecha_boliviana AT TIME ZONE'UTC' AT TIME ZONE'BOT' ) :: TIMESTAMP ), 'DD/MM/YYYY' ) AS fecha_factura,
                asesor.NAME AS nombre_asesor,
                ROUND( ai.amount_total, 4 ) AS impote_bruto_fact,
                ROUND( ai.amount_total, 4 ) AS total_descuento_fact,
                ai.fecha_boliviana AS fecha_factura2,
                'N/A'
            FROM
                account_invoice ai
                JOIN pos_order so ON so.NAME = ai.origin
                JOIN res_partner AS cliente ON cliente.ID = so.partner_id
                JOIN res_users AS usuario ON usuario.ID = so.user_id
                JOIN res_partner AS asesor ON asesor.ID = usuario.partner_id
                JOIN qr_code AS ewqc ON ewqc.ID = ai.qr_code_id
                JOIN product_pricelist pp ON pp.ID = so.pricelist_id
                JOIN res_currency rc ON rc.ID = pp.currency_id
            WHERE
                ai.TYPE = 'out_invoice'
                AND ai.STATE NOT IN ( 'draft', 'cancel' )
                AND ai.order_status = 'valida'
                AND ai.invoice_number != 0
                AND ai.type = 'out_invoice'
            """)
        else:
            consulta += ("""
                ai.id,
                ai.as_nit AS nit_cliente,
                ai.as_razon_social AS nombre_cliente,
                ewqc.numero_autorizacion AS numero_autorizacion,
                ai.control_code AS codigo_control,
            CASE
                WHEN rc.NAME = 'BOB'
                OR rc.symbol = 'Bs.' THEN
                ROUND( ai.amount_total, 4 ) ELSE ai.amount_total
                END AS importe_neto_venta,
                ROUND( ai.amount_total, 4 ) AS importe_neto_factura,
                ai.invoice_number AS numero_factura,
                to_char((( ai.fecha_boliviana AT TIME ZONE'UTC' AT TIME ZONE'BOT' ) :: TIMESTAMP ), 'DD/MM/YYYY' ) AS fecha_factura,
                asesor.NAME AS nombre_asesor,
                ROUND( ai.amount_total, 4 ) AS impote_bruto_fact,
                ROUND( ai.amount_total, 4 ) AS total_descuento_fact,
                ai.fecha_boliviana AS fecha_factura2,
                'N/A'
            FROM
                account_invoice ai
                JOIN res_partner AS cliente ON cliente.ID = ai.partner_id
                JOIN res_users AS usuario ON usuario.ID = ai.user_id
                JOIN res_partner AS asesor ON asesor.ID = usuario.partner_id
                JOIN qr_code AS ewqc ON ewqc.ID = ai.qr_code_id
                JOIN res_currency rc ON rc.ID = ai.currency_id
            WHERE
                ai.TYPE = 'out_invoice'
                AND ai.STATE NOT IN ( 'draft', 'cancel' )
                AND ai.order_status = 'valida'
                AND ai.invoice_number != 0
                AND ai.type = 'out_invoice'
            """)

        if data['form']['asesor']:
            consulta += " AND usuario.id = " + str(data['form']['asesor'])
        if data['form']['nombre_cliente']:
            consulta += " AND cliente.id = " + str(data['form']['nombre_cliente'])
        if data['form']['fecha_final']:
            consulta +=  " AND ai.fecha_boliviana BETWEEN '" + str(data['form']['fecha_inicial']) + "' AND '" + str(data['form']['fecha_final'])+ "'"

        #Definiciones generales del archivo, formatos, titulos, hojas de trabajo
        sheet = workbook.add_worksheet('Detalle de Movimientos')
        titulo1 = workbook.add_format({'font_size': 16,'font_name': 'Lucida Sans', 'align': 'center', 'bold':True,'bg_color': '#ffffff'})
        titulo2 = workbook.add_format({'font_size': 10, 'align': 'center', 'bold':True })
        titulo3 = workbook.add_format({'font_size': 9, 'align': 'left', 'bold':True })
        titulo3_number = workbook.add_format({'font_size': 10, 'align': 'right', 'bold':True, 'num_format': '#,##0.00' })
        titulo4 = workbook.add_format({'font_size': 11, 'font_name': 'Lucida Sans','align': 'center','bg_color': '#ffffff', 'bold':True })
        titulo10 = workbook.add_format({'font_size': 10, 'align': 'right','bg_color': '#ffffff', 'bold':True })
        titulo5 = workbook.add_format({'font_size': 10, 'align': 'center', 'right': False, 'bold':False })
        titulo9 = workbook.add_format({'font_size': 10, 'align': 'right', 'right': False, 'bold':False })
        titulo6 = workbook.add_format({'font_size': 10, 'align': 'center', 'right': False, 'bold':False, 'color': 'red'})
        titulo12 = workbook.add_format({'font_size': 10, 'align': 'right', 'right': False, 'bold':False, 'color': 'red'})
        titulo7 = workbook.add_format({'font_size': 10, 'align': 'left', 'right': False, 'bold':False})
        titulo8 = workbook.add_format({'font_size': 10, 'align': 'right', 'right': False, 'bold':False})

        number_left = workbook.add_format({'font_size': 9, 'align': 'left', 'num_format': '#,##0.00','bg_color': '#ffffff'})
        number_right = workbook.add_format({'font_size': 9, 'align': 'right', 'num_format': '#,##0.00','bg_color': '#ffffff'})
        number_right_bold = workbook.add_format({'font_size': 9, 'align': 'right', 'num_format': '#,##0.00', 'bold':True,'bg_color': '#ffffff'})
        number_right_col = workbook.add_format({'font_size': 9, 'align': 'right', 'num_format': '#,##0.00','bg_color': 'silver'})
        number_center = workbook.add_format({'font_size': 9, 'align': 'center', 'num_format': '#,##0.00','bg_color': '#ffffff'})
        number_right_col.set_locked(False)

        letter1 = workbook.add_format({'font_size': 9, 'align': 'left','bg_color': '#ffffff'})
        letter2 = workbook.add_format({'font_size': 9, 'align': 'left', 'bold':True,'bg_color': '#ffffff'})
        letter3 = workbook.add_format({'font_size': 9, 'align': 'right','font_size': 11,'font_name': 'Lucida Sans','bg_color': '#ffffff'})
        letter4 = workbook.add_format({'font_size': 9, 'align': 'left', 'bold': True,'bg_color': '#ffffff'})
        letter4C = workbook.add_format({'font_size': 9, 'align': 'left', 'bold': True,'color':'#000000','font_name': 'Lucida Sans','bg_color': '#ffffff' })
        letter4F = workbook.add_format({'font_size': 9, 'align': 'left', 'bold': True,'color': '#000000','bg_color': '#ffffff','font_name': 'Lucida Sans',})
        letter4G = workbook.add_format({'font_size': 9, 'align': 'left', 'bold': True,'color': '#000000','bg_color': '#f0f0f0','font_name': 'Lucida Sans',})
        letter4G2 = workbook.add_format({'font_size': 9, 'align': 'left', 'bold': True,'color': '#000000','bg_color': '#FFFAF0','font_name': 'Lucida Sans',})
        letter4S = workbook.add_format({'font_size': 9, 'align': 'left', 'bold': True,'bg_color': '#ffffff'})
        letter4S_right = workbook.add_format({'font_size': 9, 'align': 'right', 'bold': True,'bg_color': '#ffffff','num_format': '#,##0.00',})
        letter41S = workbook.add_format({'font_size': 9, 'align': 'left','bg_color': '#ffffff'})
        letter41Si = workbook.add_format({'font_size': 9, 'align': 'right','bg_color': '#ffffff'})
        letter41Sr = workbook.add_format({'font_size': 9, 'align': 'left','color': 'red','bg_color': '#ffffff'})
        letter_locked = letter3
        letter_locked.set_locked(False)

        # Aqui definimos en los anchos de columna
        sheet.set_column('A:A',15, letter1)
        sheet.set_column('B:B',15, letter1)
        sheet.set_column('C:C',15, letter1)
        sheet.set_column('D:D',18, letter1)
        sheet.set_column('E:E',15, letter1)
        sheet.set_column('F:F',15, letter1)
        sheet.set_column('G:G',15, letter3)
        sheet.set_column('H:H',15, letter3)
        sheet.set_column('I:I',15, letter3)
        sheet.set_column('J:J',15, number_center)
        sheet.set_column('K:K',18, letter1)
        sheet.set_column('L:L',18, letter1)
        sheet.set_column('M:M',18, letter1)

        # Titulos, subtitulos, filtros y campos del reporte
        sheet.merge_range('A1:M1', 'FACTURAS EMITIDAS', titulo1)
        sheet.set_row(0, 40)
        fecha = (datetime.now() - timedelta(hours=4)).strftime('%d/%m/%Y %H:%M:%S')
        fecha_inicial = datetime.strptime(data['form']['fecha_inicial'], '%Y-%m-%d').strftime('%d/%m/%Y')
        fecha_final = datetime.strptime(data['form']['fecha_final'], '%Y-%m-%d').strftime('%d/%m/%Y')
        sheet.write(1, 0, 'Rango de Fechas: ', letter4)
        sheet.merge_range('B2:D2', fecha_inicial +' - '+ fecha_final)
        sheet.merge_range('H3:I3', 'Fecha impresion: ', letter5)
        sheet.merge_range('J3:M3', fecha)
        sheet.merge_range('H4:I4', 'Usuario: ', letter5)
        sheet.merge_range('J4:M4', self.env.user.name)

        sheet.write(4, 0,'FECHA', letter4)
        sheet.write(4, 1,'NUMERACION INTERNA', letter4)
        sheet.write(4, 2,'NIT CLIENTE', letter4)
        sheet.write(4, 3,'RAZON SOCIAL', letter4)
        sheet.write(4, 4,'No AUTORIZACION', letter4)
        sheet.write(4, 5, 'CODIGO DE CONTROL', letter4)
        sheet.write(4, 6, 'IMPORTE BRUTO DE FACTURA AL CREDITO BS.', letter4)
        sheet.write(4, 7, 'DESCUENTO CREDITO BS.', letter4)
        sheet.write(4, 8, 'IMPORTE NETO DE FACTURA CREDITO BS.', letter4)
        sheet.write(4, 9, 'No FACTURA', letter4)
        sheet.write(4, 10, 'FECHA FACTURA', letter4)
        sheet.write(4, 11, 'COMERCIAL', letter4)
        sheet.write(4, 12, 'FORMA DE PAGO', letter4)
        sheet.freeze_panes(5, 0)
        sheet.set_row(4, 40)
        self.env.cr.execute(consulta)
        invoices = [j for j in self.env.cr.fetchall()]
        filas=5
        cols=0
        total_bruto=0
        total_descuento=0
        total_neto=0
        cols=0
        for invoice in invoices:
            sheet.write(filas, 0, invoice[0]) #fecha
            sheet.write(filas, 1, invoice[1]) #numeracion interna
            sheet.write(filas, 2, invoice[3]) #nit cliente
            sheet.write(filas, 3, invoice[4]) #razon social
            sheet.write(filas, 4, invoice[5]) #numero autorizacion
            sheet.write(filas, 5, invoice[6]) #codigo control
            sheet.write(filas, 6, round(self.amount_bruto(invoice[2],),6)) #importe bruto
            total_bruto+= self.amount_bruto(invoice[2])
            sheet.write(filas, 7, round(self.amount_discount(invoice[2],),6)) #descuento
            total_descuento += self.amount_discount(invoice[2])
            sheet.write(filas, 8, invoice[8],) #importe neto
            total_neto +=invoice[8]
            sheet.write(filas, 9, invoice[9]) #numero de factura
            sheet.write(filas, 10, invoice[10]) #fecha factura
            sheet.write(filas, 11, invoice[11]) #comercial
            sheet.write(filas, 12, invoice[15]) #forma de pago
            filas+=1
        coltotal= 'A'+str(filas+1)+':'+'F'+str(filas+1)
        sheet.merge_range(coltotal, 'TOTALES',letter5) #fecha
        sheet.write(filas, 6, total_bruto,letter5) #importe neto
        sheet.write(filas, 7, total_descuento,letter5) #importe neto
        sheet.write(filas, 8, total_neto,letter5) #importe neto

    def amount_bruto(self,invoice_id):
        invoices_line = self.env['account.invoice.line'].sudo().search([('invoice_id', '=', invoice_id)])
        monto=0.00
        for line in invoices_line:
            monto += (line.price_unit * line.quantity)
        return monto

    def amount_discount(self,invoice_id):
        invoices_line = self.env['account.invoice.line'].sudo().search([('invoice_id', '=', invoice_id)])
        monto=0.00
        monto_discount=0.00
        for line in invoices_line:
            if line.discount > 0.00:
                monto = (line.price_unit * line.quantity)
                monto_discount += (monto*line.discount)/100
        return monto_discount


from hashlib import sha256
import PyPDF2
import json
from datetime import datetime
class Block:
    def __init__(self, index, previous_hash, current_transactions,
timestamp, nonce):
     self.index = index
     self.previous_hash = previous_hash
     self.current_transactions = current_transactions
     self.timestamp = timestamp
     self.nonce = nonce
     self.hash = self.compute_hash()
    def compute_hash(self):
     block_string = json.dumps(self.__dict__, sort_keys=True)
     first_hash = sha256(block_string.encode()).hexdigest()
     second_hash = sha256(first_hash.encode()).hexdigest()
     return second_hash
    def __str__(self):
     return str(self.__dict__)
class BlockChain:
    def __init__(self):
     self.chain = []
     self.transactions = []
     self.genesis_block()
    def __str__(self):
     return str(self.__dict__)
    def genesis_block(self):
     genesis_block = Block('Genesis', 0x0, [3, 4, 5, 6, 7],
    'datetime.now().timestamp()', 0)
     genesis_block.hash = genesis_block.compute_hash()
     self.chain.append(genesis_block.hash)
     self.transactions.append(str(genesis_block.__dict__))
    def getLastBlock(self):
        return self.chain[-1]
    def proof_of_work(self, block: Block):
        difficulty = 1

        block.nonce = 0
        computed_hash = block.compute_hash()
        while not (computed_hash.endswith('0' * difficulty) and ('34' *
      difficulty) in computed_hash):
            block.nonce += 1
            computed_hash = block.compute_hash()
        return computed_hash
    def add(self, data):
        block = Block(len(self.chain), self.chain[-1], data,
'datetime.now().timestamp()', 0)
        block.hash = self.proof_of_work(block)
        self.chain.append(block.hash)
        self.transactions.append(block.__dict__)
        return json.loads(str(block.__dict__).replace('\'', '\"'))
    def getTransactions(self, id):
        labels = ['Ogrenci', 'Ogretmen']
        while True:
            try:
                if id == 'all':
                    for i in range(len(self.transactions) - 1):
                        print('{}:\n{}\n'.format(labels[i],
self.transactions[i + 1]))
                    break
                elif type(id) == int:
                    print(self.transactions[id])
                    break
            except Exception as e:
                print(e)
'''
 Block Template
'''
ogrenci_new_transaction = {
 'timestamp': '', # datetime.now().timestamp(),
 'product_id': 1,
 'ogrenci_numarasi': 195509018,
 'sistem': 'yoklama sistemi',
 'kurum': 'fırat üniversitesi adli bilişim mühendisliği',
 'ogrenci_adi': 'Emre Çakar',
 ### CHANGEABLE KEYS
 'mesaj': '', #'yoklama girisi basariyla gerceklesti.'
 'digital_signature': '', #kabul edildi ya da reddedildi
 'flagged': '' #Evet için 'E', hayır için 'H'
}
ogretmen_new_transaction = {
 'timestamp': '', # datetime.now().timestamp(),
 'product_id': 1,
 'ogretmen_kullanici_numarasi': 3401238045,
 'sistem': 'yoklama sistemi',
 'kurum': 'fırat üniversitesi adli bilişim mühendisliği',
 'ogretmen': 'Mehmet demirkol',
 ### CHANGEABLE KEYS
 'mesaj': '', #'yoklama girisi basariyla gerceklesti'
 'digital_signature': '', #kabul edildi ya da reddedildi
 'flagged': '' #Evet için 'E', hayır için 'H'
}

'''
 DATA BLOCKS
'''
ogrenci = {
 'transactions': []
}
ogretmen = {
 'transactions': []
}

def ogrenciBlockProcess():

    print('\nOgrenci Blok Prosesi Icin Bilgi Girisi', end='\n')
    message = ''
    while len(message) < 1:
        message = input('Bir Mesaj Giriniz: ')
    digital_signature = ''
    while not (digital_signature == 'kabul edildi' or digital_signature ==
    'reddedildi'):
        digital_signature = input('Ogrenci Bilgi Durumu nihai durumu ("kabul edildi" ya da "reddedildi"): ')
    if digital_signature == 'reddedildi':
        return False
    flagged = ''

    while not (flagged == 'E' or flagged == 'H'):
        flagged = input('Yoklama girisi basariyla gerceklesti mi ? (Evet icin "E", Hayir icin "H"): ')
    ogrenci_new_transaction["timestamp"] = datetime.now().timestamp()
    ogrenci_new_transaction["mesaj"] = message
    ogrenci_new_transaction["digital_signature"] = digital_signature
    ogrenci_new_transaction["flagged"] = flagged
    return ogrenci_new_transaction
def ogretmenBlockProcess():
    print('\Ogretmen Blok Prosesi Icin Bilgi Girisi', end='\n')
    message = ''
    while len(message) < 1:
        message = input('Bir Mesaj Giriniz: ')
        digital_signature = ''
    while not (digital_signature == 'kabul edildi' or digital_signature ==
'reddedildi'):
        digital_signature = input('Sistem Bilgisi nihai durumu ("kabul edildi" ya da "reddedildi"): ')
    if digital_signature == 'reddedildi':
        return False
    flagged = ''
    while not (flagged == 'E' or flagged == 'H'):
        flagged = input('Yoklama girisi basariyla gerceklesti mi? (Evet icin "E", Hayir icin "H"): ')
    ogretmen_new_transaction["timestamp"] = datetime.now().timestamp()
    ogretmen_new_transaction["mesaj"] = message
    ogretmen_new_transaction["digital_signature"] = digital_signature
    ogretmen_new_transaction["flagged"] = flagged
    return ogretmen_new_transaction

def main():
    print('Butun Blok Zinciri Sisteminin Baslatilmasi...', end='\n')
    B = BlockChain()
    ogrenciBlock = ogrenciBlockProcess()
    if ogrenciBlock == False:
        print('ogrenci Blok Prosesi Reddedildi')
        exit()
    ogrenci['transactions'].append(ogrenciBlock)
    a = B.add(ogrenci)
    print('ogrenci Blogu Eklendi')
    print(a)
    ogretmenBlock = ogretmenBlockProcess()
    if ogretmenBlock == False:
        print('ogretmen Blok Prosesi Reddedildi')
        exit()
    ogretmen['transactions'].append(ogretmenBlock)
    b = B.add(ogretmen)
    print('ogretmen Blogu Eklendi')
    print(b)

    print('Bloklara Kaydedilen Butun Transfer Degerlerinin Ozeti',end='\n')
    B.getTransactions('all')
if __name__ == '__main__':
    main()


import cv2

webcam = cv2.VideoCapture(0)

stop = False

#while this loop is running it is looking for one of two keys to be pressed (s or q). If s is pressed an image will be captured from the webcam if q is pressed the script will end
while stop==False:
    ret,frame = webcam.read()
    nframe = cv2.flip(frame,1)
    if ret==True:
        cv2.imshow("camera", nframe)
        key = cv2.waitKey(1)
        if key==ord("q"):
            stop = True
        if key==ord("s"):
            im_name = "testim.png"
            cv2.imwrite(im_name,nframe)


'''
Given the head of a Singly LinkedList, write a method to check if the LinkedList is a palindrome or not.

Your algorithm should use constant space and the input LinkedList should be in the original form once the algorithm is finished. The algorithm should have O(N)O(N) time complexity where ‘N’ is the number of nodes in the LinkedList.

Example 1:

Input: 2 -> 4 -> 6 -> 4 -> 2 -> null
Output: true
Example 2:

Input: 2 -> 4 -> 6 -> 4 -> 2 -> 2 -> null
Output: false
'''

class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

def is_pallindrom(head):
    slow = head
    fast = head

    while fast is not None and fast.next is not None:
        fast = fast.next.next
        slow = slow.next

    # reverse the second half
    head_second_half = reverse(slow)
    # store the head of the of reversed part to revert back later
    copy_head_second_half = head_second_half

    # compare the first and the second half
    while head is not None and head_second_half is not None:
        if head.value != head_second_half.value:
            return False

        head = head.next
        head_second_half = head_second_half.next

    reverse(copy_head_second_half)  # revert the reverse of the second half

    if head is None or head_second_half is None:
        return True

    return False

# reverse a linked list

def reverse(head):
    prev = None

    while head is not None:
        next = head.next
        head.next = prev
        prev = head
        head = next

    return prev

def main():
    head = Node(2)
    head.next = Node(4)
    head.next.next = Node(6)
    head.next.next.next = Node(4)
    head.next.next.next.next = Node(2)

    print(is_pallindrom(head))

main()

palindrome linkedlist - fast & slow pointer.py


 # Begin Post Processing
# Open the Output Data Base for the current Job
import numpy as np
from abaqus import *
from abaqusConstants import *
from odbAccess import *
from visualization import *
import os

#############################################################
# UPDATE Tot_Vol?
#############################################################

path = os.getcwd()
# file = path + "\\F_M_and_E_gl_List_pos.npz"
# saving_dir = "E_gl_M_and_PK2_M_data"

# try:
#     os.mkdir(saving_dir)
# except OSError as error:
#     print(error)

job_name = "triangle__1"
try:
    odb = openOdb(path=job_name + ".odb")
except:
    print("odb doesn't exists")

myAssembly = odb.rootAssembly
I = np.diag([1, 1, 1])
TOP_FACE=odb.rootAssembly.instances['TRIANGULAR_LATTICE_15_DEG-1'].nodeSets['TOP_FACE']

frameRepository = odb.steps["Step-1"].frames
RF_all_frames_list = []
Disp_all_frames_list = []
for frame in frameRepository:
    # frame = frameRepository[-1]
    reaction_forces = frame.fieldOutputs["RF"].getSubset(position=NODAL, region=TOP_FACE)
    reaction_forces = np.copy(reaction_forces.bulkDataBlocks[0].data)
    displacement = frame.fieldOutputs["U"].getSubset(position=NODAL, region =TOP_FACE)
    displacement = np.copy(displacement.bulkDataBlocks[0].data)
    damage = frame.fieldOutputs["FV1"].getSubset(position=ELEMENT_NODAL)
    damage = np.copy(damage.bulkDataBlocks[0].data)
    RF_total = reaction_forces.sum(axis = 0)
    Disp_applied = displacement[0]
    RF_all_frames_list.append(RF_total)
    Disp_all_frames_list.append(Disp_applied)

# REFERENCE: https://abaqus-docs.mit.edu/2017/English/IhrComponentMap/ihr-c-Abaqus-ExampleParametersExtractAdd.htmL
Strain_energy = odb.steps['Step-1'].historyRegions['Assembly ASSEMBLY'].historyOutputs['ALLSE'].data
Strain_energy = np.array(Strain_energy)

RF_all_frames_list = np.array(RF_all_frames_list)
Disp_all_frames_list= np.array(Disp_all_frames_list)

# COORD = frame.fieldOutputs["COORD"].getSubset(position=NODAL)
# COORD = np.copy(COORD.bulkDataBlocks[0].data)

Load_Disp = np.column_stack((Disp_all_frames_list, RF_all_frames_list, Strain_energy))
np.savez("Load_Disp_SE.npz", Load_Disp = Load_Disp)
np.savetxt("Load_Disp_SE.csv", Load_Disp)


from re import match as re_match

from flask import request, current_app
from flask_login import current_user

from . import bp
from core import app_config
from core.models import Article, Category, Permission
from core.helpers import restful, permission_require, signals

from peewee import fn

@bp.route('/categories/')
@restful
@permission_require(Permission.READ_CATEGORY)
def get_categories():
    """``GET`` |API_URL_BASE|/categories/

    Get a list of categories.

    :param order: **Query** supported key: *create_time(default)*,
        *article_count*, *name*
    :param boolean desc: **Query** decrease order, default: false

    Response JSON:

    .. code-block:: javascript

        // success
        {
            $errors: null,
            categories: [
                {
                    id: string,
                    name: string,
                    article_count: integer
                }
            ]
        }

    Permission: ``READ_CATEGORY``
    """
    supported_key = {
        'create_time': Category.create_time,
        'article_count': fn.Count(Article.id),
        'name': Category.name
    }
    default_key = supported_key['create_time']
    order_key = supported_key.get(request.args.get('order'), default_key)

    if request.args.get('desc', 'false') == 'true':
        order_key = order_key.desc()

    raw_categories = Category.query().order_by(order_key)
    categories = [category.to_dict() for category in raw_categories]
    return None, {'categories': categories}

@bp.route('/category/<id>')
@restful
@permission_require(Permission.READ_CATEGORY)
def get_a_category(id):
    """``GET`` |API_URL_BASE|/category/:category_id

    Get a category.

    Response JSON:

    .. code-block:: javascript

        // success
        {
            $errors: null,
            category: {
                id: string,
                name: string,
                article_count: integer
            ]
        }

    Permission: ``READ_CATEGORY``
    """
    try:
        category = Category.get(Category.id == id)
    except Category.DoesNotExist:
        return {'id': '该分类不存在'}
    return None, {'category': category.to_dict()}

@bp.route('/category/', methods=['POST'])
@restful
@permission_require(Permission.CREATE_CATEGORY)
def create_category():
    """``POST`` |API_URL_BASE|/category/:category_id

    Create a category.

    :param id: **JSON Param**, required
    :param name: **JSON Param**, required

    Response JSON:

    .. code-block:: javascript

        // success
        {
            $errors: null,
            category: {
                id: string,
                name: string,
                article_count: integer
            }
        }

        // failed
        {
            $errors: {
                id: 'this id is invalid.',
                name: 'this name is invalid.',
                id: 'this id is duplicated.'
            }
        }

    Permission: ``CREATE_CATEGORY``
    """
    json = request.get_json()

    name = json.get('name', '').strip()
    if not name:
        return {'name': '请输入有效的分类名'}

    id = json.get('id', '')
    if not re_match(app_config['CATEGORY_ID_PATTERN'], id):
        return {'id': app_config['CATEGORY_ID_DESCRIPTION']}

    if Category.select().where(Category.id == id).count() == 1:
        return {'id': '该分类ID %s 已存在' % id}

    if Category.select().where(Category.name == name).count() == 1:
        return {'name': '该分类名 %s 已存在' % name}

    new_category = Category.create(id=id, name=name)

    signals.event_emitted.send(
        current_app._get_current_object(),
        type='Category: Create',
        description='category(%s) has been create.' % new_category.id
    )

    return None, {'category': new_category.to_dict()}

@bp.route('/category/<id>', methods=['PATCH'])
@restful
@permission_require(Permission.EDIT_CATEGORY)
def edit_category(id):
    """``PATCH`` |API_URL_BASE|/category/:category_id

    Edit a category. Currently only support modify category name.

    :param name: **JSON Param**, required

    Response JSON:

    .. code-block:: javascript

        // success
        {
            $errors: null,
            category: {
                id: integer,
                name: string,
                article_count: integer
            }
        }

        // failed
        {
            $errors: {
                permission: 'you are not allowed to modify category '
                            'created by other author',
                name: 'this name is invalid.'
            }
        }

    Permission:

        * ``EDIT_CATEGORY``
        * ``EDIT_OTHERS_CATEGORY`` (if attempt to edit
          category created by other.)
    """
    json = request.get_json()
    new_name = json.get('name', '').strip()
    if not new_name:
        return {'name': '请输入有效的分类名'}

    try:
        this_category = Category.get(Category.id == id)
    except Category.DoesNotExist:
        return {'id': '该分类 %s 不存在' % id}

    if this_category.create_by_id != current_user.get_id() \
            and not current_user.can(Permission.EDIT_OTHERS_CATEGORY):
        reason = ('You are not allowed to edit category '
                  'created by other author.')
        return {'permission': reason}

    old_name = this_category.name
    this_category.name = new_name
    this_category.save()

    signals.event_emitted.send(
        current_app._get_current_object(),
        type='Category: Modify',
        description='category(%s) changed from `%s` to `%s`.' %
                    (id, old_name, new_name)
    )

    return None, {'category': this_category.to_dict()}

@bp.route('/category/<id>', methods=['DELETE'])
@restful
@permission_require(Permission.EDIT_CATEGORY)
def delete_category(id):
    """``DELETE`` |API_URL_BASE|/cate/:category_id

    Delete a category.

    :param id: category id

    Response JSON:

    .. code-block:: javascript

        // success
        {$errors: null}

        // failed
        {
            $errors: {
                not_empty: 'this category is not empty.',
                id: 'this category does not exist.'
            }
        }

    Permission: ``EDIT_CATEGORY``
    """
    try:
        this_category = Category.query().where(Category.id == id).get()
    except Category.DoesNotExist:
        return {'id': '该分类 %s 不存在' % id}

    if this_category.count > 0:
        return {'not_empty': '该分类下还有 %d 篇文章，请清空后再删除'
                             % this_category.count}

    this_category.delete_instance()

    signals.event_emitted.send(
        current_app._get_current_object(),
        type='Category: Delete',
        description='category(%s) has been deleted.' % id
    )


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 25 15:36:13 2022

@author: ricardobortothopker
"""

from pysmiles import read_smiles
import networkx as nx
import matplotlib.pyplot as plt
from complexFuncs import complexity
import numpy as np

# smiles = 'C12=C3C4=C5C6=C1C7=C8C9=C1C%10=C%11C(=C29)C3=C2C3=C4C4=C5C5=C9C6=C7C6=C7C8=C1C1=C8C%10=C%10C%11=C2C2=C3C3=C4C4=C5C5=C%11C%12=C(C6=C95)C7=C1C1=C%12C5=C%11C4=C3C3=C5C(=C81)C%10=C23'
Strychnine = "C1CN2CC3=CCOC4CC(=O)N5C6C4C3CC2C61C7=CC=CC=C75"
PubChemCS = "CC1=C(C=C(C=C1)Cl)N2CCN(CC2)C(=O)C3CC4=C(C=CC(=C4)OC)OC3"
Glucose = "OC[C@H]1OC(O)[C@H](O)[C@@H](O)[C@@H]1O"
Anandamide = "CCCCC/C=C\C/C=C\C/C=C\C/C=C\CCCC(=O)NCCO"
Adamantane = "C1C2CC3CC1CC(C2)C3"

Strychnine_mol,PubChemCS_mol,Glucose_mol = read_smiles(Strychnine),read_smiles(PubChemCS),read_smiles(Glucose)
Anandamide_mol,Adamantane_mol = read_smiles(Anandamide),read_smiles(Adamantane)

mols = [Strychnine_mol,PubChemCS_mol,Glucose_mol,Anandamide_mol,Adamantane_mol]
A = []
elements =[]
C = []
for mol in mols:
    fig,ax = plt.subplots()
    A.append(nx.to_numpy_matrix(mol))
    np.fill_diagonal(A[-1],1)
    elements.append(nx.get_node_attributes(mol, name = "element"))
    # nx.draw(mol, with_labels=True, labels = elements[-1], pos=nx.spring_layout(mol))
    # plt.gca().set_aspect('equal')
    C.append(complexity(A[-1]))


import numpy as np;
import soundfile as sf;
from sklearn.metrics import mean_squared_error;
import matplotlib.pyplot as plt;

from act import ACT;
from est import EST;
from call import CALL;
from toa import TOA;

class RUN:
    '''
    Class for running tests to find actual and
    estimated arrival times for a set of sensors
    and a target.

    Methods
    -------
    get_RMSE
        Returns the root-mean-squared error.

    get_dTSE
        Returns the estimated arrival time for
        each sensor.
    '''

    def __init__(self, target, sensors, s2n, f_call, f_sea, no_blocks):
        self.t         = target;
        self.s         = sensors;
        self.s2n       = s2n;
        self.f_call    = f_call;
        self.f_sea     = f_sea;
        self.no_blocks = no_blocks;

    def get_rmse(self):
        self.set_pars();
        self.set_act();
        self.set_call();
        self.set_est();

        rmse = mean_squared_error(self.dTSA, self.dTSE, squared=False);

        return rmse;

    def get_dTSE(self):
        return self.dTSE;

    def set_pars(self):
        self.x = np.array(self.s).transpose()[0];
        self.y = np.array(self.s).transpose()[1];
        self.n = len(self.s);

    def set_act(self):
        act       = ACT(self.s, self.t);
        self.dTSA = act.get_dTSA();
        self.tTSA = act.get_tTSA();

    def set_call(self):
        rec_len = 10;
        call    = CALL(rec_len, self.f_call, self.tTSA, self.s2n);
        call.append_call(self.f_sea);

        F0, self.rate = sf.read('F0.wav');
        F1, self.rate = sf.read('F1.wav');
        F2, self.rate = sf.read('F2.wav');

        self.samples  = rec_len*self.rate;
        self.sfs = np.zeros((self.n, self.samples));

        self.sfs[0] = F0;
        self.sfs[1] = F1;
        self.sfs[2] = F2;

        self.pk = call.get_peak();

    def set_est(self):
        block_divisor = 2;

        toa = TOA(self.sfs, self.no_blocks, self.samples, self.rate, block_divisor);
        self.tTSE = toa.get_tTSE();

        est = EST(self.s, self.tTSE);
        self.dTSE = est.get_dTSE();


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan  3 09:55:02 2020

@author: qiuwenjie
"""

'''
cs224w homework 0
Q1 & Q2
'''
import snap as sp
import numpy as np
import matplotlib.pyplot as plt
#load graph
G = sp.LoadEdgeList(sp.PNGraph, "Wiki-Vote.txt",0,1)

#------------------------------------------------------------------------------
#Q1
GNodesNum= G.GetNodes()
print("Q1.1 The number of nodes in the network: ",GNodesNum)

SelfLoopNum = 0
for EI in G.Edges():
    if EI.GetSrcNId() == EI.GetDstNId():
        SelfLoopNum += 1
print("Q1.2 The number of nodes with a self-edge: ",SelfLoopNum)

DirecEdgeNum = 0
for EI in G.Edges():
    if EI.GetSrcNId() != EI.GetDstNId():
        DirecEdgeNum += 1
print("Q1.3 The number of directed edges in the network: ",DirecEdgeNum)

UDirecEdgeNum = 0
for EI in G.Edges():
    if EI.GetSrcNId() != EI.GetDstNId():
        if G.IsEdge(EI.GetDstNId(),EI.GetSrcNId()) == False:
            UDirecEdgeNum += 1
        else:
            UDirecEdgeNum +=0.5
print("Q1.4 The number of undirected edges in the network: ",UDirecEdgeNum)

RecEdgeNum = 0
for EI in G.Edges():
    if EI.GetSrcNId() != EI.GetDstNId():
        if G.IsEdge(EI.GetDstNId(),EI.GetSrcNId()):
            RecEdgeNum += 0.5
print("Q1.5 The number of reciprocated edges in the network: ",RecEdgeNum)

ZOutNum = 0
for NI in G.Nodes():
    if NI.GetOutDeg() == 0:
        ZOutNum +=1
print("Q1.6 The number of nodes of zero-out edge: ",ZOutNum)

ZInNum = 0
for NI in G.Nodes():
    if NI.GetInDeg() == 0:
        ZInNum +=1
print("Q1.7 The number of nodes of zero-in edge: ",ZInNum)

OutG10Num = 0
for NI in G.Nodes():
    if NI.GetOutDeg() > 10:
        OutG10Num +=1
print("Q1.8 The number of nodes with more than 10 outgoing edge: ",OutG10Num)

InF10Num = 0
for NI in G.Nodes():
    if NI.GetInDeg() < 10:
        InF10Num +=1
print("Q1.9 The number of nodes with fewer than 10 incoming edge: ",InF10Num)
#Q1 end
#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
#Q2
OutDegDict = {}
for NI in G.Nodes():
    OutDeg = NI.GetOutDeg()
    if OutDeg > 0:
        if OutDeg in OutDegDict.keys():
            OutDegDict[OutDeg] += 1
        else:
            OutDegDict[OutDeg] = 1
OutDegArr = np.array(sorted(OutDegDict))
OutDegArrNum = np.zeros(OutDegArr.shape[0])
for i in range(len(OutDegArrNum)):
    OutDegArrNum[i] = OutDegDict[OutDegArr[i]]
print('Q2')
ax = plt.gca()
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_adjustable("datalim")
ax.set_xlabel('Out-Degree')
ax.set_ylabel('Count')
ax.set_title('The distribution of out-degrees of nodes in the network')
plt.plot(OutDegArr, OutDegArrNum,'-',label='Out-Degree Distribution')
LogOutDegArr = np.log10(OutDegArr)
LogOutDegArrNum = np.log10(OutDegArrNum)
reg=np.polyfit(LogOutDegArr,LogOutDegArrNum,1)
LogOutDegArrNumEst=np.power(10,reg[1])*np.power(OutDegArr,reg[0])
plt.plot(OutDegArr,LogOutDegArrNumEst,'-',label='Least-Square Regression')
ax.set_xlim(OutDegArr[0], OutDegArr[-1])
#ax.set_ylim(min(OutDegArrNum), max(OutDegArrNum))
ax.grid()
plt.legend()


from typing import Tuple

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tf_ds
from PIL import Image
from tensorflow.image import rgb_to_hsv
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow_io.python.experimental.color_ops import rgb_to_lab
from tqdm import tqdm

from autoencoders.ColoringAutoEncoder import AutoEncoderFormat

def load_image(path, format: AutoEncoderFormat, size: Tuple[int, int]) -> Tuple[np.ndarray, np.ndarray]:
    img = Image.open(path)
    img = img.resize(size)
    gray_scale = np.mean(np.asarray(img, dtype='float32') / 255.0, axis=2)
    gray_scale = np.reshape(gray_scale, (gray_scale.shape[0], gray_scale.shape[1], 1))
    img = np.asarray(img, dtype='float32') / 255.0
    if format == AutoEncoderFormat.HSV:
        img = rgb_to_hsv(img)
    elif format == AutoEncoderFormat.LAB:
        img = rgb_to_lab(img)
        img = (img + np.array([0, 128, 128])) / np.array([100, 255, 255])
    return img, gray_scale

def load_data(name, nb_samples, size=100):
    size = (size, size)
    train = tf_ds.load(name=name, split=tf_ds.Split.TEST)
    train = train.shuffle(1024).prefetch(tf.data.experimental.AUTOTUNE)

    train_x = prepare_data(train, "Train dataset", nb_samples, size)

    val = tf_ds.load(name=name, split=tf_ds.Split.TRAIN)
    val = val.shuffle(1024).prefetch(tf.data.experimental.AUTOTUNE)

    val_x = prepare_data(val, "Validation dataset", nb_samples // 5, size)
    return train_x, val_x

def prepare_data(dataset, name, n, size):
    samples = list(dataset)[:n]
    data_x = []
    first = True
    for element in tqdm(samples, desc=name):
        img = Image.fromarray(np.array(element["image"]))
        if size is not None:
            img = img.resize(size)
        x = np.asarray(img, dtype="float32") / 255.0
        if first:
            plt.imshow(x)
            plt.show()
            first = False
        data_x.append(x)
    data_x = np.array(data_x, dtype='float32')
    return data_x

class AutoEncoderImageDataGenerator(tf.keras.utils.Sequence):

    def __init__(self, x_train, batch_size: int, shuffle: bool, format: AutoEncoderFormat, data_ag: bool):
        super(AutoEncoderImageDataGenerator, self).__init__()
        self.__image_data_generator = ImageDataGenerator(
            rotation_range=30,
            width_shift_range=1.0,
            height_shift_range=1.0,
            horizontal_flip=True,
            vertical_flip=True,
        )
        self.__x_train = x_train
        self.__batch_size: int = batch_size
        self.__shuffle: bool = shuffle
        self.__format: AutoEncoderFormat = format
        self.__data_ag: bool = data_ag

    def __getitem__(self, index):
        batch = self.__x_train[index * self.__batch_size: (index + 1) * self.__batch_size]
        return self.__prepare_data(batch)

    def __len__(self):
        return len(self.__x_train) // self.__batch_size

    def on_epoch_end(self):
        if self.__shuffle:
            self.__x_train = np.random.shuffle(self.__x_train)

    def __prepare_data(self, batch):
        x_data = []
        y_data = []
        for i in batch:
            if self.__data_ag:
                x = self.__image_data_generator.random_transform(i)
            else:
                x = i
            x_data.append(tf.math.reduce_mean(x, axis=2, keepdims=True))
            if self.__format == AutoEncoderFormat.RGB:
                y = x
            elif self.__format == AutoEncoderFormat.HSV:
                y = rgb_to_hsv(x)
            elif self.__format == AutoEncoderFormat.LAB:
                y = rgb_to_lab(x)
                y = (y + np.array([0, 128, 128])) / np.array([100, 255, 255])
            else:
                raise ValueError(f"No format: {self.__format}")
            y_data.append(y)
        x_data = np.array(x_data)
        y_data = np.array(y_data)
        return x_data, y_data


from .writer import WorksheetWriter
import pandas as pd
import numpy as np
from random import seed
from random import randrange
from csv import reader
from math import sqrt
import matplotlib.pyplot as plt
from sklearn import datasets, linear_model, metrics
from sklearn.model_selection import train_test_split

class Model:
    def __init__(self):
        super().__init__()
        self.recognizer = speechRecognizer()
        self.writer = WorksheetWriter()

    def load_csv(filename):
        dataset = list()
        with open(filename, 'r') as file:
            csv_reader = reader(file)
            for row in csv_reader:
                if not row:
                    continue
                dataset.append(row)
        return dataset

    def train_test_split(dataset, split):
        train = list()
        train_size = split * len(dataset)
        dataset_copy = list(dataset)
        while len(train) < train_size:
            index = randrange(len(dataset_copy))
            train.append(dataset_copy.pop(index))
        return train, dataset_copy

    def prediction(self,X,y):
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4,
                                                            random_state=1)
        reg = linear_model.LinearRegression()
        reg.fit(X_train, y_train)
        print('Coefficients: \n', reg.coef_)
        print('Variance score: {}'.format(reg.score(X_test, y_test)))
        plt.style.use('fivethirtyeight')
        plt.scatter(reg.predict(X_train), reg.predict(X_train) - y_train,
                    color="green", s=10, label='Train data')
        plt.scatter(reg.predict(X_test), reg.predict(X_test) - y_test,
                    color="blue", s=10, label='Test data')
        plt.hlines(y=0, xmin=0, xmax=50, linewidth=2)
        plt.legend(loc='upper right')
        plt.title("Residual errors")
        plt.show()


import ccxt
from ccxt.base.errors import InvalidAddress, InvalidOrder, ExchangeError
from termcolor import cprint
from config.settings import BINANCE_API_KEY, BINANCE_API_SECRET

def binance_withdraw(address_wallet, amount_to_withdraw, symbol_to_withdraw, network):
    account_binance = ccxt.binance({
        'apiKey': BINANCE_API_KEY,
        'secret': BINANCE_API_SECRET,
        'enableRateLimit': True,
        'options': {
            'defaultType': 'spot'
        }
    })

    try:
        account_binance.withdraw(
            code=symbol_to_withdraw,
            amount=amount_to_withdraw,
            address=address_wallet,
            tag=None,
            params={
                "network": network
            }
        )
        cprint(f">>> Success | {address_wallet} | {amount_to_withdraw}", "green")
    except ExchangeError as error:
        cprint(f">>> Failed | {address_wallet} | error : {error}", "red")


import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F

class AuthorLSTM(nn.Module):
    """
    The training examples are in the form of <a sequence of characters, label>.
    In which the label is a binary variable determining that the sequence is written
    by the author or not.
    This model maps a sequence of characters to an embedding space then
    builds an LSTM network on top of it. Finally a sigmoid function is used
    to convert the LSTM outputs to the probability of the author, given the sequence.
    """

    def __init__(self, vocab_size, embedding_dim, hidden_size, n_classes, bi=True, n_layers=1):
        super(AuthorLSTM, self).__init__()

        self.embed_dim = embedding_dim
        self.hidden_dim = hidden_size
        self.out_dim = n_classes
        self.n_layers = n_layers
        self.bi = bi
        self.n_dir = 2 if bi else 1

        self.embedding = nn.Embedding(vocab_size, embedding_dim)
        self.rnn = nn.LSTM(embedding_dim, hidden_size, n_layers, bidirectional=bi, dropout=True)
        self.linear = nn.Linear(self.hidden_dim * self.n_dir, n_classes)
        self.o = F.softmax

    def init_hidden(self, batch_size):
        c0 = autograd.Variable(torch.zeros(self.n_layers * self.n_dir, batch_size, self.hidden_dim))
        h0 = autograd.Variable(torch.zeros(self.n_layers * self.n_dir, batch_size, self.hidden_dim))
        return h0, c0

    def forward(self, inputs):
        batch_size = inputs.size(0)  # batches * Sequences
        inputs = inputs.t()  # Sequences * batches
        sequence_len = inputs.size(0)

        hidden = self.init_hidden(batch_size)
        embeds = self.embedding(inputs)
        out, hidden = self.rnn(embeds, hidden)
        last_layer = out[-1]
        linear = self.linear(last_layer)  # take the last layer
        score = self.o(linear.view(batch_size, -1), 1)
        return score


import pandas as pd

miac_df = pd.read_excel('files/МИАЦ_Реднева.xlsx')

col_list = miac_df.columns.values.tolist()
print(col_list)
ages_groups =sorted(miac_df['Возрастная группа'].unique().tolist())
for i, ag in enumerate(ages_groups):
    print(f"[{i}] - {ag}")
print("Введите номер возрастной группы:")
iag = int(input())
ag = ages_groups[iag]
print(f"{iag} - {ag}")
group_06 = miac_df[miac_df['Возрастная группа'] == ag]
print(group_06[['ФИО ребенка', 'Дата рождения', 'Возрастная группа', 'ФИО врача']])


"""Util module."""
import dataclasses
from enum import Enum
from typing import Any

from deebot_client.util import DisplayNameIntEnum
from homeassistant.core import HomeAssistant
from homeassistant.util import uuid

def get_bumper_device_id(hass: HomeAssistant) -> str:
    """Return bumper device id."""
    try:
        location_name = hass.config.location_name.strip().replace(" ", "_")
    except Exception:  # pylint: disable=broad-except
        location_name = ""
    return f"Deebot-4-HA_{location_name}_{uuid.random_uuid_hex()[:4]}"

def dataclass_to_dict(obj: Any) -> dict[str, Any]:
    """Convert dataclass to dict and remove None fields."""
    dic = dataclasses.asdict(obj)
    for key, value in dic.copy().items():
        if value is None:
            dic.pop(key)
        elif isinstance(value, Enum):
            if isinstance(value, DisplayNameIntEnum):
                dic[key] = value.display_name
            else:
                dic[key] = value.value

    return dic