import pytest

import ezdxf
from ezdxf.entities.mtext import (
    load_columns_from_xdata,
    MText,
    ColumnType,
    MTextColumns,
)
from ezdxf.lldxf.extendedtags import ExtendedTags
from ezdxf.lldxf.tagwriter import TagCollector
from ezdxf.lldxf import const
from ezdxf.entities.xdata import XData
from ezdxf.math import Vec3

DYNAMIC_MANUAL_HEIGHT = """0
MTEXT
5
9C
330
1F
100
AcDbEntity
8
0
100
AcDbMText
1001
ACAD
1000
ACAD_MTEXT_COLUMN_INFO_BEGIN
1070
75
1070
2
1070
79
1070
0
1070
76
1070
3
1070
78
1070
0
1070
48
1040
50.0
1070
49
1040
12.5
1070
50
1070
3
1040
164.8
1040
154.3
1040
0.0
1000
ACAD_MTEXT_COLUMN_INFO_END
1000
ACAD_MTEXT_COLUMNS_BEGIN
1070
47
1070
3
1005
238
1005
239
1000
ACAD_MTEXT_COLUMNS_END
"""

DYNAMIC_AUTO_HEIGHT = """0
MTEXT
5
A2
330
1F
100
AcDbEntity
8
0
100
AcDbMText
1001
ACAD
1000
ACAD_MTEXT_COLUMN_INFO_BEGIN
1070
75
1070
2
1070
79
1070
1
1070
76
1070
3
1070
78
1070
0
1070
48
1040
50.0
1070
49
1040
12.5
1000
ACAD_MTEXT_COLUMN_INFO_END
1000
ACAD_MTEXT_COLUMNS_BEGIN
1070
47
1070
3
1005
23C
1005
23D
1000
ACAD_MTEXT_COLUMNS_END
1000
ACAD_MTEXT_DEFINED_HEIGHT_BEGIN
1070
46
1040
158.1
1000
ACAD_MTEXT_DEFINED_HEIGHT_END
"""

STATIC = """0
MTEXT
5
9D
330
1F
100
AcDbEntity
8
0
100
AcDbMText
1001
ACAD
1000
ACAD_MTEXT_COLUMN_INFO_BEGIN
1070
75
1070
1
1070
79
1070
0
1070
76
1070
3
1070
78
1070
0
1070
48
1040
50.0
1070
49
1040
12.5
1000
ACAD_MTEXT_COLUMN_INFO_END
1000
ACAD_MTEXT_COLUMNS_BEGIN
1070
47
1070
3
1005
23A
1005
23B
1000
ACAD_MTEXT_COLUMNS_END
1000
ACAD_MTEXT_DEFINED_HEIGHT_BEGIN
1070
46
1040
150.0
1000
ACAD_MTEXT_DEFINED_HEIGHT_END
"""

NO_COLUMN_INFO = """0
MTEXT
5
9D
330
1F
100
AcDbEntity
8
0
100
AcDbMText
1001
ACAD
"""

# The dynamic auto height and static types are very similar, the difference is
# important for CAD applications, but not for the DXF format itself.

def get_xdata(txt: str):
    tags = ExtendedTags.from_text(txt)
    return XData(tags.xdata)

def test_load_dynamic_cols_manual_height():
    """Every column can have a different height.

    The linked MTEXT entities do NOT have the "defined_height" stored in the
    XDATA section ACAD. The only source for the column height is the
    MTextColumns.heights list.

    The linked MTEXT entities do not have an ACAD section at all.

    """
    xdata = get_xdata(DYNAMIC_MANUAL_HEIGHT)
    cols = load_columns_from_xdata(MText().dxf, xdata)
    assert cols.count == 3
    assert cols.column_type == ColumnType.DYNAMIC
    assert cols.auto_height is False
    assert cols.reversed_column_flow is False
    assert cols.defined_height == 0.0, "not defined if auto_height is False"
    assert cols.width == 50.0
    assert cols.gutter_width == 12.5
    assert cols.total_width == 175.0  # 3 * 50 + 2 * 12.5
    # total_height = max(heights) even if the last column is the tallest
    assert cols.total_height == 164.8  # max height
    assert len(cols.linked_handles) == 2
    assert len(cols.heights) == 3  # not stored the main MTEXT entity
    assert cols.heights[-1] == 0.0, "last column height has to be 0.0"
    assert cols.heights == [164.8, 154.3, 0.0]

def test_load_dynamic_cols_with_auto_height():
    """All columns have the same column height.

    Each linked MTEXT has the "defined_height" stored in the XDATA section ACAD.

    """
    xdata = get_xdata(DYNAMIC_AUTO_HEIGHT)
    cols = load_columns_from_xdata(MText().dxf, xdata)
    # Count is a calculated value, group code 72 (column height count) is 0!
    assert cols.count == 3
    assert cols.column_type == ColumnType.DYNAMIC
    assert cols.auto_height is True
    assert cols.reversed_column_flow is False
    assert cols.defined_height == 158.1, "required if auto_height is True"
    assert cols.width == 50.0
    assert cols.gutter_width == 12.5
    assert cols.total_width == 175.0  # 3 * 50 + 2 * 12.5
    assert cols.total_height == 158.1
    assert len(cols.linked_handles) == 2
    assert len(cols.heights) == 0

def test_load_static_cols():
    """All columns have the same column height.

    Each linked MTEXT has the "defined_height" stored in the XDATA section ACAD.

    """
    xdata = get_xdata(STATIC)
    cols = load_columns_from_xdata(MText().dxf, xdata)
    assert cols.count == 3
    assert cols.column_type == ColumnType.STATIC
    assert cols.auto_height is False
    assert cols.reversed_column_flow is False
    assert cols.defined_height == 150.0, "required for static columns"
    assert cols.width == 50.0
    assert cols.gutter_width == 12.5
    assert cols.total_width == 175.0  # 3 * 50 + 2 * 12.5
    assert cols.total_height == 150.0
    assert len(cols.linked_handles) == 2
    assert len(cols.heights) == 0

def test_mtext_without_column_info():
    xdata = get_xdata(NO_COLUMN_INFO)
    cols = load_columns_from_xdata(MText().dxf, xdata)
    assert cols is None

def make_mtext(txt: str) -> MText:
    mtext = MText()
    xdata = get_xdata(txt)
    mtext._columns = load_columns_from_xdata(mtext.dxf, xdata)
    return mtext

@pytest.mark.parametrize(
    "txt",
    [STATIC, DYNAMIC_AUTO_HEIGHT, DYNAMIC_MANUAL_HEIGHT],
    ids=["STATIC", "DYNAMIC_AUTO", "DYNAMIC_MANUAL"],
)
def test_set_columns_xdata(txt):
    """Create column data as XDATA for DXF versions before R2018."""
    mtext = make_mtext(txt)
    mtext.set_column_xdata()
    acad = mtext.xdata.get("ACAD")
    expected_xdata = get_xdata(txt)
    assert acad == expected_xdata.get("ACAD")

def new_mtext_with_linked_columns(count=3) -> MText:
    columns = MTextColumns()
    columns.count = count
    columns.width = 10
    columns.gutter_width = 0.5
    columns.defined_height = 50
    mtext = MText.new()
    mtext.setup_columns(columns, linked=True)
    return mtext

def test_create_new_mtext_with_linked_columns():
    mtext = new_mtext_with_linked_columns(3)
    columns = mtext.columns
    assert columns.column_type == ColumnType.STATIC
    assert len(columns.linked_columns) == 2
    assert len(columns.heights) == 0, "all columns have the same defined height"
    assert mtext.dxf.width == columns.width
    assert columns.total_height == columns.defined_height
    assert columns.total_width == 31

    # default location and text direction:
    assert mtext.dxf.insert == (0, 0, 0)
    assert mtext.dxf.text_direction == (1, 0, 0)

    for column in columns.linked_columns:
        assert column.columns is None
        assert column.dxf.width == columns.width
        assert column.dxf.defined_height == columns.defined_height
        assert column.dxf.text_direction == (1, 0, 0)

    col0, col1 = columns.linked_columns
    assert col0.dxf.insert == (10.5, 0, 0)
    assert col1.dxf.insert == (21, 0, 0)

def test_destroy_mtext_with_linked_columns():
    mtext = new_mtext_with_linked_columns(3)
    columns = mtext.columns
    mtext.destroy()
    assert mtext.is_alive is False
    for col in columns.linked_columns:
        assert col.is_alive is False

@pytest.fixture(scope="module")
def doc():
    return ezdxf.new("R2013")

def test_add_mtext_with_linked_columns_to_entitydb(doc):
    db = doc.entitydb
    mtext = new_mtext_with_linked_columns(3)
    count = len(db)
    doc.entitydb.add(mtext)
    assert len(db) == count + 3, "should add all columns to the entitydb"
    columns = mtext.columns
    for col in columns.linked_columns:
        assert col.dxf.handle is not None
        assert col.dxf.handle in db, "should be stored in the entity db"

def test_add_mtext_with_linked_columns_to_msp(doc):
    msp = doc.modelspace()
    mtext = new_mtext_with_linked_columns(3)
    count = len(msp)
    msp.add_entity(mtext)
    assert len(msp) == count + 1, "should only add the main column to the msp"

    columns = mtext.columns
    db = doc.entitydb
    for col in columns.linked_columns:
        assert col.dxf.handle is not None
        assert col.dxf.handle in db, "should be stored in the entity db"
        assert col.dxf.owner is None, "should not be stored in an entity space"

def test_delete_mtext_with_linked_columns_from_entitydb(doc):
    """Delete MTEXT by EntityDB.delete_entity()."""
    db = doc.entitydb
    mtext = new_mtext_with_linked_columns(3)
    doc.entitydb.add(mtext)
    count = len(db)
    doc.entitydb.delete_entity(mtext)
    db.purge()
    assert len(db) == count - 3, "should delete all columns from entitydb"

def test_discard_mtext_with_linked_columns_from_entitydb(doc):
    """Discard MTEXT columns from entitydb, but do not destroy the entities."""
    db = doc.entitydb
    mtext = new_mtext_with_linked_columns(3)
    doc.entitydb.add(mtext)
    count = len(db)
    doc.entitydb.discard(mtext)
    assert len(db) == count - 3, "should discard all columns from entitydb"
    assert mtext.is_alive is True
    for col in mtext.columns.linked_columns:
        assert col.is_alive is True

def test_destroy_mtext_with_linked_columns_from_entitydb(doc):
    """Delete MTEXT from EntityDB using MText.destroy()."""
    db = doc.entitydb
    mtext = new_mtext_with_linked_columns(3)
    doc.entitydb.add(mtext)
    count = len(db)
    mtext.destroy()
    db.purge()
    assert len(db) == count - 3, "should delete all columns from entitydb"

def test_copy_mtext_with_linked_columns():
    mtext = new_mtext_with_linked_columns(3)
    mtext2 = mtext.copy()
    columns = mtext.columns
    columns2 = mtext2.columns
    assert columns is not columns2
    assert len(columns2.linked_columns) == 2

    for col1, col2 in zip(columns.linked_columns, columns2.linked_columns):
        assert col1 is not col2

def test_transform_mtext_with_linked_columns():
    mtext = new_mtext_with_linked_columns(3)
    offset = Vec3(1, 2, 3)
    mtext2 = mtext.copy()
    mtext2.translate(*offset.xyz)
    assert mtext2.dxf.insert.isclose(mtext.dxf.insert + offset)
    for col1, col2 in zip(
        mtext.columns.linked_columns, mtext2.columns.linked_columns
    ):
        assert col2.dxf.insert.isclose(col1.dxf.insert + offset)

def test_scale_mtext_with_linked_columns():
    mtext = new_mtext_with_linked_columns(3)
    mtext.scale(2, 3, 1)
    assert mtext.dxf.width == 20
    columns = mtext.columns
    assert columns.width == 20
    assert columns.gutter_width == 1
    assert columns.total_width == 62
    assert columns.defined_height == 150
    for column in columns.linked_columns:
        assert column.dxf.width == 20

def test_sync_common_attribs_of_linked_columns():
    mtext = new_mtext_with_linked_columns(3)
    mtext.dxf.style = "NewStyle"
    # manual sync required - this is done automatically at DXF export:
    mtext.sync_common_attribs_of_linked_columns()
    for column in mtext.columns.linked_columns:
        assert column.dxf.style == "NewStyle"

def test_remove_dependencies_from_mtext_and_linked_columns(doc):
    mtext = new_mtext_with_linked_columns(3)
    mtext.dxf.style = "StyleNotExist"
    mtext.sync_common_attribs_of_linked_columns()
    mtext.remove_dependencies(doc)
    assert mtext.dxf.style == "Standard"
    for column in mtext.columns.linked_columns:
        assert column.dxf.handle is None
        assert column.dxf.owner is None
        assert column.dxf.style == "Standard"

class TestPreprocessDXFExport:
    collector = TagCollector(dxfversion=const.DXF2000)

    def test_successful_preprocessing(self):
        mtext = new_mtext_with_linked_columns(3)
        assert mtext.preprocess_export(self.collector) is True

    def test_accept_invalid_column_count(self):
        # Changed 2021-10-17:
        # AutoCAD accepts a different column count as linked MTEXT entities,
        # see issue #558. This occurs in real world DXF files and the behavior
        # until this fix, removed valid MTEXT entities from DXF files if they
        # were exported (saveas).
        mtext = new_mtext_with_linked_columns(3)
        mtext._columns.count = 4
        assert mtext.preprocess_export(self.collector) is True

    def test_fail_for_destroyed_columns(self):
        mtext = new_mtext_with_linked_columns(3)
        mtext.columns.linked_columns[0].destroy()
        assert mtext.preprocess_export(self.collector) is False

class TestGetColumnContent:
    def new_mtext(self):
        mtext = new_mtext_with_linked_columns(3)
        mtext.text = "Line1\\PLine2\\P"
        mtext._columns.linked_columns[0].text = "Line3\\PLine4\\P"
        mtext._columns.linked_columns[1].text = "Line5\\PLine6\\P"
        return mtext

    def test_get_raw_content_of_all_columns(self):
        mtext = self.new_mtext()
        content = mtext.all_columns_raw_content()
        assert content == "Line1\\PLine2\\PLine3\\PLine4\\PLine5\\PLine6\\P"

    def test_get_plain_text_of_all_columns_as_string(self):
        mtext = self.new_mtext()
        content = mtext.all_columns_plain_text(split=False)
        assert content == "Line1\nLine2\nLine3\nLine4\nLine5\nLine6\n"

    def test_get_plain_text_of_all_columns_as_list_of_strings(self):
        mtext = self.new_mtext()
        content = mtext.all_columns_plain_text(split=True)
        assert content == "Line1 Line2 Line3 Line4 Line5 Line6".split()

if __name__ == "__main__":
    pytest.main([__file__])


from collections import defaultdict
from datetime import date, datetime
from decimal import Decimal

from django.db.models import Prefetch
from django.db.models.functions import TruncMonth, TruncYear
from rest_framework.views import APIView
# from .models import Order, OrderItem, Variant, Product, Size
from customer.models import Customer
from transaction.models import Ledger
from .serializers import CustomerSerializer
from product.models import Product
from .models import PerProduct, OrderedProduct, Order, Invoice
from .serializers import OrderSerializer
from utilities.response import ApiResponse

class PurchaseIndexView(APIView):
    def get(self, request):
        queryset = Order.objects.all()
        ser = OrderSerializer(queryset, many=True).data
        return ApiResponse(200, data=ser).response()

class DistributorOrderAPIView(APIView):

    def get(self, request, customer_id):
        customer = Customer.objects.get(id=customer_id)
        orders = customer.orders.order_by('-created_at')
        serializer = OrderSerializer(orders, many=True)
        data = {
            'customer': CustomerSerializer(customer).data,
            'orders': serializer.data
        }
        # print(data)
        return ApiResponse(200, data=data).response()

    def post(self, request, *args, **kwargs):
        customer_id = request.data.get('customer')
        products_data = request.data.get('products', [])

        try:
            customer = Customer.objects.get(id=customer_id)
        except Customer.DoesNotExist:
            return ApiResponse(400, message='Customer not found').response()

        ordered = []
        total_cost = 0

        for product_data in products_data:
            selected_product_id = product_data.get('selectedProduct')
            quantity = product_data.get('quantity')

            try:
                product = Product.objects.get(id=selected_product_id)
                ordered_product, created = PerProduct.objects.get_or_create(
                    product=product, quantity=quantity
                )
                ordered.append(ordered_product)
                total_cost += product.price * quantity
            except Product.DoesNotExist:
                return ApiResponse(400, message=f'Product with ID {selected_product_id} not found').response()

        if customer.can_order(total_cost):
            ordered_products = OrderedProduct.objects.create(customer=customer)
            ordered_products.mattresses.add(*ordered)
            ordered_products.save()
            order = Order.objects.create(
                customer=customer,
                fulfilled=True,
                cost=total_cost,
            )
            order.ordered_products.add(ordered_products)
            order.save()
            data = OrderSerializer(order).data

            print(customer.remaining_credit)
            customer.remaining_credit -= order.cost
            print(customer.remaining_credit)
            customer.save()

            ledger = Ledger.objects.create(
                customer=customer,
                description=data.get(f'New order from {customer.first_name} {customer.last_name}'),
                amount=total_cost,
                transaction_type='debit'
            )

            return ApiResponse(200, message='Order created successfully', data=data).response()
        else:
            return ApiResponse(400, message="Amount is above customer's credit unit").response()

class RetailOrderAPIView(APIView):
    def get(self, request, customer_id=None):
        orders = Order.objects.filter(retail=True).order_by('-created_at')

        serializer = OrderSerializer(orders, many=True)

        return ApiResponse(200, data=serializer.data).response()

    def post(self, request):
        ordered = []
        total_cost = 0
        for x in request.data["products"]:
            product = Product.objects.get(product_id=x['product_id'])
            ordered_product = PerProduct.objects.get_or_create(
                product=product, quantity=x['quantity']
            )[0]
            ordered.append(ordered_product)
            total_cost += product.price * x['quantity']

        ordered_products = OrderedProduct.objects.create()
        ordered_products.mattresses.add(*ordered)
        ordered_products.save()
        order = Order.objects.create(
            name=request.data["customerName"],
            fulfilled=True,
            cost=total_cost,
            retail=True
        )
        order.ordered_products.add(ordered_products)
        order.save()

        invoice = Invoice.objects.create(
            order=order,
            total_amount=total_cost,
        )
        data = OrderSerializer(order).data
        return ApiResponse(200, message='success', data=data).response()

class EarningsView(APIView):
    def get(self, request):
        current_month = datetime.now().month
        current_year = datetime.now().year

        monthly_earnings = defaultdict(Decimal)  # Initialize as Decimal
        annual_earnings = defaultdict(Decimal)  # Initialize as Decimal

        filtered_orders = Order.objects.annotate(month=TruncMonth('created_at')).annotate(year=TruncYear('created_at'))

        for order in filtered_orders:
            month = order.created_at.month
            year = order.created_at.year
            earnings = order.calculate_cost()
            monthly_earnings[month] += Decimal(str(earnings))  # Convert earnings to Decimal
            annual_earnings[year] += Decimal(str(earnings))  # Convert earnings to Decimal

        data = {
            'monthly_earnings': float(monthly_earnings[current_month]),  # Convert to float
            'annual_earnings': float(annual_earnings[current_year]),  # Convert to float
        }
        return ApiResponse(200, message='success', data=data).response()


from odoo import http
from odoo.http import request

class Grafana(http.Controller):

    @http.route('/statistics/', type='http', auth='user', csrf=False, website=True)
    def get_all_sales(self):
        """
        Funcja sprawdzająca czy użytkownik ma dostęp do jakichkolwiek statystyk, jeśli tak generuje stronę internetowa

        Parameters:
        -----
        access: boolean
            Wartośc logiczna czy użytkownik uzyskał dostęp do strony internetowej

        sales_rec: list of dict
            lista słowników zawierająca wszystkie dane z zamówień  użytkownika

        rec: dict
            słównik zawierająca wszystkie dane z zamówienia  użytkownika

        product_id: int
            zmienna zawierająca id produktu

        Return
        ------
        http.request.render():xml
            Zwraca zapytanie do strony internetowej
        """
        access = False
        sales_rec = request.env['sale.order'].search([])

        for rec in sales_rec:
            if rec.partner_shipping_id.id and rec.state == "sale":
                for product_id in rec.order_line.product_id:
                    if product_id.id == 1 or product_id.id == 2:
                        access = True

        if access:
            #wyświetlanie podstrony z statystykami
            return http.request.render('grafana.grafana_statistics',)
        else:
            #wyświetlanie koszyka
            return http.request.render('website_sale.cart',)


from django.shortcuts import render
from django.http import HttpResponse
def home(request):
    if request.method=="POST":
            a = request.POST["txtnum1"]
            b = request.POST["txtnum2"]
            c = int(a)+int(b)
            return HttpResponse("Result is "+str(c))
    else:
      return render(request,"addition.html")
def prime(request):
    if request.method=="POST":
      num=int(request.POST["num"])
      s=''
      for i in range(2,num):
        if num%i==0:
            s='not prime'
            break
      else:
        s='prime'
      return HttpResponse(s)
    else:
        return render(request,"prime.html")

def fibonacci(request):
    a=-1
    b=1
    res=''
    for i in range(10):
        c=a+b
        res+=str(c) + " "
        a=b
        b=c
    return HttpResponse(res)


#QComboBox_1.py
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic

form_class = uic.loadUiType("QComboBox_1.ui")[0]

class WindowClass (QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.syncComboBox()  #2개의 콤보박스를 동기화시키는 코드

        #function to comboBox1 (currenIndexChanged signal)
        self.comboBox_1.currentIndexChanged.connect(self.displayLabelFunc)

        #function to buttons
        self.printButton.clicked.connect(self.printFunc)
        self.clearButton.clicked.connect(self.clearFunc)
        self.addButton.clicked.connect(self.addFunc)
        self.deleteButton.clicked.connect(self.deleteFunc)

        #function to lineEdit
        self.addLine.returnPressed.connect(self.addFunc)

    def syncComboBox(self):
        for i in range(0, self.comboBox_1.count()):
            self.comboBox_2.addItem(self.comboBox_1.itemText(i))

    def displayLabelFunc(self):
        self.displayLabel.setText(self.comboBox_1.currentText())

    def printFunc(self):
        print(self.comboBox_1.currentText())

    def clearFunc(self):
        self.comboBox_1.clear()
        self.comboBox_2.clear()

    def addFunc(self):
        self.item = self.addLine.text()

        self.comboBox_1.addItem(self.item)
        self.comboBox_2.addItem(self.item)
        print(f"\"{self.item}\" is added to list.")

    def deleteFunc(self):
        self.index = self.comboBox_2.currentIndex()
        self.item_2 = self.comboBox_2.currentText()

        self.comboBox_1.removeItem(self.index)
        self.comboBox_2.removeItem(self.index)

        print(f"\"{self.item_2}\" is deleted from list.")

if __name__=="__main__":
    app = QApplication(sys.argv)
    myWindow = WindowClass()
    myWindow.show()
    app.exec_()


"""
不销毁ship实例，记录跟踪游戏的统计信息来记录飞船被装了多少次
"""

class GameStats():
    """跟踪游戏的统计信息"""

    def __init__(self, ai_settings):
        """初始化统计信息"""
        self.ai_settings = ai_settings
        self.reset_stats()
        # 游戏刚启动时处于非活动状态
        self.game_active = False
        # 在任何情况下都不重置最高得分
        self.high_score = 0

    def reset_stats(self):
        """初始化在游戏运行期间可能变化的统计信息
            在__init__()中调用这个方法，这样创建GameStats实例时将妥善的设置统计信息，同时在玩家开始新游戏时也能调用reset_stats()
        """
        self.ships_left = self.ai_settings.ship_limit
        self.score = 0
        self.level = 1


__copyright__ = 'Copyright(c) Gordon Elliott 2019'

"""
id	SURNAME	FIRST_NAME	TITLE	STATUS	main contact?	household id
ADDRESS1	ADDRESS2	ADDRESS3	County	EIRCODE	landline
mobile	other personal	email	gdpr response?	email?	phone?	post?	news?	finance?
"""

from a_tuin.metadata import IntField, StringField, ObjectFieldGroupBase, Collection

class Parishioner(ObjectFieldGroupBase):
    # Receives parishioner records from parish list

    public_interface = (
        IntField('reference_no', is_mutable=False),
        StringField('surname'),
        StringField('first_name'),
        StringField('title'),
        StringField('status'),
        StringField('main_contact'),
        IntField('household_ref_no'),
        StringField('mobile'),
        StringField('other'),
        StringField('email'),
        StringField('gdpr_response'),
        StringField('by_email'),
        StringField('by_phone'),
        StringField('by_post'),
        StringField('news'),
        StringField('finance'),
    )

class ParishionerCollection(Collection):
    pass


#!/usr/bin/env python3

#https://roboticsbackend.com/control-arduino-with-python-and-pyfirmata-from-raspberry-pi/#Step_1_Run_StandardFirmata_on_your_Arduino_board

import pyfirmata
import time
if __name__ == '__main__':
    board = pyfirmata.Arduino('/dev/ttyACM0')
    print("Communication Successfully started")

    speed = board.digital[5]
    speed.mode = pyfirmata.PWM
    forward = board.digital[7]
    backward = board.digital[8]

    d = 0
    s = 0.5
    while True:
        d = 1 - d
        backward.write(d)
        forward.write(1 - d)

        speed.write(s)
        s = s + 0.1
        if(s > 1):
            s = 0.5

        time.sleep(1)

        print("hi", d, s)

        # backward.write(0)
        # forward.write(1)
        # for dc in range(0, 51, 1):
        #     speed.write(dc / 100)
        #     time.sleep(0.1)
        #     print("forward", dc)

        # forward.write(0)
        # backward.write(1)
        # for dc in range(0, 51, 1):
        #     speed.write(dc / 100)
        #     time.sleep(0.1)
        #     print("backward", dc)


import streamlit as st
import torch
from PIL import Image
import torchvision.transforms as transforms

# Load the trained model's state dictionary
from model import Net

model = Net()
model.load_state_dict(torch.load('mnist_model_final.pth'))
model.eval()

def predict(image):
    # Preprocess the image
    image = Image.open(image).convert("L")
    image = image.resize((28,28))
    image = transforms.ToTensor()(image)
    image = image.view(-1, 1, 28, 28)

    # Pass the image through the model
    output = model(image)
    prediction = torch.argmax(output).item()
    return prediction

st.set_page_config(page_title="MNIST model", page_icon=":guardsman:", layout="wide")

st.title("MNIST model")

file_image = st.file_uploader("Please upload your image", type=["jpg", "png"])

if file_image:
    image = Image.open(file_image)
    st.image(image, caption="Uploaded Image", use_column_width=True)
    prediction = predict(file_image)
    st.write("Prediction: ", prediction)


# -*- coding: utf-8 -*-
"""
Created on Mon Aug 21 22:32:34 2023

@author: alden
"""
from sklearn.datasets import make_regression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import PredictionErrorDisplay
from sklearn.model_selection import cross_val_predict, KFold
from TabML import TabML
from hyperopt import hp
from xgboost import XGBRegressor
from sklearn.linear_model import ElasticNet
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import shap

# get some toy dataset
X, y, true_coefs = make_regression(n_samples = 100, n_features = 50, noise = 0.1, coef = True)
data = pd.DataFrame(data = X, columns = [f'x{i+1}' for i in range(X.shape[1])])
data['y'] = y

# define which model to use as blackbox (wrapper and surrogate)
# also define the hyperparameter optimization space using the hyperopt library
blackbox_model = XGBRegressor
blackbox_space = {
    'n_estimators': hp.quniform('n_estimators', 50, 500, 1),
    'learning_rate': hp.loguniform('learning_rate', 0.01, 0.3),
    'max_depth': hp.quniform('max_depth', 1,10,1),
    'colsample_bytree': hp.uniform('colsample_bytree', 0.5, 1),
    'gamma': hp.uniform('gamma', 0.1, 1),
    'reg_alpha': hp.uniform('reg_alpha', 0, 1),
    'reg_lambda': hp.uniform('reg_lambda', 0, 3),
    'subsample': hp.uniform('subsample', 0.5, 1),
    'min_child_weight': hp.quniform('min_child_weight', 1, 5, 1),
    'verbosity' : 0,
    #'tree_method': 'gpu_hist',
    #'gpu_id': 0
}

# define which hyperparameters are supposed to be integers
blackbox_space_integer_parameters = ['n_estimators','max_depth','min_child_weight']

# define which model to use as interpretable model (base and/or SAFE)
# also define the hyperparameter optimization space using the hyperopt library
interpretable_model = ElasticNet
interpretable_space = {
    'alpha': hp.uniform('alpha', 0.0, 1.0),
    'l1_ratio': hp.uniform('l1_ratio', 0.0, 1.0),
}

# define which hyperparameters are supposed to be integers
interpretable_space_integer_parameters = [None]

# define the outer and inner cross validators
outer_cv = KFold(n_splits = 10)
inner_cv = KFold(n_splits = 5)

# initiate the TabML_model
TabML_model = TabML(
    data = data,
    groups = None, # no group labels. Not applicable anyways if using non Group based CV.
    blackbox_model = blackbox_model,
    blackbox_space = blackbox_space,
    blackbox_space_integer_parameters = blackbox_space_integer_parameters,
    interpretable_model = interpretable_model,
    interpretable_space = interpretable_space,
    interpretable_space_integer_parameters = interpretable_space_integer_parameters,
    scaler = StandardScaler(), #use StandardScaler as data scaler
    contamination = 0, # do not perform outlier removal using Isolation Forest
    outer_cv = outer_cv, # cross validator used in outer folds
    inner_cv = inner_cv, # cross validator used in inner folds
    m = np.inf, # do not select the most important 'm' features - keep all features according to this criteria
    percentile = 0, # do not select the most important 'percentile'*100% of features
    max_evals = 50, # allow 50 evaluations for hyperparameter optimization in the inner CV folds
    filter_feature_selection = True, # perform filter based feature selection based on Spearman coefficient between features
    iterative_feature_selection = True, # perform iterative feature selection by eliminating all features with 0 shap values during wrapper model fitting
    target_transform = None # perform no transformation for the target before data scaling
    )

# carry out the fitting procedure (or use the .fit method of the TabML class
# first fit the wrapper model and evaluate it
wrapper_model, wrapper_data, wrapper_scaler = TabML_model.fit_model(model_key = 'wrapper')
wrapper_mse, wrapper_r2 = TabML_model.evaluate_model(model_key = 'wrapper', model_data = wrapper_data)

# fit and evaluate the surrogate model - requires blackbox model be fitted and evaluated
surrogate_model, surrogate_data, surrogate_scaler = TabML_model.fit_model(model_key = 'surrogate')
surrogate_mse, surrogate_r2 = TabML_model.evaluate_model(model_key = 'surrogate', model_data = surrogate_data)

# fit and evaluate the SAFE model - requires surrogate model be fitted but not evaluated
SAFE_model, SAFE_data, SAFE_scaler = TabML_model.fit_model(model_key = 'SAFE')
SAFE_mse, SAFE_r2 = TabML_model.evaluate_model(model_key = 'SAFE', model_data = SAFE_data)

# fit and evaluate the base interpretable model as comparison with the other models
# requires surrogate model be fitted but not evaluated
base_model, base_data, base_scaler = TabML_model.fit_model(model_key = 'base')
base_mse, base_r2 = TabML_model.evaluate_model(model_key = 'base', model_data = base_data)

# generate a summary table of model performances
summary = pd.DataFrame(
    {
     'wrapper':{
        'mse': f'{np.mean(wrapper_mse):.0f} ({np.std(wrapper_mse,ddof=1):.0f})',
        'r2': f'{np.mean(wrapper_r2):.3f} ({np.std(wrapper_r2,ddof=1):.2f})'
        },
    'surrogate':{
        'mse': f'{np.mean(surrogate_mse):.0f} ({np.std(surrogate_mse,ddof=1):.0f})',
        'r2': f'{np.mean(surrogate_r2):.3f} ({np.std(surrogate_r2,ddof=1):.2f})'
        },
    'SAFE':{
        'mse': f'{np.mean(SAFE_mse):.0f} ({np.std(SAFE_mse,ddof=1):.0f})',
        'r2': f'{np.mean(SAFE_r2):.3f} ({np.std(SAFE_r2,ddof=1):.2f})'
        },
    'base':{
        'mse': f'{np.mean(base_mse):.0f} ({np.std(base_mse,ddof=1):.0f})',
        'r2': f'{np.mean(base_r2):.3f} ({np.std(base_r2,ddof=1):.2f})'
        }
    })

print(summary)

# interested in the best model
mses = np.mean([wrapper_mse, surrogate_mse, SAFE_mse, base_mse], axis = 1).tolist()
best_index = mses.index(min(mses))
best_model = [wrapper_model, surrogate_model, SAFE_model, base_model][best_index]
best_data = [wrapper_data, surrogate_data, SAFE_data, base_data][best_index]
best_scaler = [wrapper_scaler, surrogate_scaler, SAFE_scaler, base_scaler][best_index]
best_model_key = ['wrapper','surrogate','SAFE','base'][best_index]
# interested in the original scale dataset used for the best model - use the returned data and scaler
if best_scaler != SAFE_scaler:
    original_scale_best_data = pd.DataFrame(best_scaler.inverse_transform(best_data), columns = best_scaler.feature_names_in_)
else:
    print("original scale best data is not meaningful - SAFE uses extracted categorical features")

# interested in getting a rough visual of prediction vs. true values for the best model
wrapper_model = TabML_model.wrapper_model
y_pred = cross_val_predict(best_model,best_data.iloc[:,:-1],best_data.iloc[:,-1],cv = TabML_model.outer_cv)
y_pred = TabML_model._inverse_transform_y(y_pred)
y = TabML_model._inverse_transform_y(best_data.iloc[:,-1])
resi = y-y_pred
resi = resi
fig, axs = plt.subplots(ncols=2, figsize=(8, 4))
PredictionErrorDisplay.from_predictions(y,y_pred=y_pred,kind="actual_vs_predicted",ax=axs[0])
axs[0].set_title("Actual vs. Predicted values")
PredictionErrorDisplay.from_predictions(y,y_pred=y_pred,kind="residual_vs_predicted",ax=axs[1],random_state=0)
axs[1].set_title("Residuals vs. Predicted Values")
fig.suptitle("Plotting cross-validated predictions")
plt.show()

# interested in the SHAP values of the best performing model
X = best_data.iloc[:,:-1]
try:
    explainer = shap.Explainer(best_model)
except Exception:
    try:
        explainer = shap.KernelExplainer(best_model, X)
    except Exception:
        try:
            explainer = shap.LinearExplainer(best_model, X)
        except Exception as e:
            raise RuntimeError(f"Neither shap.Explainer, shap.KernelExplainer, or shap.LinearExplainer were applicable due to {e}")

shap_values = explainer.shap_values(X)
plt.figure()
shap.summary_plot(shap_values, X)

# if best model is a linear model with attribute .coef_, plot that as well
try:
    coefs = best_model.coef_.tolist() #append a random num as 'target' for scaler to work
    plt.figure()
    plt.barh(width = coefs, y = X.columns)
    plt.title("coefficients for each feature used in the best model")
    plt.figure()
    plt.barh(width = true_coefs[true_coefs != 0], y = data.iloc[:,:-1].columns[true_coefs != 0])
    plt.title("TRUE coefficients for each feature")
except Exception:
    print("best model does not have attribute .coef_")


import random

class Persona(object):
    def __init__(self,sexo,edad,altura):
        self.sexo = sexo
        self.edad = edad
        self.altura = altura
        self.generar_dni()

    def es_mayor_edad(self):
        if self.edad >= 18:
            return True
        else:
            return False

    def print_data(self):
        print("sexo: " + self.sexo + "\nedad: " + str(self.edad) + "\naltura: " + str(self.altura) + "\ndni: " + str(self.dni))

    def generar_dni(self):
        numero = ""
        for i in range(8):
            num = random.randrange(10)
            numero += str(num)
        self.dni = numero

a = Persona("m",19,1.85)


__author__ = 'wintere', 'wchen'

import sys, os
from lxml import etree
import codecs
import re
import traceback
import conversion_dict as cd
import argparse

reserved_char = dict()

# XML reserved chars: to be stripped except for 'and'
# >
reserved_char['>'] = '|'
# <
reserved_char['<'] = '|'
# &
reserved_char['&'] = 'and'
# %
reserved_char['%'] = '|'

conversion_dict = cd.getConversionDict()
bracket_contents = cd.getBrevigraphList()

#'&c' = 'etc'
#'&' = 'and'

def strip_html(data):
    """
    Use regular expression to remove the html tags

    Return:  string without html tags
    """
    p = re.compile(r'<.*?>', re.DOTALL)
    return p.sub('', data)

def strip_htmlcomment(data):
    """
    Use regular expression to remove the html comments

    Return:  string without html comments
    """
    p = re.compile(r'', re.DOTALL)
    return p.sub('', data)

def replace_html(bytes):
    if b'&c' in bytes:
        bytes = bytes.replace(b'&c', b'etc')
    if b'&' in bytes:
        bytes = bytes.replace(b'&', b'and')
    if b'&' in bytes:
        bytes = bytes.replace(b'&', b'and')
    return bytes.decode('utf-8', errors='replace')

def isMusic(string):
    if 'note' in string or 'repeat' in string or 'timeimperf' in string or 'clef' in string or 'barline' in string or 'rest' in string:
        return True
    if string in ['fermata','direct']:
        return True
    return False

def isPunc(string):
    if 'brace' in string or 'fleur-de-lys' in string:
        return True
    if string in ['multiplier','divisor','fivedot','quotient','product','left angle','higher term']:
        return True
    else:
        return False

def brace_contents(string):
    if string in bracket_contents:
        if string == 'is':
            #standardization for english plurals rendered using brevigraphs
            return 'es'
        return string
    elif 'left blank' in string or 'punctel' in string:
        return ''
    elif isMusic(string) or isPunc(string):
        return '*'
    elif 'reversed' in string or 'inverted' in string or 'roman' in string or 'horizontal' in string:
        return re.sub(r'(roman )|(inverted )|(reverse )|(horizontal )','',string)
    else:
        return '{'+string+'}'

# process for <SEG>, <GAP>, and html comments
def special_tag_process(filepath):
    seg_tag_reg = re.compile(r'<SEG.*?>.*?</SEG>')
    gap_tag_reg = re.compile(r'<GAP.*?/>')
    sup_tag_reg = re.compile(r'.*?')
    sub_tag_reg = re.compile(r'.*?')
    brev_reg = re.compile(r'\{[^w]+\}')
    file_str = ''
    with open(filepath, mode="rb") as fr:
        file_bytes = fr.read()
        file_str = replace_html(file_bytes)
        seg_toks = seg_tag_reg.findall(file_str)
        gap_toks = gap_tag_reg.findall(file_str)
        sup_toks = sup_tag_reg.findall(file_str)
        sub_toks = sub_tag_reg.findall(file_str)
        brevi_toks = brev_reg.findall(file_str)
        if brevi_toks:
            file_str = re.sub('\{([^w^}]+)\}', lambda match: brace_contents(match.group(1)),file_str)
        for tok in seg_toks:
            new_tok = strip_html(tok)
            file_str = file_str.replace(tok, new_tok)
        for tok in gap_toks:
            if "duplicate" in tok:
                file_str = file_str.replace(tok, '')  # strip out duplicate markers
            elif "word" in tok or "foreign" in tok or "page" in tok or "span" in tok:
                file_str = file_str.replace(tok, '(...)')
            #cases where the number of missing characters is known
            elif "•" in tok:
                extent = tok.count('•')
                file_str = file_str.replace(tok, '^' * extent)
            else:
                file_str = file_str.replace(tok, '^')
        for tok in sup_toks:
            char = re.sub('|', '', tok)
            file_str = file_str.replace(tok, char)
        for tok in sub_toks:
            char = re.sub('|', '', tok)
            file_str = file_str.replace(tok, char)
    fr.close()
    file_str = strip_htmlcomment(file_str)
    return codecs.encode(file_str, encoding='utf-8', errors='ignore')

def clean_word(string):
    macron_r = r'([^w])̄'
    # remove macrons: hack for when macrons are treated as 'character,macron' rather than a single character
    string = re.sub(macron_r, lambda match: match.group(1) +'^',string)
    for char in string:
        try:
            codecs.encode(char, 'ascii', errors='strict')
        except UnicodeEncodeError:
            if char in conversion_dict:
                string = string.replace(char, conversion_dict[char])
            else:
                string = string.replace(char, '@')
    string = string.replace('|', '')
    return string

# removes all unicode characters from a utf-8 xml file
def simple_clean(filepath, strip=False):
    parser = etree.XMLParser(remove_blank_text=True, encoding='utf-8')

    # returns byte string of file
    file_bytes = special_tag_process(filepath)
    try:
        root = etree.fromstring(file_bytes, parser)
    # Deal with any special cases that break the XML parser
    except etree.XMLSyntaxError as e:
        return 0

    for node in root.iter():
        # remove unicode characters from asterisks
        if node.text is not None:
            text = node.text
            for key in reserved_char.keys():
                if key in text.split():
                    text = text.replace(key, reserved_char[key])
            node.text = clean_word(text)
        if node.tail is not None:
            tail = node.tail
            for key in reserved_char.keys():
                if key in tail.split():
                    tail = tail.replace(key, reserved_char[key])
            node.tail = clean_word(tail)
        # scrub unicode characters from attributes
        if node.attrib is not None:
            for key, val in node.attrib.items():
                node.attrib[key] = clean_word(val)
    #method returns bytes, not a string, thanks etree??
    xml_bytes = etree.tostring(root, method='xml', pretty_print=True, encoding='ascii')
    if strip:
        xml_bytes = xml_bytes.replace(b'@', b'')
    try:
        # tests that string can be converted back into an xml tree
        etree.fromstring(xml_bytes, parser)
        return xml_bytes.decode('ascii')
    except:
        traceback.print_exc(file=sys.stdout)
        return 1

# a cleaning method for plain text files
def txt_clean(filepath, strip=False):
    f = open(filepath, mode='r', encoding='utf-8', errors='ignore')
    file_str = f.readlines()
    s = ''
    for line in file_str:
        lc = clean_word(line)
        s += lc
    s = strip_html(s)
    s = strip_htmlcomment(s)
    if strip:
        s = s.replace('@', '')
    return s

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='VEP Character Cleaner')
    parser.add_argument('input_path', help='path to corpus to character clean relative to the location of this script')
    parser.add_argument('output_path', help='path to output folder relative to the location of this script')
    parser.add_argument('--strip_unknown',
                        help='strips unknown unicode characters, if disabled unknown unicode characters will be marked with @',
                        action='store_true')

    args = parser.parse_args()
    srcdir = args.input_path
    destdir = args.output_path
    strip = args.strip_unknown

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

    if not os.path.exists(srcdir):
        print("Error: Input path", srcdir, "does not exist.")
        exit()
    if os.path.isdir(srcdir):
        failedFiles = []  # retain a list of unparseable files for batch processing
        for dirpath, subdirs, files in os.walk(srcdir):
            for file in files:
                if file.endswith(".xml") or file.endswith(".txt"):  # only processing XML and TXT files
                    filePath = os.path.join(dirpath, file)
                    op_path = os.path.join(destdir, file)
                    print('generating... ' + op_path)
                    if file.endswith(".xml"):
                        outputStr = simple_clean(filePath, strip=strip)
                    else:
                        outputStr = txt_clean(filePath, strip=strip)
                    if outputStr == 0 or outputStr == 1:  # check for error codes
                        failedFiles.append(filePath)
                        continue
                    outputFile = open(op_path, mode='w', encoding='ascii')
                    outputFile.write(outputStr)
                    outputFile.close()
                else:
                    print("skipping file", file, "because it is not an .xml or .txt file")
        if len(failedFiles) > 0:
            print("\nBatch completed with errors. Unable to parse the following files: ")
            for filename in failedFiles:
                print(filename)
        else:
            print("\nBatch completed successfully.")
    # if source exists but isn't a directory, it must be a file
    else:
        filePath = srcdir
        if filePath.endswith(".xml"):
            outputStr = simple_clean(filePath)
        elif filePath.endswith(".txt"):
            outputStr = txt_clean(filePath)
        else:
            print("Error: invalid input file.", filePath, "is not an .xml or .txt file.")
            exit()
        fn = os.path.basename(filePath)
        outputPath = os.path.join(destdir, fn)
        outputFile = open(outputPath, mode='w', encoding='ascii')
        print('generating... ' + outputPath)
        outputFile.write(outputStr)
        outputFile.close()


import decimal
service_charge_rate = decimal.Decimal(0.005)

class Account:

    capital = decimal.Decimal(100000.0)

    stock = decimal.Decimal(0.0)

    open_times = 0

    total_money_arr = []

    trade_data_arr = []

    def __init__(self):
        pass

    def open(self, price, t):
        if self.capital == 0:
            return
        self.trade_data_arr.append({
            't': t,
            'price': price,
            'status': 'open'
        })
        self.open_times = self.open_times + 1
        self.stock = self.stock + self.capital / (price * (1 + service_charge_rate))
        self.capital = decimal.Decimal(0.0)

    def close(self, price, t):
        if self.stock == 0:
            return
        self.trade_data_arr.append({
            't': t,
            'price': price,
            'status': 'close'
        })
        self.capital = self.capital + self.stock * price
        self.stock = decimal.Decimal(0.0)

    def report(self, price):
        self.total_money_arr.append(float(self.capital + self.stock * price))

    def print_msg(self):
        print('capital:%2f'%(self.capital))
        print('stock:%2f'%(self.stock))


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

import re
import csv
import urllib2

OUTPUT_CSV = 'output.csv'
TITLE = [
        u'Название',
        u'Регион',
        u'Район',
        u'Населённый пункт',
        u'Адрес',
        u'Широта',
        u'Долгота',
        u'Телефоны',
        u'Время работы',
         ]
START_URL = 'http://www.yadonor.ru/common/js/google_maps/google.php'

MARKER_RE = re.compile('var point = new GLatLng\((.*),(.*)\);')
DATA_RE = re.compile(".*(.*)
(.*)

',markerOptions\);")
PART_RE = re.compile('(.*?): (.*)')

def writerow(data):
    data = [unicode(value).encode('utf-8').strip() for value in data]
    output.writerow(data)

output = csv.writer(open(OUTPUT_CSV, 'wb'), delimiter=';', quotechar='"', )
writerow(TITLE)

start_connection = urllib2.urlopen(START_URL)

lines = []

for line in start_connection:
    lines.append(line)

while not lines[0].startswith('var point'):
	lines = lines[1:]

while len(lines) > 0:
	title = ''
	parts = ''
	region = ''
	subregion = ''
	town = ''
	address = ''
	lat = ''
	lng = ''
	phone = ''
	times = ''

	coords = lines[0];
	data = lines[1]
	lines = lines[3:]

	match = MARKER_RE.search(coords)
	if not match:
		continue

	lat = match.group(1)
	lng = match.group(2)

	match = DATA_RE.search(data.decode('utf-8'))
	if not match:
		continue

	title = match.group(1)
	parts = match.group(2).split('
')

	for part in parts:
		match = PART_RE.search(part)
		if not match:
			continue
		k = match.group(1)
		v = match.group(2).strip()
		if k == u'Регион':
			region = v
		if k == u'Район':
			subregion = v
		if k == u'Город':
			town = v
		if k == u'Адрес':
			address = v
		if k == u'Телефон' and len(phone) == 0:
			phone = v
		if k == u'Время работы':
			times = v

	writerow([
		title,
		region,
		subregion,
		town,
		address,
		lat,
		lng,
		phone,
		times
		])

Станции службы крови Российской Федерации/parse.py


import re

str1 = '3.14159,425,-dalin,Big2.3Data,small5data.64132.432 !dsad?2020.ab 123.456.789.0'
reS1 = '\d+\.\d+'
pattern1 = re.compile(reS1)
reMatch1 = pattern1.findall(str1)
print(reMatch1)

str2 = 'Business Information Systems BSc (Hons)'
reS2 = '(.*?)'
pattern2 = re.compile(reS2)
reMatch2 = pattern2.findall(str2)
print(reMatch2)

str31 = '123! dalin ?zhoudalin 111dalin222'
str32 = 'dalin123! dalin ?zhoudalin 111dalin222'
str33 = '123! dalin ?zhoudalin 111dalin222dalin'
#compare ^ and $
reS31 = '^dalin'
reS32 = 'dalin$'
pattern31 = re.compile(reS31)
pattern32 = re.compile(reS32)
reMatch31 = pattern31.findall(str31)
reMatch32 = pattern32.findall(str31)
print(reMatch31)
print(reMatch32)
reMatch33 = pattern31.findall(str32)
reMatch34 = pattern32.findall(str32)
print(reMatch33)
print(reMatch34)
reMatch35 = pattern31.findall(str33)
reMatch36 = pattern32.findall(str33)
print(reMatch35)
print(reMatch36)

#str4 =
#compare .* and .*?
str4 = 'ddnaaddndnlinnn'
reS41 = 'd.*n'
reS42 = 'd.*?n'
pattern41 = re.compile(reS41)
reMatch41 = pattern41.findall(str4)
print(reMatch41)
pattern42 = re.compile(reS42)
reMatch42 = pattern42.findall(str4)
print(reMatch42)

#str5 =
#use of {}
str5 = 'abcddd aabbccddd 12313 222 223344 dalin dalindalin !?'
reS51 = '\d{2}'
reS52 = 'dalin{2}'
reS53 = 'a{1,3}'
pattern51 = re.compile(reS51)
reMatch51 = pattern51.findall(str5)
print(reMatch51)
pattern52 = re.compile(reS52)
reMatch52 = pattern52.findall(str5)
print(reMatch52)
pattern53 = re.compile(reS53)
reMatch53 = pattern53.findall(str5)
print(reMatch53)


# -*- coding: utf-8 -*-
"""
Created on Thu Jan 25 11:11:04 2018

@author: leshuangjiang
"""

import pandas as pd
import xlwings as xw

def get_data_fromexcel():
    app = xw.App(visible=False, add_book=False)
    app.display_alerts = False
    app.screen_updating = False
    xb = app.books.open(r"D:\文档\表格\绩效计算\成本数据1-12.xlsx")
    sheet = xb.sheets[0]
    sheet.activate()
    rng = sheet.range('a1:au100000').options(pd.DataFrame, index=False).value
    xb.close()
    app.quit()
    xw.App.kill(app)
    print('数据已经写入到内存中……\n')
    return rng

def data_screen(rng):
    df = rng.dropna(axis=0, how='all')
    df = df.dropna(axis=1, how='all')
    df = df.loc[df['中类'] != '公司赠送'].copy()
    df['创建日期'] = df['创建日期'].astype('str')
    df['月份'] = df['创建日期'].str.split('-').str[0].str[-2:] + 'M' + df['创建日期'].str.split('-').str[1]
    df['结果中类'] = df['绩效部门'].copy()
    df_tat = df.loc[(df['绩效部门'] == '外套') | (df['绩效部门'] == '衬衫')
                     |(df['绩效部门'] == '裤子') | (df['绩效部门'] == '裙子')
                     |(df['绩效部门'] == '西服风衣呢')].copy()
    df_tat['结果中类'] = '梭织'
    result = pd.concat([df, df_tat], join='outer', ignore_index=True)
    print('梭织数据已经加入\n')
    return result

purchase_dic = {'101': '牛仔',
                '102': '针织',
                '104': '毛衫',
                '103': '梭织',
                '106': '鞋品',
                '120': '梭织',
                '121': '梭织',
                '122': '梭织',
                '123': '梭织',
                '124': '针织',
                '125': '毛衫',
                '126': '牛仔',
                'A02': 'GSON',
                'A04': 'GSON',
                'A08': 'GSON',
                'A07': '广州产品部',
                'A06': '原点采购组',
                'A10': '潮流运动',
                'A11': '新男装',
                '127': '新商品',
                '105': '配件'}

tatting_dic = {'00': '针织', '01': '针织', '02': '针织', '03': '外套', '04': '衬衫', '05': '衬衫', '06': '毛衫',
               '07': '毛衫', '08': '外套', '09': '外套', '10': '西服风衣呢',  '11': '西服风衣呢',    '12': '外套',
               '13': '外套', '14': '裙子', '15': '外套', '16': '针织', '17': '外套', '18': '西服风衣呢', '19': '衬衫',
               '20': '裙子', '21': '裤子', '22': '牛仔', '23': '牛仔', '24': '牛仔', '25': '裤子',  '26': '裤子',
               '27': '裤子', '40': '鞋品','41': '鞋品', '42': '鞋品', '43': '鞋品', '44': '鞋品', '45': '鞋品',
               '47': '鞋品', '48': '鞋品', '50': '配件', '51': '配件', '52': '配件', '53': '配件', '54': '配件',
               '55': '配件', '56': '配件', '57': '配件', '58': '配件', '59': '促销品', '60': '配件', '61': '配件',
               '62': '配件', '70': '配件', '71': '配件', '72': '配件', '73': '配件', '74': '配件',
               '75': '鞋品', '76': '配件', '77': '配件', '90': '公司赠送', '91': '物流工服',
               '92': '品牌推广赠送', '93': '外部团体采购', '46': '鞋品', '82': '配件', '84': '配件'}
other = {'Y': '原点采购组',
         'G': 'GSON',
         'F': '潮流运动'}

def data_change(result):
    result['加减价金额'] = pd.to_numeric(result['加减价金额'])
    result['标准核价总额'] = pd.to_numeric(result['标准核价总额'])
    result.rename(columns={'订单类型（采购）': '模式', '供应商简称': '正确简称', '采购凭证号': '采购订单号', '物料号': '款号'}, inplace=True)
    group_one = result.groupby(['月份', '正确简称', '结果中类', '模式', '款号'], sort=True)
    second = group_one[ '标准核价总额', '加减价金额'].sum().reset_index()
    ssd = second.groupby([ '月份', '正确简称', '结果中类'])['标准核价总额', '加减价金额'].sum().reset_index()
    ssd.to_excel('d:\\成本偏差结果表.xlsx')
    return '数据已经保存在-d:\\成本偏差结果表.xlsx'

if __name__ == '__main__':
    RNG = get_data_fromexcel()
    SCREEN = data_screen(RNG)
    print(data_change(SCREEN))
    print('all is ok')


from django.contrib import admin
from django.urls import path,re_path,include
from chat import views
urlpatterns = [
    path('', views.index,name="index"),
    path('<str:room_name>/', views.room,name="room"),
    path('getusername',views.getusername,name="getusername"),
    path('tempchatroom',views.tempchatroom,name="tempchatroom"),
    path('fetchremdata',views.fetchdremdata,name="fetchremdata"),
]


import time
import random

from elasticsearch import Elasticsearch

es_client: Elasticsearch = Elasticsearch("localhost:9200")

def saving_data_test():
    start = time.time()
    for i in range(10000):
        es_client.index(index="test_index", id=str(i), document={"id": i, "some_data": f"some_data_{i}"})
    return time.time() - start

def get_data():
    start = time.time()
    es_client.search(index="test_index", body={"query": {"match_all": {}}}, size=10000)
    return time.time() - start

def get_find_data():
    start = time.time()
    random_id = random.randint(0, 10000)
    es_client.search(index="test_index", body={"query": {"match": {"message": {"query": random_id}}}}, size=10000)
    return time.time() - start

if __name__ == '__main__':
    print(saving_data_test())
    print(get_data())
    print(get_find_data())


import sys

# For getting input
# sys.stdin = open('input1.txt', 'r')
# sys.stdin = open('input2.txt', 'r')
sys.stdin = open('input3.txt', 'r')

# Printing the Output
# sys.stdout = open('result1.txt', 'w')
# sys.stdout = open('result2.txt', 'w')
sys.stdout = open('result3.txt', 'w')

number_of_test_cases = number_of_test_cases = int(sys.stdin.readline())

case = 1

for box in range(number_of_test_cases):
    length, width, height = map(int, sys.stdin.readline().split())

    if length > 20:
        sys.stdout.write(f"Case {case}: bad" + "\n")
    elif width > 20:
        sys.stdout.write(f"Case {case}: bad" + "\n")
    elif height > 20:
        sys.stdout.write(f"Case {case}: bad" + "\n")
    else:
        sys.stdout.write(f"Case {case}: good" + "\n")

    case += 1


f = open("covid_19_india.csv")
dict = {}
for line in f:
    w = line.rstrip("\n").split(",")
    state = (w[3])
    cure = int(w[-3])
    death = int(w[-2])
    confirm_case = int(w[-1])
    dict[state] = {"state": state, "confirm_case": confirm_case, "cure": cure, "death": death}
print(dict)


import re
from typing import Iterable, Match, Optional, Pattern

from pydantic import BaseModel, PositiveInt

from .settings import DEFAULT_MODULE_DELIMITER, MODULE_DELIMITERS

class Module(BaseModel):
    """Representation of the 'module' as defined in the taxonomy."""

    section: PositiveInt
    module: PositiveInt

    def __str__(self):
        return self.to_string()

    def __field_to_str(self, field: str):
        if field not in self.__annotations__:
            raise ValueError(f"Field '{field}' is not defined in the model.")
        return field[0].upper() + str(getattr(self, field))

    def __fields_to_str(self, fields: Iterable[str], delimiter: str):
        return delimiter.join((self.__field_to_str(field) for field in fields))

    def to_string(self, delimiter: str = DEFAULT_MODULE_DELIMITER) -> str:
        """Generate a string representation suitable for a FastText line."""
        return self.__fields_to_str(Module.all_fields(), delimiter)

    @staticmethod
    def all_fields() -> Iterable[str]:
        return Module.__annotations__.keys()

    @classmethod
    def from_string(
        cls,
        s: str,
        *,
        label_prefix: str = "",
        delimiters: Iterable[str] = MODULE_DELIMITERS,
    ):
        """Parse a string representation of a module, optionally with a prefix (e.g. '__label__')."""

        delimiters_pattern: str = "|".join(delimiters)
        pattern: Pattern = re.compile(
            rf"^{label_prefix}(?:S|s)(?P<section>\d\d?)({delimiters_pattern})(?:M|m)(?P<module>\d\d?)$"
        )

        match: Optional[Match] = pattern.fullmatch(s)

        if match is None:
            raise ValueError(f"Invalid module string: {s}")
        else:
            return cls(
                section=int(match.group("section")),
                module=int(match.group("module")),
            )


from threading import Thread
import math
import random
import time
import numpy as np
import sys
import reader

global graph
graph = reader.read_instance('./data/myciel5.col')

iterations = 1000
particles = 100

def swarm_optimization(function, dimensions, alfa, cognition, social, low, high):
    positions = generate_random_position(particles,dimensions, low, high)
    velocitys = generate_random_velocity(particles,dimensions, low, high)
    best_local_positions = [position[:] for position in positions]
    best_team_position = positions[np.argmin([function(position) for position in positions])][:]

    for i in range(0,iterations):
        for particle in range(0,particles):
            for dimension in range(0, dimensions):
                velocitys[particle][dimension] = alfa * velocitys[particle][dimension] + random.random() * cognition * (best_local_positions[particle][dimension] - positions[particle][dimension]) + random.random() * social * (best_team_position[dimension] - positions[particle][dimension])
            positions[particle] = np.add(positions[particle], velocitys[particle])
            if(function(positions[particle]) < function(best_local_positions[particle])):
                best_local_positions[particle] = positions[particle][:]
                if(function(best_local_positions[particle]) < function(best_team_position) and has_bad_edge(best_local_positions[particle]) == False):
                    best_team_position = best_local_positions[particle][:]

        write_statistics(function, function(best_team_position))

        if(alfa > 0.01):
            alfa = alfa - 0.0001

    print(function.__name__, function(best_team_position), function(best_team_position) - len(set(translate_to_colors(best_team_position))), translate_to_colors(best_team_position))

def generate_random_position(population_size, dimensions, low, high):
    population = []
    for individual in range(0, population_size):
        population.append([random.uniform(low, high) for dimension in range(0, dimensions)])

    return population

def generate_random_velocity(population_size, dimensions, low, high):
    population = []
    for individual in range(0, population_size):
        population.append([random.uniform(-abs(high-low), abs(high-low)) for dimension in range(0, dimensions)])

    return population

def translate_to_colors(individual, newMin = 0, newMax = graph.vertex_count - 1):
    result = [0] * len(individual)

    min_val = min(individual)
    max_val = max(individual)

    for (index,value) in enumerate(individual):
        result[index] = (newMax - newMin) * (value - min_val) / (max_val - min_val) + newMin
        result[index] = round(result[index])

    return result

def coloring_function(individual_continous):
    individual = translate_to_colors(individual_continous)
    bad_edges_counter = 0
    for vertex in range(0, len(individual)):
        if(vertex + 1 in graph.edges):
            neighbours = graph.edges[vertex + 1]
            for neighbour in neighbours:
                if(individual[vertex] == individual[neighbour - 1]):
                    bad_edges_counter = bad_edges_counter + 1

    return (bad_edges_counter / 2) + len(set(individual))

def has_bad_edge(individual_continous):
    individual = translate_to_colors(individual_continous)
    for vertex in range(0, len(individual)):
        if(vertex + 1 in graph.edges):
            neighbours = graph.edges[vertex + 1]
            for neighbour in neighbours:
                if(individual[vertex] == individual[neighbour - 1]):
                    return True

    return False

def write_statistics(function, fitness_value):
    file_handler= open("./myciel5.col", "a")
    file_handler.write(function.__name__ + " " + str(fitness_value) + "\n")
    file_handler.close()

swarm_optimization(coloring_function, graph.vertex_count, 0.5, 2, 2, 0, graph.vertex_count - 1)


clientes = int(input("Cuantos clientes hay?"))

Costo = float(input("Cual es el monto a pagar? "))
Pago = float(input("Cual es el monto recivido? "))

def caja_registradora (Pago, Costo):
	cambio = float(Pago - Costo)
	if cambio > 0:
		print("El cambio es: ", cambio)
		print("Paga con:")
	else:
		print("Eh compa, falta feria, dame", -(cambio), "pesos")

	i = float(0)
	while i < (cambio-500):
		billete500 += 1
		i += 500
	while i <= (cambio-200):
		billete200 += 1
		i += 200
	while i <= (cambio-100):
		billete100 += 1
		i += 100
	while i <= (cambio - 50):
		billete50 += 1
		i += 50
	while i <= (cambio - 20):
		billete20 += 1
		i += 20
	while i <= (cambio - 10):
		moneda10 += 1
		i += 10
	while i <= (cambio - 5):
		moneda5 += 1
		i += 5
	while i <= (cambio - 2):
		moneda2 += 1
		i += 2
	while i <= (cambio - 1):
		moneda1 += 1
		i += 1
	while i <= (cambio - 0.50):
		moneda50c += 1
		i += 0.50

	if billete500 > 0:
		print(billete500, "billetes de 500")
	if billete200 > 0:
		print(billete200, "billetes de 200")
	if billete100 > 0:
		print(billete100, "billetes de 100")
	if billete50 > 0:
		print(billete50, "billetes de 50")
	if billete20 > 0:
		print(billete20, "billetes de 20")
	if moneda10 > 0:
		print(moneda10, "monedas de 10")
	if moneda5 > 0:
		print(moneda5, "monedas de 5")
	if moneda2 > 0:
		print(moneda2, "monedas de 2")
	if moneda1 > 0:
		print(moneda1, "monedas de 1")
	if moneda50c > 0:
		print(moneda50c, "monedas de 50 centavos")

i=0
while i < clientes:
	caja_registradora(Pago, Costo)
	i += 1


#coding=utf-8

'''
 This program finds acronym inside the text article.

 One instance of an acronym is it could be inside of a parentheses. eg: "Official Development Assistance (ODA)"

'''

from wordfeatures import getpos
from nltk.tokenize import word_tokenize

def checkifsameletter(acronym):
    #checks if acronym is same letter (eg: PPP)
    ch = {}
    y = list(acronym)
    for i in y:
        try:
            ch[i] = ch[i] + 1
        except KeyError:
            ch[i] = 1

    if len(ch) == 1 and ch[acronym[0]] == len(acronym):
        # print acronym, "> True"
        return True
    else:
        # print acronym, "> False"
        return False

def checkifrecurringletter(acronym):
    #check if acronym has recurring letter like SWS
    ch = {}
    y = list(acronym)
    for i in y:
        try:
            ch[i] = ch[i] + 1
        except KeyError:
            ch[i] = 1

    double = False

    for a in list(acronym):
        if ch[a] > 1:
            double = True

    return double
    # print acronym, double

def startchecker(acronym, tokens, code):
    # code 0 = normal, 1 = same, 2 = recurring
    tokenlen = len(tokens)
    ignore = ('and', 'of', 'the', 'on')
    start = []
    s = -1
    if code == 0: #recurring
        for i in range(0, tokenlen): #iteration thru the tokens
            if tokens[i].lower().startswith(acronym[0].lower()) and tokens[i] not in ignore: #checks if token is starting with the first letter of the acronym and not in ignore list
                s = i   #checks where the meaning checking should start
    else:
        for i in range(0, tokenlen): #iteration thru the tokens
            if tokens[i].lower().startswith(acronym[0].lower()) and tokens[i] not in ignore:
                start.append(i)   #appends all possible starts

        if code == 1: # same letter acronym
            if len(start) >= len(acronym): #if the number of possible starts is greater than or equal to the acronym length it's okay. unlike if lesser, the acronym meaning is probably not there
                s = start[len(start) - len(acronym)] #to get the possible start, get the difference between the acronym length and start length and set this as an index on the start array.
            else:
                s = -1
        elif code == 2: #recurring
            ch = {}
            y = list(acronym)
            for i in y:
                try:
                    ch[i] = ch[i] + 1
                except KeyError:
                    ch[i] = 1
            if len(start) > 0:
                try:
                    s = start[len(start) - ch[acronym[0]]] #set the starting index to the difference of the number of starts and the number of the first letter of the acronym
                except IndexError:
                    s = 0
    return s

def meaningchecker(tokens, acronym, *positional_parameters, **keyword_parameters): # meaningchecker(list, string)
# tokens - the words where to find the meaning of the acronym.
    start = -1  #initialize
    tokenlen = len(tokens)  #get the token length
    ignore = ('and', 'of', 'the', 'on')  # ignore list
    ignorecount = {}
    if ('start' in keyword_parameters):
        start = 0
    else:
        if checkifsameletter(acronym):
            start = startchecker(acronym, tokens, 1)
        elif checkifrecurringletter(acronym):
            start = startchecker(acronym, tokens, 2)
        else:
            start = startchecker(acronym, tokens, 0)
    accepted = False

    # print "meaningchecker", tokens, acronym

    if start != -1 and start+1 < tokenlen and len(acronym) > 1: #just checking if start != -1 w/c means the acronym may not be defined near it and if it's not a single letter only.
        a = 1 #init
        meaning = tokens[start] #meaning variable takes the value of the starting token.
        if meaning in ignore: #just checking if the first word is in ignore
            return (False, "")  #if yes, stop the process immediately.
        for j in range(start+1, tokenlen): #iteration thru the tokens

            # if tokens[j].lower().startswith(acronym[a].lower()): #if the words starts with the current letter of the acronym
            #     meaning = meaning + " " + tokens[j]  #add it
            #     print "1_added->", tokens[j]
            #     a = a + 1  #a is the counter and sentinel to check if the acronym meaning is completed.
            #     accepted = True # also keep tracks if whether the meaning is still accepted or not

            # print "checking.....", tokens[j]
            if tokens[j].lower().startswith(acronym[a].lower()): #if the words starts with the current letter of the acronymtok
                if not checkifrecurringletter(acronym):
                    if tokens[j] in ignore:
                        try:
                            if tokens[j+1].lower().startswith(acronym[a].lower()): #if yung next
                                # print "1_a", tokens[j]
                                meaning = meaning + " " + tokens[j] # added the ignore
                                accepted = True
                            else:
                                # print "1_b", tokens[j]
                                meaning = meaning + " " + tokens[j]  #add it
                                a = a + 1  #a is the counter and sentinel to check if the acronym meaning is completed.
                                accepted = True # also keep tracks if whether the meaning is still accepted or not
                        except IndexError:
                            # print "1_c", tokens[j]
                            meaning = meaning + " " + tokens[j]  #add it
                            a = a + 1  #a is the counter and sentinel to check if the acronym meaning is completed.
                            accepted = True # also keep tracks if whether the meaning is still accepted or no
                    else:
                        # print "1_d", tokens[j]
                        meaning = meaning + " " + tokens[j]  #add it
                        a = a + 1  #a is the counter and sentinel to check if the acronym meaning is completed.
                        accepted = True # also keep tracks if whether the meaning is still accepted or no
                else:
                    # print "1_e", tokens[j]
                    meaning = meaning + " " + tokens[j]  #add it
                    a = a + 1  #a is the counter and sentinel to check if the acronym meaning is completed.
                    accepted = True # also keep tracks if whether the meaning is still accepted or no

            elif tokens[j] in ignore: #if in ignore, it's fine. eg the words 'of', 'and' & 'the' are normally not included in the acronym but is included in the meaning.
                meaning = meaning + " " + tokens[j] #add it
                # print "2_added->", tokens[j]
                accepted = True #still accepted
                #this try and except statement keeps track if the ignored words appears only once. if not, the meaning is immediately unaccepted.
                try:
                    err = ignorecount[tokens[j]]
                    accepted = False
                    break
                except KeyError:
                    ignorecount[tokens[j]] = 1
            else:
                accepted = False
                break
            # print "accepted", accepted
            if len(acronym) == a: #checks if the acronym length is already achieved
                break

        if len(acronym) != a: #sometimes the looping process and the last checking of variable a and len(acronym) is not executed so it's a must to check if 'a' meets the length of the acronym
            accepted = False #if not, it's false. it's not the meaning of the acronym

        if accepted:
            # print acronym, meaning
            return (True, meaning)
        else:
            return (False, "")
    else:
        return (False, "")

def getacronym(tagged_sentences):
    acronyms = []
    for se in tagged_sentences:
        x = len(se)
        for i in range(0, x):
            if se[i][1] == "allCaps" or se[i][1] == "insideparen":
                acronyms.append(se[i][0])
    return list(set(acronyms))

def getacronymmeaning(acronyms, text):
    ls = []
    try:
        text = text.decode('utf-8')
        tokens = word_tokenize(text)
        x = len(tokens)
        for acronym in acronyms:
            for i in range(1, x):
                if tokens[i] == acronym:
                    # print "checking...", acronym
                    # print tokens[i], "--- ", i
                    init = 5
                    #there's a problem in here that sometimes when the range is not right, it returns an empty array.
                    # eg if an array has 5 elements and it was sliced from index 1 to 6, it will return an empty array
                    words = []
                    while not words:
                        s = i - len(acronym) - init
                        words = tokens[s:i]
                        init = init - 1
                    check, meaning = meaningchecker(words, acronym.replace('s', ''))
                    if check:
                        ls.append(meaning)
                        break
                    # else:
                        ls.append(acronym)
    except:
        ls = []
    return list(set(ls))

def matcher(tokens, acronym): # meaningchecker(list, string)
    # tokens - the words where to find the meaning of the acronym.
    start = 0  #initialize
    tokenlen = len(tokens)  #get the token length
    ignore = ('and', 'of', 'the', 'on')  # ignore list
    ignorecount = {}

    accepted = False

    if start != -1 and start+1 < tokenlen and len(acronym) > 1: #just checking if start != -1 w/c means the acronym may not be defined near it and if it's not a single letter only.
        a = 1 #init
        meaning = tokens[start] #meaning variable takes the value of the starting token.
        if meaning in ignore or not meaning.startswith(acronym[start].lower()): #just checking if meaning is in ignore
            return False  #if yes, stop the process immediately.
        for j in range(start+1, tokenlen): #iteration thru the tokens
            if tokens[j].lower().startswith(acronym[a].lower()): #if the words starts with the current letter of the acronym
                meaning = meaning + " " + tokens[j]  #add it
                a = a + 1  #a is the counter and sentinel to check if the acronym meaning is completed.
                accepted = True # also keep tracks if whether the meaning is still accepted or not
            elif tokens[j] in ignore: #if in ignore, it's fine. eg the words 'of', 'and' & 'the' are normally not included in the acronym but is included in the meaning.
                meaning = meaning + " " + tokens[j] #add it
                accepted = True #still accepted
                #this try and except statement keeps track if the ignored words appears only once. if not, the meaning is immediately unaccepted.
                try:
                    err = ignorecount[tokens[j]]
                    accepted = False
                    break
                except KeyError:
                    ignorecount[tokens[j]] = 1
            else:
                accepted = False
            if len(acronym) == a: #checks if the acronym length is already achieved
                break

        if len(acronym) != a: #sometimes the looping process and the last checking of variable a and len(acronym) is not executed so it's a must to check if 'a' meets the length of the acronym
            accepted = False #if not, it's false. it's not the meaning of the acronym

        if accepted:
            # print acronym, meaning
            return True
        else:
            return False
    else:
        return False

# print matcher(['Sugar', 'Regulatory', "Administrative"], 'SRA')


"""This file implements models for object detection. """

from functools import partial

import tensorflow as tf
import tensorflow.contrib.slim as slim

from models.loss import focal_loss_sigmoid, focal_loss_softmax
from models import gnn

regularizer_dict = {
    'l2': slim.l2_regularizer,
    'l1': slim.l1_regularizer,
    'l1_l2': slim.l1_l2_regularizer,
}
keras_regularizer_dict = {
    'l2': tf.keras.regularizers.l1_l2,
    'l1': tf.keras.regularizers.l1,
    'l1_l2': tf.keras.regularizers.l1_l2,
}

class MultiLayerFastLocalGraphModelV2(object):
    """General multiple layer GNN model. The graphs are generated outside this
    model and then feeded into this model. This model applies a list of layers
    sequentially, while each layer chooses the graph they operate on.
    """

    def __init__(self, num_classes, box_encoding_len, regularizer_type=None,
        regularizer_kwargs=None, layer_configs=None, mode=None):
        """
        Args:
            num_classes: int, the number of object classes.
            box_encoding_len: int, the length of encoded bounding box.
            regularizer_type: string, one of 'l2','l1', 'l1_l2'.
            regularizer_kwargs: dict, keyword args to the regularizer.
            layer_config: A list of layer configurations.
            mode: string, one of 'train', 'eval', 'test'.
        """
        self.num_classes = num_classes
        self.box_encoding_len = box_encoding_len
        if regularizer_type is None:
            assert regularizer_kwargs is None, 'No regularizer no kwargs'
            self._regularizer = None
        else:
            self._regularizer = regularizer_dict[regularizer_type](
                **regularizer_kwargs)
        self._layer_configs = layer_configs
        self._default_layers_type = {
            'scatter_max_point_set_pooling': gnn.PointSetPooling(
                point_feature_fn=gnn.multi_layer_neural_network_fn,
                aggregation_fn=gnn.graph_scatter_max_fn,
                output_fn=gnn.multi_layer_neural_network_fn
                ),
            'scatter_max_graph_auto_center_net': gnn.GraphNetAutoCenter(
                edge_feature_fn=gnn.multi_layer_neural_network_fn,
                aggregation_fn=gnn.graph_scatter_max_fn,
                update_fn=gnn.multi_layer_neural_network_fn,
                auto_offset_fn=gnn.multi_layer_neural_network_fn,
                ),
            'classaware_predictor': gnn.ClassAwarePredictor(
                cls_fn=partial(gnn.multi_layer_fc_fn, Ks=(64,), num_layer=2),
                loc_fn=partial(gnn.multi_layer_fc_fn,
                    Ks=(64, 64,), num_layer=3)
                ),
            'classaware_predictor_128': gnn.ClassAwarePredictor(
                cls_fn=partial(gnn.multi_layer_fc_fn, Ks=(128,), num_layer=2),
                loc_fn=partial(gnn.multi_layer_fc_fn,
                    Ks=(128, 128), num_layer=3)
                ),
            'classaware_separated_predictor': gnn.ClassAwareSeparatedPredictor(
                cls_fn=partial(gnn.multi_layer_fc_fn, Ks=(64,), num_layer=2),
                loc_fn=partial(gnn.multi_layer_fc_fn,
                    Ks=(64, 64,), num_layer=3)
                ),
        }
        assert mode in ['train', 'eval', 'test'], 'Unsupported mode'
        self._mode = mode

    def predict(self,
        t_initial_vertex_features,
        t_vertex_coord_list,
        t_keypoint_indices_list,
        t_edges_list,
        is_training,
        ):
        """
        Predict the objects with initial vertex features and a list of graphs.
        The model applies layers sequentially while each layer choose the graph
        that they operates. For example, a layer can choose the i-th graph,
        which is composed of t_vertex_coord_list[i], t_edges_list[i], and
        optionally t_keypoint_indices_list[i]. It operates on the graph and
        output the updated vertex_features. Then the next layer takes the
        vertex_features and also choose a graph to further update the features.

        Args:
            t_initial_vertex_features: a [N, M] tensor, the initial features of
            N vertices. For example, the intensity value of lidar reflection.
            t_vertex_coord_list: a list of [Ni, 3] tensors, the coordinates of
            a list of graph vertices.
            t_keypoint_indices_list: a list of [Nj, 1] tensors or None. For a
            pooling layer, it outputs a reduced number of vertices, aka. the
            keypoints. t_keypoint_indices_list[i] is the indices of those
            keypoints. For a gnn layer, it does not reduce the vertex number,
            thus t_keypoint_indices_list[i] should be set to 'None'.
            t_edges_list: a list of [Ki, 2] tensors. t_edges_list[i] are edges
            for the i-th graph. it contains Ki pair of (source, destination)
            vertex indices.
            is_training: boolean, whether in training mode or not.
        returns: [N_output, num_classes] logits tensor for classification,
        [N_output, num_classes, box_encoding_len] box_encodings tensor for
        localization.
        """
        with slim.arg_scope([slim.batch_norm], is_training=is_training), \
            slim.arg_scope([slim.fully_connected],
                weights_regularizer=self._regularizer):
                tfeatures_list = []
                tfeatures = t_initial_vertex_features
                tfeatures_list.append(tfeatures)
                for idx in range(len(self._layer_configs)-1):
                    layer_config = self._layer_configs[idx]
                    layer_scope = layer_config['scope']
                    layer_type = layer_config['type']
                    layer_kwargs = layer_config['kwargs']
                    graph_level = layer_config['graph_level']
                    t_vertex_coordinates = t_vertex_coord_list[graph_level]
                    t_keypoint_indices = t_keypoint_indices_list[graph_level]
                    t_edges = t_edges_list[graph_level]
                    with tf.variable_scope(layer_scope, reuse=tf.AUTO_REUSE):
                        flgn = self._default_layers_type[layer_type]
                        print('@ level %d Graph, Add layer: %s, type: %s'%
                            (graph_level, layer_scope, layer_type))
                        if 'device' in layer_config:
                            with tf.device(layer_config['device']):
                                tfeatures = flgn.apply_regular(
                                    tfeatures,
                                    t_vertex_coordinates,
                                    t_keypoint_indices,
                                    t_edges,
                                    **layer_kwargs)
                        else:
                            tfeatures = flgn.apply_regular(
                                tfeatures,
                                t_vertex_coordinates,
                                t_keypoint_indices,
                                t_edges,
                                **layer_kwargs)

                        tfeatures_list.append(tfeatures)
                        print('Feature Dim:' + str(tfeatures.shape[-1]))
                predictor_config = self._layer_configs[-1]
                assert (predictor_config['type']=='classaware_predictor' or
                    predictor_config['type']=='classaware_predictor_128' or
                    predictor_config['type']=='classaware_separated_predictor')
                predictor = self._default_layers_type[predictor_config['type']]
                print('Final Feature Dim:'+str(tfeatures.shape[-1]))
                with tf.variable_scope(predictor_config['scope'],
                reuse=tf.AUTO_REUSE):
                    logits, box_encodings =  predictor.apply_regular(tfeatures,
                        num_classes=self.num_classes,
                        box_encoding_len=self.box_encoding_len,
                        **predictor_config['kwargs'])
                    print("Prediction %d classes" % self.num_classes)
        return logits, box_encodings

    def postprocess(self, logits):
        """Output predictions. """
        prob = tf.nn.softmax(logits, axis=-1)
        return prob

    def loss(self, logits, labels, pred_box, gt_box, valid_box,
             cls_loss_type='focal_sigmoid', cls_loss_kwargs={},
             loc_loss_type='huber_loss', loc_loss_kwargs={},
             loc_loss_weight=1.0,
             cls_loss_weight=1.0):
        """Output loss value.

        Args:
            logits: [N, num_classes] tensor. The classification logits from
            predict method.
            labels: [N] tensor. The one hot class labels.
            pred_box: [N, num_classes, box_encoding_len] tensor. The encoded
            bounding boxes from the predict method.
            gt_box: [N, 1, box_encoding_len] tensor. The ground truth encoded
            bounding boxes.
            valid_box: [N] tensor. An indicator of whether the vertex is from
            an object of interest (whether it has a valid bounding box).
            cls_loss_type: string, the type of classification loss function.
            cls_loss_kwargs: dict, keyword args to the classifcation loss.
            loc_loss_type: string, the type of localization loss function.
            loc_loss_kwargs: dict, keyword args to the localization loss.
            loc_loss_weight: scalar, weight on localization loss.
            cls_loss_weight: scalar, weight on the classifcation loss.
        returns: a dict of cls_loss, loc_loss, reg_loss, num_endpoint,
        num_valid_endpoint. num_endpoint is the number of output vertices.
        num_valid_endpoint is the number of output vertices that have a valid
        bounding box. Those numbers are useful for weighting during batching.
        """
        if isinstance(loc_loss_weight, dict):
            loc_loss_weight = loc_loss_weight[self._mode]
        if isinstance(cls_loss_weight, dict):
            cls_loss_weight = cls_loss_weight[self._mode]
        if isinstance(cls_loss_type, dict):
            cls_loss_type = cls_loss_type[self._mode]
            cls_loss_kwargs = cls_loss_kwargs[self._mode]
        if isinstance(loc_loss_type, dict):
            loc_loss_type = loc_loss_type[self._mode]
            loc_loss_kwargs = loc_loss_kwargs[self._mode]

        loss_dict = {}
        assert cls_loss_type in ['softmax', 'top_k_softmax',
            'focal_sigmoid', 'focal_softmax']
        if cls_loss_type == 'softmax':
            point_loss =tf.nn.sparse_softmax_cross_entropy_with_logits(
                labels=tf.squeeze(labels, axis=1), logits=logits)
            num_endpoint = tf.shape(point_loss)[0]
        if cls_loss_type == 'focal_sigmoid':
            point_loss = focal_loss_sigmoid(labels, logits, **cls_loss_kwargs)
            num_endpoint = tf.shape(point_loss)[0]
        if cls_loss_type == 'focal_softmax':
            point_loss = focal_loss_softmax(labels, logits, **cls_loss_kwargs)
            num_endpoint = tf.shape(point_loss)[0]
        if cls_loss_type == 'top_k_softmax':
            point_loss =tf.nn.sparse_softmax_cross_entropy_with_logits(
                labels=tf.squeeze(labels, axis=1), logits=logits)
            num_endpoint = tf.shape(point_loss)[0]
            k = cls_loss_kwargs['k']
            top_k_cls_loss, _ = tf.math.top_k(point_loss, k=k, sorted=True)
            point_loss = top_k_cls_loss
        cls_loss = cls_loss_weight* tf.reduce_mean(point_loss)
        batch_idx = tf.range(tf.shape(pred_box)[0])
        batch_idx = tf.expand_dims(batch_idx, axis=1)
        batch_idx = tf.concat([batch_idx, labels], axis=1)
        pred_box = tf.gather_nd(pred_box, batch_idx)
        pred_box = tf.expand_dims(pred_box, axis=1)
        #pred_box = tf.batch_gather(pred_box, labels)
        if loc_loss_type == 'huber_loss':
            all_loc_loss = loc_loss_weight*tf.losses.huber_loss(
                gt_box,
                pred_box,
                delta=1.0,
                weights=valid_box,
                reduction=tf.losses.Reduction.NONE)
            print(all_loc_loss.shape)
            all_loc_loss = tf.squeeze(all_loc_loss, axis=1)
            if 'classwise_loc_loss_weight' in loc_loss_kwargs and\
            self._mode == 'train':
                classwise_loc_loss_weight = loc_loss_kwargs[
                    'classwise_loc_loss_weight']
                classwise_loc_loss_weight = tf.gather(
                    classwise_loc_loss_weight, labels)
                all_loc_loss = all_loc_loss*classwise_loc_loss_weight
            num_valid_endpoint = tf.reduce_sum(valid_box)
            mean_loc_loss = tf.reduce_mean(all_loc_loss, axis=1)
            loc_loss = tf.div_no_nan(tf.reduce_sum(mean_loc_loss),
                num_valid_endpoint)
            classwise_loc_loss = []
            for class_idx in range(self.num_classes):
                class_mask = tf.where(tf.equal(tf.squeeze(labels, axis=1),
                    tf.constant(class_idx, tf.int32)))
                l = tf.reduce_sum(tf.gather(all_loc_loss, class_mask), axis=0)
                l = tf.squeeze(l, axis=0)
                is_nan_mask = tf.is_nan(l)
                l = tf.where(is_nan_mask, tf.zeros_like(l),l)
                classwise_loc_loss.append(l)
            loss_dict['classwise_loc_loss'] = classwise_loc_loss
        if loc_loss_type == 'top_k_huber_loss':
            k = loc_loss_kwargs['k']
            all_loc_loss = loc_loss_weight*tf.losses.huber_loss(
                gt_box,
                pred_box,
                delta=1.0,
                weights=valid_box,
                reduction=tf.losses.Reduction.NONE)
            all_loc_loss = tf.squeeze(all_loc_loss, axis=1)
            if 'classwise_loc_loss_weight' in loc_loss_kwargs \
                and self._mode == 'train':
                classwise_loc_loss_weight = loc_loss_kwargs[
                    'classwise_loc_loss_weight']
                classwise_loc_loss_weight = tf.gather(
                    classwise_loc_loss_weight, labels)
                all_loc_loss = all_loc_loss*classwise_loc_loss_weight
            loc_loss = tf.reduce_mean(all_loc_loss, axis=1)
            top_k_loc_loss, top_k_indices = tf.math.top_k(loc_loss,
                k=k, sorted=True)
            valid_box = tf.squeeze(valid_box, axis=2)
            valid_box = tf.squeeze(valid_box, axis=1)
            top_k_valid_box = tf.gather(valid_box, top_k_indices)
            num_valid_endpoint = tf.reduce_sum(top_k_valid_box)
            loc_loss = tf.div_no_nan(tf.reduce_sum(top_k_loc_loss),
                num_valid_endpoint)
            top_k_labels = tf.gather(labels, top_k_indices)
            all_top_k_loc_loss = tf.gather(all_loc_loss, top_k_indices)
            classwise_loc_loss = []
            for class_idx in range(self.num_classes):
                class_mask = tf.where(tf.equal(tf.squeeze(top_k_labels),
                    tf.constant(class_idx, tf.int32)))
                l = tf.reduce_sum(tf.gather(all_top_k_loc_loss, class_mask),
                    axis=0)
                l = tf.squeeze(l, axis=0)
                is_nan_mask = tf.is_nan(l)
                l = tf.where(is_nan_mask, tf.zeros_like(l),l)
                classwise_loc_loss.append(l)
            loss_dict['classwise_loc_loss'] = classwise_loc_loss

        with tf.control_dependencies([tf.assert_equal(tf.is_nan(loc_loss),
        False)]):
            reg_loss = tf.reduce_sum(tf.losses.get_regularization_losses())
        loss_dict.update({'cls_loss': cls_loss, 'loc_loss': loc_loss,
            'reg_loss': reg_loss, 'num_endpoint': num_endpoint,
            'num_valid_endpoint':num_valid_endpoint})
        return loss_dict

def get_model(model_name):
    """Fetch a model class."""
    model_map = {
        'multi_layer_fast_local_graph_model_v2':
            MultiLayerFastLocalGraphModelV2,
    }
    return model_map[model_name]


#!/usr/bin/env python
# coding: utf-8
# %%
# Developer: Luis Carlos Herrera Quesada
# Date: 10/04/2023
# Universidad Carlos III de Madrid
# %%

import os
import subprocess
import pandas as pd

def get_values_df():
    act_dir = os.listdir()

    for file in act_dir:
        if file.endswith(".xlsx"):
            df = file

    dataframe = pd.read_excel(df)
    om_0 = dataframe["Frequency"]
    gamma = dataframe["Growth Rate"]
    rad = dataframe["radial_pos_maximum"]

    return om_0, gamma, rad

def substitute_values(om_0, gamma, rad, files,sh_name):

    #print(rad.values[0])
    for i in range(len(files)):
        if rad.values[i] >= 0.85:
            os.remove(f"{files[i]}/{sh_name}")

    ## Change executable
        if rad.values[i] < 0.85:
            freq, gr = om_0.values[i], gamma.values[i]

            with open(f"{files[i]}/{sh_name}", 'r') as tfile:
                ndata    = tfile.readlines()

            ## Change frequency
            tline        = [idx for idx,line in enumerate(ndata) if 'xEigen' in line][0]
            ndata[tline] = f"        ./../../../../../../Addon/Eigensolver/xEigen {freq} {gr}\n"

            with open(f"{files[i]}/{sh_name}", 'w') as nfile:
                nfile.writelines(ndata)

    return 0


#
# @lc app=leetcode.cn id=1 lang=python3
#
# [1] 两数之和
#
from typing import List
# @lc code=start

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for index, value in enumerate(nums):
            dic[value] = index
        for ri1, value in enumerate(nums):
            ri2 = dic.get(target - value)
            if(ri2 is not None and ri1 != ri2):
                return [ri1, ri2]

# @lc code=end
so = Solution()

so.twoSum([2, 7, 5, 3, 6], 11)


import matplotlib.pyplot as plt
import networkx as nx
import numpy as np

'''
row1 = [0,0,0,0,0,0] # used for the first 3 rows of the K_3,3 adjacency matrix
row2 = [0.3,1,0.3,0,0,0] # used for the last 3 rows of the K_3,3 adjacency matrix
# Standard adjacency matrix (this one is of K_3,3)
# Directed edges from column label node to row label node
# (i.e. if element (4,1) = 1, then
adjacency=np.matrix([row1, row1, row1, row2, row2, row2])
# Dictionary with keys as node labels (same ordering as adjacency matrix)
# and values as 2D positions.
nodes = {0: [0, 1], 1: [1, 1], 2: [2, 1], 3: [0, 0], 4: [1, 0], 5: [2, 0]}
# Generating the graph
G=nx.from_numpy_matrix(adjacency, create_using=nx.DiGraph)
colors = [20 for i in range(9)]
colors[0]=100
# Drawing the graph (must supply graph AND node positions)
plt.figure(1)
nx.draw_networkx(G=G, pos=nodes, arrows=True, with_labels=True, node_size = 50, edge_color=colors, edge_cmap=plt.get_cmap('RdYlGn'))
# Show
plt.figure(2)
nx.draw_networkx(G=G, pos=nodes, arrows=True, with_labels=True, node_size = 50, edge_color=colors, edge_cmap=plt.get_cmap('Accent'))
plt.show()
'''

# https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.drawing.nx_pylab.draw_networkx.html
# https://stackoverflow.com/questions/25639169/networkx-change-color-width-according-to-edge-attributes-inconsistent-result

# There are ways to include other labels
# (such as particle energy, ordering by index of hits, etc)
# but for now the adjacency matrix must be in the same order as the node
# positions. The node positions have to be 2D, so maybe use the positions
# as projected on the Y-Z plane or X-Z plane (ignore either Y coordinate or X coordinate).

class GraphVisualizer:
    # Parameters:
    # threshold = cutoff probability for counting a hit as valid or invalid.
    # graphrep: GraphRepresentation object that holds all graph data.
    def __init__(self, graphrep, threshold=0.5):
        self.threshold = threshold
        self.graphrep = graphrep

    # Parameters:
    # adj_matrix: adjacency matrix with probabilities of true edge.
    # -- Default value is a placeholder 0 to denote event.trueAdjMatrix, defined within the method.
    # dimensions: whether to project onto XZ plane or YZ plane.
    def visualize_hits(self, adjmatrix, dimensions='XZ'):
        positions = self.graphrep.XYZ
        types = self.graphrep.Type
        assert adjmatrix.shape[0] == adjmatrix.shape[1] == positions.shape[0]
        # The above line means adjacency matrix needs rows/columns even for nodes that have no edges at all.
        position_map = {}
        colors = [0 for _ in range(adjmatrix.shape[0])]
        for i in range(adjmatrix.shape[0]):
            position_map[i] = [positions[i, 0], positions[i, 2]] if dimensions == 'XZ' \
                else [positions[i, 1], positions[i, 2]]
            if types[i] != "e":
                colors[i] = 100
        G = nx.from_numpy_matrix(np.where(adjmatrix > self.threshold, 1, 0), create_using=nx.DiGraph)
        ########
        # NOTE #
        ########
        # Need to reorder nodes according to the scattering for node labels (with_labels=True) to actually be accurate!
        nx.draw_networkx(G=G, pos=position_map, arrows=True, with_labels=True, node_color=colors)
        plt.show()

        return

    # hit visualizer with variable darkness edges
    def visualize_hits_advanced(self, adjmatrix, dimensions='XZ'):
        adjmatrix = np.where(adjmatrix > self.threshold, adjmatrix, 0)
        edge_colors = [c for c in (adjmatrix.flatten(order='C') * 100).tolist() if c != 0]
        positions = self.graphrep.XYZ
        types = self.graphrep.Type
        assert adjmatrix.shape[0] == adjmatrix.shape[1] == positions.shape[0]
        # The above line means adjacency matrix needs rows/columns even for nodes that have no edges at all.
        position_map = {}
        colors = [0 for _ in range(adjmatrix.shape[0])]
        for i in range(adjmatrix.shape[0]):
            position_map[i] = [positions[i, 0], positions[i, 2]] if dimensions == 'XZ' \
                else [positions[i, 1], positions[i, 2]]
            if types[i] != "e":
                colors[i] = 100

        G = nx.from_numpy_matrix(adjmatrix, create_using=nx.DiGraph)
        ########
        # NOTE #
        ########
        # Need to reorder nodes according to the scattering for node labels (with_labels=True) to actually be accurate!
        nx.draw_networkx(G=G, pos=position_map, arrows=True, with_labels=True, node_color=colors,
                         edge_color=edge_colors, edge_cmap=plt.get_cmap('RdYlGn'), edge_vmin=self.threshold*100, edge_vmax=101)
        plt.show()

        return

    # Parameters:
    # time: number of seconds before closing all visualization windows.
    def closeVisualization(self, time=5):
        plt.pause(time)
        plt.close()