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

import rospy
import csv

from sensor_msgs.msg import PointCloud2
from sensor_msgs.msg import Image
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import TwistStamped
from autoware_msgs.msg import Lane
from autoware_msgs.msg import DetectedObjectArray
from std_msgs.msg import String

from ras_carla.msg import RasObjectArray
from visualization_msgs.msg import InteractiveMarkerUpdate
from visualization_msgs.msg import InteractiveMarkerFeedback
from derived_object_msgs.msg import ObjectArray

class TopicAnalyze(object):
    def __init__(self):
        rospy.init_node('topic_analyze_node', anonymous=True)

        # # sensor
        # self.sub_points_raw = rospy.Subscriber('/points_raw', PointCloud2, self.pointsRawCallback)
        # self.points_raw_time = rospy.get_time()
        # self.points_raw_rate = ['points_raw']
        #
        self.sub_image_raw = rospy.Subscriber('/carla/ego_vehicle/camera/rgb/ros_camera/image_color', Image, self.imageRawCallback)
        self.image_raw_time = rospy.get_time()
        self.image_raw_rate = ['image_raw']
        #
        # # pre processing
        # self.sub_points_filtered = rospy.Subscriber('/filtered_points', PointCloud2, self.filteredPointsCallback)
        # self.filtered_points_time = rospy.get_time()
        # self.filtered_points_delay = ['filtered_points']
        #
        # self.sub_points_no_ground = rospy.Subscriber('/points_no_ground', PointCloud2, self.pointsNoGroundCallback)
        # self.points_no_ground_time = rospy.get_time()
        # self.points_no_ground_delay = ['points_no_ground']
        #
        # # recognition localization
        # self.sub_ndt = rospy.Subscriber('/ndt_pose', PoseStamped, self.ndtCallback)
        # self.ndt_pose_time = rospy.get_time()
        # self.ndt_pose_delay = ['ndt_pose']
        #
        # # recognition detection lidar
        # self.sub_lidar_objects = rospy.Subscriber('/detection/lidar_objects', DetectedObjectArray, self.lidarObjectsCallback)
        # self.lidar_objects_time = rospy.get_time()
        # self.lidar_objects_delay = ['lidar_objects']
        #
        # self.sub_lidar_tracked_objects = rospy.Subscriber('/detection/lidar_tracker/objects', DetectedObjectArray, self.lidarTrakcedObjectsCallback)
        # self.lidar_tracked_objects_time = rospy.get_time()
        # self.lidar_tracked_objects_delay = ['lidar_tracked_objects']
        #
        # # recognition detection camera
        # self.sub_vision_objects = rospy.Subscriber('/detection/vision_objects', DetectedObjectArray, self.visionObjectCallback)
        # self.vision_objects_time = rospy.get_time()
        # self.vision_objects_delay = ['vision_objects']
        #
        # self.sub_vision_tracked_objects = rospy.Subscriber('/detection/tracked_objects', DetectedObjectArray, self.visionTrackedObjectsCallback)
        # self.vision_tracked_objects_time = rospy.get_time()
        # self.vision_tracked_objects_delay = ['vision_tracked_objects']
        #
        # # recognition detection combine
        # self.sub_combined_objects = rospy.Subscriber('/detection/combined_objects', DetectedObjectArray, self.combinedObjectsCallback)
        # self.combined_objects_time = rospy.get_time()
        # self.combined_objects_delay = ['combined_objects']
        #
        # # decision
        # self.sub_final_waypoints = rospy.Subscriber('/final_waypoints', Lane, self.finalWaypointsCallback)
        # self.final_waypoints_time = rospy.get_time()
        # self.final_waypoints_delay = ['final_waypoints']
        #
        # # control
        # self.sub_twist_cmd = rospy.Subscriber('/twist_cmd', TwistStamped, self.twistCmdCallback)
        # self.twist_cmd_time = rospy.get_time()
        # self.twist_cmd_delay = ['twist_cmd']

        # carla HMI check
        self.sub_carla_objects = rospy.Subscriber('/carla/ego_vehicle/objects', ObjectArray, self.carlaObjectsCallback)
        self.carla_objects_time = rospy.get_time()
        self.carla_objects_rate = ['carla_objects']

        self.sub_visualized_objects = rospy.Subscriber('/ras_visualizer_node/update', InteractiveMarkerUpdate, self.visualizedObjectsCallback)
        self.visualized_objects_time = rospy.get_time()
        self.visualized_objects_delay = ['visualized_objects']

        self.sub_operation = rospy.Subscriber('/ras_visualizer_node/feedback', InteractiveMarkerFeedback, self.operationCallback)
        self.operation_time = rospy.get_time()

        self.sub_ras_objects = rospy.Subscriber('/managed_objects', RasObjectArray, self.rasObjectsCallback)
        self.ras_objects_time = rospy.get_time()
        self.ras_objects_delay = ['ras_objects']

    # def pointsRawCallback(self, in_msg):
    #     self.points_raw_rate.append(self.points_raw_time - rospy.get_time())
    #     self.points_raw_time = rospy.get_time()
    #     print('points_raw')
    #
    def imageRawCallback(self, in_msg):
        self.image_raw_rate.append(self.image_raw_time - rospy.get_time())
        self.image_raw_time = rospy.get_time()
        print('image_raw')
    #
    # def filteredPointsCallback(self, in_msg):
    #     self.filtered_points_time = rospy.get_time()
    #     self.filtered_points_delay.append(self.filtered_points_time - self.points_raw_time)
    #     # print('filtered_points : ', self.filtered_points_time - self.points_raw_time)
    #
    # def pointsNoGroundCallback(self, in_msg):
    #     self.points_no_ground_time = rospy.get_time()
    #     self.points_no_ground_delay.append(self.points_no_ground_time - self.points_raw_time)
    #     # print('points_no_ground : ', self.points_no_ground_time - self.points_raw_time)
    #
    # def ndtCallback(self, in_msg):
    #     self.ndt_pose_time = rospy.get_time()
    #     self.ndt_pose_delay.append(self.ndt_pose_time - self.filtered_points_time)
    #
    # def lidarObjectsCallback(self, in_msg):
    #     self.lidar_objects_time = rospy.get_time()
    #     self.lidar_objects_delay.append(self.lidar_objects_time - self.points_no_ground_time)
    #
    # def lidarTrakcedObjectsCallback(self, in_msg):
    #     self.lidar_tracked_objects_time = rospy.get_time()
    #     self.lidar_tracked_objects_delay.append(self.lidar_tracked_objects_time - self.lidar_objects_time)
    #
    # def visionObjectCallback(self, in_msg):
    #     self.vision_objects_time = rospy.get_time()
    #     self.vision_objects_delay.append(self.vision_objects_time - self.image_raw_time)
    #
    # def visionTrackedObjectsCallback(self, in_msg):
    #     self.vision_tracked_objects_time = rospy.get_time()
    #     self.vision_tracked_objects_delay.append(self.vision_tracked_objects_time - self.vision_objects_time)
    #
    # def combinedObjectsCallback(self, in_msg):
    #     self.combined_objects_time = rospy.get_time()
    #     self.combined_objects_delay.append(self.combined_objects_time - max(self.vision_tracked_objects_time, self.lidar_tracked_objects_time))
    #
    # def finalWaypointsCallback(self, in_msg):
    #     self.final_waypoints_time = rospy.get_time()
    #     self.final_waypoints_delay.append(self.final_waypoints_time - self.combined_objects_time)
    #
    # def twistCmdCallback(self, in_msg):
    #     self.twist_cmd_time = rospy.get_time()
    #     self.twist_cmd_delay.append(self.twist_cmd_time - self.final_waypoints_time)

    def carlaObjectsCallback(self, in_msg):
        self.carla_objects_rate.append(rospy.get_time() - self.carla_objects_time)
        self.carla_objects_time = rospy.get_time()

    def visualizedObjectsCallback(self, in_msg):
        self.visualized_objects_time = rospy.get_time()
        self.visualized_objects_delay.append(self.visualized_objects_time - self.carla_objects_time)

    def operationCallback(self, in_msg):
        self.operation_time = rospy.get_time()

    def rasObjectsCallback(self, in_msg):
        if self.operation_time is not None:
            self.ras_objects_time = rospy.get_time()
            self.ras_objects_delay.append(self.ras_objects_time - self.operation_time)
            self.operation_time = None

    def save(self):
        buf = []
        # buf.append(self.points_raw_rate)
        buf.append(self.image_raw_rate)
        # buf.append(self.points_no_ground_delay)
        # buf.append(self.filtered_points_delay)
        # buf.append(self.ndt_pose_delay)
        # buf.append(self.lidar_objects_delay)
        # buf.append(self.lidar_tracked_objects_delay)
        # buf.append(self.vision_objects_delay)
        # buf.append(self.vision_tracked_objects_delay)
        # buf.append(self.combined_objects_delay)
        # buf.append(self.final_waypoints_delay)
        # buf.append(self.twist_cmd_delay)

        buf.append(self.carla_objects_rate)
        buf.append(self.visualized_objects_delay)
        buf.append(self.ras_objects_delay)

        print(buf)
        with open('topic_analyze_result.csv', 'w') as f:
            writer = csv.writer(f, lineterminator='\n')
            writer.writerows(buf)

        print('results saved')

def main():
    try:
        topic_analyze = TopicAnalyze()
        print('started')
        rospy.spin()
    finally:
        topic_analyze.save()
        print('finished')

if __name__ == '__main__':
    main()


#!/usr/bin/env python3

import numpy as np
from galois_field.core import validator

def experiment(fw):
    primes = [n for n in range(2,100) if validator.is_prime(n)]
    for p in primes:
        for i in range (1,p):
            poly_array = [1] + (p-2)*[0]+[i]
            poly = np.poly1d(poly_array)
            is_irreducible = validator.is_irreducible_poly(poly, p)
            if is_irreducible:
                print (p, poly_array)
                fw.write(f"    (np.poly1d([1] + ({p}-2)*[0]+[{i}]), {p}, True),\n")
                break

HEADER="""#!/usr/bin/env python3

import numpy as np
import pytest

from galois_field.core import validator

@pytest.mark.parametrize('poly, p, expected', [
"""

FOOTER="""])
def test_is_irreducible_poly(poly, p, expected):
    assert validator.is_irreducible_poly(poly, p) == expected
"""

def main():
    with open('poly_validator_test.py', 'w') as fw:
        fw.write(HEADER)
        experiment(fw)
        fw.write(FOOTER)
if __name__ == '__main__':
    main()


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()
    setuptools.setup(
     name='pydrip',
     version='0.2.0',
     author="Matthew Clarkson",
     author_email="mpclarkson@gmail.com",
     description="A Python 3 client for the Drip API.",
     long_description=long_description,
     long_description_content_type="text/markdown",
     url="https://github.com/flypaperplanes/pydrip",
     packages=['pydrip'],
     classifiers=[
         "Programming Language :: Python :: 3",
         "License :: OSI Approved :: MIT License",
         "Operating System :: OS Independent",
     ],
     install_requires=[
          'requests',
      ],
 )


#!/usr/bin/python

import getopt
import sys

from Life import Game

def getInput(filename, steps):
    if filename == '':
        print("Please write count of steps\n")
        steps[0] = int(input())
        print("Please write ocean size (hight, witdh)\n")
        hight, witdh = map(int, input().split())
        print("Please write the ocean\n")
        field = []
        for i in range(hight):
            field.append(list(input()))
        # print(field)
        return field
    else:
        with open(filename, 'r') as f:
            steps[0] = int(f.readline())
            hight, witdh = map(int, f.readline().split())
            field = []
            for i in range(hight):
                field.append(list(*f.readline().split()))
            # print(field)
            return field

def output(game, outputfile=''):
    if outputfile == '':
        print(game)
    else:
        with open(outputfile, 'w') as f:
            f.write(str(game))

def main(argv):
    inputfile = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(argv, "h:i:o:", ["help", "ifile=", "ofile="])
    except getopt.GetoptError:
        print('incorrect command, please use flag -h/--help to read how to use Life')
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print('script.py\n-i\t--ifile\t<inputfile>\n-o\t--ofile\t<outputfile>\n-h\t--help\thelp infomation about '
                  'script')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
    steps = [0]
    game = Game(getInput(inputfile, steps))
    steps = steps[0]
    game.step(steps)
    output(game, outputfile)

if __name__ == "__main__":
    main(sys.argv[1:])


# coding: utf-8
from rest_framework import serializers
from swutils.phone import gen_canonical_phone, CanonicalPhoneGenerationException
from sms_devino.client import DevinoException
from core import models

class Sms(serializers.ModelSerializer):
    result = serializers.SerializerMethodField()

    class Meta:
        model = models.Sms
        fields = ('uuid', 'source_address', 'destination_address', 'message', 'validity_minutes', 'result')
        extra_kwargs = {'destination_address': {'max_length': 20}}

    def get_result(self, obj):
        try:
            result = models.SmsSendResult.objects.get(sms=obj)
            return SmsSendResult(instance=result).data
        except models.SmsSendResult.DoesNotExist:
            return None

    def validate_destination_address(self, value):
        try:
            return gen_canonical_phone(value)
        except CanonicalPhoneGenerationException as ex:
            raise serializers.ValidationError(str(ex))

class SmsSendResult(serializers.ModelSerializer):
    class Meta:
        model = models.SmsSendResult
        fields = ('send_dt', 'is_success')

class SmsSendError(serializers.ModelSerializer):

    class Meta:
        model = models.SmsSendError
        fields = ('sms', 'message', 'code', 'description')

    @classmethod
    def register_exception(cls, sms: models.Sms, ex: DevinoException) -> 'SmsSendError':
        data = {
            'sms': sms.pk,
            'message': ex.message,
        }
        if ex.error:
            if ex.error.code:
                data['code'] = ex.error.code
            if ex.error.description:
                data['description'] = ex.error.description

        serializer = cls(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return serializer

class GetState(serializers.Serializer):
    sms = serializers.UUIDField()

    def validate_sms(self, value):
        try:
            sms = models.Sms.objects.get(uuid=value)

            if not sms.send_result.is_success:
                raise serializers.ValidationError('Sms was not successful sent')

            if not sms.parts.exists():
                raise serializers.ValidationError('No info about sent sms')

            return sms
        except models.Sms.DoesNotExist:
            raise serializers.ValidationError('Sms with uuid "{0}" not found'.format(value))

class SmsPartSendState(serializers.ModelSerializer):
    sms_part_external_id = serializers.SerializerMethodField()

    class Meta:
        model = models.SmsPartSendState
        exclude = ('id', 'sms_part', )

    def get_sms_part_external_id(self, obj):
        return obj.sms_part.external_id


# # var1是全局名称
# var1 = 5
# def some_func():
#
#     var2 = 6       # # var2是局部名称
#     def some_inner_func():
#         var3 = 7        # # var2是内嵌局部名称

"""
有四种作用域：在局部找不到，便会去局部外的局部找（例如闭包），再找不到就会去全局找，再者去内置中找。

L（Local）：最内层，包含局部变量，比如一个函数/方法内部。
E（Enclosing）：包含了非局部(non-local)也非全局(non-global)的变量。比如两个嵌套函数，一个函数（或类） A 里面又包含了一个函数 B ，那么对于 B 中的名称来说 A 中的作用域就为 nonlocal。
G（Global）：当前脚本的最外层，比如当前模块的全局变量。
B（Built-in）： 包含了内建的变量/关键字等。，最后被搜索
"""
import builtins
print(dir(builtins))

"""
Python 中只有模块（module），类（class）以及函数（def、lambda）才会引入新的作用域，
其它的代码块（如 if/elif/else/、try/except、for/while等）是不会引入新的作用域的，也就是说这些语句内定义的变量，外部也可以访问，如下代码：
"""
# if True:
#     msg = "I am from Runoob"
#
# print(msg)
#
# # 如果将 msg 定义在函数中，则它就是局部变量，外部不能访问：
# def test():
#     msg_inner = "I am from Runoob"
#
# print(msg_inner)

"""
全局变量和局部变量
"""
# total = 0
#
# def sum(arg1, arg2):
#     total = arg1 + arg2
#     print("函数内是局部变量：", total)
#     return total
#
# sum(10, 20)
# print("函数外是全局变量：", total)

"""
global 和 nonlocal关键字:当内部作用域想修改外部作用域的变量时，就要用到global和nonlocal关键字了。
"""
# # 修改全局变量 num
# num = 1
# def fun1():
#     global num
#     print(num)
#     num = 123
#     print(num)
# fun1()
# print(num)
#
# # 如果要修改嵌套作用域（enclosing 作用域，外层非全局作用域）中的变量则需要 nonlocal 关键字了
# def outer():
#     num = 10
#     def inner():
#         nonlocal num
#         num = 100
#         print(num)
#     inner()
#     print(num)
# outer()

a = 10
def test():
    global a        # 修改 a 为全局变量：
    a += 1
    print(a)
test()

a = 1
def test(a):        # 通过函数参数传递
    a += 1
    print(a)
test(a)

随便写写/python3 命名空间作用域.py


'''
http://effbot.org/librarybook/binascii.htm
http://www.programcreek.com/python/example/1814/binascii.a2b_base64
'''
import binascii

text = b'hello, mrs teal'

data = binascii.b2a_base64(text)
text = binascii.a2b_base64(data)
print (text, "<=>", repr(data))

data = binascii.b2a_uu(text)
text = binascii.a2b_uu(data)
print (text, "<=>", repr(data))

data = binascii.b2a_hqx(text)
text = binascii.a2b_hqx(data)[0]
print (text, "<=>", repr(data))

# 2.0 and newer
data = binascii.b2a_hex(text)
text = binascii.a2b_hex(data)
print (text, "<=>", repr(data))

## $ python binascii-example-1.py
## hello, mrs teal <=> 'aGVsbG8sIG1ycyB0ZWFs\012'
## hello, mrs teal <=> '/:&5L;&\\L(&UR<R!T96%L\012'
## hello, mrs teal <=> 'D\'9XE\'mX)\'ebFb"dC@&X'
## hello, mrs teal <=> '68656c6c6f2c206d7273207465616c'

#if __name__ == "__main__":


# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.11.3
#   kernelspec:
#     display_name: Python 3 (ipykernel)
#     language: python
#     name: python3
# ---

# +
"""
This cell sets up the information necessary to update the section for all media in the source
section. It is safe to run repeatedly and will not make any changes to media stored in tator.
"""

# Hostname of tator cloud instance, do not change
host = "https://cloud.tator.io"

# Your user token
token = "your-token-here"

# ID of project containing the source section
project_id = 123

# Source section, must already exist
source_section = "Source Section Name"

# Destination section, may already exist
dest_section = "New Section Name"

# +
"""
This cell tests the information set up in the previous cell. It is safe to run repeatedly and will
not make any changes to media stored in tator. It will raise an exception if it finds an issue with
any of the variables set up in the first cell. If no issues are found, it will print out information
about the source section and affected media.
"""

# Get tator api with credentials
common_err = "please fix the first cell and start over"
import tator

try:
    api = tator.get_api(host=host, token=token)
except:
    print(f"Could not get api at '{host}' with token '{token}', {common_err}")
    raise

# Test project access
try:
    api.get_project(project_id)
except:
    print(f"Could not access project with id {project_id}, {common_err}")
    raise

# Make sure source section exists
response = api.get_section_list(project=project_id, name=source_section)
assert len(response) == 1, f"No unique section matching the name '{source_section}', {common_err}"
source_section_id = response[0].id

# Get media count from source section
media_count = api.get_media_count(project=project_id, section=source_section_id)

print(
    f"Accessed project {project_id} successfully, source section '{source_section}' has id {source_section_id} and {media_count} media"
)

print("Running the next cell will move media to the new section!")

# +
"""
This cell will create the new section, move media from the source section to the new section, and
hide the empty source section from view. Running this WILL CHANGE MEDIA IN TATOR and it should ONLY
BE RUN ONCE after all preceeding cells have run without exception.
"""
from uuid import uuid4

# Create or find dest section
response = api.get_section_list(project=project_id, name=dest_section)
n_sections = len(response)

if n_sections > 1:
    raise ValueError(
        f"Found more than one section associated with name '{dest_section}', try another name"
    )

if n_sections == 1:
    new_user_section = response[0].tator_user_sections
    if not response[0].visible:
        api.update_section(id=new_section_id, section_update={"visible": True})
else:
    new_user_section = str(uuid4())
    section_spec = {"name": dest_section, "visible": True, "tator_user_sections": new_user_section}
    api.create_section(project=project_id, section_spec=section_spec)

# Create media bulk update spec
try:
    media_bulk_update = {
        "attributes": {"tator_user_sections": new_user_section},
    }
except NameError:
    print(
        "A variable from the previous cell is not set, please run it before trying to run this cell again"
    )
    raise

# Move media to dest section
response = api.update_media_list(
    project=project_id, section=source_section_id, media_bulk_update=media_bulk_update
)
print(response)

# Archive source section
response = api.update_section(id=source_section_id, section_update={"visible": False})
# -

"""
To determine the source section of a given media entity:

1. Get changelog for media in question
2. Find entry where the `tator_user_sections` attribute changed
3. Note the old value of it
4. Get the list of sections in the project
5. Find the section in the list of sections whose `tator_user_sections` value matches the value from
   line 3
6. Look at its name
"""


# stdlib imports
import sqlite3
import xml.etree.ElementTree as ET
import copy
from collections import OrderedDict
import re
import logging

# third party imports
import numpy as np

# local imports

TABLES = OrderedDict((
    ('station',
     OrderedDict((
         ('id', 'str primary key'),  # id is net.sta
         ('network', 'str'),
         ('code', 'str'),
         ('name', 'str'),
         ('lat', 'float'),
         ('lon', 'float'),
         ('elev', 'float'),
         ('vs30', 'float'),
         ('stddev', 'float'),
         ('instrumented', 'int')
     ))
     ),
    ('imt',
     OrderedDict((
         ('id', 'integer primary key'),
         ('imt_type', 'str')
     ))
     ),
    ('amp',
     OrderedDict((
         ('id', 'integer primary key'),
         ('station_id', 'str'),
         ('imt_id', 'int'),
         ('original_channel', 'str'),
         ('orientation', 'str'),
         ('amp', 'float'),
         ('stddev', 'float'),
         ('flag', 'str')
     ))
     )
))

#
# These are the netid's that indicate MMI data
#
CIIM_TUPLE = ('dyfi', 'mmi', 'intensity', 'ciim')

class StationList(object):
    """
    A class to facilitate reading ShakeMap formatted XML fies of peak
    amplitudes and MMI, and
    produce tables of station data. Seismic stations are considered to
    be 'instrumented'; MMI data is not instrumented and is indicated
    in the ShakeMap XML with a ``netid`` attribute of "DYFI," "MMI,"
    "INTENSITY," or "CIIM."

    .. note::
      Typically the user will call the class method :meth:`fromXML`
      to create a :class:`StationList` object the first time
      a set of station files are processed. (Or, as an alternative,
      the user can call :meth:`loadFromXML` and :meth:`fillTables`
      sequentially.)
      This will create a database at the location specified by the
      ``dbfile`` parameter to :meth:`fromXML`. Subsequent programs
      can use the default constructor to simply load ``dbfile``.

    """

    def __init__(self, db):
        """
        The default constructor reads a pre-built SQLite database of
        station data.

        Args:
            dbfile (str):
                A SQLite database file containing pre-processed
                station data.

        Returns:
            A :class:`StationList` object.

        """
        self.db = db
        self.cursor = self.db.cursor()

    def __del__(self):
        """
        Closes out the database when the object is destroyed.
        """
        self.db.commit()
        self.cursor.close()
        self.db.close()

#    def _load_features(self, xmlfile):
        # each station is a feature in a geojson file
        #        tree = ET.parse(xmlfile)
        #        root = tree.getroot()
        #        imt_translate = {}
        #        for sl in root.iter('stationlist'):
        #            for station in sl:
        #                feature = {'type':'Feature'}
        #                netid = station.attrib['netid']
        #                code = station.attrib['code']
        #                feature['id'] = '%s.%s' % (netid,code)
        #                lat = code = float(station.attrib['lat'])
        #                lon = code = float(station.attrib['lon'])
        #                feature['geometry'] = \
        #                    {'type':'Point','coordinates':[lon,lat]}
        #                properties = {}
        #                properties['name'] = station.attrib['name']
        #                properties['intensity_flag'] = station.attrib['']#??
        #                properties['distance'] = \
        #                    float(station.attrib['distance'])
        #                properties['location'] = station.attrib['loc']
        #                properties['code'] = station.attrib['code']
        #                properties['commType'] = station.attrib['commtype']
        #                properties['source'] = station.attrib['source']
        #                properties['network'] = station.attrib['netid']
        #                properties['instrumentType'] = \
        #                    station.attrib['insttype']
        #                properties['intensity'] = \
        #                    float(station.attrib['intensity'])
        #                channels = []
        #                for comp in station:
        #                    channel = {'name':comp.attrib['name']}
        #                    for component in comp:
        #                        pgmdict, imtset = self._getGroundMotions(
        #                            component, imt_translate)
#        pass

    @classmethod
    def loadFromSQL(cls, sql, dbfile=':memory:'):
        """
        Create a new object from saved SQL code (see :meth:`dumpToSQL`).

        Args:
            sql (str):
                SQL code to create and populate the database
            dbfile (str):
                The path to a file in which the database will reside.
                The default is ':memory:' for an in-memory database.

        Returns:
            :class:`Stationlist` object.
        """

        db = sqlite3.connect(dbfile)
        self = cls(db)
        self.cursor.executescript(sql)
        return self

    def dumpToSQL(self):
        """
        Dump the database as a string of SQL code (see :meth:`loadFromSQL`).

        Args:
            None

        Returns:
            A string of SQL sufficient to restore and repopulate the
            database.
        """

        return "\n".join(list(self.db.iterdump()))

    @classmethod
    def loadFromXML(cls, xmlfiles, dbfile=':memory:'):
        """
        Create a StationList object by reading one or more ShakeMap XML input
        files.

        Args:
            xmlfiles (sequence of str):
                Sequence of ShakeMap XML input files to read.
            dbfile (str):
                Path to a file into which to write the SQLite database.
                The default is ':memory:' for an in-memory database.

        Returns:
            :class:`StationList` object

        """
        # Create the database and tables
        db = sqlite3.connect(dbfile)
        self = cls(db)
        self._createTables()
        return self.addData(xmlfiles)

    def getGeoJson(self):
        jdict = {'type': 'FeatureCollection',
                 'features': []}

        self.cursor.execute(
            'SELECT id, network, code, name, lat, lon, elev, vs30, '
            'instrumented from station'
        )
        sta_rows = self.cursor.fetchall()

        for sta in sta_rows:
            # print('doing station %s' % (str(sta[2])))
            if str(sta[2]).startswith(sta[1] + '.'):
                myid = str(sta[2])
            else:
                myid = sta[1] + '.' + str(sta[2])
            feature = {
                'type': 'Feature',
                'id': myid,
                'properties': {
                    'code': str(sta[2]),
                    'name': sta[3],
                    'instrumentType': 'UNK' if sta[8] is True else 'OBSERVED',
                    'source': sta[1],
                    'network': sta[1],
                    'commType': 'UNK',
                    'location': '',
                    'intensity': None,
                    'intensity_flag': '',
                    'intensity_stddev': None,
                    'pga': None,
                    'pgv': None,
                    'distance': None,
                    'channels': []
                },
                'geometry': {
                    'type': 'Point',
                    'coordinates': [sta[5], sta[4]]
                }
            }
            self.cursor.execute(
                'SELECT a.amp, i.imt_type, a.original_channel, '
                'a.flag, a.stddev '
                'FROM amp a, imt i '
                'WHERE a.station_id = "%s" '
                'AND a.imt_id = i.id' % (str(sta[0]))
            )
            amp_rows = self.cursor.fetchall()
            channels = {}
            for amp in amp_rows:
                # print('doing channel %s imt %s' % (amp[2], amp[1]))
                if amp[2] not in channels:
                    channels[amp[2]] = {'name': amp[2], 'amplitudes': []}
                if amp[0] == 'NULL':
                    myamp = np.nan
                else:
                    myamp = amp[0]
                if amp[1] == 'PGV':
                    value = np.exp(myamp)
                    units = 'cm/s'
                elif amp[1] == 'MMI':
                    value = myamp
                    units = 'intensity'
                else:
                    value = np.exp(myamp) * 100
                    units = '%g'
                this_amp = {'name': amp[1].lower(),
                            'value': '%.4f' % value,
                            'units': units,
                            'flag': str(amp[3]),
                            'ln_stddev': '%.4f' % amp[4]
                           }
                channels[amp[2]]['amplitudes'].append(this_amp)
            for channel in channels.values():
                feature['properties']['channels'].append(channel)
            jdict['features'].append(feature)

        return jdict

    def addData(self, xmlfiles):
        """
        Create a StationList object by reading one or more ShakeMap XML input
        files.

        Args:
            xmlfiles (sequence of str):
                Sequence of ShakeMap XML input files to read.
        Returns:
            :class:`StationList` object

        """
        # Parse the xml into a dictionary
        stationdict = {}
        imtset = set()
        for xmlfile in xmlfiles:
            stationdict, ims = self._filter_station(xmlfile, stationdict)
            imtset |= ims
        # fill the database and create the object from it
        self._loadFromDict(stationdict, imtset)
        return self

    def _loadFromDict(self, stationdict, imtset):
        """
        Internal method to turn the station dictionary created from the
        ShakeMap XML input files into a SQLite database.

        Args:
            stationdictlist (list of stationdicts):
                A list of station dictionaries returned by _filter_station().
            dbfile (string):
                The path to which the SQLite database will be written.

        Returns:
            :class:`StationList` object
        """
        #
        # Get the current IMTs and their IDs and add any new ones
        #
        imts_in_db = self.getIMTtypes()
        new_imts = imtset - imts_in_db
        if any(new_imts):
            self.cursor.executemany('INSERT INTO imt (imt_type) VALUES (?)',
                                    zip(new_imts))
            self.db.commit()

        # Now get the updated list of IMTs and their IDs
        query = 'SELECT imt_type, id FROM imt'
        self.cursor.execute(query)
        imt_hash = dict(self.cursor.fetchall())

        #
        # Get the station codes for all the stations in the db
        #
        query = 'SELECT id FROM station'
        self.cursor.execute(query)
        sta_set = set([z[0] for z in self.cursor.fetchall()])

        #
        # Insert any new stations into the station table
        #
        station_rows = []
        for sta_id, station_tpl in stationdict.items():
            if sta_id in sta_set:
                continue
            else:
                sta_set.add(sta_id)
            station_attributes, comp_dict = station_tpl
            lat = station_attributes['lat']
            lon = station_attributes['lon']
            network = station_attributes['netid']
            code = station_attributes['code']
            if 'name' in station_attributes:
                name = station_attributes['name']
            else:
                name = None
            if 'elev' in station_attributes:
                elev = station_attributes['elev']
            else:
                elev = None
            if 'vs30' in station_attributes:
                vs30 = station_attributes['vs30']
            else:
                vs30 = None
            if 'stddev' in station_attributes:
                stddev = station_attributes['stddev']
            else:
                stddev = 0

            instrumented = int(network.lower() not in CIIM_TUPLE)

            station_rows.append((sta_id, network, code, name, lat, lon,
                                 elev, vs30, stddev, instrumented))

        self.cursor.executemany(
            'INSERT INTO station (id, network, code, name, lat, lon, '
            'elev, vs30, stddev, instrumented) VALUES '
            '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', station_rows
        )
        self.db.commit()

        #
        # Now add the amps, first get the current set so we don't add
        # any duplicates; a unique amp will be (station_id, imt_id,
        # original_channel)
        #
        query = 'SELECT station_id, imt_id, original_channel FROM amp'
        self.cursor.execute(query)
        amp_rows = self.cursor.fetchall()
        # Create a unique identifier for each amp so we don't repeat any
        amp_set = set([str(v[0]) + '.' + str(v[1]) + '.' + str(v[2])
                       for v in amp_rows])

        #
        # Insert the amps for each component
        #
        amp_rows = []
        for sta_id, station_tpl in stationdict.items():
            station_attributes, comp_dict = station_tpl
            instrumented = int(station_attributes['netid'].lower()
                               not in CIIM_TUPLE)
            for original_channel, pgm_dict in comp_dict.items():
                orientation = self._getOrientation(original_channel)
                for imt_type, imt_dict in pgm_dict.items():
                    if (instrumented == 0) and (imt_type != 'MMI'):
                        continue
                    imtid = imt_hash[imt_type]
                    amp_id = str(sta_id) + '.' + str(imtid) + '.' + \
                        str(original_channel)
                    if amp_id in amp_set:
                        continue
                    else:
                        amp_set.add(amp_id)
                    amp = imt_dict['value']
                    units = imt_dict['units']
                    stddev = imt_dict['stddev']
                    flag = imt_dict['flag']
                    if np.isnan(amp):
                        amp = 'NULL'
                        flag = 'G'
                    elif imt_type == 'MMI':
                        if amp <= 0:
                            amp = 'NULL'
                            flag = 'G'
                        else:
                            pass
                    elif imt_type == 'PGV':
                        if units == 'cm/s':
                            if amp <= 0:
                                amp = 'NULL'
                                flag = 'G'
                            else:
                                amp = np.log(amp)
                        elif units == 'ln(cm/s)':
                            pass
                        else:
                            raise ValueError('Unknown units %s in input'
                                             % units)
                    else:
                        if units == '%g':
                            if amp <= 0:
                                amp = 'NULL'
                                flag = 'G'
                            else:
                                amp = np.log(amp / 100.0)
                        elif units == 'ln(g)':
                            pass
                        else:
                            raise ValueError('Unknown units %s in input'
                                             % units)

                    amp_rows.append((sta_id, imtid, original_channel,
                                     orientation, amp, stddev, flag))

        self.cursor.executemany(
            'INSERT INTO amp (station_id, imt_id, original_channel, '
            'orientation, amp, stddev, flag) VALUES (?, ?, ?, ?, ?, ?, ?)',
            amp_rows
        )
        self.db.commit()
        return

    def getIMTtypes(self):
        """
        Return a set of IMT types found in the database

        Args:
            None

        Returns:
            A set of IMT types
        """
        self.cursor.execute('SELECT imt_type FROM imt')
        return set([z[0] for z in self.cursor.fetchall()])

    def getStationDictionary(self, instrumented=True):
        """
        Return a dictionary of the instrumented or non-instrumented
        stations. The keys describe the parameter, the values are Numpy
        arrays of the parameter in question.

        For the standard set of ShakeMap IMTs (mmi, pga, pgv, psa03, psa10,
        psa30), the keys in the dictionary would be:

        'id', 'network', 'code', 'name', 'lat', 'lon', 'elev', 'vs30',
        'stddev', 'instrumented', 'PGA', 'PGA_sd', 'PGV', 'PGA_sd',
        'SA(0.3)', 'SA(0.3)_sd, 'SA(1.0)', 'SA(1.0)_sd, 'SA(3.0)',
        'SA(3.0)_sd'

        For the non-instrumented dictionary, the keys would be:

        'id', 'network', 'code', 'name', 'lat', 'lon', 'elev', 'vs30',
        'stddev', 'instrumented', 'MMI', 'MMI_sd'

        The **id** column is **network** and **code** concatenated with a
        period (".") between them.

        All ground motion units are natural log units. Distances are in km.

        Args:
            instrumented (bool):
                Set to True if the dictionary is to contain the instrumented
                stations, or to False if the dictionary is to contain the
                non-instrumented (MMI) stations.

        Returns:
            dict: A dictionary of Numpy arrays.
        """

        columns = list(TABLES['station'].keys())
        dstr = ', '.join(columns)
        self.cursor.execute(
            'SELECT %s FROM station where instrumented = %d' %
            (dstr, instrumented)
        )

        station_rows = self.cursor.fetchall()
        nstation_rows = len(station_rows)
        if not nstation_rows:
            return None
        station_columns = list(zip(*station_rows))
        df = OrderedDict()
        for ic, col in enumerate(columns):
            df[col] = np.array(station_columns[ic])

        for imt in self.getIMTtypes():
            if (instrumented and 'MMI' in imt) or \
               (not instrumented and 'MMI' not in imt):
                continue
            df[imt] = np.full(nstation_rows, np.nan)
            df[imt + '_sd'] = np.full(nstation_rows, 0.0)

        id_dict = dict(zip(df['id'], range(nstation_rows)))

        #
        # Get all of the unflagged amps with the proper orientation
        #
        self.cursor.execute(
            'SELECT a.amp, i.imt_type, a.station_id, a.stddev FROM '
            'amp a, station s, imt i WHERE a.flag = "0" '
            'AND s.id = a.station_id '
            'AND a.imt_id = i.id '
            'AND s.instrumented = %d AND a.orientation NOT IN ("Z", "U") '
            'AND a.amp IS NOT NULL' % (instrumented)
        )
        amp_rows = self.cursor.fetchall()

        #
        # Go through all the amps and put them into the data frame
        #
        for this_row in amp_rows:
            #
            # Set the cell to the peak amp
            #
            rowidx = id_dict[this_row[2]]
            cval = df[this_row[1]][rowidx]
            amp = this_row[0]
            stddev = this_row[3]
            if np.isnan(cval) or (cval < amp):
                df[this_row[1]][rowidx] = amp
                df[this_row[1] + '_sd'][rowidx] = stddev

        return df

    @staticmethod
    def _getOrientation(orig_channel):
        """
        Return a character representing the orientation of a channel.

        Args:
            orig_channel (string):
                String representing the seed channel (e.g. 'HNZ'). The
                final character is assumed to be the (uppercase) orientation.

        Returns:
            Character representing the channel orientation. One of 'N',
            'E', 'Z', 'H' (for horizontal), or 'U' (for unknown).
        """
        if orig_channel == 'mmi':
            orientation = 'H'           # mmi is arbitrarily horizontal
        elif orig_channel[-1] in ('N', 'E', 'Z'):
            orientation = orig_channel[-1]
        elif orig_channel[-1] == "K":   # Channel is "UNK"; assume horizontal
            orientation = 'H'
        else:
            orientation = 'U'  # this is unknown
        return orientation

    @staticmethod
    def _getGroundMotions(comp, imt_translate):
        """
        Get a dictionary of peak ground motions (values and flags).
        Output keys are one of: [pga,pgv,psa03,psa10,psa30]
        Even if flags are not specified in the input, they will
        be guaranteed to at least have a flag of '0'.
        """
        pgmdict = {}
        imtset = set()
        for pgm in comp:
            if pgm.tag == '#text':
                continue
            key = pgm.tag
            if key not in imt_translate:
                if key in ('acc', 'pga'):
                    new_key = 'PGA'
                elif key in ('vel', 'pgv'):
                    new_key = 'PGV'
                elif 'mmi' in key:
                    new_key = 'MMI'
                elif 'psa' in key:
                    pp = get_imt_period(key)
                    new_key = 'SA(' + str(pp) + ')'
                else:
                    raise ValueError('Unknown amp type in input: %s' % key)
                imt_translate[key] = new_key
            else:
                new_key = imt_translate[key]
            key = new_key

            if 'value' in pgm.attrib:
                try:
                    value = float(pgm.attrib['value'])
                except ValueError:
                    logging.warn('Unknown value in XML: %s for amp: %s' %
                                 (pgm.attrib['value'], pgm.tag))
                    continue
            else:
                logging.warn('No value for amp %s' % pgm.tag)
                continue
            if 'flag' in pgm.attrib and pgm.attrib['flag'] != '':
                flag = pgm.attrib['flag']
            else:
                flag = '0'
            if 'ln_stddev' in pgm.attrib:
                stddev = float(pgm.attrib['ln_stddev'])
            else:
                stddev = 0
            if 'units' in pgm.attrib:
                units = pgm.attrib['units']
            else:
                if key == 'PGV':
                    units = 'cm/s'
                elif key == 'MMI':
                    units = 'intensity'
                else:
                    units = '%g'
            pgmdict[key] = {'value': value,
                            'flag': flag,
                            'stddev': stddev,
                            'units': units}
            imtset.add(key)
        return pgmdict, imtset, imt_translate

    def _filter_station(self, xmlfile, stationdict):
        """
        Filter individual xmlfile into a stationdict data structure.

        Args:
            xmlfile (string):
                Path to ShakeMap XML input file (or file-like object)
                containing station data.

        Returns:
            stationdict data structure
        """
        imt_translate = {}
        imtset = set()
        tree = ET.parse(xmlfile)
        root = tree.getroot()
        for sl in root.iter('stationlist'):
            for station in sl:
                if station.tag != 'station':
                    continue
                # look at the station attributes to figure out if this is a
                # DYFI-type station or a station with instruments measuring
                # PGA, PGV, etc.
                attributes = station.attrib.copy()
                if 'netid' in attributes:
                    netid = attributes['netid']
                else:
                    netid = ''
                instrumented = int(netid.lower() not in CIIM_TUPLE)

                if 'code' not in attributes:
                    logging.warn(
                            'Station does not have station code: skipping')
                    continue
                code = attributes['code']
                if code.startswith(netid + '.'):
                    sta_id = code
                    code = code.replace(netid + '.', '')
                else:
                    sta_id = netid + '.' + code

                if sta_id in stationdict:
                    compdict = stationdict[sta_id][1]
                else:
                    compdict = {}
                for comp in station:
                    if 'name' not in comp.attrib:
                        logging.warn(
                                'Unnamed component for station %s; skipping'
                                % (sta_id))
                        continue
                    compname = comp.attrib['name']
                    if 'Intensity Questionnaire' in str(compname):
                        compdict['mmi'] = {}
                        continue
                    tpgmdict, ims, imt_translate = \
                            self._getGroundMotions(comp, imt_translate)
                    if compname in compdict:
                        pgmdict = compdict[compname]
                    else:
                        pgmdict = {}
                    pgmdict.update(tpgmdict)
                    # copy the VALUES, not REFERENCES, of the component list
                    # into our growing dictionary
                    compdict[compname] = copy.copy(pgmdict)
                    imtset |= ims
                if ('intensity' in attributes) and (instrumented == 0):
                    if 'mmi' not in compdict:
                        compdict['mmi'] = {}
                    if 'intensity_stddev' in attributes:
                        stddev = float(attributes['intensity_stddev'])
                    else:
                        stddev = 0
                    compdict['mmi']['MMI'] = \
                        {'value': float(attributes['intensity']),
                         'stddev': stddev,
                         'flag': '0',
                         'units': 'intensity'}
                    imtset.add('MMI')
                stationdict[sta_id] = (attributes, copy.copy(compdict))
        return stationdict, imtset

    def _createTables(self):
        """
        Build the database tables.
        """
        for table in TABLES.keys():
            sql = 'CREATE TABLE %s (' % table
            nuggets = []
            for column, ctype in TABLES[table].items():
                nuggets.append('%s %s' % (column, ctype))
            sql += ','.join(nuggets) + ')'
            self.cursor.execute(sql)

        self.db.commit()
        return

def get_imt_period(imt):

    p = re.search('(?<=psa)\d+', imt)
    return float(p.group(0)[:-1] + '.' + p.group(0)[-1])


import random
import matplotlib.pyplot as plt
import numpy as np

class Bucket:
    def __init__(self, start, end, sub_sum=None):
        self.start = start
        self.end = end
        self.sub_sum = sub_sum if sub_sum is None else sub_sum

    def __repr__(self):
        return f"({self.start},{self.end})"

class DGIM:
    def __init__(self):
        self.bucket_tower = [[]]
        self.ts = 0

    def put(self, bit):

        if bit == 1:

            self.bucket_tower[0].insert(0, Bucket(self.ts, self.ts))

            layer = 0
            while len(self.bucket_tower[layer]) > 2:
                if len(self.bucket_tower) <= layer + 1:
                    self.bucket_tower.append([])
                b1 = self.bucket_tower[layer].pop()
                b2 = self.bucket_tower[layer].pop()

                b1.end = b2.end

                self.bucket_tower[layer + 1].insert(0, b1)
                layer += 1

        self.ts += 1

    def count(self, k):
        s = self.ts - k

        cnt = 0

        for layer, buckets in enumerate(self.bucket_tower):
            for bucket in buckets:
                if s <= bucket.start:
                    cnt += (1 << layer)
                elif s <= bucket.end:
                    cnt += (1 << layer) * (bucket.end - s + 1) // (bucket.end - bucket.start + 1)
                    return cnt
                else:
                    return cnt
        return cnt

    def reset(self):
        self.ts = 0
        self.bucket_tower = [[]]

class DGIM_int:
    def __init__(self):
        self.bucket_tower = [[]]
        self.ts = 0

    def put(self, num):

        self.bucket_tower[0].insert(0, Bucket(self.ts, self.ts, num))

        layer = 0
        while len(self.bucket_tower[layer]) > 2:
            if len(self.bucket_tower) <= layer + 1:
                self.bucket_tower.append([])

            if self.bucket_tower[layer][1].sub_sum + self.bucket_tower[layer][2].sub_sum <= (1 << layer+1):
                b1 = self.bucket_tower[layer].pop()
                b2 = self.bucket_tower[layer].pop()

                b1.end = b2.end
                b1.sub_sum += b2.sub_sum
            else:
                b1 = self.bucket_tower[layer].pop()

            self.bucket_tower[layer + 1].insert(0, b1)
            layer += 1

        self.ts += 1

    def sum(self, k):
        s = self.ts - k

        dgim_sum = 0

        for layer, buckets in enumerate(self.bucket_tower):
            for bucket in buckets:
                if s <= bucket.start:
                    dgim_sum += bucket.sub_sum
                elif s <= bucket.end:
                    dgim_sum += round(bucket.sub_sum * ((bucket.end - s + 1) / (bucket.end - bucket.start + 1)))
                    return dgim_sum
                else:
                    return dgim_sum
        return dgim_sum

def to_binary(num):
    num_bin = [0 for i in range(MAX_BIT)]
    i = 3
    while num > 0:
        num_bin[i] = num % 2
        num //= 2
        i -= 1
    return num_bin

dgim = DGIM()
MAX_BIT = 4 # 한정된 비트 상수 선언
bitstream = [[] for i in range(MAX_BIT)]

intstream = [random.randint(0, 15) for i in range(10000)]

# 방법 1

for i in intstream:
    each_bit = to_binary(i)
    for j in range(MAX_BIT):
        bitstream[j].append(each_bit[MAX_BIT - j - 1])

dgim_sum_bit_list = []

for k in range(1, 2001):
    index = 0
    dgim_sum = 0
    for each_bitstream in bitstream:
        for bit in each_bitstream:
            dgim.put(bit)
        dgim_sum += dgim.count(k) * (1 << index)
        index += 1
        dgim.reset()
    dgim_sum_bit_list.append(dgim_sum)

# 방법 2

dgim_int = DGIM_int()

dgim_sum_int_list = []
real_sum = []

for num in intstream:
    dgim_int.put(num)

for k in range(1, 2001):
    dgim_sum_int_list.append(dgim_int.sum(k))
    print(dgim_sum_int_list[-1])
    real_sum.append(sum(intstream[-k:]))

# 그래프 그리는 부분
x = np.arange(1, 2001)
plt.plot(x, np.array(dgim_sum_bit_list), label="DGIM method 1 sum")
plt.plot(x, np.array(dgim_sum_int_list), label="DGIM method 2 sum")
plt.plot(x, np.array(real_sum), label="real sum")
plt.legend()
plt.show()


# 16진수를 2진수로 변환하기(convert hexadecimal to binary number)
# 16진수가 입력되면 2진수로 변환하여 출력하시오.
# 예를 들어, 7AF 를 2진수로 변환하면, 0111 1010 1111이다.
# 입력으로 16진수가 입력되고 알파벳은 대문자로 입력된다.(각 자리는 : 0~9,
# A~F) (길이는 50,000글자 이내)
# 2진수로 변환하여 4자리씩 끊어서 출력한다. 단, 최상위 비트의 불필요한 0도
# 출력한다.( 1  -> 0001)
# method 1
s = input()
for i in range(len(s)):
    if s[i] >= 'A' and s[i] <= 'F':
        t = ord(s[i]) - 55
    else:
        t = int(s[i])
    b = 1
    r = 0
    while t != 0:
        r += t % 2 * b
        b *= 10
        t //= 2
    print('%04d' % r, end=' ')


"""
2005B DVD租赁
考虑如下的在线DVD租赁问题。顾客缴纳一定数量的月费成为会员，订购DVD租赁服务。会员对哪些DVD有兴趣，只要在线提交订单，网站就会通过快递的方式尽可能满足要求。会员提交的订单包括多张DVD，这些DVD是基于其偏爱程度排序的。网站会根据手头现有的DVD数量和会员的订单进行分发。每个会员每个月租赁次数不得超过2次，每次获得3张DVD。请考虑以下问题：
数据中会在测试点中给出。数据包括：网站n种DVD的现有张数和当前需要处理的m位会员的在线订单。 如何对这些DVD进行分配，才能使会员获得最大的满意度。
具体数据大家可以参考2005年全国大学生数学建模竞赛B题。
"""
import numpy as np
import cvxpy as cp
m,n=[eval(x) for x in input().split()]
p=np.zeros((m,n))
for i in range(m):
    p[i,:]=[eval(x) for x in input().split()]
d=[eval(x) for x in input().split()]
s=np.zeros((m,n))
for i in range(m):
    for j in range(n):
        if p[i,j]>0:
            s[i,j]=2**(11-p[i,j])
x=cp.Variable((m,n),boolean=True)
obj=cp.Maximize(cp.sum(cp.multiply(s,x)))
cons=[cp.sum(x,axis=0)<=d,cp.sum(x,axis=1)<=3]
prob=cp.Problem(obj,cons)
prob.solve(solver='GLPK_MI')
print(int(prob.value))

山东大学 数学模型 程序汇总/2005年全国大学生数学建模竞赛B题 DVD租赁.py

2005年全国大学生数学建模竞赛B题 DVD租赁.py


import tkinter as tk
from tkinter import ttk

mainWindow = tk.Tk()
mainWindow.title("svenmap")

mainMenu = tk.Menu(mainWindow)

scanMenu = tk.Menu(mainMenu, tearoff=0)
scanMenu.add_command(label="Scan", command=None)
mainMenu.add_cascade(menu=scanMenu, label="Scan")

toolsMenu = tk.Menu(mainMenu, tearoff=0)
toolsMenu.add_command(label="Tools")
mainMenu.add_cascade(menu=toolsMenu, label="Tools")

profileMenu = tk.Menu(mainMenu, tearoff=0)
profileMenu.add_command(label="Edit Current Profile")
mainMenu.add_cascade(menu=profileMenu, label="Profile")

helpMenu = tk.Menu(mainMenu, tearoff=0)
helpMenu.add_command(label="F.A.Q.")
helpMenu.add_command(label="Credits")
mainMenu.add_cascade(menu=helpMenu, label="Help")

mainWindow.config(menu=mainMenu)

mainFrame = tk.Frame(mainWindow)
scanFrame = tk.Frame(mainFrame)
targetLabel = tk.Label(scanFrame, text="Target:")
targetLabel.pack(side="left")
targetEntry = tk.Entry(scanFrame)
targetEntry.pack(side="left", fill="x", expand=1)
profileLabel = tk.Label(scanFrame, text="Profile:")
profileLabel.pack(side="left")
profileEntry = tk.Entry(scanFrame)
profileEntry.pack(side="left", fill="x", expand=1)
scanButton = tk.Button(scanFrame, text="Scan")
scanButton.pack(side="left")
cancelButton = tk.Button(scanFrame, text="Cancel")
cancelButton.pack(side="left")
scanFrame.pack(side="top", fill="x")
commandFrame = tk.Frame(mainFrame)
commandLabel = tk.Label(commandFrame, text="Command:")
commandLabel.pack(side="left")
commandEntry = tk.Entry(commandFrame)
commandEntry.pack(side="left", fill="x", expand=1)
commandFrame.pack(side="top", fill="x")

resultsFrame = tk.Frame(mainFrame)
leftNotebook = ttk.Notebook(resultsFrame)
hostsFrame = tk.Frame(leftNotebook)
hostsFrame.pack(side="left", fill="y")
leftNotebook.add(hostsFrame, text="Hosts")
servicesFrame = tk.Frame(leftNotebook)
servicesFrame.pack(side="left", fill="y")
leftNotebook.add(servicesFrame, text="Services")
leftNotebook.pack(side="left", fill="y")
rightNotebook = ttk.Notebook(resultsFrame)
outputFrame = tk.Frame(rightNotebook)
outputText = tk.Text(outputFrame)
outputText.pack(side="top", fill="both", expand=1)
outputFrame.pack(side="left", fill="both", expand=1)
rightNotebook.add(outputFrame, text="Nmap Output")
detailsFrame = tk.Frame(rightNotebook)
detailsFrame.pack(side="left", fill="both", expand=1)
rightNotebook.add(detailsFrame, text="Host Details")
topologyFrame = tk.Frame(rightNotebook)
topologyFrame.pack(side="left", fill="both", expand=1)
rightNotebook.add(topologyFrame, text="Topology")
scansFrame = tk.Frame(rightNotebook)
scansFrame.pack(side="left", fill="both", expand=1)
rightNotebook.add(scansFrame, text="Scans")
rightNotebook.pack(side="left", fill="both", expand=1)
resultsFrame.pack(side="top", fill="both", expand=1)
mainFrame.pack(side="top", fill="both", expand=1)

mainWindow.update()
mainWindow.minsize(mainWindow.winfo_width(), mainWindow.winfo_height())

mainFrame.mainloop()


"""
randomized hill climbing: estimated average number of evaluations before reaching the global optimum
"""

import numpy as np
import random

def find_peak(index, f):
    peak = False
    indices_evaluated = []
    while not peak:
        if index == 0:
            f_right = f[index + 1]
            if index not in indices_evaluated:
                indices_evaluated.append(index)
            if index + 1 not in indices_evaluated:
                indices_evaluated.append(index + 1)

            if f_right > f[index]:
                index += 1
            else:
                peak = True

        elif 0 < index < len(f) - 1:
            f_left = f[index - 1]
            f_right = f[index + 1]
            if index not in indices_evaluated:
                indices_evaluated.append(index)
            if index - 1 not in indices_evaluated:
                indices_evaluated.append(index - 1)
            if index + 1 not in indices_evaluated:
                indices_evaluated.append(index + 1)

            if f_left > f[index] and f_right > f[index]:
                direction = random.randint(-1, 1)
                index += direction
            elif f_left > f[index] > f_right:
                index -= 1
            elif f_left < f[index] < f_right:
                index += 1
            else:
                peak = True

        elif index == len(f) - 1:
            f_left = f[index - 1]
            if index not in indices_evaluated:
                indices_evaluated.append(index)
            if index - 1 not in indices_evaluated:
                indices_evaluated.append(index - 1)
            if f_left > f[index]:
                index -= 1
            else:
                peak = True

    return len(indices_evaluated), f[index]

if __name__ == '__main__':
    y1 = list(np.linspace(0, 1, 3))
    y2 = list(np.linspace(1, 0, 2))
    y3 = list(np.linspace(0, 2, 5))
    y4 = list(np.linspace(2, 0, 8))
    y5 = list(np.linspace(0, 4, 4))
    y6 = list(np.linspace(4, 0, 3))
    y7 = list(np.linspace(0, 2, 8))
    y8 = list(np.linspace(2, 0, 2))
    y = y1[:-1] + y2[0:-1] + y3[0:-1] + y4[0:-1] + y5[0:-1] + y6[0:-1] + y7[0:-1] + y8

    samples = []
    iterations = 100000
    for i in range(iterations):
        local_opt = -float("inf")
        total_evals = 0
        while True:
            n = random.randint(1, 28)
            n_evals, local_opt = find_peak(n - 1, y)
            total_evals += n_evals
            if local_opt == max(y):
                print(local_opt)
                break

        samples.append(total_evals)

    print(sum(samples) / iterations)


import time
from splinter import Browser
from bs4 import BeautifulSoup
from selenium import webdriver

def init_browser():
    # @NOTE: Replace the path with your actual path to the chromedriver
    executable_path = {"executable_path": r"C:/Users/ddzmi/Desktop/chromedriver.exe"}
    return Browser("chrome", **executable_path, headless=False)

# this funciton will return a dictionary for image that we can use to store in mongo DB
def img_portfolio(img_src,alt):
    return {
        "src": img_src,
        "alt": alt
    }

def scrape():
    # we can store image data in array
    all_images = []
    browser = init_browser()
    images_website = "https://www.pexels.com/"
    browser.visit(images_website)
    time.sleep(2)
    html = browser.html
    img_soup = BeautifulSoup(html, "html.parser")
    container = img_soup.find("div", {"class": "photos"})
    all_Images = container.find_all('img')
    for img in all_Images:
        if(img.attrs.get('srcset')):
                _altInfo = img.attrs.get('alt')
                #will give an array of two src
                sources = img.attrs.get('srcset').split(',')
                # we need a smalest source of it
                smal_img_src = sources[0].split(' ')[0]
                # and we get our picture info in pretty dictionary
                # print(img_portfolio(smal_img_src,_altInfo))
                # Now we can append our data to array and return it
                all_images.append(img_portfolio(smal_img_src,_altInfo))
    return all_images


import cv2
from matplotlib import pyplot as plt
import numpy as np
img = cv2.imread('flower.jpg',0)
equ = cv2.equalizeHist(img)
res = np.hstack((img,equ))
cv2.imshow('histogram img',res)
cv2.waitKey(0)
cv2.destroyAllWindows()
histg = cv2.calcHist([img],[0],None,[250],[0,256])
plt.plot (histg)
plt.show()


import sys

f_count = False
f_num = False
f_sort = False
file = None

for el in sys.argv:
    if el == '--num':
        f_num = True
    elif el == '--count':
        f_count = True
    elif el == '--sort':
        f_sort = True
    else:
        file = el

try:
    with open(file, 'r', encoding='utf-8') as f:
        data = list(map(str.strip, f.readlines()))
        if f_sort:
            data = sorted(data)
        if f_num:
            for i, el in enumerate(data):
                print(i, el)
        else:
            for el in data:
                print(el)
        if f_count:
            print(f'rows count: {len(data)}')
except FileNotFoundError:
    print('ERROR')


from flask_classful import FlaskView, route
from flask import request, jsonify
from application.API.utils import AuthorizeRequest, notLoggedIn, b64_to_data
from application.API.Factory.BLFactory import BF
from application.API.Factory.SchemaFactory import SF
class APIPostView(FlaskView):

    def index(self):
        response = dict({"isLoggedIn": True})
        user = AuthorizeRequest(request.headers)
        if not user:
            return jsonify(notLoggedIn)

        posts = BF.getBL("post").get_posts(user)
        response.update({"posts": posts})
        return jsonify(response)

    def get(self, id):
        response = dict({"isLoggedIn": True})
        user = AuthorizeRequest(request.headers)
        if not user:
            return jsonify(notLoggedIn)

        post = BF.getBL("post").get_post_by_id(user, id)
        response.update({"post": post})
        return jsonify(response)

    @route('/delete_post/<string:post_id>/')
    def delete_post(self, post_id):
        response = dict({"isLoggedIn": True})
        user = AuthorizeRequest(request.headers)
        if not user:
            return jsonify(notLoggedIn)

        bl = BF.getBL("post")
        post = bl.get_post_obj_by_id(post_id, user)
        if not post:
            return jsonify(notLoggedIn)

        isDeleted = bl.delete_post(post)
        response.update({"isDeleted": isDeleted})
        return jsonify(response)

    def posts(self, id):
        response = dict({"isLoggedIn": True})
        user_id = id
        user = AuthorizeRequest(request.headers)
        if not user:
            return jsonify(notLoggedIn)

        if str(id) == "me":
            user_id = user.user_id

        post = BF.getBL("post").get_user_posts(user, user_id)
        response.update({"posts": post})
        return jsonify(response)

    def search(self, search):
        response = dict({"isLoggedIn": True})
        user = AuthorizeRequest(request.headers)
        if not user:
            return jsonify(notLoggedIn)

        posts = BF.getBL("post").search_posts(user, search)
        response.update({"posts": posts})
        return jsonify(response)

    @route('/create/', methods=['POST'])
    def create(self):
        response = dict({"isLoggedIn": True})
        user = AuthorizeRequest(request.headers)
        image = None
        if not user:
            return jsonify(notLoggedIn)

        print(request.files)

        if request.method == "POST":
            if request.form["post_title"] == "" or request.form["description"] == "":
                response.update(
                    {"isPostCreated": False, "message": "Post title and description cannot be empty."}
                )
                return jsonify(response)

            post_title = b64_to_data(request.form["post_title"])
            post_description = b64_to_data(request.form["description"])
            if request.files:
                image = request.files['image']

            if not post_title or not post_description:
                response.update(
                    {"isPostCreated": False, "message": "Post title and description cannot be empty."}
                )
                return jsonify(response)

            isPostAdded, post = BF.getBL("post").add_post(post_title, post_description, image, user)
            if isPostAdded:
                post = SF.getSchema("post", isMany=False).dump(post)
            response.update({"isPostCreated": isPostAdded, "post": post, "isError": not isPostAdded})
            return jsonify(response)
        else:
            return "invalid request"

    @route('/update/<string:post_id>/', methods=['POST'])
    def update(self, post_id):
        response = dict({"isLoggedIn": True})
        user = AuthorizeRequest(request.headers)
        image = None
        if not user:
            return jsonify(notLoggedIn)

        post = BF.getBL("post").get_post_obj_by_id(post_id)
        if not post:
            return jsonify(notLoggedIn)

        if request.method == "POST":
            if request.form["post_title"] == "" or request.form["description"] == "":
                response.update(
                    {"isPostCreated": False, "message": "Post title and description cannot be empty."}
                )
                return jsonify(response)

            post_title = b64_to_data(request.form["post_title"])
            post_description = b64_to_data(request.form["description"])
            if request.files:
                image = request.files['image']

            if not post_title or not post_description:
                response.update(
                    {"isPostCreated": False, "message": "Post title and description cannot be empty."}
                )
                return jsonify(response)

            isPostUpdated, updated_post = BF.getBL("post").add_post(post_title, post_description, image, user, post=post)
            if isPostUpdated:
                updated_post = SF.getSchema("post", isMany=False).dump(updated_post)
            response.update({"isPostUpdated": isPostUpdated, "post": updated_post, "isError": not isPostUpdated})
            return jsonify(response)
        else:
            return "invalid request"


# coding: utf-8

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from predict import FineTuningNet
from pydantic import BaseModel

app = FastAPI()

# モデルの定義
net = FineTuningNet()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

class PerfumeImg(BaseModel):
    base_64: str

@app.post("/perfume/")
def predict_perfume(img: PerfumeImg):
    return net.predcit_result(img.base_64)


import base64
import io
import json
import os
from os import listdir
from os.path import join
from time import time
import PIL.Image
import numpy as np
import matplotlib.pyplot as plt
import cv2
import src.data.utils.utils as utils
import src.data.constants as c

'''
There will be folders inside masks_test called 'filename_json'.

The algorithm

1. Walk through every subfolder called
'filename_json'
2. Fetch the 'label.png' in each subfolder,
3. Threshold the image.

The manual annotation will be processed: grayscale, threshold.

test/imgs:
_00000.png
00000.npy
etc.

test/masks:
(folder): _00000_json (complete annotation from labelme script)
_00000.png (automatic annotation)

test/masks_full:
00000.npy (thresholded complete annotation)

This algorithm will be applied to the folder `imgs` in the future.
So: imgs, masks, masks_full.
'''

# Set working directory to script location
utils.set_cwd(__file__)

files = c.RAW_FILES_GENERALIZE
kernel = c.MEDIAN_FILTER_KERNEL
threshold = c.SIMPLE_THRESHOLD
mode = 'test'

img_dir = c.IMG_DIR
mask_dir = c.MASK_DIR
mask_dir_full = c.MASK_DIR_FULL

# Create folder in case it doesn't exist yet
folder_name = c.MASK_DIR
folder = join(c.DATA_DIR, mode, folder_name)
utils.make_dir(folder)
utils.make_dir(join(c.DATA_DIR, mode, mask_dir_full))
utils.make_dir(c.FIG_DIR)

# How often to print out with matplotlib
debug_every = c.DBG_EVERY

# Name of the folder in which the images will reside
imgs_path = join(c.DATA_DIR, mode, c.IMG_DIR)
masks_path = join(c.DATA_DIR, mode, c.MASK_DIR)
# List of filenames of the .npy images
# .jpg files are for visualizing the process
images = [image for image in listdir(imgs_path) if '.json' in image]
masks = [mask for mask in listdir(masks_path) if '.npy' in mask]
# Get full image paths from filename list `images`
image_paths = sorted([join(imgs_path, image) for image in images])

# This is the index we will start on, in case there are already
# data files in there
# So, we are only adding to the existing list of files in /imgs/
# -1 for zero-indexing, +1 because we want to start at the next free index
img_idx = len(masks) - 1 + 1
idx = img_idx if img_idx > 0 else 0  # numbering for images

thresholds = []
idx = 0
tic = time()
manual_labels = []
auto_labels = []
for folders, subfolders, files in os.walk(join(c.DATA_DIR, mode, mask_dir)):
    for file in files:
        # if '.npy' in file:
        #     img_idx = file[0:5]
        #     load_path = join(c.DATA_DIR, mask_dir)
        #     auto_img = np.load(join(load_path, f'{img_idx}.npy'))
        #     if len(auto_img.shape) > 2:
        #         print(file)
        #         print(auto_img.shape)

        if file == 'label.png':
            img_idx = folders.split('_')[-2]
            path = join(folders, file)
            added_img = PIL.Image.open(path)
            added_img = np.array(added_img)
            added_img *= 255

            _, thresh = cv2.threshold(
                added_img, c.SIMPLE_THRESHOLD, 255, cv2.THRESH_BINARY)
            save = join(c.DATA_DIR, mode, mask_dir_full)
            np.save(join(save, img_idx), thresh)

            if idx % debug_every == 0:
                plt.imsave(join(save, f'_{img_idx}.png'), thresh)  # debug

            idx += 1

toc = time()
print(f'annotate_from_json.py complete after {(toc-tic)/60: .1f} minutes.')


# -*- coding: utf-8 -*-
__author__ = 'Mr.Finger'
__date__ = '2017/10/16 14:11'
__site__ = ''
__software__ = 'PyCharm'
__file__ = '3.tensorflow中的Variable.py'

import tensorflow as tf

state = tf.Variable(0, name='counter') # 在tensorflow中只有定义了他是变量，他才是变量
print(state.name) # counter:0

one = tf.constant(1)

new_value = tf.add(state, one)
update = tf.assign(state, new_value)

init = tf.initialize_all_variables() # 如果定义了变量，那么必须要有这句话

with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))


import theano
import theano.tensor as T
import numpy as np

from neupy.core.properties import (NumberProperty, ProperFractionProperty,
                                   ParameterProperty)
from neupy.utils import asfloat, as_tuple
from neupy.core.init import Initializer, Constant
from .activations import AxesProperty
from .utils import dimshuffle
from .base import BaseLayer

__all__ = ('BatchNorm',)

def find_opposite_axes(axes, ndim):
    """
    Based on the total number of dimensions function
    finds all axes that are missed in the specified
    list ``axes``.

    Parameters
    ----------
    axes : list or tuple
        Already known axes.
    ndim : int
        Total number of dimensions

    Returns
    -------
    list

    Examples
    --------
    >>> from neupy.layers.normalization import find_opposite_axes
    >>> find_opposite_axes([0, 1], ndim=4)
    [2, 3]
    >>>
    >>> find_opposite_axes([], ndim=4)
    [0, 1, 2, 3]
    >>>
    >>> find_opposite_axes([0, 1, 2], ndim=3)
    []
    """
    if any(axis >= ndim for axis in axes):
        raise ValueError("Some axes have invalid values. Axis value "
                         "should be between 0 and {}".format(ndim))

    return [axis for axis in range(ndim) if axis not in axes]

class BatchNorm(BaseLayer):
    """
    Batch-normalization layer.

    Parameters
    ----------
    axes : int, tuple with int or None
        The axis or axes along which normalization is applied.
        ``None`` means that normalization will be applied over
        all axes except the first one. In case of 4D tensor it will
        be equal to ``(0, 2, 3)``. Defaults to ``None``.
    epsilon : float
        Epsilon is a positive constant that adds to the standard
        deviation to prevent the division by zero.
        Defaults to ``1e-5``.
    alpha : float
        Coefficient for the exponential moving average of
        batch-wise means and standard deviations computed during
        training; the closer to one, the more it will depend on
        the last batches seen. Value needs to be between ``0`` and ``1``.
        Defaults to ``0.1``.
    gamma : array-like, Theano variable, scalar or Initializer
        Default initialization methods you can
        find :ref:`here <init-methods>`.
        Defaults to ``Constant(value=1)``.
    beta : array-like, Theano variable, scalar or Initializer
        Default initialization methods you can
        find :ref:`here <init-methods>`.
        Defaults to ``Constant(value=0)``.

    Methods
    -------
    {BaseLayer.Methods}

    Attributes
    ----------
    {BaseLayer.Attributes}

    References
    ----------
    .. [1] Batch Normalization: Accelerating Deep Network Training
           by Reducing Internal Covariate Shift,
           http://arxiv.org/pdf/1502.03167v3.pdf
    """
    axes = AxesProperty(default=None)
    alpha = ProperFractionProperty(default=0.1)
    epsilon = NumberProperty(default=1e-5, minval=0)
    gamma = ParameterProperty(default=Constant(value=1))
    beta = ParameterProperty(default=Constant(value=0))

    def initialize(self):
        super(BatchNorm, self).initialize()

        input_shape = as_tuple(None, self.input_shape)
        ndim = len(input_shape)

        if self.axes is None:
            # If ndim == 4 then axes = (0, 2, 3)
            # If ndim == 2 then axes = (0,)
            self.axes = tuple(axis for axis in range(ndim) if axis != 1)

        if any(axis >= ndim for axis in self.axes):
            raise ValueError("Cannot apply batch normalization on the axis "
                             "that doesn't exist.")

        opposite_axes = find_opposite_axes(self.axes, ndim)
        parameter_shape = [input_shape[axis] for axis in opposite_axes]

        if any(parameter is None for parameter in parameter_shape):
            unknown_dim_index = parameter_shape.index(None)
            raise ValueError("Cannot apply batch normalization on the axis "
                             "with unknown size over the dimension #{} "
                             "(0-based indeces).".format(unknown_dim_index))

        self.running_mean = theano.shared(
            name='running_mean_{}'.format(self.layer_id),
            value=asfloat(np.zeros(parameter_shape))
        )
        self.running_inv_std = theano.shared(
            name='running_inv_std_{}'.format(self.layer_id),
            value=asfloat(np.ones(parameter_shape))
        )

        if isinstance(self.gamma, Initializer):
            self.gamma = self.gamma.sample(parameter_shape)

        if isinstance(self.beta, Initializer):
            self.beta = self.beta.sample(parameter_shape)

        self.gamma = theano.shared(
            name='gamma_{}'.format(self.layer_id),
            value=asfloat(self.gamma),
        )
        self.beta = theano.shared(
            name='beta_{}'.format(self.layer_id),
            value=asfloat(self.beta),
        )
        self.parameters = [self.gamma, self.beta]

    def output(self, input_value):
        epsilon = asfloat(self.epsilon)
        alpha = asfloat(self.alpha)
        gamma, beta = self.gamma, self.beta

        ndim = input_value.ndim
        axes = self.axes

        running_mean = self.running_mean
        running_inv_std = self.running_inv_std

        input_mean = input_value.mean(axes)
        input_var = input_value.var(axes)
        input_inv_std = T.inv(T.sqrt(input_var + epsilon))

        self.updates = [(
            running_inv_std,
            asfloat(1 - alpha) * running_inv_std + alpha * input_inv_std
        ), (
            running_mean,
            asfloat(1 - alpha) * running_mean + alpha * input_mean
        )]

        if not self.training_state:
            mean = running_mean
            inv_std = running_inv_std

        else:
            mean = input_mean
            inv_std = input_inv_std

        opposite_axes = find_opposite_axes(axes, ndim)

        beta = dimshuffle(beta, ndim, opposite_axes)
        gamma = dimshuffle(gamma, ndim, opposite_axes)
        mean = dimshuffle(mean, ndim, opposite_axes)
        inv_std = dimshuffle(inv_std, ndim, opposite_axes)

        normalized_value = (input_value - mean) * inv_std
        return gamma * normalized_value + beta


def bubblesort(list):
    intercambio = True
    while intercambio:
        intercambio = False
        for i in range(len(list) - 1):
            if list[i].tiempo_llegada > list[i+1].tiempo_llegada:
                list[i], list[i+1] = list[i+1], list[i]
                intercambio = True
    return list

def fifo(list):
    # lista_ordenada = sorted(list, key=lambda x: x.tiempo_llegada)
    lista_ordenada = bubblesort(list)
    time = 0
    for proceso in lista_ordenada:
        tiempo_comienzo = time
        tiempo_fin = time + proceso.tiempo_cpu
        time = tiempo_fin
        proceso.set_values(tiempo_comienzo, tiempo_fin)
        proceso.show_all_info()


from typing import Optional, List

from .types import LanguageConfig, ModifierType, ResourceStr, PRODUCES_ADD, PRODUCES_MULT, \
    UPKEEP_MULT, UPKEEP_ADD, EconomicCategoryKey, COST_MULT, COST_ADD
from .utils import Writer, generate_resource_loc

def _unpack_resource_id(resource: ResourceStr):
    return resource if isinstance(resource, str) else resource[0]

def _get_loc_from_args(economic_category_loc: str, modifier_type: ModifierType, args: list):
    if len(args) and isinstance(args[-1], dict):
        if modifier_type.split('_')[-1] in args[-1]:
            return args[-1][modifier_type.split('_')[-1]]
    return economic_category_loc

def _should_write_custom_add(args: list, resource: ResourceStr, modifier_type: ModifierType):
    if isinstance(resource, list) and len(resource) == 3:
        if not modifier_type.replace('add', 'mult') in resource[2]:
            return True
    return 'mult' in args[-1] if len(args) and isinstance(args[-1], dict) else False

def _generate_modifier_localization_key(economic_category: EconomicCategoryKey, modifier_type: ModifierType,
                                        resource: Optional[ResourceStr] = None):
    return f"mod_{economic_category}_{_unpack_resource_id(resource) + '_' if resource else ''}{modifier_type}"

def _resource_has_modifier_type(resource: ResourceStr, modifier_type: ModifierType):
    if isinstance(resource, list) and len(resource) == 3:
        return modifier_type in resource[2]
    return True

def _generate_resource_mult_modifier(
        writer: Writer, economic_category: EconomicCategoryKey, modifier_type: ModifierType,
        template: str, economic_category_loc: str, args: list, resource: Optional[ResourceStr] = None):
    writer.write_localization(
        _generate_modifier_localization_key(economic_category, modifier_type, resource),
        template.format(
            *args,
            resource=generate_resource_loc(resource) if resource else None,
            category=_get_loc_from_args(economic_category_loc, modifier_type, args)
        ),
    )

def _generate_resource_add_modifier(
        writer: Writer, economic_category: EconomicCategoryKey, modifier_type: ModifierType,
        template: str, economic_category_loc: str, args: list, resource: Optional[ResourceStr] = None):
    if _should_write_custom_add(args, resource, modifier_type):
        writer.write_localization(
            _generate_modifier_localization_key(economic_category, modifier_type, resource),
            template.format(
                *args,
                resource=generate_resource_loc(
                    resource),
                category=_get_loc_from_args(economic_category_loc, modifier_type, args)
            ),
        )
    else:
        writer.write_localization(
            _generate_modifier_localization_key(economic_category, modifier_type, resource),
            f"${_generate_modifier_localization_key(economic_category, modifier_type.replace('add', 'mult'), resource)}$",
        )

def _get_resources(resources: List[ResourceStr], args: list):
    if len(args) and isinstance(args[-1], dict):
        if 'resources' in args[-1]:
            return [r for r in resources if r in args[-1]['resources'] or isinstance(r, list) and r[0] in args[-1]['resources']]
    return resources

def generate_modifiers(writer: Writer, config: LanguageConfig, resources: list[ResourceStr]):
    for economic_category, (economic_category_loc, template_key, *args) in config['economic_categories'].items():
        template = config['templates'][template_key]
        with writer.with_spacer():
            writer.write_comment(
                f"{economic_category} - {economic_category_loc}{f' - {args}' if len(args) > 0 else ''}")

            writer.write_localization(
                f"mod_base_{economic_category}",
                f"{economic_category_loc}",
            )

            with writer.with_spacer():
                for key in template:
                    if 'generic' in key:
                        _generate_resource_mult_modifier(
                            writer, economic_category, key.split('_')[-1] + '_mult',
                            template[key], economic_category_loc, args
                        )
        for key in template:
            if 'resource' in key:
                modifier_type: ModifierType = key.split('_')[-1] + '_mult'
                with writer.with_spacer():
                    for resource in _get_resources(resources, args):
                        if _resource_has_modifier_type(resource, modifier_type):
                            _generate_resource_mult_modifier(
                                writer, economic_category, modifier_type,
                                template[key], economic_category_loc, args, resource
                            )

                modifier_type: ModifierType = key.split('_')[-1] + '_add'
                with writer.with_spacer():
                    for resource in _get_resources(resources, args):
                        if _resource_has_modifier_type(resource, modifier_type):
                            _generate_resource_add_modifier(
                                writer, economic_category, modifier_type,
                                template[key], economic_category_loc, args, resource
                            )

def generate_buildings_loc(writer: Writer, config: LanguageConfig):
    for key, (loc, template_key) in config['districts_and_buildings'].items():
        template = config['templates'][template_key]
        with writer.with_spacer():
            writer.write_localization(
                f"mod_planet_{key}_build_speed_mult",
                template['build_speed'].format(
                    building=loc
                ),
            )
            writer.write_localization(
                f"mod_{key}_max",
                template['max_add'].format(
                    building=loc
                ),
            )


import logging
import os

from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.utils import executor

from smartcontract_interaction import *
from dotenv import load_dotenv

load_dotenv()

logging.basicConfig(level=logging.INFO)

API_TOKEN = os.getenv("API_KEY")

bot = Bot(token=API_TOKEN)

storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)

class Form(StatesGroup):
    first_name = State()
    second_name = State()
    third_name = State()
    benefits = State()
    documents = State()

@dp.message_handler(commands='start')
async def cmd_start(message: types.Message):
    await Form.first_name.set()
    await message.answer("Привіт 👋 \n\n "
                         "🏠 Цей бот допоможе Вам зареєструватися в чергу до гуртожитку! \n\n"
                         "✔Для заповнення заявки Ви маєте надати такі персональні дані: \n"
                         "1. Ім`я\n"
                         "2. Прізвище\n"
                         "3. По батькові\n"
                         "4. У яку чергу Вас записувати? (пільгову чи звичайну)\n"
                         "5. Документи для поселення в гуртожиток (бажано додати в архів дані заявки) 🧾 \n"
                         "\t\t5.1 (Направлення на поселення (видане комісією з поселення)\n"
                         "\t\t5.2 Заява на поселення\n"
                         "\t\t5.3 Копія паспорта\n"
                         "\t\t5.4 Копія ідентифікаційного коду\n"
                         "\t\t5.5 Фотокартка 3 x 4 \n"
                         "\n"
                         "\n"
                         "Для перевірки прозорості всіх транзакцій використовується мережа "
                         "Rinkeby Ethereum\n"
                         "https://rinkeby.etherscan.io/address/0xcec0faa3dfbcdc5c6e3de6e5c5955a65245483fb",
                         parse_mode="HTML")

# You can use state '*' if you need to handle all states
@dp.message_handler(state='*', commands='cancel')
async def cancel_handler(message: types.Message, state: FSMContext):
    current_state = await state.get_state()
    if current_state is None:
        return

    logging.info('Cancelling state %r', current_state)
    # Cancel state and inform user about it
    await state.finish()
    await message.reply('Відмінено! ❌', reply_markup=types.ReplyKeyboardRemove())

@dp.message_handler(state=Form.second_name)
async def process_second_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['first_name'] = message.text

    await Form.next()
    await message.reply("Введіть Ваше Прізвище: ")

@dp.message_handler(state=Form.third_name)
async def process_third_name(message: types.Message, state: FSMContext):
    # Update state and data
    await Form.next()
    await state.update_data(second_name=message.text)
    await message.reply("Введіть Ваше По Батькові: ")

@dp.message_handler(state=Form.benefits)
async def process_benefits(message: types.Message, state: FSMContext):
    # Update state and data
    await Form.next()
    await state.update_data(third_name=message.text)
    await message.reply("Введіть +, якщо Ви є іноземцем або студентом з пільгами: ")

@dp.message_handler(lambda message: "+" in message.text or "-" in message.text, state=Form.documents)
async def process_gender(message: types.Message, state: FSMContext):
    if message.text == '-':
        await state.update_data(benefits=False)
    else:
        await state.update_data(benefits=True)

    async with state.proxy() as data:
        data['documents'] = message.document
        User().create_record(message.document, Form.first_name, Form.second_name, Form.third_name, Form.benefits)

    # Finish conversation
    await state.finish()

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)


import pyttsx3
from datetime import *
import speech_recognition as sr
import wikipedia
import webbrowser
import os

#Initialization of pyttsx3 module
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voices', voices[0].id)

#Creating a function which will speak the given command
def speak(audio):
    engine.say(audio)
    engine.runAndWait()

#A function which will greet the user according to time of the system
def wish():
    hour = int(datetime.now().hour)
    if hour >= 0 and hour < 12:
        print("Good Morning!")
        speak("Good Morning!")

    elif hour >= 12 and hour < 17:
        print("Good Afternoon!")
        speak("Good Afternoon!")

    else:
        print("Good Evening!")
        speak("Good Evening!")

    print("How may I help you?")
    speak("How may I help you?")

#SpeechRecognition intialization with expection handling
#It will take the input from the user as speech and will store in query
def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")

    except Exception as e:
        print("say that again please...")
        speak("say that again please!")
        return  "None"
    return query

if __name__ == "__main__":
    wish()
    while True:
        #Converting the input from user in lower so that no problem occurs when matching with query
        query = takeCommand().lower()

        #When the user asks it's name, this condition will execute
        if 'your name' in query:
            print("I am Jarvis. Jarvis stands for Just A Rather Very Intelligent System")
            speak('I am Jarvis!.Jarvis stands for! Just A Rather Very Intelligent System ')
            print()

        #If the input from the user contains "how are you" string, this condition will undergo
        elif 'how are you' in query:
            print("For computer software, I'm living the dream. Thanks for asking")
            speak("For computer software,, I'm living the dream. Thanks for asking")
            print()

        # This command will show wikipedia results
        # You just have to say for example Chris Evans Wikipedia
        # It will search for Chris Evans on wikipedia
        elif 'wikipedia' in query:
            print('Searching Wikipedia...')
            speak('Searching Wikipedia')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)  # sentences = 2 implies read 2 sentences only from the results
            print('According to wikipedia')
            speak('According to wikipedia')
            print(results)
            speak(results)
            print()

        #Open youtube command will open youtube on your system broswer
        elif 'open youtube' in query:
            print("Opening youtube...")
            speak("Opening youtube")
            webbrowser.open("youtube.com")
            break #As you have opened youtube, the while loop will break

        #Same goes for opening google and email
        elif 'open google' in query:
            print("Opening Google...")
            speak("Opening google")
            webbrowser.open("google.com")
            break #As you have opened google, the while loop will break

        elif 'open email' in query:
            print("Opening Email...")
            speak("Opening E-mail")
            webbrowser.open("gmail.com")
            break #As you have opened email, the while loop will break

        elif 'open spotify' in query:
            musicPath = "C:\\Users\\DELL\\Desktop\\Spotify" #You must add path of spotify in your system.
            print("Opening Spotify...")
            speak("Opening Spotify")
            os.startfile(musicPath)
            break #As you have opened spotify, the while loop will break

        elif 'open twitter' in query:
            print("Opening Twitter...")
            speak("Opening Twitter")
            webbrowser.open("twitter.com")
            break #As you have opened twitter, the while loop will break

        #This command will open whatsapp in web
        elif 'open whatsapp' in query:
            print("Opening Whatsapp...")
            speak("Opening Whatsapp")
            webbrowser.open("web.whatsapp.com")
            break #As you have opened whatsapp, the while loop will break

        #For general talking you can ask it questions
        elif 'What you can do for me' in query:
            print('All that you expect from me')
            speak('All that you expect from me!')
            print()

        elif ('do you have any friend' or 'do you have any friends') in query:
            print("Yeah! Alexa, Google assistant and Siri are my friends and my idols")
            speak("Yeah! Alexa, Google assistant and Siri are my friends and my idols")
            print()

        #This command will give you the current time as per your system timings
        elif 'the time' in query:
            strTime = datetime.now().strftime("%H:%M:%S")
            print("It's", strTime)
            speak(f"It's {strTime}")
            print()

        #For closing the program, Just use close or quit in your input
        elif 'close' in query:
            print("Good-Bye until next time")
            speak("Good-Byeee! until next time")
            break

        elif 'quit' in query:
            print("Quiting...   GoodBye..")
            speak("Quiting!! Goodbyeee")
            break


import sys
import os
# Tell syspath where to import modules from other folders in root direcotry
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from env import EnvReader
from model.combine import CombineData

class Command:
    """ Command line command execution  """

    def __init__(self):
        self.debug = EnvReader.getDebugMode(self)
        self.csvPath = EnvReader.getCsvFolder(self)
        sys.tracebacklimit = self.debug

    def getArgs(self):
        """ Get arguments passed to command
            Returns:
                List of arguments
        """
        arguments = len(sys.argv) - 1

        # Command parameters validation
        if arguments < 2:
            raise Exception('Missing arguments. Please provide input and output csv file')

        if arguments > 2:
            raise Exception('Too many arguments. Please provide input and output csv file')

        response = []
        for i, arg in enumerate(sys.argv):
            if i != 0:
                response.append(arg)

        # Output file name validation
        if response[1].split('.')[-1]  != 'csv':
            raise Exception('Provided output file name is not valid csv file')

        return response

    def runCommand(self):
        """ Run command """
        params = self.getArgs()
        x = CombineData()
        # Return response from CombineData.combine() to be printed in cli
        return x.combine(self.csvPath + params[0], self.csvPath + params[1])

""" Command line call """
x = Command()
output = x.runCommand()
#print(output)