from concurrent import futures
import logging
import sqlite3
import sys
import json

import grpc
import sql_pb2 as sql_pb2
import sql_pb2_grpc as sql_pb2_grpc
import time

class SQLServicer(sql_pb2_grpc.SQLServicer):
    def __init__(self, list):
        self.logger = logging.getLogger(__name__)
        self.list = list
        self.id = 0

    def ExecuteSQL(self, request, context):
        self.logger.info("Got SQL request: %s", request.sql)
        sql_call = {}
        sql_call['sql'] = request.sql
        sql_call['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.id += 1
        sql_call['id'] = str(self.id)
        sql_call['result'] = []
        db = sqlite3.connect("library.db")
        # excute sql and commit
        cursor = db.cursor()
        cursor.execute(request.sql)
        # get columns name
        if cursor.description is not None:
            columns = [column[0] for column in cursor.description]
            sql_call['columns'] = columns
        db.commit()
        # get result
        for row in cursor:
            self.logger.info("fetch row: %s", row)
            sql_call['result'].append(row)
            yield sql_pb2.Record(json=json.dumps(row))
        self.list.append(sql_call)
        cursor.close()
        db.close()

def serve(port, list):
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
    sql_pb2_grpc.add_SQLServicer_to_server(SQLServicer(list), server)
    server.add_insecure_port('[::]:{}'.format(port))
    server.start()
    server.wait_for_termination()

if __name__ == '__main__':
    logging.basicConfig()
    # read arg port
    port = sys.argv[1]
    serve(port)


from odoo import models, fields, api, _
from datetime import datetime, timedelta
from odoo.tools import float_is_zero
import pytz

import logging
log = logging.getLogger(__name__)

class fleet_vehicle(models.Model):
	_inherit = "fleet.vehicle"

	invoice_count=fields.Integer(default='0', readonly=True)
	write_date = fields.Datetime(string='Write date', readonly=True, copy=False)
	partner_id = fields.Many2one('res.partner', string='Partner')
	organization_id = fields.Many2one('res.partner', string='Organization', domain=[('company_type','=','company')])
	driver_ids = fields.Many2many('res.partner', string='Drivers')

class AccountMove(models.Model):
	_inherit = "account.move"
	vehicle_plate = fields.Char(string='Placa')
	vehicle_driver = fields.Char(string='Conductor')
	vehicle_odometer = fields.Char(string='Odometro')
	hose_id= fields.Many2one('pos_psms.hose', string='Manguera')

class PosOrder(models.Model):
	_inherit = 'pos.order'
	vehicle_id = fields.Many2one('fleet.vehicle', string='Vehicle', help='The Vehicle where this order was served')
	vehicle_plate = fields.Char(string='Placa')
	vehicle_driver = fields.Char(string='Conductor')
	vehicle_odometer = fields.Char(string='Odometro')
	hose_id= fields.Many2one('pos_psms.hose', string='Manguera')
	summary_products = fields.Char(string='Purchased Summary',store=True)

	@api.model
	def _order_fields(self, ui_order):
		res = super(PosOrder,self)._order_fields(ui_order)
		res['vehicle_plate'] = ui_order.get('vehicle_plate',False)
		res['vehicle_driver'] = ui_order.get('vehicle_driver',False)
		res['vehicle_odometer'] = ui_order.get('vehicle_odometer',False)
		res['hose_id'] = ui_order.get('hose_id',False)
		return res

	def _prepare_invoice_vals(self):
		res = super(PosOrder,self)._prepare_invoice_vals()
		res['vehicle_plate'] = self.vehicle_plate
		res['vehicle_driver'] = self.vehicle_driver
		res['vehicle_odometer'] = self.vehicle_odometer
		if self.hose_id:
			res['hose_id'] = self.hose_id.id
		return res

	def create_picking(self):
		"""Create a picking for each order and validate it."""
		Picking = self.env['stock.picking']
		Move = self.env['stock.move']
		StockWarehouse = self.env['stock.warehouse']
		HoseStatement = self.env['pos_psms.statement.hose']
		for order in self:
			if not order.lines.filtered(lambda l: l.product_id.type in ['product', 'consu']):
				continue
			address = order.partner_id.address_get(['delivery']) or {}
			picking_type = order.picking_type_id
			return_pick_type = order.picking_type_id.return_picking_type_id or order.picking_type_id
			order_picking = Picking
			return_picking = Picking
			moves = Move
			location_id = order.hose_id.location_id.id if order.hose_id else order.location_id.id
			if order.partner_id:
				destination_id = order.partner_id.property_stock_customer.id
			else:
				if (not picking_type) or (not picking_type.default_location_dest_id):
					customerloc, supplierloc = StockWarehouse._get_partner_locations()
					destination_id = customerloc.id
				else:
					destination_id = picking_type.default_location_dest_id.id

			if picking_type:
				message = _("This transfer has been created from the point of sale session: %s") % (order.id, order.name)
				picking_vals = {
					'origin': order.name,
					'partner_id': address.get('delivery', False),
					'date_done': order.date_order,
					'picking_type_id': picking_type.id,
					'company_id': order.company_id.id,
					'move_type': 'direct',
					'note': order.note or "",
					'location_id': location_id,
					'location_dest_id': destination_id,
				}
				pos_qty = any([x.qty > 0 for x in order.lines if x.product_id.type in ['product', 'consu']])
				if pos_qty:
					order_picking = Picking.create(picking_vals.copy())
					order_picking.message_post(body=message)
				neg_qty = any([x.qty < 0 for x in order.lines if x.product_id.type in ['product', 'consu']])
				if neg_qty:
					return_vals = picking_vals.copy()
					return_vals.update({
						'location_id': destination_id,
						'location_dest_id': return_pick_type != picking_type and return_pick_type.default_location_dest_id.id or location_id,
						'picking_type_id': return_pick_type.id
					})
					return_picking = Picking.create(return_vals)
					return_picking.message_post(body=message)

			for line in order.lines.filtered(lambda l: l.product_id.type in ['product', 'consu'] and not float_is_zero(l.qty, precision_rounding=l.product_id.uom_id.rounding)):
				moves |= Move.create({
					'name': line.name,
					'product_uom': line.product_id.uom_id.id,
					'picking_id': order_picking.id if line.qty >= 0 else return_picking.id,
					'picking_type_id': picking_type.id if line.qty >= 0 else return_pick_type.id,
					'product_id': line.product_id.id,
					'product_uom_qty': abs(line.qty),
					'state': 'draft',
					'location_id': location_id if line.qty >= 0 else destination_id,
					'location_dest_id': destination_id if line.qty >= 0 else return_pick_type != picking_type and return_pick_type.default_location_dest_id.id or location_id,
				})

				#AQUI SE MODIFICA EL STATEMENT DE LA MAGUERA ASOCIADA
				if order.hose_id:
					statement_hose = HoseStatement.search([('hose_id', '=', order.hose_id.id),('pos_session_id','=',order.session_id.id)])
					if statement_hose:
						statement_hose[0].write({'total_quantity':statement_hose[0].total_quantity+line.qty,'total_transactions':statement_hose[0].total_transactions+1})

			# prefer associating the regular order picking, not the return
			order.write({'picking_id': order_picking.id or return_picking.id})

			if return_picking:
				order._force_picking_done(return_picking)
			if order_picking:
				order._force_picking_done(order_picking)

			# when the pos.config has no picking_type_id set only the moves will be created
			if moves and not return_picking and not order_picking:
				moves._action_assign()
				moves.filtered(lambda m: m.state in ['confirmed', 'waiting'])._force_assign()
				moves.filtered(lambda m: m.product_id.tracking == 'none')._action_done()

		return True

	@api.model
	def get_print(self, order_id):
		res = super(PosOrder,self).get_print(order_id)
		order = self.browse(order_id)
		res['vehicle_plate'] = order.vehicle_plate
		res['vehicle_driver'] = order.vehicle_driver
		res['vehicle_odometer'] = order.vehicle_odometer
		return res


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def Line(test_x, m, c):
    y_value = m*test_x + c
    return y_value

def MSECost(y,x,m,c):
    cost = 0
    for i in range(len(y)):
        cost = cost + (y[i]- Line(x[i],m,c))**2
        cost = cost/len(y)
    print(cost)
    return cost

#print(MSECost(Y,X,0.255826,0.003871))

def Grad(y,x,m,c,lr):
    dm = 0
    dc = 0
    for i in range(len(y)):
        dm = dm + x[i]*(y[i]- Line(x[i],m,c))
        dc = dc + (y[i]- Line(x[i],m,c))
    mean_dm = -2*dm/len(x)
    mean_dc = -2*dc/len(x)
    m = m - lr*mean_dm
    c = c - lr*mean_dc
    print(m,c)

    return mean_dm, mean_dc

def OptimizeSampleFullDataset(epochs, m, c,thld, x, y, lr):
    for i in range(epochs):
        cost=MSECost(y,x,m,c)
        if (((cost) < thld)):
            break
        else:
            #a.append(cost)
            dm,dc = Grad(y,x,m,c,lr)
            m -=dm*lr
            c -=dc*lr
            a.append(MSECost(y,x,m,c))
    return m,c,a

lr = 0.0000001
epochs = 6000
M = 0
C = 0
finalM, finalC, plotCosts = OptimizeSampleFullDataset(epochs, M, C,0.1, X, Y, lr)
finalM,finalC

plt.plot(X, [xi*finalM + finalC for xi in X])
plt.scatter(X,Y)

plt.plot(X, [x*2 for x in range(len(X))])
plt.show()


import pygame

class Player:
    turn = None
    move = ''

    def __init__(self):
        pass

class rectangle:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        if (self.x, self.y) == (175, 175):
            self.index = 1
        elif (self.x, self.y) == (175, 225):
            self.index = 2
        elif (self.x, self.y) == (175, 275):
            self.index = 3
        elif (self.x, self.y) == (225, 175):
            self.index = 4
        elif (self.x, self.y) == (225, 225):
            self.index = 5
        elif (self.x, self.y) == (225, 275):
            self.index = 6
        elif (self.x, self.y) == (275, 175):
            self.index = 7
        elif (self.x, self.y) == (275, 225):
            self.index = 8
        elif (self.x, self.y) == (275, 275):
            self.index = 9

    def draw(self, win):
        pygame.draw.rect(win, (200, 200, 200), (self.x, self.y))

    def isclicked(self, a):

        if (a[0] in range(self.x, self.x + 50)) and (a[1] in range(self.y, self.y + 50)):
            return True
        else:
            return False

class Game:
    players = [Player(), Player()]
    id = None
    moveCount = 0
    ready = None
    p1 = []
    p2 = []
    coordinates = [(175, 175), (175, 225), (175, 275), (225, 175), (225, 225), (225, 275), (275, 175), (275, 225), (275, 275)]
    winners = [(1, 2, 3), (1, 4, 7), (1, 5, 9), (2, 5, 8), (3, 6, 9), (4, 5, 6), (7, 8, 9), (3, 5, 7)]
    win_player = ''

    def __init__(self, id1):
        self.id = id1
        self.cross = pygame.image.load('cross.jpg')
        self.circle = pygame.image.load('circle.png')
        self.rectangles = [rectangle(175, 175), rectangle(175, 225), rectangle(175, 275), rectangle(225, 175), rectangle(225, 225), rectangle(225, 275), rectangle(275, 175), rectangle(275, 225), rectangle(275, 275)]

    def draw(self,win):
        win.fill((255, 255, 255))
        for rectangle_ in self.rectangles:
            rectangle_.draw(win)
        for p in self.p1:
            self.draw_cross(self.rectangles[p-1], win)
        for p in self.p2:
            self.draw_ccircle(self.rectangles[p-1], win)
    def draw_cross(self, rect, win):
        win.blit(self.cross, (rect.x, rect.y))

    def draw_circle(self, rect, win):
        win.blit(self.circle, (rect.x, rect.y))

    def check_win_p1(self):
        count = 0
        for winner in self.winners:
            for a1 in self.p1:
                if a1 in winner:
                    count =+1
            if count == 3:
                return True

            else:
                count = 0

        return False

    def check_win_p2(self):
        count = 0
        for winner in self.winners:
            for a1 in self.p2:
                if a1 in winner:
                    count = +1
            if count == 3:
                return True

            else:
                count = 0

        return False


class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if matrix == [[]]:
            return False
        if matrix == []:
            return False
        col = [row[0] for row in matrix]
        result, idx = self.helper(col, target)
        if idx == -1:
            return False
        row = matrix[idx]
        result, idx = self.helper(row, target)
        return result

    def helper(self, nums, target):
        left, right = 0, len(nums) - 1
        while 1:
            if nums[left] > target:
                return False, left
            if nums[right] < target:
                return False, right
            if nums[left] == target:
                return True, left
            if nums[right] == target:
                return True, right
            if left + 1 == right:
                return False, left
            mid = (left + right) // 2
            if nums[mid] < target:
                left = mid
            else:
                right = mid


# Mathy! I've been awake for 29 hours, so I'm going to improve this later.
# Part1: 0:40:50
# Part2: 0:51:08

import numpy as np
import utils as u

def start(inp, lines):
    data = u.split_list(lines, '')
    monkeys = []
    for d in data:
        m = {
            'items': list(np.array(d[1][18:].split(',')).astype(int)),
            'operation': d[2][19:],
            'test': [int(d[4][29:]), int(d[5][30:]), int(d[3][21:])],
            'inspected': 0
        }
        monkeys.append(m)
    gcd = 1
    for m in monkeys:
        gcd *= m['test'][2]
    for i in range(0,10000):
        for m in monkeys:
            items = m['items']
            m['items'] = []
            for i in items:
                m['inspected'] += 1
                old = i
                worry = eval(m['operation']) % gcd
                mindex = (m['test'][0] if (worry % m['test'][2]) == 0 else m['test'][1])
                monkeys[mindex]['items'].append(worry)
    inspected = []
    for m in monkeys:
        inspected.append(m['inspected'])
    print(np.product(sorted(inspected)[-2:]))


import FWCore.ParameterSet.Config as cms

nTupleMuons = cms.EDProducer("BristolNTuple_Muons",
    InputTag = cms.InputTag('slimmedMuons'),
    Prefix = cms.string('Muons.'),
    Suffix = cms.string(''),
    MaxSize = cms.uint32(99),
    minPtToStore = cms.double(10.),
    MuonID = cms.string('GlobalMuonPromptTight'),
    BeamSpotCorr = cms.bool(True),
    VertexInputTag = cms.InputTag('offlineSlimmedPrimaryVertices'),
    BeamSpotInputTag = cms.InputTag('offlineBeamSpot'),
    storePFIsolation = cms.bool(True)
)


import time

from math import isqrt
from database_connection import DatabaseConnection

# TODO: Segment array when large to improve performance

def create_primes_table():
    """ Creates the 'primes.db' database \
        it then  populates the database with the value of 2 \
        the first prime number, which helps prevent crashes \
        from later functions
    """
    with DatabaseConnection('primes.db') as connection:
        cursor = connection.cursor()
        cursor.execute(
            '''CREATE TABLE IF NOT EXISTS primes
            (prime_number INTEGER PRIMARY KEY)''')
        val = 2
        cursor.execute(
            f"INSERT OR REPLACE INTO primes (prime_number) VALUES ({val})")

def prime_finder(upper_bound: int) -> list:
    """ Searches for the primes between 2 and the defined upper_bound.
        It does this by initialising an array, and using the \
        Sieve of Eratosthenes method quickly finds more primes.

    Args:
        upper_bound (int): An integer defining the upper bounds of the array \
            in which primes are searched for within

    Returns:
        list: A List of prime numbers found between the lower_bound=2 \
        and your upper_bound
    """
    prime_array = [True] * upper_bound
    prime_array[0] = False
    prime_array[1] = False

    for i in range(2, 1+isqrt(upper_bound)):
        if prime_array[i]:
            for x in range(i*i, upper_bound, i):
                prime_array[x] = False
    return [i for i in range(upper_bound) if prime_array[i]]

def write_primes_to_db(n: list) -> None:
    """ Writes the input list to the DB
        In this case takes a list and writes each item to the \
        column prime_number in the table primes, \
        in the database primes.db.

    Args:
        n (list): A list of inputs to be written to a database
    """
    with DatabaseConnection('primes.db') as connection:
        cursor = connection.cursor()
        for val in n:
            cursor.execute(
                f"INSERT OR REPLACE INTO primes (prime_number) VALUES ({val})")

def return_primes() -> list:
    """ Reads from the DB and returns all the primes

    Returns:
        list: Returns a list of all the columns \
        found within the table primes, within the database primes.db
    """
    create_primes_table()
    with DatabaseConnection('primes.db') as connection:
        cursor = connection.cursor()
        cursor.execute('SELECT * FROM primes')
        primes = [row[0] for row in cursor.fetchall()]
        return(primes)

# Initialising menu for finding the primes
def find_primes_workflow(upper_bound: int = None,) -> None:
    """ The main workflow function for the prime number searching functionality.
        This can function can be called directly for automated workflows,
        or this function will be called from the App Menu found in app.py.

        This function works in several stage:
            1. Established an upper_bound for the array, \
            either through user input or passed argumennts
            2. Creates the database if required
            3. Finds all the primes up to the upper_bound, \
            while timing the function
            4. writes the found primes to the database

    Args:
        upper_bound (int, optional): This intiger can be provided by calling \
        this function directly, or from inputs. Defaults to None.
    """

    if not upper_bound:
        while True:
            try:
                upper_bound = int(
                    input("Input an integer for upper bound 3 or above: "))
                if upper_bound <= 2:
                    print("Please make the value above 2")
                    continue
                break
            except ValueError:
                print("That is not a valid intiger.")
                continue

    # Creates db if needed
    create_primes_table()

    # Find the primes with a timer wrapper
    start = time.perf_counter()
    write = prime_finder(upper_bound)
    end = time.perf_counter()

    print(f"To find primes up to {upper_bound} it took {end - start} Seconds")

    # write the primes to a database with a timer wrapper
    start = time.perf_counter()
    write_primes_to_db(write)
    end = time.perf_counter()
    print(f"To write it took {end - start} Seconds")


from keras.models import Sequential
from keras.layers import Dense
import numpy
import pandas as pd
# fix random seed for reproducibility
numpy.random.seed(7)

# load pima indians dataset
train = pd.read_csv("C:/Users/TheUnlikelyMonk/Desktop/Analytics Vidhya/LTFS/newtraindata.csv")
test = pd.read_csv("C:/Users/TheUnlikelyMonk/Desktop/Analytics Vidhya/LTFS/newtestdata.csv")

X = train[:,0:40]
Y = train[:,41]

model = Sequential()
model.add(Dense(12, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Fit the model
model.fit(X, Y, epochs=150, batch_size=10)

scores = model.evaluate(X, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

# calculate predictions
predictions = model.predict(test)
# round predictions
rounded = [round(x[0]) for x in predictions]
print(rounded)

fp = open("out.csv","w")
fp.write(repr(rounded))


# coding: utf-8

"""
    DeepVISS TAG

    DeepVISS (Deep Vision Interoperability Specification Standard) allows several computer vision solutions to produce, consume and exchange events in the same format.  # noqa: E501

    The version of the OpenAPI document: 1.2.0
    Contact: office@deepviss.org
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

from openapi_client.configuration import Configuration

class Style(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'font_style': 'str',
        'font_variant': 'str',
        'font_size': 'int',
        'font_color': 'str'
    }

    attribute_map = {
        'font_style': 'font-style',
        'font_variant': 'font-variant',
        'font_size': 'font-size',
        'font_color': 'font-color'
    }

    def __init__(self, font_style=None, font_variant=None, font_size=None, font_color=None, local_vars_configuration=None):  # noqa: E501
        """Style - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._font_style = None
        self._font_variant = None
        self._font_size = None
        self._font_color = None
        self.discriminator = None

        if font_style is not None:
            self.font_style = font_style
        if font_variant is not None:
            self.font_variant = font_variant
        if font_size is not None:
            self.font_size = font_size
        if font_color is not None:
            self.font_color = font_color

    @property
    def font_style(self):
        """Gets the font_style of this Style.  # noqa: E501

        Character encoding type  # noqa: E501

        :return: The font_style of this Style.  # noqa: E501
        :rtype: str
        """
        return self._font_style

    @font_style.setter
    def font_style(self, font_style):
        """Sets the font_style of this Style.

        Character encoding type  # noqa: E501

        :param font_style: The font_style of this Style.  # noqa: E501
        :type: str
        """
        allowed_values = ["serif", "sans-serif", "handwritten", "collage"]  # noqa: E501
        if self.local_vars_configuration.client_side_validation and font_style not in allowed_values:  # noqa: E501
            raise ValueError(
                "Invalid value for `font_style` ({0}), must be one of {1}"  # noqa: E501
                .format(font_style, allowed_values)
            )

        self._font_style = font_style

    @property
    def font_variant(self):
        """Gets the font_variant of this Style.  # noqa: E501

        Character encoding type  # noqa: E501

        :return: The font_variant of this Style.  # noqa: E501
        :rtype: str
        """
        return self._font_variant

    @font_variant.setter
    def font_variant(self, font_variant):
        """Sets the font_variant of this Style.

        Character encoding type  # noqa: E501

        :param font_variant: The font_variant of this Style.  # noqa: E501
        :type: str
        """
        allowed_values = ["all-caps", "no-caps", "handwritten", "collage"]  # noqa: E501
        if self.local_vars_configuration.client_side_validation and font_variant not in allowed_values:  # noqa: E501
            raise ValueError(
                "Invalid value for `font_variant` ({0}), must be one of {1}"  # noqa: E501
                .format(font_variant, allowed_values)
            )

        self._font_variant = font_variant

    @property
    def font_size(self):
        """Gets the font_size of this Style.  # noqa: E501

        Size of font  # noqa: E501

        :return: The font_size of this Style.  # noqa: E501
        :rtype: int
        """
        return self._font_size

    @font_size.setter
    def font_size(self, font_size):
        """Sets the font_size of this Style.

        Size of font  # noqa: E501

        :param font_size: The font_size of this Style.  # noqa: E501
        :type: int
        """

        self._font_size = font_size

    @property
    def font_color(self):
        """Gets the font_color of this Style.  # noqa: E501

        Color in hex format   # noqa: E501

        :return: The font_color of this Style.  # noqa: E501
        :rtype: str
        """
        return self._font_color

    @font_color.setter
    def font_color(self, font_color):
        """Sets the font_color of this Style.

        Color in hex format   # noqa: E501

        :param font_color: The font_color of this Style.  # noqa: E501
        :type: str
        """

        self._font_color = font_color

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, Style):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, Style):
            return True

        return self.to_dict() != other.to_dict()


"""
расширяем класс Hello, а не просто прикрепляем его

для этоо переопределяем некоторые его методы в новом подклассе, который сам
станет специализированным виджетом Frame.

Метод make_widgets этого подкласса сначала создает виджеты обращением к методу суперкласса,
а затем добавляет справа вторую кнопку Extend
"""
from tkinter import *
from example_07_20 import Hello

class HelloExtender(Hello):
    def make_widgets(self):  # расширение метода
        Hello.make_widgets(self)
        Button(self, text='Extend', command=self.quit).pack(side=RIGHT)

    def message(self):
        print('hello', self.data)  # переопределение метода

if __name__ == '__main__':
    HelloExtender().mainloop()


from src.glouton import run
from src.local import local_heuristic
from src.progdyn import dynamic_programming

import csv
import gc
import time

premiere_ligne = ["Taille", "Serie", "Glouton", "Revenue", "Prog_dynamic", "Revenue", "heuristic_local"
                            , "Revenue"]
with open('results.csv', 'a', newline='') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(premiere_ligne)

exemplaires_size = [10000]
exemplaire_serie = [10, 100, 1000]

for size in exemplaires_size:
    for serie in exemplaire_serie:

        exec_times = {'glouton': 0, 'dyn_prog': 0, 'heuristic_local': 0}
        best_sums = {'glouton': 0, 'dyn_prog': 0, 'heuristic_local': 0}

        for i in range(1, 11):
            path = "exemplaires/WC-" + str(size) + "-" + str(serie) + "-" + str(i).zfill(2) + '.txt'

            print('path', path)

            data = {
                'nbEmplacements': 0,
                'emplacements': [],
                'capacite': 0
            }

            with open(path, "r") as fp:
                for j, line in enumerate(fp):
                    if j == 0:
                        data['nbEmplacements'] = int(line.strip())
                    elif j <= data['nbEmplacements']:
                        data['emplacements'].append(tuple(map(int, line.strip().split())))
                    else:
                        data['capacite'] = int(line.strip())

            print('environnement de test: Taille: ', size, ' serie: ', serie, ' exemplaire: ', i)

            # start_time = time.time()
            # best_G_sol, best_sum = run(data)
            # exec_time = time.time() - start_time
            # print("duration glouton : {}".format(exec_time))
            # exec_times['glouton'] += exec_time
            # best_sums['glouton'] += best_sum
            #
            # start_time = time.time()
            # best_LH_sol, best_sum = local_heuristic(data)
            # exec_time = time.time() - start_time
            # print("duration local_heuristic : {}".format(exec_time))
            # exec_times['heuristic_local'] += exec_time
            # best_sums['heuristic_local'] += best_sum

            start_time = time.time()
            try:
                best_DP_sol, best_sum = dynamic_programming(data)
                print('max_revenu', best_sum)
            except MemoryError as e:
                print('(PROG_DYN)_ERROR IN: ', size, ' serie: ', serie, ' exemplaire: ', i)
                best_sum = 0
                pass
            exec_time = time.time() - start_time
            print("duration dynamic_programming : {}".format(exec_time))
            exec_times['dyn_prog'] += exec_time
            best_sums['dyn_prog'] += best_sum

            print('************************************************************')

        new_line = [size, serie, exec_times['glouton']/10, best_sums['glouton']/10, exec_times['dyn_prog']/10,
                    best_sums['dyn_prog']/10, exec_times['heuristic_local']/10, best_sums['heuristic_local']/10]

        with open('results_prog_dyn.csv', 'a', newline='') as myfile:
            wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
            wr.writerow(new_line)

        gc.collect()


#----------------------------------------------------------------------------
# Created By  : Sayak Mukherjee
# Created Date: 09-May-2023
#
# References:
# 1. https://github.com/The-AI-Summer/byol-cifar10/blob/main/ai_summer_byol_in_cifar10.py
# 2. https://docs.lightly.ai/self-supervised-learning/examples/byol.html
# ---------------------------------------------------------------------------
# Dataset utility functions such as collate and custom transforms
# ---------------------------------------------------------------------------

import torch
import torch.nn as nn
import numpy as np
import torchvision.transforms as T

from typing import Callable, List, Optional, Type, Tuple, Union
from torch.utils.data import Dataset
from torchvision.transforms import functional as TF
from PIL import Image

IMAGENET_NORMALIZE = {"mean": [0.485, 0.456, 0.406], "std": [0.229, 0.224, 0.225]}

class SaltPepperNoise(object):

    def __init__(self):

        # self.sp_prob = sp_prob
        pass

    def __call__(self, image: Union[Image.Image, torch.Tensor]):

        image_np = image.cpu().numpy()

        # TODO: Get values
        seed = 40
        amount = 0.1
        prop_salt_pepper = 0.5

        random_gen = np.random.default_rng(seed)

        selected_pixels = self._bernoulli(amount, image_np.shape, random_gen)
        salted = self._bernoulli(prop_salt_pepper, image_np.shape, random_gen)
        peppered = ~salted

        image_np[selected_pixels & salted] = 0.
        image_np[selected_pixels & peppered] = 1.

        image = torch.from_numpy(image_np).to(image.device)

        return image

    def _bernoulli(self, p, shape, random_state):
        """Bernoulli trails at a given probability

        Ref: https://github.com/scikit-image/scikit-image/blob/v0.20.0/skimage/util/noise.py#L39-L234

        Args:
            p (float): probability of returning `True`
            shape (int or tuple): Shape of ndarray to return
            random_state (numpy.random.Generator): generator instance

        Returns:
            _type_: _description_
        """
        if p == 0:
            return np.zeros(shape, dtype=bool)
        if p == 1:
            return np.ones(shape, dtype=bool)
        return random_state.random(shape) <= p

class RandomRotate:

    def __init__(self, rr_prob: float, rr_degrees= Union[None, float, Tuple[float, float]]):
        self.prob = rr_prob

        if rr_degrees is None:
            self.angle = 90
            self.transform = None
        else:
            self.angle = None
            self.transform = T.RandomApply([T.RandomRotation(degrees=rr_degrees)], p=rr_prob)

    def __call__(self, image: Union[Image.Image, torch.Tensor]):

        if self.transform is None:
            prob = np.random.random_sample()
            if prob < self.prob:
                image = TF.rotate(image, self.angle)
            return image
        else:
            return self.transform(image)

class CustomCollate(nn.Module):

    def __init__(
            self,
            input_size: int = 64,
            cj_prob: float = 0.8,
            cj_bright: float = 0.7,
            cj_contrast: float = 0.7,
            cj_sat: float = 0.7,
            cj_hue: float = 0.2,
            min_scale: float = 0.15,
            random_gray_scale: float = 0.2,
            gaussian_blur: float = 0.5,
            kernel_size: Optional[float] = None,
            sigma: Tuple[float, float] = (0.2, 2),
            vf_prob: float = 0.0,
            hf_prob: float = 0.5,
            rr_prob: float = 0.0,
            rr_degrees: Union[None, float, Tuple[float, float]] = None,
            normalize: dict = IMAGENET_NORMALIZE
        ):
        super(CustomCollate, self).__init__()

        if isinstance(input_size, tuple):
            input_size_ = max(input_size)
        else:
            input_size_ = input_size

        color_jitter = T.ColorJitter(cj_bright, cj_contrast, cj_sat, cj_hue)
        blur = T.GaussianBlur(kernel_size=kernel_size, sigma=sigma)

        transform = [
            # T.ToTensor(),
            T.RandomResizedCrop(size=input_size, scale=(min_scale, 1.0)),
            RandomRotate(rr_prob=rr_prob, rr_degrees=rr_degrees),
            T.RandomHorizontalFlip(p=hf_prob),
            T.RandomVerticalFlip(p=vf_prob),
            T.RandomApply([color_jitter], p=cj_prob),
            T.RandomApply([blur], p=gaussian_blur),
            T.RandomGrayscale(p=random_gray_scale)
        ]

        if normalize:
            transform += [T.Normalize(mean=normalize["mean"], std=normalize["std"])]

        self.transform = T.Compose(transform)

    def forward(self, batch):

        batch_size = len(batch)

        # list of indexes
        indexes = torch.LongTensor([item[0] for item in batch])

        # list of transformed images
        transforms = [
            self.transform(batch[i % batch_size][1]).unsqueeze_(0)
            for i in range(2 * batch_size)
        ]

        # list of labels
        labels = torch.LongTensor([item[2] for item in batch])

        # tuple of transforms
        transforms = (
            torch.cat(transforms[:batch_size], 0),
            torch.cat(transforms[batch_size:], 0),
        )

        return indexes, transforms, labels

class SimCLRCollate(CustomCollate):

    def __init__(
        self,
        input_size: int = 32,
        cj_prob: float = 0.8,
        cj_strength: float = 0.5,
        min_scale: float = 0.08,
        random_gray_scale: float = 0.2,
        gaussian_blur: float = 0.5,
        kernel_size: Optional[float] = 3,
        sigma: Tuple[float, float] = (0.1, 2.0),
        vf_prob: float = 0.0,
        hf_prob: float = 0.5,
        rr_prob: float = 0.0,
        rr_degrees: Union[None, float, Tuple[float, float]] = None,
        normalize: dict = IMAGENET_NORMALIZE,
    ):
        super(SimCLRCollate, self).__init__(
            input_size=input_size,
            cj_prob=cj_prob,
            cj_bright=cj_strength * 0.8,
            cj_contrast=cj_strength * 0.8,
            cj_sat=cj_strength * 0.8,
            cj_hue=cj_strength * 0.2,
            min_scale=min_scale,
            random_gray_scale=random_gray_scale,
            gaussian_blur=gaussian_blur,
            kernel_size=kernel_size,
            sigma=sigma,
            vf_prob=vf_prob,
            hf_prob=hf_prob,
            rr_prob=rr_prob,
            rr_degrees=rr_degrees,
            normalize=normalize,
        )


import pandas as pd
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_selection import RFECV
from sklearn.linear_model import Lasso
from sklearn.datasets import make_classification

def rawSelect(divideNum, minGap):
    f = open("divide_" + str(divideNum) + ".txt", "r")
    gaps = f.read().split(",")
    gaps = [float(x) for x in gaps]

    selected = []
    for i in range(len(gaps)):
        if gaps[i] >= minGap:
            selected.append(str(i))
    return selected

features = rawSelect(50, 0.12)

trainDf = pd.read_csv("Data/train.csv")
testDf = pd.read_csv("Data/test.csv").drop(["id"], axis=1)

X = trainDf.drop(["id", "target"], axis=1)[features]
y = trainDf["target"]
# y.loc[y['target'] == 1, 'target'] = int(1)
# y.loc[y['target'] == 0, 'target'] = int(0)

estimator = SVC(kernel="linear")
# estimator = Lasso(alpha=0.03, tol=0.01, warm_start=True, selection="random")
min_features_to_select = 1
rfecv = RFECV(
    estimator=estimator,
    cv=StratifiedKFold(4),
    scoring="accuracy",
    min_features_to_select=min_features_to_select,
)
rfecv.fit(X, y)

print("Optimal number of features : %d" % rfecv.n_features_)
print("features", list(rfecv.feature_names_in_))
print(list(rfecv.get_support(indices=True)))


import boto3
from botocore.exceptions import ClientError, EndpointConnectionError
import json
import os
import time
from datetime import datetime, timezone
from dateutil import tz

from antiope.aws_account import *
from common import *

import logging
logger = logging.getLogger()
logger.setLevel(getattr(logging, os.getenv('LOG_LEVEL', default='INFO')))
logging.getLogger('botocore').setLevel(logging.WARNING)
logging.getLogger('boto3').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)

RESOURCE_PATH = "secretsmanager/secret"

def lambda_handler(event, context):
    logger.debug("Received event: " + json.dumps(event, sort_keys=True))
    message = json.loads(event['Records'][0]['Sns']['Message'])
    logger.info("Received message: " + json.dumps(message, sort_keys=True))

    try:
        target_account = AWSAccount(message['account_id'])
        for r in target_account.get_regions():
            try:
                discover_secrets(target_account, r)
            except ClientError as e:
                # Move onto next region if we get access denied. This is probably SCPs
                if e.response['Error']['Code'] == 'AccessDeniedException':
                    logger.error(f"AccessDeniedException for region {r} in function {context.function_name} for {target_account.account_name}({target_account.account_id})")
                    continue
                else:
                    raise  # pass on to the next handlier

    except AntiopeAssumeRoleError as e:
        logger.error("Unable to assume role into account {}({})".format(target_account.account_name, target_account.account_id))
        return()
    except ClientError as e:
        if e.response['Error']['Code'] == 'UnauthorizedOperation':
            logger.error("Antiope doesn't have proper permissions to this account")
            return(event)
        logger.critical("AWS Error getting info for {}: {}".format(message['account_id'], e))
        capture_error(message, context, e, "ClientError for {}: {}".format(message['account_id'], e))
        raise
    except Exception as e:
        logger.critical("{}\nMessage: {}\nContext: {}".format(e, message, vars(context)))
        capture_error(message, context, e, "General Exception for {}: {}".format(message['account_id'], e))
        raise

def discover_secrets(target_account, region):
    '''Iterate across all regions to discover Cloudsecrets'''

    try:
        secrets = []
        client = target_account.get_client('secretsmanager', region=region)
        response = client.list_secrets()
        while 'NextToken' in response:  # Gotta Catch 'em all!
            secrets += response['SecretList']
            response = client.list_secrets(NextToken=response['NextToken'])
        secrets += response['SecretList']

        for s in secrets:
            process_secret(client, s, target_account, region)

    except EndpointConnectionError as e:
        logger.info("Region {} not supported".format(region))

def process_secret(client, secret, target_account, region):
    resource_item = {}
    resource_item['awsAccountId']                   = target_account.account_id
    resource_item['awsAccountName']                 = target_account.account_name
    resource_item['resourceType']                   = "AWS::SecretsManager::Secret"
    resource_item['source']                         = "Antiope"
    resource_item['awsRegion']                      = region
    resource_item['configurationItemCaptureTime']   = str(datetime.datetime.now())
    resource_item['configuration']                  = secret
    resource_item['supplementaryConfiguration']     = {}
    resource_item['resourceId']                     = "{}-{}-{}".format(target_account.account_id, region, secret['Name'].replace("/", "-"))
    resource_item['resourceName']                   = secret['Name']
    resource_item['errors']                         = {}
    resource_item['ARN']                            = secret['ARN']

    try:
        response = client.get_resource_policy(SecretId=secret['ARN'])
        if 'ResourcePolicy' in response:
            resource_item['supplementaryConfiguration']['ResourcePolicy']    = json.loads(response['ResourcePolicy'])
    except ClientError as e:
        if e.response['Error']['Code'] == "AccessDeniedException":
            resource_item['errors']['ResourcePolicy'] = e.response['Error']['Message']
        else:
            raise

    if 'Tags' in secret:
        resource_item['tags']              = parse_tags(secret['Tags'])

    save_resource_to_s3(RESOURCE_PATH, resource_item['resourceId'], resource_item)


#! /usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Copernicus Marine User Support Team"
__copyright__ = "(C) 2021 E.U. Copernicus Marine Service Information"
__credits__ = ["E.U. Copernicus Marine Service Information"]
__license__ = "MIT License - You must cite this source"
__version__ = "202105"
__maintainer__ = "D. Bazin, E. DiMedio, J. Cedillovalcarce, C. Giordan"
__email__ = "servicedesk dot cmems at mercator hyphen ocean dot eu"

def motu_option_parser(script_template, usr, pwd, output_filename):
    dictionary = dict(
        [e.strip().partition(" ")[::2] for e in script_template.split('--')])
    dictionary['variable'] = [value for (var, value) in [e.strip().partition(" ")[::2] for e in script_template.split('--')] if var == 'variable']  # pylint: disable=line-too-long
    for k, v in list(dictionary.items()):
        if v == '<OUTPUT_DIRECTORY>':
            dictionary[k] = '.'
        if v == '<OUTPUT_FILENAME>':
            dictionary[k] = output_filename
        if v == '<USERNAME>':
            dictionary[k] = usr
        if v == '<PASSWORD>':
            dictionary[k] = pwd
        if k in ['longitude-min', 'longitude-max', 'latitude-min',
                 'latitude-max', 'depth-min', 'depth-max']:
            dictionary[k] = float(v)
        if k in ['date-min', 'date-max']:
            dictionary[k] = v[1:-1]
        dictionary[k.replace('-','_')] = dictionary.pop(k)
    dictionary.pop('python')
    dictionary['auth_mode'] = 'cas'
    return dictionary


#crop an area and determine black or white

import cv2
import numpy as np
import pandas as pd

im = cv2.imread('chess.png')

cv2.imshow('chess',im)
cv2.waitKey(0)
def board_position(im,row,col):
    [rows,columns,n] = np.shape(im)
    board_size = int(rows/8)
    row_st=row*board_size+1
    col_st=col*board_size+1
    row_end=row_st+board_size-1
    col_end=col_st+board_size-1
    print(row_st,row_end,col_st,col_end)

    im_crop=im[row_st:row_end,col_st:col_end]

    cv2.imshow('cropped',im_crop)

    im_gray =cv2.cvtColor(im_crop,cv2.COLOR_BGR2GRAY)

    n = np.count_nonzero(im_gray)
    m = np.size(im_gray)
    s = im_gray[0]
    im_gray = [i-im_gray[0] for i in im_gray ]
    if np.count_nonzero(im_gray) == np.size(im_gray):
        #cv2.addText(im_crop,'empty',(300,300),cv2.FONT_HERSHEY_COMPLEX,1,(0,150,0),1)
        print('empty')
    else:
        white_pixel = int(n/m*100)
        print(white_pixel)
        if white_pixel>80:
            #cv2.addText(im_crop,'white',(300,300),cv2.FONT_HERSHEY_COMPLEX,1,(0,150,0),1)
            print('white')
        else:
            #cv2.addText(im_crop,'black',(300,300),cv2.FONT_HERSHEY_COMPLEX,1,(0,150,0),1)
            print('black')
    im_gray = [i + s for i in im_gray]

    cv2.waitKey(0)
    print(np.shape(im_gray))
    return im_gray

'''a = board_position(im,7,1)
df = pd.DataFrame(a)
writer = pd.ExcelWriter('hahaha.xlsx')
df.to_excel(writer,'page_1')
writer.save()'''
a = board_position(im, 7, 1)
df = pd.DataFrame(a)
writer = pd.ExcelWriter('hahaha.xlsx')
df.to_excel(writer, 'page_1')
writer.save()


import RPi.GPIO as GPIO
from time import sleep

def setup(ledMap,buttonMap):
    GPIO.setmode(GPIO.BCM)
    for x in ledMap:
        GPIO.setup(x,GPIO.OUT)
    for x in buttonMap:
        GPIO.setup(x,GPIO.IN)

def buttonCheck(buttonMap):
    on = []
    for x in buttonMap:
        if GPIO.input(x):
            on.append(True)
        else:
            on.append(False)
    return on

"""
ledMap = [21,20,16]
buttonMap = [26,19,13,6]
setup(ledMap,buttonMap)

on = buttonCheck(buttonMap)
GPIO.setup(12,GPIO.OUT)
pwm = GPIO.PWM(12, 1000)

while True:
    on = buttonCheck(buttonMap)

    GPIO.output(ledMap[0],True)
    GPIO.output(ledMap[1],False)
    GPIO.output(ledMap[2],False)

    if(not on[0]):
        GPIO.output(ledMap[1],True)
    if(not on[1]):
        GPIO.output(ledMap[2],True)
    if(not on[2]):
        pwm.start(50)
    if(not on[3]):
        pwm.stop()
"""


from utility.bcolors import bcolors
from utility.inputChecks import checkForGoodInput
from utility.options import options
import random

def castMagic(player, enemies):
    player.choose_magic()
    magic_choice = checkForGoodInput("\tChoose magic: ", len(player.magic))
    spell = player.magic[magic_choice]
    current_mp = player.get_mp()

    if spell.cost > current_mp:
        print(bcolors.FAIL + "\nNot enough MP\n" + bcolors.ENDC)
        return False

    player.reduce_mp(spell.cost)
    spell.castSpell(player,enemies)
    return True

def elixerBoost(player,item):
    hpBoost = item.rollForAffect()
    mpBoost = item.rollForAffect()
    player.heal(hpBoost)
    player.gain_mp(mpBoost)
    print(bcolors.OKGREEN + "\n" + item.name +
            " restores HP" + str(hpBoost) + bcolors.ENDC)
    print(bcolors.OKGREEN + "\n" + item.name +
            " restores MP" + str(mpBoost) + bcolors.ENDC)

def useItem(player, party, enemies):
    player.choose_item()
    item_choice = checkForGoodInput("\tChoose item: ", len(player.items))
    if item_choice == -1:
        return False
    if player.items[item_choice].qnty == 0:
        print(bcolors.FAIL + "\nNone left..." + bcolors.ENDC)
        return False

    item = player.items[item_choice]
    player.items[item_choice].qnty -= 1

    if item.type == "potion":
        healAmount = item.rollForAffect()
        player.heal(healAmount)
        if player.hp > player.maxHp:
            player.hp == player.maxHp
        print(bcolors.OKGREEN + "\n" + item.name +
                " heals for " + str(healAmount)
                 + " HP" + bcolors.ENDC)
    elif item.type == "elixer":
        if item.name == "megaElixer":
            for player in party:
                elixerBoost(player,item)
        else:
            elixerBoost(player,item)
    elif item.type == "attack":
        enemy = enemies[choose_target(enemies)]
        enemy.take_damage(item.prop)
        print(bcolors.FAIL + "\n" + item.name + " deals " +
                str(item.prop) + " points of damage to " + enemies[enemy].name + "." + bcolors.ENDC)
        deathCheck(enemies,enemy)
    return True

def choose_target(enemies):
    i = 1
    choice = 0
    print("\n" + bcolors.FAIL + bcolors.BOLD + "\tTarget:" + bcolors.ENDC)
    for enemy in enemies:
        enemy.get_enemy_stats(i)
        i += 1
    choice = checkForGoodInput("\tChoose target: ",len(enemies))
    return choice

def checkWinCon(party,enemies):
    if not enemies:
        print(bcolors.OKGREEN + "You win!" + bcolors.ENDC)
        return False

    passedOut = 0
    for player in party:
        if player.get_hp() == 0:
            passedOut += 1
    if passedOut == len(party):
        print(bcolors.FAIL + "Your enemy has defeated you" + bcolors.ENDC)
        return False
    return True

def baddiesTurn(party,enemies):
    for enemy in enemies:
        enemy_action = random.randrange(0,len(enemies))
        target = random.randrange(0, len(party))
        if enemy.actions[enemy_action] == "attack":
            toAttack = party[target]
            enemy_dmg = enemy.damage(toAttack)
            if enemy_dmg:
                toAttack.takeDamage(enemy_dmg)
                print(bcolors.FAIL + "Enemy attacks " + party[target].name + " for " + str(enemy_dmg) + bcolors.ENDC)
        elif enemy.actions[enemy_action] == "magic":
            if enemy.mp < 10:
                print(bcolors.FAIL + enemy.name + " tries to cast magic but fails!" + bcolors.ENDC)
                break
            spell, dmg = enemy.choose_enemy_spell()
            enemy.reduce_mp(spell.cost)
            if spell.type == "white":
                enemy.heal(dmg)
                print(bcolors.FAIL + enemy.name + " heals for " + str(dmg) + " hp!" + bcolors.ENDC)
            else:
                party[target].take_damage(dmg)
                print(bcolors.FAIL + enemy.name + " casts " + spell.name + " targeting " +
                    party[target].name + " for " + str(dmg) + bcolors.ENDC)

def deathCheck(enemies,enemy):
    if enemy.get_hp() == 0:
        print(bcolors.FAIL + enemy.name + " has died!" +bcolors.ENDC)
        enemies.remove(enemy)

def combatMenu(index, player, enemies, party):
    if player.actions[index] == "attack":
        enemy = enemies[choose_target(enemies)]
        dmg = player.damage(enemy)
        if dmg:
            enemy.takeDamage(dmg)
            print(bcolors.HEADER + player.name + "atacked " + enemy.name + " for " +
                    str(dmg) + " points of damage." + bcolors.ENDC)
            deathCheck(enemies, enemy)

    elif player.actions[index] == "spells":
        magicCast = castMagic(player, enemies)
        if not magicCast:
            return False

    elif player.actions[index] == "items":
        usedItem = useItem(player, party, enemies)
        if not usedItem:
            return False

    elif player.actions[index] == "options":
        choice = options()
        return choice

    return True

def combat(party, enemies):
    combat = True
    print(bcolors.FAIL + bcolors.BOLD + "AN ENEMY ATTACKS!" + bcolors.ENDC)
    while combat:
        print("-----------------------------------")

        print("\n")
        print(bcolors.OKBLUE + bcolors.BOLD + "Party Members" + bcolors.ENDC)
        print("NAME               HP                                              MP")
        for player in party:
            player.getStats()
        print("\n")

        print(bcolors.FAIL + bcolors.BOLD + "Enemies Members" + bcolors.ENDC)
        print("NAME                   HP")
        for enemy in enemies:
            enemy.get_enemy_stats(False)

        for player in party:
            player.choose_action()
            index = checkForGoodInput("\tChoose action: ", len(player.actions))

            success = combatMenu(index, player, enemies,party)
            if not success:
                continue

            combat = checkWinCon(party, enemies)

            if not combat:
                break

        baddiesTurn(party,enemies)
        if combat:
            combat = checkWinCon(party,enemies)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.util import random_seed
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import gen_dataset_ops
from tensorflow.python.util import deprecation
from tensorflow.python.util.tf_export import tf_export

class _ShuffleAndRepeatDataset(dataset_ops.UnaryUnchangedStructureDataset):
  """A `Dataset` that fuses `shuffle` and `repeat`."""

  def __init__(self, input_dataset, buffer_size, count=None, seed=None):
    self._input_dataset = input_dataset
    self._buffer_size = ops.convert_to_tensor(
        buffer_size, dtype=dtypes.int64, name="buffer_size")
    if count is None:
      self._count = constant_op.constant(-1, dtype=dtypes.int64, name="count")
    else:
      self._count = ops.convert_to_tensor(
          count, dtype=dtypes.int64, name="count")
    self._seed, self._seed2 = random_seed.get_seed(seed)
    variant_tensor = gen_dataset_ops.shuffle_and_repeat_dataset(
        self._input_dataset._variant_tensor,  # pylint: disable=protected-access
        buffer_size=self._buffer_size,
        count=self._count,
        seed=self._seed,
        seed2=self._seed2,
        **self._flat_structure)
    super(_ShuffleAndRepeatDataset, self).__init__(input_dataset,
                                                   variant_tensor)

@deprecation.deprecated(
    None,
    "Use `tf.data.Dataset.shuffle(buffer_size, seed)` followed by "
    "`tf.data.Dataset.repeat(count)`. Static tf.data optimizations will take "
    "care of using the fused implementation.")
@tf_export("data.experimental.shuffle_and_repeat")
def shuffle_and_repeat(buffer_size, count=None, seed=None):
  """Shuffles and repeats a Dataset returning a new permutation for each epoch.

  `dataset.apply(tf.data.experimental.shuffle_and_repeat(buffer_size, count))`

  is equivalent to

  `dataset.shuffle(buffer_size, reshuffle_each_iteration=True).repeat(count)`

  The difference is that the latter dataset is not serializable. So,
  if you need to checkpoint an input pipeline with reshuffling you must use
  this implementation.

  Args:
    buffer_size: A `tf.int64` scalar `tf.Tensor`, representing the
      maximum number elements that will be buffered when prefetching.
    count: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the
      number of times the dataset should be repeated. The default behavior
      (if `count` is `None` or `-1`) is for the dataset be repeated
      indefinitely.
    seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the
      random seed that will be used to create the distribution. See
      `tf.compat.v1.set_random_seed` for behavior.

  Returns:
    A `Dataset` transformation function, which can be passed to
    `tf.data.Dataset.apply`.
  """

  def _apply_fn(dataset):  # pylint: disable=missing-docstring
    return _ShuffleAndRepeatDataset(dataset, buffer_size, count, seed)

  return _apply_fn


from typing import List

class ShuffleTheArray:
    """
        O(n)
        2 pointer solution, we put a pointer at the beggining of the array, and a pointer at n
        and we append values from each pointer in each iteration
    """
    def shuffle(self, nums: List[int], n: int) -> List[int]:
        y_pointer = n
        shuffled_array = []

        # we don't use while because it is much slower than a normal for in python
        for x_pointer in range(n):
            shuffled_array.append(nums[x_pointer])
            shuffled_array.append(nums[y_pointer])

            y_pointer += 1

        return shuffled_array

if __name__ == '__main__':
    object = ShuffleTheArray()

    print(object.shuffle([2,5,1,3,4,7], 3))


from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework import status
from drf_yasg.utils import swagger_auto_schema
from ..models import (
    ProductImage,
)
from ..serializers import (
    ProductImageSerializer,
    CreateProductImageSerializer,
)

class ProductImageCreateView(APIView):
    @swagger_auto_schema(
        request_body=CreateProductImageSerializer,
        operation_description="Create new product image",
        operation_summary="Create new product image",
        responses={
            201: ProductImageSerializer,
            400: "Bad request"
        }
    )
    def post(self, request: Request):
        serializer = CreateProductImageSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        print(serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ProductImageUpdateView(APIView):
    @swagger_auto_schema(
        request_body=ProductImageSerializer,
        operation_description="Update product image",
        operation_summary="Update product image",
        responses={
            200: ProductImageSerializer,
            400: "Bad request"
        }
    )
    def put(self, request: Request, pk: int):
        productimage = ProductImage.objects.get(pk=pk)
        productimage.image = request.data['image']
        productimage.save()
        serializer = ProductImageSerializer(productimage)
        return Response(serializer.data, status=status.HTTP_200_OK)

class ProductImageDeleteView(APIView):
    @swagger_auto_schema(
        operation_description="Delete product image",
        operation_summary="Delete product image",
        responses={
            200: "OK",
            400: "Bad request"
        }
    )
    def delete(self, request: Request, pk: int):
        productimage = ProductImage.objects.get(pk=pk)
        productimage.delete()
        return Response(status=status.HTTP_200_OK)

class ProductImageGetIdView(APIView):
    @swagger_auto_schema(
        operation_description="Get product image by id",
        operation_summary="Get product image by id",
        responses={
            200: ProductImageSerializer,
            400: "Bad request"
        }
    )
    def get(self, request: Request, pk: int):
        productimage = ProductImage.objects.get(pk=pk)
        serializer = ProductImageSerializer(productimage)
        return Response(serializer.data, status=status.HTTP_200_OK)

class ProductImageGetView(APIView):
    @swagger_auto_schema(
        operation_description="Get all product images",
        operation_summary="Get all product images",
        responses={
            200: ProductImageSerializer,
            400: "Bad request"
        }
    )
    def get(self, request: Request):
        productimages = ProductImage.objects.all()
        serializer = ProductImageSerializer(productimages, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


from openpyxl import load_workbook
import os

# HTML append to start/end
start = """{% extends "base.html" %}
{% block content %}

"""

end = """

{% endblock content %}"""

# load workbook
wb = load_workbook(filename = 'input.xlsx', data_only = True)
ws = wb.worksheets[0]
max_row = ws.max_row

views_list = []
url_list = []

# loop through sheet
for x in range(1, max_row + 1):

    # read excel
    template_name = ws.cell(x, 1).value
    HTMLcode = ws.cell(x, 2).value
    HTMLcode_django_tagged = start + HTMLcode + end

    # parse path
    if "/" in template_name:
        path = template_name.split("/")[0]
    else:
        path = ""
    file = template_name.split("/")[-1]

    # path slash or underscore file
    if path != "":
        path_slash_file = path + "/" + file
        path_file = path + "_" + file
    else:
        path_slash_file = file
        path_file = file

    # mkdir and output file
    if path != "":
        if not os.path.exists("output/" + path):
            os.mkdir("output/" + path)
    with open("output/" + path_slash_file + ".html", "w+", encoding='utf-8') as text_file:
        print(HTMLcode_django_tagged, file=text_file)

    # generate views.py and url.py list
    view_entry = "def " + path_file + """(request):
    return render(request, '""" + path_slash_file + ".html')"
    url_entry = "url(r'^" + path_slash_file + "/$', views." + path_file + ", name='" + path_file + "'),"

    views_list.append(view_entry)
    url_list.append(url_entry)

#  output final view_list and url_list
with open("output/" + "view_list.txt", "w+", encoding='utf-8') as text_file:
    print("\n\n\n".join(views_list), file=text_file)

with open("output/" + "url_list.txt", "w+", encoding='utf-8') as text_file:
    print("\n".join(url_list), file=text_file)


from rest_framework import serializers
from .models import Suppliers, SupplierItems

class SupplierItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = SupplierItems
        fields = ('item_code', 'item_name')

class SupplierSerializer(serializers.ModelSerializer):
    supplier_items = SupplierItemSerializer(many=True)

    class Meta:
        model = Suppliers
        fields = ('id', 'supplier_name', 'supplier_items')

    def create(self, validated_data):
        supplier_items_data = validated_data.pop('supplier_items')
        supplier = Suppliers.objects.create(**validated_data)
        for supplier_item_data in supplier_items_data:
            SupplierItems.objects.create(supplier=supplier, **supplier_item_data)
        return supplier

    def update(self, instance, validated_data):
        instance.supplier_name = validated_data.get('supplier_name', instance.supplier_name)
        supplier_items_data = validated_data.pop('supplier_items')
        for supplier_item_data in supplier_items_data:
            supplier_item = SupplierItems.objects.get(pk=supplier_item_data)
            supplier_item.item_code = supplier_item_data.item_code
            supplier_item.item_name = supplier_item_data.item_name
        instance.save()
        return instance


from django.conf.urls import url
from . import views
from django.contrib.auth.views import login, logout

# Add Django site authentication urls (for login, logout, password management)
urlpatterns = [
    url(r'^register/$', views.register, name='register'),
    url(r'^login/$', views.login, name='login'),
    url(r'^logout/$', views.logout, name='logout'),
    url(r'^profile/$', views.profile, name='profile'),
    url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
    url(r'^$', views.home, name='home'),
    # contact url
    url(r'^contact/$', views.contact, name='contact'),
]


#!/usr/bin/env python

import sys

# read in the file
try:
    if sys.argv[1] == "-":
        lines = sys.stdin.read()
    else:
        # use open() to open a file
        lines = open(sys.argv[1]).read()
except:
    print("Usage: %s <filename|->" % sys.argv[0])
    sys.exit(1)

# create a dictionary to store words and their lengths
words_lengths = {}

# fill in the dictionary
for word in lines.split():
	words_lengths[word]=len(word)

# sort the dictionary based on its values (word lengths)
sorted_dictionary = sorted(words_lengths.items(), key= lambda x: x[1], reverse=True)
print(sorted_dictionary[:10])

# read from a list, is for line in lines ok then? right now repetition messes things up?
# where is the dict/words file?


#!/usr/bin/env python3

"""
The Universal Translator is an offline alternative to web based translation services.

As of now it utilizes the following engines:
m2m100
opus-mt

"""

from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles  # In order to host static files like images
from frontend.core.config import settings # Location of ML models, version names and so on
from frontend.api.router import api_router
from frontend.website.base import api_router as webapp_router

def include_router(app):
    app.include_router(api_router)
    app.include_router(webapp_router)

def configure_static(app):
    app.mount("/static", StaticFiles(directory="frontend/website/static"), name="static")

def start_webserver_application():
    app = FastAPI(title=settings.PROJECT_NAME, version=settings.PROJECT_VERSION, docs_url=None)
    include_router(app)
    configure_static(app)

    @app.get('/favicon.ico', include_in_schema=False)
    async def get_favicon():
        favicon_path = "frontend/website/static/icons8-intelligence-96.png"
        #favicon_path = "website/static/OCP2.png"
        return FileResponse(favicon_path)

    return app

app = start_webserver_application()


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 14 20:04:25 2020

@author: Kristen
"""

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import tensorflow as tf
from tensorflow import keras as k
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn import preprocessing
import tensorflow_addons as tfa
# if file is in same working directory as data, you can just use the file name
data=pd.read_csv('machine0df.csv', index_col=0)
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(data.values)
data = pd.DataFrame(x_scaled, columns=data.columns,index=data.index.values)
#we have two target values, damage in x and y
# xtarget=data['Machines > Bridgeport Mill 1 > Spindle > X-Axial > Damage Accumulation']
# ytarget=data['Machines > Bridgeport Mill 1 > Spindle > Y-Radial > Damage Accumulation']

xtarget=data[data.columns[1]]
ytarget=data[data.columns[11]]
target=pd.concat([xtarget,ytarget],axis=1)

#create features dataframe by dropping the target columns
# features=data.drop(['Machines > Bridgeport Mill 1 > Spindle > Y-Radial > Damage Accumulation','Machines > Bridgeport Mill 1 > Spindle > X-Axial > Damage Accumulation'],axis=1)
features=data.drop(data.columns[11],axis=1)
features=features.drop(features.columns[1],axis=1)

model = Sequential()
model.add(k.layers.BatchNormalization())
model.add(Dense(128, input_dim=11, activation='selu'))     #CHANGE INPUT_DIM to number of features
# dense layers are fully connected layers, dense(32) means 32 outputs
model.add(Dense(256, activation='selu'))
model.add(Dense(128, activation='selu'))
model.add(Dense(2, activation='relu'))   #output predicted xdamage and ydamage, both stored in target

#Adam optimizer is used for preliminary results. Other optimizers may be more stable/robust, perhaps less efficient
#Use Keras MSLE metric
# model.compile(optimizer='adam',loss=tf.keras.losses.MeanSquaredError()) #I think this is MeanSquaredError function

def custom_loss(labels, predictions):
    # result = tfa.metrics.RSquare()
    # result.update_state(y_true, y_pred)
    # return result
    unexplained_error = tf.reduce_sum(tf.square(labels - predictions))
    total_error = tf.reduce_sum(tf.square(labels - tf.reduce_mean(labels, axis=0)))
    R2 = 1. - tf.math.divide(unexplained_error, total_error)
    return -R2

def r2_tf(y_true, y_pred):
    SS_res =  tf.reduce_sum(tf.math.square(y_true - y_pred),0)
    SS_tot = tf.reduce_sum(tf.math.square(y_true -  tf.reduce_mean(y_true,0)),0)
    return (1-SS_res/(SS_tot + tf.keras.backend.epsilon()))

# model.compile(optimizer='adam',loss='mse')
model.compile(optimizer='adam',loss=custom_loss)
#Adjust number of epochs (iterations over set), validation split, other arguments, and verbosity
#Change input as needed

history = model.fit(features, target, validation_split=0.2, epochs=100,verbose=0)

model.summary()

#print("model.fit outputs: ",history)
#print("NN Average RMSE: ",np.average(history.history['loss']))

print("NN Average RMSE over last 50 points: ",np.average(history.history['val_loss'][-50:]))

#Model evaluation

evaltest = model.evaluate(features,target,batch_size=1)
#print('Accuracy: %.2f' % (accuracy*100))
#print(evaltest)

#Plot loss over epochs

plt.plot(history.history['val_loss'][10:],label= 'Test loss')
plt.plot(history.history['loss'][10:],label= 'Train loss')
plt.show()


import tweepy
import os
import dotenv
from datetime import date, timedelta
import random, requests, time, json
import env

dotenv.load_dotenv()

auth_handler = tweepy.OAuthHandler(env.API_KEY, env.API_SECRET_KEY)
auth_handler.set_access_token(env.ACCESS_TOKEN, env.ACCESS_TOKEN_SECRET)
headers = {
    "Authorization": f"Bearer {env.BEARER_TOKEN}"
    }
api = tweepy.API(auth_handler, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
try:
    api.verify_credentials()
    print('Authentication OK')
except:
    print('Error during authentication')

def sahaay_tweeter(data):
    status = f'''
Resource available : #{data['resource']}
Available at : #{data['place']}
Quantity available : #{data['quantity']}
Price : #{data['price']}
Contact : {data['phone']}

#{data['place']} #{data['resource']} #sahaay
visit https://sahaay.xyz for more resources
    '''
    api.update_status(status)

def data_tweeter(data):
    untweeted = []
    with open(os.path.join(os.path.expanduser('~/Sahaay-Bot'), 'states.json')) as json_file:
        states = json.load(json_file)["states"]
    status = ""
    for place in data:
        for resource in data[place]:
            for resource_id in data[place][resource]:
                details = data[place][resource][resource_id]
                state = ""
                for state_data in states:
                    for district in state_data["districts"]:
                        if district.lower() == place.lower():
                            state = state_data["state"]
                            break
                    if state != "":
                        break
                if state != "":
                    status = f'''
Verification Status: {details['isVerified']}
Resource available : #{resource.capitalize()}
Available at : #{place.capitalize().replace(' ', '_')}, #{state.replace(' ', '_')}
Name : {details['name']}
Contact : {details['phone']}

#{place.capitalize()} #{state} #{resource.capitalize()} #sahaay
visit https://sahaay.xyz for more resources'''
                    pass
                else:
                    status = f'''
Verification Status: {details['isVerified']}
Resource available : #{resource.capitalize()}
Available at : #{place.capitalize()}
Name : {details['name']}
Contact : {details['phone']}

#{place.capitalize()} #{resource.capitalize()} #sahaay
visit https://sahaay.xyz for more resources'''
                    pass
                # print(status)
                try:
                    api.update_status(status)
                    print("New tweet : ", resource.capitalize(), " at ", place.capitalize())
                except:
                    print("Twitter kai ozhinju makkale !")
                    untweeted.append(resource_id)
                time.sleep(60)
    print("Bot termination: ", len(untweeted), " tweets failed !")
    with open(os.path.join(os.path.expanduser('~/Sahaay-Bot'), 'untweeted.txt')) as text_file:
        text_file.write(untweeted)

def retweeter():
    resources = ["oxygen", "icu", "(bed OR beds)", "(ambulance OR ambulances)", "(food OR foods OR tiffin OR tiffins)", "favipiravir", "tocilizumab", "plasma", "(ventilator OR ventilators)", "fabiflu", "remdesivir", "(test OR tests OR testing)", "(ambulance OR ambulances)"]
    cities = ['Delhi', 'Noida', 'Gurgaon', 'Bangalore', 'Hyderabad', 'Chennai', 'Mumbai']
    city = cities[random.randint(0, len(cities) - 1)]
    resource = resources[random.randint(0, len(resources) - 1)]
    hashtag = f"""verified {city} {resource} -any - requirement - requirements - requires - require - required - request - requests - requesting - needed - needs - need - seeking - seek - not verified - notverified - looking - unverified - urgent - urgently - urgently required - sending - send - help - dm - get - year - old - male - female - saturation -is:reply -is:retweet -is:quote&max_results=20&tweet.fields=created_at,public_metrics&expansions=author_id"""
    yesterday = date.today() - timedelta(days = 1)
    print(hashtag, yesterday)

    try:
        tweets = requests.get(f"https://api.twitter.com/2/tweets/search/recent?query={hashtag}", headers=headers).json()
        for tweet in tweets['data']:
            for key in tweet.keys():
                api.retweet(tweet['id'])
                time.sleep(20)
    except tweepy.TweepError as e:
        print(e)

def main():
    dummy_data = {
        "resource": "Test Resource",
        "place": "Test City",
        "quantity": "20",
        "price": "100",
        "phone": "1234567890",
        "email": "test@test.co",
    }
    # tweeter(dummy_data)
    retweeter()


import pandas as pd
# 设置打印展示输出
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 10000)

import sys
sys.path.append("/Users/apple/Documents/project/analyze/tools")
from binning import binning_sparse_col,binning_cate,binning_num,binning_aeq

def handle(x):
    if not x:
        return x
    return x.split("_")[0]

df = pd.read_json('new/strategy_judge_no_label.csv',lines=True)
cols1= ["callRecord_1m_cnt","callRecord_3m_cnt","over_location_cnt_2m","over_location_cnt_3m","over_location_cnt_6m"]
for col in cols1:
    df.drop(columns=[col], inplace=True)

cols2 = ["callRecord_7day_cnt","callRecord_6m_cnt","over_location_cnt_7day","over_location_cnt_1m"]
for col ,_range in zip(cols2,[pd.RangeIndex(-1,2),pd.RangeIndex(313,331),pd.RangeIndex(-1,3),pd.RangeIndex(460,479)]):
    df[col] = df[col].map(lambda x: 0 if x in _range else 1)

df.to_csv("new/lastResutl_no_label_convert.csv",index=False)


import csv

def leer_bicicletas_csv(nombre_archivo):
    bicicletas = {}
    with open(nombre_archivo, newline='') as archivo:
        lector_csv = csv.DictReader(archivo)
        for fila in lector_csv:
            nombre = fila['Nombre']
            tipo = fila['Tipo']
            tamaño = fila['Tamaño']
            color = fila['Color']
            precio = float(fila['Precio por hora'])
            bicicletas[nombre] = {'Tipo': tipo, 'Tamaño': tamaño, 'Color': color, 'Precio por hora': precio}
    return bicicletas

import csv

import csv

def read_csv_to_dict(file_path):
    """
    Lee un archivo CSV y guarda los datos en un diccionario.
    Cada fila del archivo CSV se convierte en un registro de diccionario.
    """
    with open(file_path, mode='r') as file:
        reader = csv.DictReader(file)
        data = []
        for row in reader:
            data.append(row)
    return data


from heapq import *
from collections import Counter
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        num_freq = Counter(nums)
        heap = []
        for num, freq in num_freq.items():
            if len(heap) < k:
                heappush(heap, (freq, num))
                continue
            if freq > heap[0][0]:
                heappushpop(heap, (freq, num))

        res = [0] * k
        for i in range(k -1, -1, -1):
            res[i] = heappop(heap)[1]
        return res


from cyclopts import Parameter
from typing_extensions import Annotated

from gnwmanager.cli._parsers import GnWType, convert_location
from gnwmanager.cli.main import app

def validate_internal_code(type_, value):
    if (0x0800_0000 <= value <= 0x0804_0000) or (0x0810_0000 <= value <= 0x0814_0000):
        return
    raise ValueError("Invalid start address.")

@app.command
def start(
    location: Annotated[
        int,
        Parameter(
            converter=convert_location,
            validator=validate_internal_code,
        ),
    ],
    offset: int = 0,
    *,
    halt: bool = False,
    gnw: GnWType,
):
    """Start firmware at location.

    Parameters
    ----------
    location: Union[int, Literal["bank1", "bank2"]]
        Either an absolute address (e.g. 0x08000000) or one of {bank1, bank2}.
    offset: int
        Offset into location.
    halt: bool
        Start in a halted state.
    """
    # Do NOT start gnwmanager
    addr = location + offset

    gnw.backend.reset_and_halt()
    gnw.backend.write_register("msp", gnw.read_uint32(addr))
    gnw.backend.write_register("pc", gnw.read_uint32(addr + 4))

    if not halt:
        gnw.backend.resume()


"""
Utility functions
"""
import numpy as np
from collections import OrderedDict, defaultdict
from datetime import datetime, timedelta
import uuid
import re

# compile regex for camel case to snake case
first_cap_re = re.compile('(.)([A-Z][a-z]+)')
all_cap_re = re.compile('([a-z0-9])([A-Z])')

def make_serializable(d):
    """
    Convert data types within dict/list to JSON serializable.
    Parameters
    ----------
    d : dict or list
    Returns
    -------
    dict or list
        Data structure of same type as input.
    Notes
    -----
    numpy.ndarray is converted to list.
    datetime.datetime object is converted to ISO format string
    datetime.timedelta object is converted to float (total seconds).
    UUID is converted to string.
    """

    def convert_dict(dd):
        for k, v in dd.items():
            if type(v) in (dict, OrderedDict, defaultdict):
                dd[k] = convert_dict(v)
            else:
                dd[k] = convert_value(v, key=k)
        return dd

    def convert_value(v, key=""):
        if isinstance(v, list):
            v = [convert_value(_) for _ in v]
        elif isinstance(v, uuid.UUID):
            v = str(v)
        elif isinstance(v, np.ndarray):
            if v.ndim > 1:
                raise NotImplementedError(f"Unable to JSON serialize multidimensional ndarrays. Key = '{key}'.")
            v = list(v)
        elif isinstance(v, datetime):
            v = v.isoformat()
        elif isinstance(v, timedelta):
            v = v.total_seconds()
        elif type(v) in (dict, OrderedDict, defaultdict):
            v = convert_dict(v)
        return v

    # convert numpy arrays to lists (only 1-dim arrays are handled)
    # why? because json.dump will raise TypeError if any of the submitted data is a numpy ndarray
    if type(d) in (dict, OrderedDict, defaultdict):
        d = convert_dict(d)
    elif isinstance(d, list):
        d = [convert_value(v) for v in d]
    else:
        raise NotImplementedError(f"Unable to convert object of type '{type(d)}' to JSON serializable.")
    return d

def to_snake_case(d):
    """
    Convert data with camelCase keys to snake_case
    Parameters
    ----------
    d : str or list or dict
        Data with camelCase keys
    Returns
    -------
    str or list or dict
        Data with snake case keys
    """

    def snake(s):
        s1 = first_cap_re.sub(r'\1_\2', s).replace('__', '_')
        return all_cap_re.sub(r'\1_\2', s1).lower()

    if isinstance(d, str):
        return snake(d)
    elif isinstance(d, list):
        return [to_snake_case(_) for _ in d]
    elif isinstance(d, dict):
        dd = dict()
        for k, v in d.items():
            if isinstance(k, str):
                k = snake(k)

            if isinstance(v, (list, dict)):
                v = to_snake_case(v)
            elif isinstance(v, str):
                v = snake(v)

            dd[k] = v
        return dd

def to_camel_case(d):
    """
    Convert data with snake_case keys to lowerCamelCase
    Parameters
    ----------
    d : str or list or dict
        Data with snake case keys
    Returns
    -------
    str or list or dict
        Data with camel case keys
    """

    def camel(s):
        first, *others = s.split('_')
        return ''.join([first.lower(), *map(str.title, others)])

    if isinstance(d, str):
        return camel(d)
    elif isinstance(d, list):
        return [to_camel_case(_) for _ in d]
    elif isinstance(d, dict):
        dd = dict()
        for k, v in d.items():
            if isinstance(k, str):
                k = camel(k)

            if isinstance(v, (list, dict)):
                v = to_camel_case(v)
            elif isinstance(v, str):
                v = camel(v)

            dd[k] = v
        return dd

def from_datetime_string(s):
    """
    Convert formatted date time string to date time object.
    Parameters
    ----------
    s : str
        ISO RFC3339 formatted date time string
    Returns
    -------
    datetime
        Date time object.
    Notes
    -----
    Examples of  ISO RFC 3339 formatted date time strings
        2008-09-03T20:56:35.450686Z
        2008-09-03T20:56:35.450686+00:00
        2008-09-03T20:56:35.450686+05:00
        2008-09-03T20:56:35.450686-10:30
    """
    # datetime.fromisoformat() does not support Z as short notation for Zulu-time aka. +00:00
    if "Z" in s or "+" in s:
        s = s.replace("Z", "+00:00")

        # datetime.fromisoformat() and .strptime() does only handle 0, 3 or 6 decimal places (microseconds) but
        # I frequently encounter deviations like 7 decimals. Truncate datetime string to 26 characters (6 decimals).
        dt, tz = s.split("+")
        s = "+".join([dt[:26], tz])

    return datetime.fromisoformat(s)

def format_class_name(s):
    s = s.split("API")
    return s[0].lower()


import tornado.ioloop
import tornado.web
from tornado_demo.controllers import t1_home

settings = {
    'template_path': 'views',
    'static_path': 'statics'
}

# 路由映射
application = tornado.web.Application([
    (r"/index", t1_home.MainHandler),
], **settings)

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()


from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
_magic_number = 2
_modified_time = 1206913005.191421
_template_filename='/home/archive/archive/archive/templates/type/image.mak'
_template_uri='/type/image.mak'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
_exports = ['page_style', 'title_text']

def _mako_get_namespace(context, name):
    try:
        return context.namespaces[(__name__, name)]
    except KeyError:
        _mako_generate_namespaces(context)
        return context.namespaces[(__name__, name)]
def _mako_generate_namespaces(context):
    pass
def _mako_inherit(template, context):
    _mako_generate_namespaces(context)
    return runtime._inherit_from(context, '/type/default.mak', _template_uri)
def render_body(context,**pageargs):
    context.caller_stack.push_frame()
    try:
        __M_locals = dict(pageargs=pageargs)
        h = context.get('h', UNDEFINED)
        c = context.get('c', UNDEFINED)
        g = context.get('g', UNDEFINED)
        # SOURCE LINE 2
        context.write(u'\n')
        # SOURCE LINE 9
        context.write(u'\n')
        # SOURCE LINE 19
        context.write(u'\n
\n')
        # SOURCE LINE 21
        if c.title:
            # SOURCE LINE 22
            context.write(u'
 ORA Image: "')
            context.write(filters.decode.utf8(c.title))
            context.write(u'"
\n')
            # SOURCE LINE 23
        elif c.id:
            # SOURCE LINE 24
            context.write(u'
 ORA Image: ')
            context.write(filters.decode.utf8(c.id))
            context.write(u'
\n')
        # SOURCE LINE 26
        context.write(u'
\n')
        # SOURCE LINE 27
        for image in c.image_list:
            # SOURCE LINE 28
            context.write(u'\n\n\n')
        # SOURCE LINE 32
        context.write(u'
\n
\n')
        # SOURCE LINE 34
        runtime._include_file(context, '/metadata/dc.mak', _template_uri)
        context.write(u'\n
Trackback URL: ')
        # SOURCE LINE 35
        context.write(filters.decode.utf8("%strackback/%s" % (g.root, c.id)))
        context.write(u'
\n')
        # SOURCE LINE 36
        runtime._include_file(context, '/relationship_display.mak', _template_uri)
        context.write(u'\n')
        # SOURCE LINE 37
        runtime._include_file(context, '/trackback_display.mak', _template_uri)
        context.write(u'\n
\n
\n')
        # SOURCE LINE 40
        if c.download_list:
            # SOURCE LINE 41
            runtime._include_file(context, '/type/downloads.mak', _template_uri)
            context.write(u'\n')
        # SOURCE LINE 43
        runtime._include_file(context, '/type/terms.mak', _template_uri)
        context.write(u'\n
\n
\n')
        return ''
    finally:
        context.caller_stack.pop_frame()

def render_page_style(context):
    context.caller_stack.push_frame()
    try:
        # SOURCE LINE 10
        context.write(u'\n    div#image_container {\n        width: 90%;\n        float: left;\n    }\n    img.inline_image {\n        max-width:60em;\n        height: auto;\n    }\n')
        return ''
    finally:
        context.caller_stack.pop_frame()

def render_title_text(context):
    context.caller_stack.push_frame()
    try:
        c = context.get('c', UNDEFINED)
        # SOURCE LINE 3
        context.write(u'\n')
        # SOURCE LINE 4
        if c.title:
            # SOURCE LINE 5
            context.write(u'<title> ORA Image: "')
            context.write(filters.decode.utf8(c.title))
            context.write(u'" - ')
            context.write(filters.decode.utf8(c.id))
            context.write(u'</title>\n')
            # SOURCE LINE 6
        elif c.id:
            # SOURCE LINE 7
            context.write(u'<title> ORA Documentation: ')
            context.write(filters.decode.utf8(c.id))
            context.write(u'</title>\n')
        return ''
    finally:
        context.caller_stack.pop_frame()


# -*- coding: utf-8 -*-
"""
Created on Tue Mar  7 21:44:14 2017

@author: Oliver
"""

# -*- coding: utf-8 -*-
"""
Created on Tue Mar  7 21:40:05 2017

@author: Oliver
"""

from functools import wraps
from inspect import signature, Parameter
from math import log
from collections import defaultdict
from types import GeneratorType

class Context(object):
	GENS_TYPES = (zip, range, map, filter, GeneratorType)

	def __init__(self):
		self._vars = {}
		self._post = {}

	def __getattr__(self, name):
		return self.__getitem__(name)

	def __setattr__(self, name, value):
		if name[0] is '_':
			self.__dict__[name] = value
		else:
			self.__setitem__(name, value)

	def __delitem__(self, key):
		del self._vars[key]

	def __getitem__(self, key):
		if key not in self._vars:
			return None

		hist = self._vars[key]
		if len(hist) == 0 :
			return None

		return hist[-1]

	def __setitem__(self, key, val):
		if key not in self._vars:
			self._vars[key] = [val]
		else:
			self._vars[key].append(val)

	def __contains__(self, key):
		return key in self._vars

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

	def __repr__(self):
		return 'Context: '+self._vars.__repr__()

	def _repr_html_(self):
		return "
" +  \
			''.join('
{0}	 {1}	 {2}
'.format(n,len(vals), vals[-1]) for n,vals in self._vars.items()) + \
			"
"

	def __dir__(self):
		return super(object,self).__dir__() + list(self._vars.keys())

	def hist(self, name):
		return self._vars[name]

	def output_lists(self, should_output_lists):
		self._post['listify'] = should_output_lists

	def transform(self, obj):
		""" after calling a method, there might be a mapping. Sometimes we want to
		automatically turn mappings and zips and stuff into lists"""
		if self._post.get('listify', False) and isinstance(obj, Context.GENS_TYPES):
			return list(obj)

		return obj

	################ helpful methods that use properties of contexts ################

#	def revert(self, name, index):

#if type(locals().get('CXT', None)).__name__ is not Context.__name__:
#if __name__ is not '__main__':
global CXT
CXT = Context()

def _score(position, param):
	return log(len(param.name)) \
		- position \
		+ 5*param.name[0].isupper() # - 10*(param.default is Parameter.empty)

def sub(D, keys):
	for k in keys:
		if k in D:
			del D[k]

def nodefault(param):
	return param.default is Parameter.empty

def _append_doc(fun, text):
	if fun.__doc__ is None:
		fun.__doc__ = text
	else:
		fun.__doc__ += '\n'+text

def makepart(function, param):
	sig = signature(function)

	if type(param) is str:
		param = sig.parameters[param]

	@wraps(function)
	def fun(*args, **kwargs):
		@wraps(function)
		def f(value):
			kwargs[param.name] = value
			return function(*args, **kwargs)

		_append_doc(f, 'Preselected Arguments: %s -- %s'%(str(args), str(kwargs)))
		_append_doc(f, 'Awaiting Final Parameter %s'% param.name)
		f.__signature__ = sig.replace(parameters = [param])
		return f

	_append_doc(fun, '[<%s> will be filled later, and cannot be supplied]' % param.name)

	newparams = sig.parameters.copy()
	del newparams[param.name]
	fun.__signature__ = sig.replace(parameters = newparams.values())
	return contextual(fun)

def contextual(func):
	params = signature(func).parameters

	groups = defaultdict(list)

	for n,par in params.items():
		groups[par.kind].append(par)

	# first fill all of the positional-only parameters;
	num_ponly = len(groups[Parameter.POSITIONAL_ONLY])
	kwgroups = groups[Parameter.POSITIONAL_OR_KEYWORD] + groups[Parameter.KEYWORD_ONLY]
	has_varpos = len(groups[Parameter.VAR_POSITIONAL]) > 0
	has_varkey = len(groups[Parameter.VAR_KEYWORD]) > 0

	@wraps(func) # just want to keep doc 'n stuff the same.
	def wrapper(*args, **kwargs):
		global CXT
		# First priority: kwargs, second:args; third: context
		# BUT: args are last in name priority
		# so after applying kwargs and

		debug = kwargs.get('debug', False)

		if debug:
			del kwargs['debug']
			print('#'*80)
			print("Wrapper around ", func, 'explicitly passed', args,kwargs)
			print('  with signature: ', signature(func))
			print('   and context', CXT)

		newargs, args = list(args[:num_ponly]), list(args[num_ponly:])
		# The next step is to deal with kwargs passed recently

		# then filter the new kewargs not to have any extra values
		newkwargs = {k:v for k,v in kwargs.items() if( has_varkey or params[k] in kwgroups) }
		kwcands = [c for c in kwgroups if c.name not in newkwargs]

		if debug:
			for k,v in newkwargs.items():
				print('\tusing passed kwarg %s = '%k, v)

		# Then add kwargs from context leaving room for *args passed recently
		candidates = sorted((_score(i, r), r.name) for i,r in enumerate(kwcands))
		if debug > 1: print("CONTEXT SCORES: {", ', '.join('%s:%0.2f'%(k,v) for v,k in reversed(candidates)),'}')

		#
		# Then, deal with keyword-or-positional args
		while((len(kwcands) > len(args) or has_varpos)  and len(candidates) > 0):
				# there are more unsatisfied parameters that need values
				# than unused positional values, so take one from context
			sco, arg = candidates.pop()
			if debug > 1: print('Popped: ', arg,sco)
			if arg in CXT:
				# I there is a default argument, we don't want to overwrite it until
				# we have to. Ex: func(a, b, c=3), where a is in context. Then f(1,2) should
				# assign to a and b, but not c, even though we could have taken a from context
				# and assigned to b and c.
				if nodefault(params[arg]) and sum(map(nodefault, kwcands)) <= len(args):
					if not has_varpos:
						continue
				newkwargs[arg] = CXT[arg]
				kwcands.remove(params[arg])
				if debug: print('\tusing context variable', arg)

		for k, v in zip(tuple(kwcands), tuple(args)):
			if k.kind is Parameter.KEYWORD_ONLY:
				continue
			newkwargs[k.name] = v
			kwcands.remove(k)
			args.remove(v) # will remove the first value (that matches), as desired.
			if debug: print('\tassigning passed value ',v,' to var ', k, 'of kind ', k.kind)

		if debug > 1: print('Successfully assigned arguments')

		if has_varpos and len(args) > 0:
			# Need to reconstruct the earlier arguments to be positional
			for p in groups[Parameter.POSITIONAL_OR_KEYWORD]:
				n = p.name
				if n in newkwargs:
					newargs.append(newkwargs[n])
					del newkwargs[n]
			newargs += args
		if len(groups[Parameter.VAR_KEYWORD]) > 0:
			newkwargs = dict(kwargs, **newkwargs) #There should be no duplicates now.

		if debug: print('  FINAL INVOCATION: ', newargs, newkwargs)

		return CXT.transform(func(*newargs, **newkwargs))

	wrapper.original = func
	_append_doc(wrapper, """This method will autofill parameters from <interactive.CXT>;
		to see what inferences have been made, run with the parameter debug=True, or debug=<num>.
		To access the original, call <%s.original>"""%func.__name__)

	for p in kwgroups:
		setattr(wrapper, "expect_%s"%p.name, makepart(wrapper, p))

	return wrapper


SERVER_IP = "127.0.0.1"
SERVER_PORT = "8080"
SERVER_URL = "http://" + SERVER_IP + ":" + SERVER_PORT
SERVER_UPLOAD_SUFFIX = "/upload"
SERVER_UPLOAD_URL = SERVER_URL + SERVER_UPLOAD_SUFFIX

FILE_UPLOAD_FIELD_NAME = "upload_file"

NUKE_SAVED_FILES_ON_STARTUP = True
REALLY_NUKE_SAVED_FILES_ON_STARTUP = True


from openerp import models, fields, api

class ProjectIssue(models.Model):

    _inherit='project.issue'

    def valuedef(self):
        res=self.env['project.task'].browse(['name','=',self.name])
        for i in res:
            if self.name:
                i.name=self.name
                val=i.name
                i.write({'name':val})
        return {}


# Create multiple line charts on common plot where three data ranges are plotted on same charts. The data ranges to be plotted is/are:
#data=[[5.,25.,45.,20.],[8.,13.,29.,27.],[9.,29.,27.,39.]]

import numpy as np
import matplotlib.pyplot as plt
data=[[5.,25.,45.,20.],[8.,13.,29.,27.],[9.,29.,27.,39.]]
x=np.arange(4)
plt.plot(x,data[0],color='r',label='range1')
plt.plot(x,data[1],color='b',label='range2')
plt.plot(x,data[2],color='g',label='range3')
plt.legend(loc='upper left')
plt.title("MultiRange Line Chart")
plt.xlabel('X')
plt.ylabel('Y')
plt.show()


'''Script for data exploration
'''
import glob
import os
import threading
import pickle

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

SET = "train" # 'train' or 'valid'
DATAPATH = "assets/flower_data/" + SET
FILE_EXT = ".jpg"

NUM_THREADS = 4
image_hist = {
    'filenames': [],
    'row_sizes': [],
    'col_sizes': [],
    'depths':    [],
}

LOAD_PKL = True
PKL_FN = os.path.join('assets', SET + "_data_hst.pkl")

class ReadImageThread(threading.Thread):
    '''Thread class for processing the images
    '''
    def __init__(self, name, fn):
        threading.Thread.__init__(self)
        self.fn = fn
        self.name = name

    def run(self):
        global image_hist

        for file in self.fn:
            im = Image.open(file)
            nd_img = np.asarray(im)
            im.close()

            image_hist['filenames'].append(file)
            image_hist['row_sizes'].append(nd_img.shape[0])
            image_hist['col_sizes'].append(nd_img.shape[1])
            image_hist['depths'].append(nd_img.shape[2])

def show_dim_data(image_hist):
    '''Show histogram of dimensions
    '''
    heights = np.array(image_hist['row_sizes'])
    widths = np.array(image_hist['col_sizes'])
    depths = np.array(image_hist['depths'])
    asps = np.array(image_hist['row_sizes']) / np.array(image_hist['col_sizes'])

    _, ax = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))
    ax[0, 0].hist(heights, bins=10)
    ax[0, 0].set_title("height")
    ax[0, 1].hist(widths, bins=10)
    ax[0, 1].set_title("width")
    ax[1, 0].hist(depths, bins=10)
    ax[1, 0].set_title("depth")
    ax[1, 1].hist(asps, bins=10)
    ax[1, 1].set_title("aspect ratio")

    plt.show()

def display_images_by_aspect_ratio(image_hist, n_bins):
    '''Display images grouped according to aspect ratio
    '''
    # aspect ratio
    asps = np.array(image_hist['row_sizes']) / np.array(image_hist['col_sizes'])

    # get range of values
    min_asp = min(asps)
    max_asp = max(asps)

    step = (max_asp - min_asp) / n_bins
    imgs = np.array(image_hist['filenames'])
    for b in range(n_bins):
        # get bin boundaries
        lb = min_asp + (b * step)
        ub = lb + step
        bn = imgs[np.logical_and((asps >= lb), (asps < ub))]

        # sample for displaying
        if len(bn) > 4:
            disp_img = np.random.choice(bn, size=4)
        else:
            disp_img = bn

        _, ax = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))
        for i, sb in enumerate(ax.flatten()):
            if i >= len(bn):
                break

            im = Image.open(disp_img[i])
            sb.imshow(im)
            sb.set_title(disp_img[i])
            im.close()

        plt.show()

def main():
    '''Main
    '''
    filenames = glob.glob(os.path.join(DATAPATH, '**/*' + FILE_EXT), recursive=True)

    if LOAD_PKL:
        with open(PKL_FN, 'rb') as handle:
            image_hist = pickle.load(handle)

    else:
        readImageThreads = []

        print("Generating image size histogram using %d threads..." % (NUM_THREADS))
        for thread_idx in range(NUM_THREADS):
            # assign each thread a subset to process
            readImageThreads.append(ReadImageThread("ReadImageThread-{}".format(thread_idx),
                                                    filenames[thread_idx:][::NUM_THREADS]))
            readImageThreads[thread_idx].start()

        for thread_idx in range(NUM_THREADS):
            readImageThreads[thread_idx].join()

        with open(PKL_FN, 'wb') as handle:
            pickle.dump(image_hist, handle, protocol=pickle.HIGHEST_PROTOCOL)
            print("Saved dataset properties to %s!" % PKL_FN)

    # show_dim_data(image_hist)
    # display_images_by_aspect_ratio(image_hist, 7)

    # label histogram
    labels = [int(os.path.basename(os.path.dirname(fn))) for fn in filenames]
    print("Range: %d - %d" % (min(labels), max(labels)))
    plt.hist(np.array(labels), bins=len(set(labels)))
    plt.show()

if __name__ == "__main__":
    main()