import datetime as dt
from calendar import monthrange
from typing import Optional

from hypothesis.errors import InvalidArgument
from hypothesis.internal.conjecture import utils
from hypothesis.internal.validation import check_type, check_valid_interval
from hypothesis.strategies._internal.core import (
    defines_strategy_with_reusable_values,
    deprecated_posargs,
    just,
    none,
)
from hypothesis.strategies._internal.strategies import SearchStrategy

DATENAMES = ("year", "month", "day")
TIMENAMES = ("hour", "minute", "second", "microsecond")

def is_pytz_timezone(tz):
    if not isinstance(tz, dt.tzinfo):
        return False
    module = type(tz).__module__
    return module == "pytz" or module.startswith("pytz.")

def draw_capped_multipart(data, min_value, max_value):
    assert isinstance(min_value, (dt.date, dt.time, dt.datetime))
    assert type(min_value) == type(max_value)
    assert min_value <= max_value
    result = {}
    cap_low, cap_high = True, True
    duration_names_by_type = {
        dt.date: DATENAMES,
        dt.time: TIMENAMES,
        dt.datetime: DATENAMES + TIMENAMES,
    }
    for name in duration_names_by_type[type(min_value)]:
        low = getattr(min_value if cap_low else dt.datetime.min, name)
        high = getattr(max_value if cap_high else dt.datetime.max, name)
        if name == "day" and not cap_high:
            _, high = monthrange(**result)
        if name == "year":
            val = utils.integer_range(data, low, high, 2000)
        else:
            val = utils.integer_range(data, low, high)
        result[name] = val
        cap_low = cap_low and val == low
        cap_high = cap_high and val == high
    return result

class DatetimeStrategy(SearchStrategy):
    def __init__(self, min_value, max_value, timezones_strat):
        assert isinstance(min_value, dt.datetime)
        assert isinstance(max_value, dt.datetime)
        assert min_value.tzinfo is None
        assert max_value.tzinfo is None
        assert min_value <= max_value
        assert isinstance(timezones_strat, SearchStrategy)
        self.min_value = min_value
        self.max_value = max_value
        self.tz_strat = timezones_strat

    def do_draw(self, data):
        result = draw_capped_multipart(data, self.min_value, self.max_value)
        result = dt.datetime(**result)
        tz = data.draw(self.tz_strat)
        try:
            if is_pytz_timezone(tz):
                # Can't just construct; see http://pytz.sourceforge.net
                return tz.normalize(tz.localize(result))
            return result.replace(tzinfo=tz)
        except (ValueError, OverflowError):
            msg = "Failed to draw a datetime between %r and %r with timezone from %r."
            data.note_event(msg % (self.min_value, self.max_value, self.tz_strat))
            data.mark_invalid()

@defines_strategy_with_reusable_values
@deprecated_posargs
def datetimes(
    min_value: dt.datetime = dt.datetime.min,
    max_value: dt.datetime = dt.datetime.max,
    *,
    timezones: SearchStrategy[Optional[dt.tzinfo]] = none()
) -> SearchStrategy[dt.datetime]:
    """datetimes(min_value=datetime.datetime.min, max_value=datetime.datetime.max, *, timezones=none())

    A strategy for generating datetimes, which may be timezone-aware.

    This strategy works by drawing a naive datetime between ``min_value``
    and ``max_value``, which must both be naive (have no timezone).

    ``timezones`` must be a strategy that generates
    :class:`~python:datetime.tzinfo` objects (or None,
    which is valid for naive datetimes).  A value drawn from this strategy
    will be added to a naive datetime, and the resulting tz-aware datetime
    returned.

    .. note::
        tz-aware datetimes from this strategy may be ambiguous or non-existent
        due to daylight savings, leap seconds, timezone and calendar
        adjustments, etc.  This is intentional, as malformed timestamps are a
        common source of bugs.

    :py:func:`hypothesis.extra.pytz.timezones` requires the :pypi:`pytz`
    package, but provides all timezones in the Olsen database.
    :py:func:`hypothesis.extra.dateutil.timezones` requires the
    :pypi:`python-dateutil` package, and similarly provides all timezones
    there.  If you want to allow naive datetimes, combine strategies
    like ``none() | timezones()``.

    Alternatively, you can create a list of the timezones you wish to allow
    (e.g. from the standard library, :pypi:`dateutil <python-dateutil>`,
    or :pypi:`pytz`) and use :py:func:`sampled_from`.

    Examples from this strategy shrink towards midnight on January 1st 2000,
    local time.
    """
    # Why must bounds be naive?  In principle, we could also write a strategy
    # that took aware bounds, but the API and validation is much harder.
    # If you want to generate datetimes between two particular moments in
    # time I suggest (a) just filtering out-of-bounds values; (b) if bounds
    # are very close, draw a value and subtract its UTC offset, handling
    # overflows and nonexistent times; or (c) do something customised to
    # handle datetimes in e.g. a four-microsecond span which is not
    # representable in UTC.  Handling (d), all of the above, leads to a much
    # more complex API for all users and a useful feature for very few.
    check_type(dt.datetime, min_value, "min_value")
    check_type(dt.datetime, max_value, "max_value")
    if min_value.tzinfo is not None:
        raise InvalidArgument("min_value=%r must not have tzinfo" % (min_value,))
    if max_value.tzinfo is not None:
        raise InvalidArgument("max_value=%r must not have tzinfo" % (max_value,))
    check_valid_interval(min_value, max_value, "min_value", "max_value")
    if not isinstance(timezones, SearchStrategy):
        raise InvalidArgument(
            "timezones=%r must be a SearchStrategy that can provide tzinfo "
            "for datetimes (either None or dt.tzinfo objects)" % (timezones,)
        )
    return DatetimeStrategy(min_value, max_value, timezones)

@defines_strategy_with_reusable_values
@deprecated_posargs
def times(
    min_value: dt.time = dt.time.min,
    max_value: dt.time = dt.time.max,
    *,
    timezones: SearchStrategy[Optional[dt.tzinfo]] = none()
) -> SearchStrategy[dt.time]:
    """times(min_value=datetime.time.min, max_value=datetime.time.max, *, timezones=none())

    A strategy for times between ``min_value`` and ``max_value``.

    The ``timezones`` argument is handled as for :py:func:`datetimes`.

    Examples from this strategy shrink towards midnight, with the timezone
    component shrinking as for the strategy that provided it.
    """
    check_type(dt.time, min_value, "min_value")
    check_type(dt.time, max_value, "max_value")
    if min_value.tzinfo is not None:
        raise InvalidArgument("min_value=%r must not have tzinfo" % min_value)
    if max_value.tzinfo is not None:
        raise InvalidArgument("max_value=%r must not have tzinfo" % max_value)
    check_valid_interval(min_value, max_value, "min_value", "max_value")
    day = dt.date(2000, 1, 1)
    return datetimes(
        min_value=dt.datetime.combine(day, min_value),
        max_value=dt.datetime.combine(day, max_value),
        timezones=timezones,
    ).map(lambda t: t.timetz())

class DateStrategy(SearchStrategy):
    def __init__(self, min_value, max_value):
        assert isinstance(min_value, dt.date)
        assert isinstance(max_value, dt.date)
        assert min_value < max_value
        self.min_value = min_value
        self.max_value = max_value

    def do_draw(self, data):
        return dt.date(**draw_capped_multipart(data, self.min_value, self.max_value))

@defines_strategy_with_reusable_values
def dates(
    min_value: dt.date = dt.date.min, max_value: dt.date = dt.date.max
) -> SearchStrategy[dt.date]:
    """dates(min_value=datetime.date.min, max_value=datetime.date.max)

    A strategy for dates between ``min_value`` and ``max_value``.

    Examples from this strategy shrink towards January 1st 2000.
    """
    check_type(dt.date, min_value, "min_value")
    check_type(dt.date, max_value, "max_value")
    check_valid_interval(min_value, max_value, "min_value", "max_value")
    if min_value == max_value:
        return just(min_value)
    return DateStrategy(min_value, max_value)

class TimedeltaStrategy(SearchStrategy):
    def __init__(self, min_value, max_value):
        assert isinstance(min_value, dt.timedelta)
        assert isinstance(max_value, dt.timedelta)
        assert min_value < max_value
        self.min_value = min_value
        self.max_value = max_value

    def do_draw(self, data):
        result = {}
        low_bound = True
        high_bound = True
        for name in ("days", "seconds", "microseconds"):
            low = getattr(self.min_value if low_bound else dt.timedelta.min, name)
            high = getattr(self.max_value if high_bound else dt.timedelta.max, name)
            val = utils.integer_range(data, low, high, 0)
            result[name] = val
            low_bound = low_bound and val == low
            high_bound = high_bound and val == high
        return dt.timedelta(**result)

@defines_strategy_with_reusable_values
def timedeltas(
    min_value: dt.timedelta = dt.timedelta.min,
    max_value: dt.timedelta = dt.timedelta.max,
) -> SearchStrategy[dt.timedelta]:
    """timedeltas(min_value=datetime.timedelta.min, max_value=datetime.timedelta.max)

    A strategy for timedeltas between ``min_value`` and ``max_value``.

    Examples from this strategy shrink towards zero.
    """
    check_type(dt.timedelta, min_value, "min_value")
    check_type(dt.timedelta, max_value, "max_value")
    check_valid_interval(min_value, max_value, "min_value", "max_value")
    if min_value == max_value:
        return just(min_value)
    return TimedeltaStrategy(min_value=min_value, max_value=max_value)


import datetime
import logging

import math
import os
import pickle

from pytocl.analysis import DataLogWriter
from pytocl.car import State, Command, MPS_PER_KMH
from pytocl.controller import CompositeController, ProportionalController, IntegrationController, \
    DerivativeController

_logger = logging.getLogger(__name__)

class Driver:
    """Driving logic.

    Implement the driving intelligence in this class by processing the current car state as inputs
    creating car control commands as a response. The ``drive`` function is called periodically
    every 20ms and must return a command within 10ms wall time.
    """

    def __init__(self, logdata=True):
        self.steering_ctrl = CompositeController(
            ProportionalController(0.4),
            IntegrationController(0.2, integral_limit=1.5),
            DerivativeController(2)
        )
        self.acceleration_ctrl = CompositeController(
            ProportionalController(3.7),
        )
        self.data_logger = DataLogWriter() if logdata else None

    @property
    def range_finder_angles(self):
        """Iterable of 19 fixed range finder directions [deg].

        The values are used once at startup of the client to set the directions of range finders.
        During regular execution, a 19-valued vector of track distances in these directions is
        returned in ``state.State.tracks``.
        """
        return -90, -75, -60, -45, -30, -20, -15, -10, -5, 0, 5, 10, 15, 20, 30, 45, 60, 75, 90

    def on_shutdown(self):
        """Server requested driver shutdown.

        Optionally implement this event handler to clean up or write data before the application is
        stopped.
        """
        if self.data_logger:
            self.data_logger.close()
            self.data_logger = None

    def drive(self, carstate: State) -> Command:
        """Produces driving command in response to newly received car state.

        This is a dummy driving routine, very dumb and not really considering a lot of inputs. But
        it will get the car (if not disturbed by other drivers) successfully driven along the race
        track.
        """
        command = Command()
        self.steer(carstate, 0.0, command)

        #ACC_LATERAL_MAX = 6400 * 5
        #v_x = min(80, math.sqrt(ACC_LATERAL_MAX / abs(command.steering)))
        v_x = 80

        self.accelerate(carstate, v_x, command)

        if self.data_logger:
            self.data_logger.log(carstate, command)

        return command

    def accelerate(self, carstate, target_speed, command):
        # compensate engine deceleration, but invisible to controller to prevent braking:
        speed_error = 1.0025 * target_speed * MPS_PER_KMH - carstate.speed_x
        acceleration = self.acceleration_ctrl.control(speed_error, carstate.current_lap_time)

        # stabilize use of gas and brake:
        acceleration = math.pow(acceleration, 3)

        if acceleration > 0:
            if abs(carstate.distance_from_center) >= 1:
                # off track, reduced grip:
                acceleration = min(0.4, acceleration)

            command.accelerator = min(acceleration, 1)

            if carstate.rpm > 8000:
                command.gear = carstate.gear + 1

        #else:
        #    command.brake = min(-acceleration, 1)

        if carstate.rpm < 2500:
            command.gear = carstate.gear - 1

        if not command.gear:
            command.gear = carstate.gear or 1

    def steer(self, carstate, target_track_pos, command):
        steering_error = target_track_pos - carstate.distance_from_center
        command.steering = self.steering_ctrl.control(steering_error, carstate.current_lap_time)


## importing required modules and libraries
import sys, subprocess, csv
try:
    import fitz
except ImportError:
    print("PyMuPDF is not installed. Installing now...")
    try: subprocess.check_call([sys.executable, "-m", "pip", "install", "PyMuPDF"]); print("PyMuPDF installed successfully."); import fitz
    except subprocess.CalledProcessError: print("Failed to install PyMuPDF.\nPlease use internet to install 'PyMuPDF' package."); sys.exit()
try:
    from tkinter import filedialog
except ImportError:
    print('tkinter is not installed. Installing now...')
    try: subprocess.check_call([sys.executable, "-m", "pip", "install", "tkinter"]); print('tkinker intalled successfully.'); from tkinter import filedialog
    except subprocess.CalledProcessError: print('Failed to install tkinter.\nPlease use internet to install \'Tkinter\' package.'); sys.exit()

filepaths = {'answerkey':None,'transcript':None}

## required functions for task
def GetFiles():
    global filepaths
    print('\nSelect Answer Key pdf file')
    AnswerKey = filedialog.askopenfilename(title='Answer Key',filetypes=[('Answer Key', '*.pdf')])
    print('selected file :',AnswerKey)
    print('Select Transcript pdf file')
    Transcript = filedialog.askopenfilename(title='Transcript',filetypes=[('Transcript', '*.pdf')])
    print('selected file :',Transcript,'\n')
    if FileCheck(AnswerKey,'A') and FileCheck(Transcript,'T'):
        filepaths['answerkey']=AnswerKey
        filepaths['transcript']=Transcript
        return filepaths
    else: print('Please select CORRECT Answer Key and Transcript!'); sys.exit()
# no problem below
def FileCheck(file, K):
    try:
        import fitz
        doc = fitz.open(file)
        text = doc[0].get_text().split('\n')
        print(text)
        if K=='A':
            if 'Indian Institute of Technology, Madras - BS in Data Science and Applications' in text:
                return True
        elif K=='T':
            if 'Name' in text and 'QP Set' in text:
                return True
        return False
    except:
        return False

def TransCSV(file):
    trans = open('./csv files/trans.txt','w',newline='')
    write = csv.writer(trans)
    #reading transcript pdf
    doc = fitz.open(file)
    text = ''.join([page.get_text() for page in doc])
    text = [line.strip() for line in text.split('\n')][:-1]
    # writing information
    write.writerow([text[1]])
    write.writerow([text[3][text[3].index('QP'):]])
    for i in range(11,len(text)):
        if i%2!=0 and i!=len(text)-1 and text[i+1]!='Unanswered':
            if text[i][:4]==text[i+1][:4]:
                write.writerow([text[i],'$'.join(text[i+1].split(','))])
            else:
                write.writerow([text[i],text[i+1]])

def AnswerCSV(file):
    def color(num):
        return 'Green' if num==32512 else 'Red' if num==16711680 else 'Other'
    doc = fitz.open(file)
    answer = open('./csv files/key.txt','w',newline='')
    write = csv.writer(answer)
    #writing question paper id in key
    text=doc[0].get_text().strip().split('\n')
    for x in text:
        if 'IIT M' in x and 'QP' in x:
            write.writerow([x[x.index('QP'):].split()[0]])
            break
    #questions data saving
    def add(Question_id,Question_marks,Question_type,COptions,WOptions):
        if Question_id==None: return
        if Question_type in ['MSQ','MCQ']:
            write.writerow([Question_id,Question_marks,Question_type,'$'.join(COptions),'$'.join(WOptions)])
        elif Question_type in ['SA']:
            write.writerow([Question_id,Question_marks,Question_type,':'.join(COptions[0].split(' to ')),'$'.join(WOptions)])
        Question_id=None;Question_marks=None;Question_type=None;COptions=[];WOptions=[]
    Qcount=0;Question_id=None;Question_marks=None;Question_type=None;COptions=[];WOptions=[]
    for i in range(len(doc)):
        page = doc[i]
        blocks = page.get_text("dict", flags=11)["blocks"]
        for b in blocks:  # iterate through the text blocks
            for l in b["lines"]:  # iterate through the text lines
                for s in l["spans"]:  # iterate through the text spans
                    if s['size']==18 and s['text'][:5]!='Group':
                        if Question_id!=None:
                            add(Question_id,Question_marks,Question_type,COptions,WOptions)
                        Question_id=None;Question_marks=None;Question_type=None;COptions=[];WOptions=[]
                        write.writerow([s['text']])
                    elif ('Question Id' in s['text'] and 'COMPREHENSION' not in s['text']):
                        if Question_id!=None: add(Question_id,Question_marks,Question_type,COptions,WOptions)
                        Question_id=None;Question_marks=None;Question_type=None;COptions=[];WOptions=[]
                        Qcount+=1
                        row = s['text'].split(' ')
                        Question_id = row[7];Question_marks=0;Question_type=row[11];COptions=[];WOptions=[]
                    elif 'Correct Marks' in s['text']:
                        Question_marks = s['text'].split()[3]
                    elif color(s['color']) in ['Green','Red']:
                        if len(s['text'])==len('6406531931004. ') and str(s['text'][:4])=='6406531931004. '[:4]:
                            if color(s['color'])=='Green':
                                COptions.append(s['text'][:-2])
                            elif color(s['color'])=='Red':
                                WOptions.append(s['text'][:-2])
                        elif Question_type=='SA' and color(s['color'])=='Green':
                            COptions.append(s['text'])
                            add(Question_id,Question_marks,Question_type,COptions,WOptions)
                            Question_id=None;Question_marks=None;Question_type=None;COptions=[];WOptions=[]
                    if (i== len(doc)-1 and blocks.index(b)==len(blocks)-1):
                        add(Question_id,Question_marks,Question_type,COptions,WOptions)
                        Question_id=None;Question_marks=None;Question_type=None;COptions=[];WOptions=[]
    # print(f'Total no of questions ():{Qcount}')

def CheckCode():
    key = open('./csv files/key.txt')
    trans = open('./csv files/trans.txt')
    Name = trans.readline() # to remove first line
    Akey = key.readline().strip(); Tkey = trans.readline().strip() #selecting QP set codes
    return (Akey, Tkey)

def Evaluate():
    key = open('./csv files/key.txt')
    trans = open('./csv files/trans.txt')
    Name = trans.readline().strip()
    Akey = key.readline().strip(); Tkey = trans.readline().strip()
    if Akey!=Tkey:
        return 'keys not matching'
    Key = [ques.strip() for ques in key]
    Resp = {}
    for line in trans:
        line = line.strip()
        Resp[line.split(',')[0]]=line.split(',')[1]
    print(f'Hey, {Name}. Your scores in each subject are: ')
    #Grouping courses and evaluating
    Course=None;Answerkey=[];result=[]
    for line in Key:
        if len(line.split(','))==1 or Key.index(line)==len(Key)-1:
            if Course!=None:
                res=(Calculate(Course, Answerkey, Resp))
                if res!=None:
                    result.append(res)
            Course=line;Answerkey=[]
        else:
            Answerkey.append(line.split(','))
    return result

def Calculate(Course, SecQs, Resp):
    if SecQs[0][0] not in Resp:
        return None
    Tmarks=0;Smarks=0
    for ques in SecQs:
        Tmarks+=float(ques[1])
        if ques[0] in Resp:
            if ques[2]=='SA':
                if len(ques[3].split(':'))==1:
                    if ques[3]==Resp[ques[0]]:
                        Smarks+=float(ques[1])
                else:
                    # print(float(ques[3].split(':')[0]),float(Answ[ques[0]]),float(ques[3].split(':')[1]))
                    if float(ques[3].split(':')[0]) <= float(Resp[ques[0]]) <= float(ques[3].split(':')[1]):
                        Smarks+=float(ques[1])
            else:
                count=0;total=len(ques[3].split('$'))
                for ans in Resp[ques[0]].split('$'):
                    if ans in ques[4].split('$'):
                        count=0; break
                    if ans in ques[3].split('$'):
                        count+=1
                Smarks+=(count/total)*float(ques[1])
    marks = (Smarks/Tmarks)*100
    return (Course, marks)

def clear():
    trans = open('./csv files/trans.txt','w',newline='')
    trans.writelines('')
    answ = open('./csv files/key.txt','w',newline='')
    answ.writelines('')


from datetime import datetime
from app import db

class Bloque(db.Model):
    __tablename__ = "bloques"

    id_bloque = db.Column(
        db.Integer, db.Sequence("bloques_id_bloque_seq"), primary_key=True, unique=True
    )
    id_sesion = db.Column(
        db.Integer,
        db.ForeignKey("sesiones.id_sesion", ondelete="cascade"),
        nullable=False,
    )
    ejercicios = db.relationship(
        "EjercicioXBloque",
        lazy="subquery",
        backref=db.backref("bloques", lazy=True),
        order_by="EjercicioXBloque.num_ejercicio",
        cascade="all, delete-orphan",
    )
    num_bloque = db.Column(db.Integer)
    series = db.Column(db.Integer)
    creado_en = db.Column(db.DateTime, default=datetime.utcnow)
    actualizado_en = db.Column(db.DateTime, default=None)

    def __init__(self, ejercicios, num_bloque, series, id_sesion=None):
        self.id_sesion = id_sesion
        self.ejercicios = ejercicios
        self.num_bloque = num_bloque
        self.series = series

    def __repr__(self):
        return "<Bloque {}>".format(self.id_bloque)

    def to_json(self):
        return {
            "id": self.id_bloque,
            "ejercicios": [ejercicio.to_json() for ejercicio in self.ejercicios],
            "numBloque": self.num_bloque,
            "series": self.series,
            "creadoEn": self.creado_en,
            "actualizadoEn": self.actualizdo_en,
        }

class EjercicioXBloque(db.Model):
    __tablename__ = "ejerciciosxbloque"

    id_ejerciciosxbloque = db.Column(
        db.Integer,
        db.Sequence("ejerciciosxbloque_id_ejerciciosxbloque_seq"),
        primary_key=True,
        unique=True,
    )
    id_ejercicio = db.Column(db.Integer, db.ForeignKey("ejercicios.id_ejercicio"))
    id_bloque = db.Column(db.Integer, db.ForeignKey("bloques.id_bloque"))
    num_ejercicio = db.Column(db.Integer)
    ejercicio = db.relationship("Ejercicio", uselist=False)
    # bloque = db.relationship("Bloque", uselist=False)
    repeticiones = db.Column(db.Integer)
    carga = db.Column(db.Float)

    def __init__(self, num_ejercicio, ejercicio, repeticiones, carga):
        self.num_ejercicio = num_ejercicio
        self.ejercicio = ejercicio
        self.repeticiones = repeticiones
        self.carga = carga

    def __repr__(self):
        return "<EjercicioXBloque {}>".format(self.id_ejerciciosxbloque)

    def to_json(self):
        return {
            "id": self.id_ejerciciosxbloque,
            "num_ejercicio": self.num_ejercicio,
            "ejercicio": self.ejercicio.nombre,
            "patron": self.ejercicio.patron.nombre,
            "carga": self.carga,
            "repeticiones": self.repeticiones,
        }


# -*- coding: utf-8 -*-
import datetime
from collections import namedtuple

import h5py

from dlgo import agent
from dlgo import scoring
from dlgo.goboard_fast import GameState, Player, Point

BOARD_SIZE = 19
COLS = 'ABCDEFGHJKLMNOPQRST'
STONE_TO_CHAR = {
    None: '.',
    Player.black: 'x',
    Player.white: 'o',
}

def avg(items):
    if not items:
        return 0.0
    return sum(items) / float(len(items))

def print_board(board):
    for row in range(BOARD_SIZE, 0, -1):
        line = []
        for col in range(1, BOARD_SIZE + 1):
            stone = board.get(Point(row=row, col=col))
            line.append(STONE_TO_CHAR[stone])
        print('%2d %s' % (row, ''.join(line)))
    print('   ' + COLS[:BOARD_SIZE])

class GameRecord(namedtuple('GameRecord', 'moves winner margin')):
    pass

def name(player):
    if player == Player.black:
        return 'B'
    return 'W'

def simulate_game(black_player, white_player):
    moves = []
    game = GameState.new_game(BOARD_SIZE)
    agents = {
        Player.black: black_player,
        Player.white: white_player,
    }
    while not game.is_over():
        next_move = agents[game.next_player].select_move(game)
        moves.append(next_move)
        # if next_move.is_pass:
        #    print('%s passes' % name(game.next_player))
        game = game.apply_move(next_move)

    print_board(game.board)
    game_result = scoring.compute_game_result(game)
    print(game_result)

    return GameRecord(
        moves=moves,
        winner=game_result.winner,
        margin=game_result.winning_margin,
    )

def main():
    # parser = argparse.ArgumentParser()
    # parser.add_argument('--agent1', required=True)
    # parser.add_argument('--agent2', required=True)
    # parser.add_argument('--num-games', '-n', type=int, default=10)
    #
    # args = parser.parse_args()
    #
    # agent1 = agent.load_policy_agent(h5py.File(args.agent1))
    # agent2 = agent.load_policy_agent(h5py.File(args.agent2))

    # ==================================================
    import os
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

    import tensorflow as tf
    config = tf.compat.v1.ConfigProto()
    config.gpu_options.per_process_gpu_memory_fraction = 0.95
    config.gpu_options.allow_growth = True
    config.log_device_placement = True
    sess = tf.compat.v1.Session(config=config)
    tf.compat.v1.keras.backend.set_session(sess)
    # ==================================================
    pth = '//home//nail//Code_Go//checkpoints//'
    num_games = int(input("Количество игр :"))
    agent1 = input('Игрок(агент) №1:')
    agent2 = input('Игрок(агент) №2:')
    agent1 = pth + agent1+".h5"
    agent2 = pth + agent2+".h5"
    agent1 = agent.load_policy_agent(h5py.File(agent1, "r"))
    agent2 = agent.load_policy_agent(h5py.File(agent2, "r"))

    wins = 0
    losses = 0
    color1 = Player.black

    for i in range(num_games):
        print('Симуляция игры %d/%d...' % (i + 1, num_games))  # args.num_games))
        if color1 == Player.black:
            black_player, white_player = agent1, agent2
            print('Агент №1 - играет Черными, Агент №2  - играет Белыми')
        else:
            white_player, black_player = agent1, agent2
            print('Агент №1 - играет Белыми, Агент №2  - играет Черными')
        game_record = simulate_game(black_player, white_player)
        if game_record.winner == color1:
            wins += 1
        else:
            losses += 1
        color1 = color1.other
    print('Agent 1 record: %d/%d' % (wins, wins + losses))

if __name__ == '__main__':
    main()


#!/usr/bin/env python3

task = """
Task:
Write a Python program to check whether multiple variables have the same value.
"""

print(task)

a = 'a'
b = 'a'
c = 'a'

if a == b == c:
    print("Variables are the same")


import requests
import json
import os
import sys
import re

oldDir = input("enter Directory");

movieList=[]

apiUrl = 'http://www.omdbapi.com/?tomatoes=true&t='

try:
	movieList = os.listdir(oldDir)
except Exception as e:
	print('No such Directory found !')
	sys.exit(0)

def getExactMovieName(movie):
	# delete everything starting with (
	n_movie = re.sub(r'\(.*$', '', movie)
	n_movie = re.sub(r'\d.*$', '', n_movie)
	n_movie = re.sub(r'\.', ' ', n_movie)
	return n_movie;

for movie in movieList:
	try:
		n_movie = getExactMovieName(movie)
		print('requesting for '+n_movie)
		result = requests.get(apiUrl+n_movie)
		j_result = json.loads(result.text)
		if oldDir[-1] != '/':
			oldDir+='/'
		imdbRating = j_result['imdbRating']
		tomatoRating = j_result['tomatoRating']
		newDir = oldDir+'IMDB('+imdbRating+') TOMATO('+tomatoRating+') '+n_movie+'/'
		os.mkdir(newDir)
		os.rename(oldDir+movie , newDir+movie)
		with open(newDir+'info.txt', 'w+') as fp:
			fp.write(result.text)
		print('request completed for '+n_movie)
	except Exception as e:
		print("IMDB rating not found")


from django.urls import path
from .views import PeopleView, update_result, FollowView

app_name="people"

urlpatterns = [
    path('search', update_result, name="search"),
    path('follow/<int:id>', FollowView.as_view(), name='follow'),
    path('', PeopleView.as_view(), name="index"),
]


#encoding:utf-8
'''
Sorted Array
     Merge Two Sorted Arrays / Merge k Sorted Arrays
     Median Of Two Sorted Arrays
Subarray
    Best Time to Buy and Sell Stocks I, II, III
    Subarray I, II, III, IV
Two Pointers
    Two sum, 3Sum, 4Sum, k Sum, 3Sum Closest
    Partition Array
'''
#merge sorter array
class Solution:
    '''
    双指针法
    '''
    def intersect(self, nums1, nums2):
        if len(nums1) == 0 or len(nums2) == 0:
            return []
        result = []
        nums1.sort()
        nums2.sort()
        left = 0
        right = 0
        while left < len(nums1) and right < len(nums2):
            if nums1[left] > nums2[right]:
                right += 1
            elif nums1[left] < nums2[right]:
                left += 1
            else:
                result.append(nums1[left])
                left += 1
                right += 1
        return result

# 14z最长公共前缀
class Solution:
    def longestCommonPrefix(self, strs):
        if not strs:
            return ""

        prefix, count = strs[0], len(strs)
        for i in range(1, count):
            prefix = self.lcp(prefix, strs[i])
            if not prefix:
                break
        return prefix

    def lcp(self, str1, str2):
        length, index = min(len(str1), len(str2)), 0
        while index < length and str1[index] == str2[index]:
            index += 1
        return str1[:index]

#26，27原地删除数组

class Solution:
    def removeDuplicates(self, nums):
        i = 0
        for j in range(1, len(nums)):
            if nums[j] != nums[i]:
                i += 1
                nums[i] = nums[j]
        return i + 1

class Solution:
    def removeElement(self, nums, val):
        slow=0
        fast=0
        while fast<len(nums):
            if nums[fast]!=val:
                nums[slow]=nums[fast]
                slow+=1
            fast+=1
        return slow

#66加一
class Solution:
    def plusOne(self, digits):
        for i in range(len(digits)-1, -1, -1):
            if digits[i] is not 9:
                digits[i] += 1
                return digits
            else:
                digits[i] = 0
                if digits[0] is 0:
                    digits.insert(0, 1)
                    return digits

#俩个数和
class Solution:
    def twoSum(self, nums, target):
        tmp = {}
        for k, v in enumerate(nums):
            if target - v in tmp:
                return [tmp[target - v], k]
            tmp[v] = k


def decimalToBinary(n):
    binary = ""                 # String variable is declared to append the values
    while (n > 0):              # Looped till the value is zero
        binary += str(n%2)
        n = n//2

    return binary[::-1]         # Returned string is reversed so that the correct binary value is returned

def binaryToDecimal(n):
    decimalVal, count = 0, 0    # 2 variables are declared, one for the decimal value that would be returned and count which will incremented once
    while (n != 0):             # Looped through till value is zero
        decimalVal += ((n%10) * (2 ** count))
        count += 1
        n = (n // 10)

    return decimalVal

print(decimalToBinary(13))
print(binaryToDecimal(110))


import threading
import json

class Session():
  def __init__(cls, session_id, client_socket):
    cls.session_id = session_id;
    cls.client_socket = client_socket;
    cls.context = dict();
    cls.context_lock = threading.Lock();

  # 세션 컨텍스트에 데이터 저장
  def add_context(cls, key, value):
    cls.context_lock.acquire();
    cls.context[key] = value;
    cls.context_lock.release();

  # 세션 컨텍스트에서 데이터 가져오기
  def get_context(cls, key):
    cls.context_lock.acquire();
    result = (False, None);
    if key in cls.context:
      result = (True, cls.context[key]);

    cls.context_lock.release();
    return result;

  # 명시적 소켓 종료
  def close_socket(cls):
    cls.client_socket.close();

  # 이 세션에 메시지 보내기
  def send_message(cls, message):
    msg = json.dumps(message);
    print("session_id:", cls.session_id, "send message=", msg);
    bytes = msg.encode();
    msg_len = len(bytes);

    cls.client_socket.sendall(msg_len.to_bytes(4, byteorder="little"));
    cls.client_socket.sendall(bytes);


import json
import unittest

from bootstrap.create_content import create_content_handler

class TestCreateContent(unittest.TestCase):
    @staticmethod
    def get_base_event():
        """
        Sample event from https://docs.aws.amazon.com/lambda/latest/dg/lambda-services.html
        :return: dict
        """
        return {
            "requestContext": {
                "elb": {
                    "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a"
                }
            },
            "httpMethod": "GET",
            "path": "/lambda",
            "queryStringParameters": {
                "query": "1234ABCD"
            },
            "headers": {
                "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                "accept-encoding": "gzip",
                "accept-language": "en-US,en;q=0.9",
                "connection": "keep-alive",
                "host": "lambda-alb-123578498.us-east-2.elb.amazonaws.com",
                "upgrade-insecure-requests": "1",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
                "x-amzn-trace-id": "Root=1-5c536348-3d683b8b04734faae651f476",
                "x-forwarded-for": "72.12.164.125",
                "x-forwarded-port": "80",
                "x-forwarded-proto": "http",
                "x-imforwards": "20"
            },
            "body": "",
            "isBase64Encoded": False
        }

    def test_main(self):
        # given
        event = TestCreateContent.get_base_event()
        context = {"aws_request_id": 1111}  # https://docs.aws.amazon.com/lambda/latest/dg/python-context.html
        # when
        result = create_content_handler(event, context)
        # then
        self.assertEqual(json.loads(result["body"])["message"], "Hello 1234ABCD!")


from rest_framework import routers
from django.urls import path, include
from apps.managers.views import (
    TaskView,
    TaskDetailView,
    MyTaskView,
    CompletedTaskView,
    AssignTaskToUser,
    CompleteTaskView,
    # CommentAddView,
    # CommentView,
    TimeWorkView,
    TimeView,
    TaskMonthView,
    TopBiggestTimeTask,
)

router = routers.SimpleRouter()
router.register(r'work-time', TimeWorkView)
router.register(r'time', TimeView)
router.register(r'task', TaskView)

urlpatterns = [
    #path('task', TaskView.as_view(), name='create-task-view'),
    path('task/detail/<int:pk>', TaskDetailView.as_view(), name='task-info-view'),
    path('task/top-biggest-time-task', TopBiggestTimeTask.as_view(), name='task-time-log-view'),
    path('time-month', TaskMonthView.as_view(), name='task-time-log-view'),
    path('mytask', MyTaskView.as_view(), name='my-task-view'),
    path('complete', CompletedTaskView.as_view(), name='completed-task'),
    path('add-task-to-user/<int:pk>/', AssignTaskToUser.as_view(), name="add-task-to-user"),
    path('complete/<int:pk>', CompleteTaskView.as_view(), name="complete-task-view"),
    path('test/', include("apps.managers.GenericTest.urls"))

]
urlpatterns += router.urls


class Solution(object):
    def flipMatchVoyage(self, root, voyage):
        """
        :type root: TreeNode
        :type voyage: List[int]
        :rtype: List[int]
        """
        self.ans = []
        self.flag = True
        def dfs(r):
            # 如果根节点存在 并且flag为true
            if r and self.flag:
                #如果voyage为空 或 当前树值无法匹配数列首元素，flag=false
                if not voyage or r.val != voyage.pop(0):
                    self.flag = False
                #如果两子树都存在且右子树等于数列的首元素，就需要交换左右子树
                elif r.left and r.right and r.right.val == voyage[0]:
                    self.ans += [r.val]
                    dfs(r.right)
                    dfs(r.left)
                # 如果两个子树都存在且左子树等于数列首元素，不需要交换左右子树，继续向下递归
                else:
                    dfs(r.left)
                    dfs(r.right)
        dfs(root)
        return self.ans if self.flag else [-1]


import numpy as np
from abc import abstractmethod

from app.styles.utils import rootspace

class SpiralBase:
    def __init__(self, step: float=0.0063) -> None:
        self._step = step
        self._num_points = self._calc_num_poins(self._step)

    def _get_spiral_points(self) -> np.array:
        b = self._step / np.pi
        a = b
        r_max = 0.45
        phi_max = (r_max - a) / b
        phi = rootspace(0, phi_max, self._num_points, power=1.9)
        r = (a + b * phi)

        x = r * np.cos(phi)
        y = r * np.sin(phi)

        points = np.hstack([x.reshape(-1, 1), y.reshape(-1, 1)])
        return points

    def _get_envelope(self, image: np.array, spiral_points: np.array) -> np.array:
        scale = min(image.shape[:2])
        offset = scale // 2
        px_points = np.intp(spiral_points * scale + offset)
        max_width = int(self._step * scale / 2.)

        weights = []

        for point in px_points:
            x, y = point
            mean_color = np.mean(image[y - max_width:y + max_width + 1, x - max_width:x + max_width + 1])
            weights.append(mean_color)

        return np.array(weights) / max(weights)

    @abstractmethod
    def transform_image(image: np.array) -> np.array:
        pass

    def _calc_num_poins(self, step: float) -> int:
        return int(1 / step * 2_000)


from typing import Any, Dict, Mapping, Optional

from airbyte_cdk.config_observation import emit_configuration_as_airbyte_control_message
from airbyte_cdk.models import ConnectorSpecification
from airbyte_cdk.sources.file_based.file_based_source import FileBasedSource
from airbyte_cdk.utils import is_cloud_environment
from source_s3.source import SourceS3Spec
from source_s3.v4.legacy_config_transformer import LegacyConfigTransformer

_V3_DEPRECATION_FIELD_MAPPING = {
    "dataset": "streams.name",
    "format": "streams.format",
    "path_pattern": "streams.globs",
    "provider": "bucket, aws_access_key_id, aws_secret_access_key and endpoint",
    "schema": "streams.input_schema",
}

class SourceS3(FileBasedSource):
    def read_config(self, config_path: str) -> Mapping[str, Any]:
        """
        Used to override the default read_config so that when the new file-based S3 connector processes a config
        in the legacy format, it can be transformed into the new config. This happens in entrypoint before we
        validate the config against the new spec.
        """
        config = super().read_config(config_path)
        if not self._is_v4_config(config):
            parsed_legacy_config = SourceS3Spec(**config)
            converted_config = LegacyConfigTransformer.convert(parsed_legacy_config)
            emit_configuration_as_airbyte_control_message(converted_config)
            return converted_config
        return config

    def spec(self, *args: Any, **kwargs: Any) -> ConnectorSpecification:
        s3_spec = SourceS3Spec.schema()
        s4_spec = self.spec_class.schema()

        if s3_spec["properties"].keys() & s4_spec["properties"].keys():
            raise ValueError("Overlapping properties between V3 and V4")

        for v3_property_key, v3_property_value in s3_spec["properties"].items():
            s4_spec["properties"][v3_property_key] = v3_property_value
            s4_spec["properties"][v3_property_key]["airbyte_hidden"] = True
            s4_spec["properties"][v3_property_key]["order"] += 100
            s4_spec["properties"][v3_property_key]["description"] = (
                SourceS3._create_description_with_deprecation_prefix(_V3_DEPRECATION_FIELD_MAPPING.get(v3_property_key, None))
                + s4_spec["properties"][v3_property_key]["description"]
            )
            self._clean_required_fields(s4_spec["properties"][v3_property_key])

        if is_cloud_environment():
            s4_spec["properties"]["endpoint"].update(
                {
                    "description": "Endpoint to an S3 compatible service. Leave empty to use AWS. "
                    "The custom endpoint must be secure, but the 'https' prefix is not required.",
                    "pattern": "^(?!http://).*$",  # ignore-https-check
                }
            )

        return ConnectorSpecification(
            documentationUrl=self.spec_class.documentation_url(),
            connectionSpecification=s4_spec,
        )

    def _is_v4_config(self, config: Mapping[str, Any]) -> bool:
        return "streams" in config

    @staticmethod
    def _clean_required_fields(v3_field: Dict[str, Any]) -> None:
        """
        Not having V3 fields root level as part of the `required` field is not enough as the platform will create empty objects for those.
        For example, filling all non-hidden fields from the form will create a config like:
        ```
        {
          <...>
          "provider": {},
          <...>
        }
        ```

        As the field `provider` exists, the JSON validation will be applied and as `provider.bucket` is needed, the validation will fail
        with the following error:
        ```
          "errors": {
            "connectionConfiguration": {
              "provider": {
                "bucket": {
                  "message": "form.empty.error",
                  "type": "required"
                }
              }
            }
          }
        ```

        Hence, we need to make any V3 nested fields not required.
        """
        if "properties" not in v3_field:
            return

        v3_field["required"] = []
        for neste_field in v3_field["properties"]:
            SourceS3._clean_required_fields(neste_field)

    @staticmethod
    def _create_description_with_deprecation_prefix(new_fields: Optional[str]) -> str:
        if new_fields:
            return f"Deprecated and will be removed soon. Please do not use this field anymore and use {new_fields} instead. "
        return "Deprecated and will be removed soon. Please do not use this field anymore. "


def solution(enter, leave):
    answer = []
    for idx, i in enumerate(enter):
        cnt = 0
        li = []
        check = leave.index(i)
        for idx2, j in enumerate(leave):
            check2 = enter.index(j)
            if idx2 >= idx and (idx2 < check or idx > check):
                cnt += 1
                li.append(check2)
            try:
                if check2 > idx and max(li) > check2:
                    cnt += 1
            except:
                pass

        answer.append(cnt)

    return answer

enter = [1,4,2,3]
leave = [2,1,3,4]
print(solution(enter, leave))


import json
from flask import Flask, render_template

app = Flask(__name__, static_folder='static', static_url_path='')

@app.route("/")
def start_page():
    decisions = [decision_name for decision_name,
                 _ in load_decisions().items()]

    return render_template('start.html', decisions=decisions)

@app.route("/article/<string:id>")
def decision_page(id: str):
    print(id)
    decisions = load_decisions()
    decision = decisions[id]

    # load matching paragraphs:
    paragraphs = decision['paragraphs']
    with open('../comparison_values.json', 'r', encoding='utf-8') as file:
        comparison_data = json.load(file)
    for paragraph in paragraphs:
        hash = __correct_hash(paragraph['hash'])

        if hash in comparison_data:
            matches: dict = comparison_data[hash]
            paragraph['matches'] = []
            paragraph['matches'] = matches
            for match, match_rate in matches.items():
                for decision_name, dec in decisions.items():
                    for par in dec['paragraphs']:
                        if __correct_hash(par['hash']) == match:
                            matches[match] = {
                                'decision': decision_name,
                                'id': decision_name.replace(' ', '-'),
                                'original': par['original'],
                                'confidence': match_rate,
                                'index': par['index']}
                pass
            print('gugus!!!!!!!!!')

    return render_template('decision.html', decision=id, decision_object=decision)

def load_decisions() -> dict:
    with open('static/json_data.json', 'r', encoding='utf-8') as file:
        decision = json.load(file)
    return decision

def __correct_hash(hash: str) -> str:
    """Just in case the binary arrays haven't been saved
    correctly as a string"""

    if hash[:2] == "b'" and hash[-1] == "'":
        hash = hash[2:-1]
    return hash

app.run(debug=True)


from tkinter import *
from tkinter.messagebox import *
from random import randint
from collections import OrderedDict
from operator import itemgetter
class Case:

#On définit un objet avec des attributs comme un abscisse, une ordonné, un type(Bombe ou pas) et un numéro. On peut noter que l'absisse et l'ordonne sont maintenant inutile mais nous avons décidé de les laisser pour essayer de vous montrer la démarche que nous avons suivi.

    def __init__(self, compteur, abse, Ord, Type):

        self.abse = abse
        self.ord = Ord
        self.type = Type
        self.compteur = compteur
        self.etat = "caché"

def Change(Case, Type):
    Bse_donnee[Case].type = Type

def SETBOMBE(nombredebombes):

#Fonction plaçant les bombes dans la grille
#La liste d'interdits est une liste contenant les cases où les bombes ont déjà été placées, pour éviter de les superposer

    for loop in range(nombredebombes):
        x = randint(0,((LargeurGrille*LargeurGrille) - 1))
        while x in Bse_Bombe:
            print("Bombe répétée:", x)
            x = randint(0,((LargeurGrille*LargeurGrille) - 1))
        Bse_donnee[x].type = "Bombe"
        Bse_Bombe.append(x)

def ActualiserUneCaseAutourDUneBombe(NumeroCase, NombreAAjouter):

#Fonction servant plusieurs fois dans les fonctions suivantes
#Pour chaque case ayant une bombe, cette fonction ajoute "+1" aux cases adjacentes (pour la valeur du nombre de bombes adjacentes)
#Sert aussi dans le bouton de triche

    if Bse_donnee[NumeroCase+NombreAAjouter].type != "Bombe":
        Bse_donnee[NumeroCase+NombreAAjouter].type += 1

#Les fonctions suivantes traient à part les cas des bords du tableau

def lineUp(numero, case):
    if case in LINEUP:
        ActualiserUneCaseAutourDUneBombe(case,+LargeurGrille)
        ActualiserUneCaseAutourDUneBombe(case,+1)
        ActualiserUneCaseAutourDUneBombe(case,-1)
        ActualiserUneCaseAutourDUneBombe(case,+LargeurGrille+1)
        ActualiserUneCaseAutourDUneBombe(case,+LargeurGrille-1)

def columnRight(numero, case):
    if case in LINERIGHT:
        ActualiserUneCaseAutourDUneBombe(case,-1)
        ActualiserUneCaseAutourDUneBombe(case,+LargeurGrille)
        ActualiserUneCaseAutourDUneBombe(case,-LargeurGrille)
        ActualiserUneCaseAutourDUneBombe(case,+LargeurGrille-1)
        ActualiserUneCaseAutourDUneBombe(case,-LargeurGrille-1)

def columnLeft(numero, case):
    if case in LINELEFT:
        ActualiserUneCaseAutourDUneBombe(case,+1)
        ActualiserUneCaseAutourDUneBombe(case,+LargeurGrille)
        ActualiserUneCaseAutourDUneBombe(case,-LargeurGrille)
        ActualiserUneCaseAutourDUneBombe(case,+LargeurGrille+1)
        ActualiserUneCaseAutourDUneBombe(case,-LargeurGrille+1)

def lineDown(numero, case):
    if case in LINEDOWN:
        ActualiserUneCaseAutourDUneBombe(case,-LargeurGrille)
        ActualiserUneCaseAutourDUneBombe(case,+1)
        ActualiserUneCaseAutourDUneBombe(case,-1)
        ActualiserUneCaseAutourDUneBombe(case,-LargeurGrille-1)
        ActualiserUneCaseAutourDUneBombe(case,-LargeurGrille+1)

def cornerRightU(numero, case):
    if case == CORNERRIGHTU:
        ActualiserUneCaseAutourDUneBombe(case,-1)
        ActualiserUneCaseAutourDUneBombe(case,+LargeurGrille-1)
        ActualiserUneCaseAutourDUneBombe(case,+LargeurGrille)

def cornerLeftU(numero, case):
    if case == CORNERLEFTU:
        ActualiserUneCaseAutourDUneBombe(case,+1)
        ActualiserUneCaseAutourDUneBombe(case,+LargeurGrille)
        ActualiserUneCaseAutourDUneBombe(case,+LargeurGrille+1)

def cornerRightD(numero, case):
    if case == CORNERRIGHTD:
        ActualiserUneCaseAutourDUneBombe(case,-1)
        ActualiserUneCaseAutourDUneBombe(case,-LargeurGrille)
        ActualiserUneCaseAutourDUneBombe(case,-LargeurGrille-1)

def cornerLeftD(numero, case):
    if case == CORNERLEFTD:
        ActualiserUneCaseAutourDUneBombe(case,+1)
        ActualiserUneCaseAutourDUneBombe(case,-LargeurGrille+1)
        ActualiserUneCaseAutourDUneBombe(case,-LargeurGrille)

def DetectBombe():

#Fonction déterminant le nombre de bombes adjacentes (en appelant les fonctions précédentes)

    global NBBOMBES

    for loop in range(NBBOMBES):

        Bombe = Bse_Bombe[loop]

        if Bse_Bombe[loop] in LINEDOWN:
            lineDown(loop, Bombe)
        elif Bse_Bombe[loop] in LINEUP:
            lineUp(loop, Bombe)
        elif Bse_Bombe[loop] in LINERIGHT:
            columnRight(loop,Bombe)
        elif Bse_Bombe[loop] in LINELEFT:
            columnLeft(loop,Bombe)
        elif Bse_Bombe[loop] == CORNERRIGHTU:
            cornerRightU(loop, Bombe)
        elif Bse_Bombe[loop] == CORNERLEFTD:
            cornerLeftD(loop,Bombe)
        elif Bse_Bombe[loop] == CORNERRIGHTD:
            cornerRightD(loop,Bombe)
        elif Bse_Bombe[loop] == CORNERLEFTU:
            cornerLeftU(loop,Bombe)
        else:
            ActualiserUneCaseAutourDUneBombe(Bombe,+1)
            ActualiserUneCaseAutourDUneBombe(Bombe,-1)
            ActualiserUneCaseAutourDUneBombe(Bombe,+LargeurGrille)
            ActualiserUneCaseAutourDUneBombe(Bombe,-LargeurGrille)
            ActualiserUneCaseAutourDUneBombe(Bombe,-LargeurGrille-1)
            ActualiserUneCaseAutourDUneBombe(Bombe,+LargeurGrille+1)
            ActualiserUneCaseAutourDUneBombe(Bombe,-LargeurGrille+1)
            ActualiserUneCaseAutourDUneBombe(Bombe,+LargeurGrille-1)

def ActualiseAll():

#Fonction actualisant les cases

    for loop in range(LargeurGrille*LargeurGrille):
        Bse_Case[loop].config(text=Bse_donnee[loop].type)

def firstcase(x):
    #Foncrion révélant plusieurs cases lorsque l'on clique sur une case pour la première fois.
    global CasesRévélées
    ListeOrientation = [1,-1,10,-10,9,-9,11,-11]
    if CasesRévélées == 0:
        listeRayons = [0]*8

        T = ((LargeurGrille-5)//3)

        Compteur = x
        ListeOrientation[6]

        for loop in range(8):
            Rayon = randint(1, T+1)
            for pool in range(Rayon):
                if Bse_donnee[x + pool*ListeOrientation[loop]].type == "Bombe":
                    pass
                else:
                    ClicCase(x + pool*ListeOrientation[loop])
                    print("pool : ",pool)
                    print("Rayon : ",Rayon)
                    print(ListeOrientation[loop])
                    print("fin")

def ClicCase(x):
    print("Case cliquée : ", x)

#Fonction réalisant une action lorsque l'on clique sur une case
    global CasesRévélées
    global statut
    global Dico
    global ListeDrapeau
    print(CasesRévélées)
    if ValeurDrapeau == 0:

    #Cas où la pose de drapeau est désactivée, donc lorsque l'on veut dévoiler une case

        if Bse_Case_Drapeau[x] == 0:

        #Cas où il n'y a pas de drapeau posé sur la case
            NbBombesAdjacentesPossibles = 0
            if Bse_donnee[x].type == "Bombe":
                for k in range(LargeurGrille*LargeurGrille):
                    if k in Bse_Bombe:
                        if Bse_Case_Drapeau[k] == 1:
                            Bse_Case[k].config(image = ImageDrapeauVrai, state = "disabled")
                        else:
                            Bse_Case[k].config(image = ImageBombe, state = "disabled")
                    if Bse_Case_Drapeau[k] == 1:
                        if k not in Bse_Bombe:
                            Bse_Case[k].config(image = ImageDrapeauFaux, state = "disabled")
                Bse_Case[x].config(image = ImageBombeFaux, state = "disabled")
                Perdu = showwarning("Fin du game", message = "Vous avez perdu", default = "ok")
                statut = "lose"
            else:
                while NbBombesAdjacentesPossibles != Bse_donnee[x].type:
                    NbBombesAdjacentesPossibles += 1
                if Bse_donnee[x].etat == "révélée":
                    pass
                else:
                    Bse_Case[x].config(image = ImagesNuméros[NbBombesAdjacentesPossibles], state = "disabled")
                    CasesRévélées += 1
                    Bse_donnee[x].etat = "révélée"
                    ListeCasesRévélées.append(x)
                    Dico[x] = Bse_donnee[x].type #inutile, une liste fonctionne mieux.
                    if Bse_donnee[x].type == 0:

                        Liste = (itemgetter(*[idx for idx,e in enumerate(list(Dico.values())) if e == 0])(list(Dico.keys())))
                    else:
                        pass

    if ValeurDrapeau == 1:
        if Bse_Case_Drapeau[x] == 0:
            Bse_Case[x].config(image = ImageDrapeau)
            Bse_Case_Drapeau[x] = 1
            Bse_donnee[x].etat == "Drapeau"
            ListeDrapeau.append(x)
        elif Bse_Case_Drapeau[x] ==1:
            Bse_Case[x].config(image = ImageBlanc)
            Bse_Case_Drapeau[x] = 0
            Bse_donnee[x].etat == "caché"
            del ListeDrapeau[ListeDrapeau.index(x)]

    if CasesRévélées + NBBOMBES == LargeurGrille*LargeurGrille:
        for k in range(LargeurGrille*LargeurGrille):
            if Bse_Case_Drapeau[k] == 1:
                    Bse_Case[k].config(image = ImageDrapeauVrai, state = "disabled")
        Gagné = showinfo("Fin du game", message = "Vous avez gagné", default = "ok")
        statut = "win"
def fonction(x):
    firstcase(x)
    ClicCase(x)
'''def TriDico():
    sorted(Dico.items(), Type=lambda t: t[1])
    DicoTrie = OrderedDict(sorted(Dico.items(), Type=lambda t: t[0]))
'''
def ClicDrapeau():

#Fonction permettant d'activer/désactiver la pose de drapeau

    global ValeurDrapeau
    if ValeurDrapeau == 0:
        IndicateurDrapeau.config(image = ImageVert)
        ValeurDrapeau = 1
    else:
        IndicateurDrapeau.config(image = ImageRouge)
        ValeurDrapeau = 0
def VerificationEtat(ValeurAAjouter):
    #On vérifie si la case est un drapeau pour éviter de cliquer dessus une nouvelle fois.
    global Numero
    global Liste
    global ListeZérosT
    print(VerificationEtat)
    print(Bse_donnee[Liste[VariableLoop]])
    if len(Liste) == 0:
        Liste = (itemgetter(*[idx for idx,e in enumerate(list(Dico.values())) if e == 0])(list(Dico.keys())))
    #Cette condition est nécéssaire car si il y a qu'une case vide de révélée alors il Liste est une variable et non une liste.
    elif Bse_donnee[Liste[VariableLoop]] in ListeCasesRévélées:
        NombreDeZérosDévoilée -=1
    else:
        if Bse_donnee[Liste[Numero]+ValeurAAjouter].etat == "Drapeau":
            pass
        else:
            ClicCase(Liste[Numero]+ValeurAAjouter)
            Liste = (itemgetter(*[idx for idx,e in enumerate(list(Dico.values())) if e == 0])(list(Dico.keys())))

def AutomatisationResolveur(Boucle, ValeursPoss):
    global Numero
    global NombreDeZérosDévoilée
    for loop in range(Boucle):
        VerificationEtat(ValeursPoss[loop])
    NombreDeZérosDévoilée +=1
    print("NombreDeZérosDévoilée : ",NombreDeZérosDévoilée)
    Numero += 1

def near(case, cmd1, cmd2, cmd3, cmd4, cmd5, cmd6,cmd7 ,cmd8,cmd9):
    if case in LINEDOWN:
        cmd1
    elif case in LINEUP:
        cmd2
    elif case in LINERIGHT:
        cmd3
    elif case in LINELEFT:
        cmd4
    elif case == CORNERRIGHTU:
        cmd5
    elif case == CORNERLEFTD:
        cmd6
    elif case == CORNERRIGHTD:
        cmd7
    elif case == CORNERLEFTU:
        cmd8
    else:
        cmd9

def Resolve():
    global NombreDeZérosDévoilée
    global Liste
    global LineUp
    global ListeZerosRévélés
    loop = 0
    global NombreDeZérosTraités
    global statut
    #Etape 1: Si aucune case n'a été activé: en activer une.
    if not Dico:
        firstcase(randint(0,99))#On clique sur une case aléatoire
    else:
        VariableLoop = 0
        if not Liste:
            #On actualise la liste des valeurs cliqué. Problème : on est dans une fonction
            Liste = (itemgetter(*[idx for idx,e in enumerate(list(Dico.values())) if e == 0])(list(Dico.keys())))

        while NombreDeZérosDévoilée != len(Liste):
            NombreDeZérosTraités += 1

            if Liste[loop] in LINEUP:

                if Dico[Liste[loop]] == 0:
                    AutomatisationResolveur(5, ValeursPossibles1)

            elif Liste[loop] in LINEDOWN:
                if Dico[Liste[loop]] == 0:
                    AutomatisationResolveur(5, ValeursPossibles2)

            elif Liste[loop] in LINERIGHT:
                if Dico[Liste[loop]] == 0:
                    AutomatisationResolveur(5, ValeursPossibles3)
                    #Erreur ici
            elif Liste[loop] in LINELEFT:
                if Dico[Liste[loop]] == 0:
                    AutomatisationResolveur(5, ValeursPossibles4)

            elif Liste[loop] == CORNERLEFTD:

                if Dico[Liste[loop]] == 0:
                    AutomatisationResolveur(3, ValeursPossibles5)

            elif Liste[loop] == CORNERLEFTU:
                if Dico[Liste[loop]] == 0:
                    AutomatisationResolveur(3, ValeursPossibles6)

            elif Liste[loop] == CORNERRIGHTD:
                if Dico[Liste[loop]] == 0:
                    AutomatisationResolveur(3, ValeursPossibles8)

            elif Liste[loop] == CORNERRIGHTU:
                if Dico[Liste[loop]] == 0:
                    AutomatisationResolveur(3, ValeursPossibles7)

            else:
                if Dico[Liste[loop]] == 0:
                    AutomatisationResolveur(8, ValeursPossibles)
            if statut == "lose":
                Bse_Case[Liste[loop]].config(image = ImageVert)
                break
            elif loop == len(Liste):
                break
            else:
                pass
            loop +=1

            print("NombreDeZérosTraités: ", NombreDeZérosTraités)
            print(loop)

def VerifiDrapEtat(Etat, NumeroCase, x, y):
    if Bse_donnee[NumeroCase].compteur in LINEUP:
        pass
    if Bse_donnee[NumeroCase].compteur in LINEDOWN:
        pass
    if Bse_donnee[NumeroCase].compteur in LINERIGHT:
        pass
    if Bse_donnee[NumeroCase].compteur in LINELEFT:
        pass
    if Bse_donnee[NumeroCase].compteur == 99:
        pass
    if Bse_donnee[NumeroCase].compteur == 0:
        pass
    if Bse_donnee[NumeroCase].compteur == 9:
        pass
    if Bse_donnee[NumeroCase].compteur == 90:
        pass
    else:
        if (Bse_donnee[NumeroCase+x].type != 0 and Bse_Case_Drapeau[NumeroCase+x] == 0)and (Bse_donnee[NumeroCase+y].type != 0 and Bse_Case_Drapeau[NumeroCase+y] == 0):
            if Bse_donnee[NumeroCase+x].etat == Etat and Bse_donnee[NumeroCase+x].etat == Etat:

                return True
        else:
            return False

m = 0
def Drap(ValeursPoss, posDrap):
    for element in ValeursPoss:
        if Bse_donnee[posDrap + element].type == 1:
            for i in ValeursPoss :
                ClicCase(Bse_donnee[posDrap + element + i].compteur)
Liste1 = []

def VerifDrapeau():
    for boucle in ListeDrapeau:
        near(boucle, Drap(ValeursPossibles2, boucle), Drap(ValeursPossibles1, boucle), Drap(ValeursPossibles4, boucle),Drap(ValeursPossibles3, boucle) , Drap(ValeursPossibles5, boucle), Drap(ValeursPossibles6, boucle),Drap(ValeursPossibles7, boucle) ,Drap(ValeursPossibles8, boucle),Drap(ValeursPossibles, boucle))
def CornExtend():
    for l in range(len(ListeDrapeau)):
        for loop in ValeursPossibles:
            VerifCoin(LINEUP, ValeursPossibles1, loop)
            VerifCoin(LINEDOWN, ValeursPossibles2, loop)
            VerifCoin(LINERIGHT, ValeursPossibles3, loop)
            VerifCoin(LINELEFT, ValeursPossibles4, loop)

def Coin(a,b,c,d,e,f,g,h):
    global Liste
    global Bse_donnee
    #On supprime toute les cases traités par le programme précédemment.

    #Maintenant on va demander au programme de reconnaître les paternes en formes de coins dans lesquels nous sommes sûr qu'il y a une bombe au boût avec un coin avec une valeur de 1.
        #On crée une nouvelle liste avec tout les cases avec la valeur 1 de révélée.
    Liste1 = (itemgetter(*[idx for idx,e in enumerate(list(Dico.values())) if e == 1])(list(Dico.keys())))
    for NumeroCase in Liste1:

        ev = a
        eb = b
        print("NumeroCase : ", NumeroCase, )
        #if NumeroCase in LINEUP == False and NumeroCase in LINELEFT == False and NumeroCase in LINERIGHT == False and NumeroCase in LINEDOWN == False and NumeroCase != 0 and NumeroCase != 90 and NumeroCase != 9 and NumeroCase != 99:
        if VerifiDrapEtat("révélée",NumeroCase, ev, eb) == True :
            if Bse_donnee[NumeroCase+c].etat != "caché" and Bse_donnee[NumeroCase + d].etat != "caché" and Bse_donnee[NumeroCase+e].etat != "caché" and Bse_donnee[NumeroCase+f].etat != "caché" and Bse_donnee[NumeroCase+g].etat != "caché":
                if Bse_donnee[NumeroCase+h].etat == "Drapeau":
                    pass

                elif Bse_donnee[NumeroCase+h].etat == "caché":

                    ClicDrapeau()
                    ClicCase(NumeroCase+h)
                    #Bse_Case[NumeroCase+h].config(image = ImageVert)
                    ClicDrapeau()
                    print(NumeroCase, "Sucess")
                    Bse_Case[NumeroCase].config(image = ImageVert)
            else:
                print("Erreur 1")
        else:
            print("Erreur 2")

def ResolveCoin():
    Coin(10,1,-1,+9,-11,-10,-9,+11)#Coin Haut Gauche

    Coin(-10, -1,+1,+11,+11,+10,+9,-9)#Coin Bas Droite
    Coin(-10,+1,-1,-11,+9,+10,+11,-9)#Coin Bas Gauche
    Coin(+10,-1,+1,+11,-9,-10,-11,+9)#Coin Haut Droite

Numero = 0
ListeZérosT = []
NombreDeZérosTraités = 0

ListeCasesRévélées = []
VariableLoop = 0
    #Fonction résolvant le démineur; Le dioctionnaire sert ici.
ValeursPossibles = [1,-1,10,-10,11,-11,9,-9]
ValeursPossibles1 = [1,-1,10,9,11] #LineUp
ValeursPossibles2 = [1,-1,-10,-9,-11]#LineDown
ValeursPossibles3 = [-1,10,-10,9,-11]#Right
ValeursPossibles4 = [1,10,-10,-9,11]
ValeursPossibles5 = [1,-10,-9]
ValeursPossibles6 = [1,10,11]
ValeursPossibles7 = [-1,10,9]
ValeursPossibles8 = [-1,10,-11]

NombreDeZérosDévoilée = 0
Liste = []
ListeDrapeau = []

#-------------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------------
TableauDémineur = Tk()
TableauDémineur.title("Démineur - Aristide, Matéo et Raphaël - ISN 2018-2019")
#
Dico = {}
#Largeur de la grille
LargeurGrille = 10

#Nombre de Bombes sur la grille
NBBOMBES = 10

#Bse_donne contient les informations des cases
Bse_donnee = [0]*LargeurGrille*LargeurGrille

#Bse_Case contient les boutons (cases)
Bse_Case = [0]*LargeurGrille*LargeurGrille

#Bse_Bombe contient les numéros des cases où les bombes sont situées
Bse_Bombe = []*NBBOMBES

#Bse_Case_Drapeau contient l'information de la présence d'un drapeau ou non sur une case
Bse_Case_Drapeau = [0]*LargeurGrille*LargeurGrille

#Nombre de cases révélées (pour savoir où l'on en est dans la partie
CasesRévélées = 0

#Si la valeur du drapeau est 0, alors le drapeau n'est pas activé (Rouge). Si c'est 0, alors il est activé (Vert).

ValeurDrapeau = 0
#Partie Gaganée ou Perdue
statut = ""

#Listes endroits spécifiques (côtés et coins)
LINEUP = []
for k in range(LargeurGrille - 2):
    LINEUP.append(1 + k)

LINELEFT = []

for k in range(LargeurGrille - 2):
    LINELEFT.append((LargeurGrille * k) + LargeurGrille)

LINERIGHT = []
for k in range(LargeurGrille - 2):
    LINERIGHT.append((LargeurGrille * k) + ((LargeurGrille*2) - 1))

LINEDOWN = []
for k in range(LargeurGrille - 2):
    LINEDOWN.append((LargeurGrille * LargeurGrille) - LargeurGrille + 1 + k)

CORNERRIGHTU = LargeurGrille - 1
CORNERLEFTU = 0
CORNERRIGHTD = (LargeurGrille * LargeurGrille) - 1
CORNERLEFTD = (LargeurGrille * LargeurGrille) - LargeurGrille

#Création des images

ImageBlanc = PhotoImage(file="ImageBlanc.png")
ImageDrapeau = PhotoImage(file="ImageDrapeau.png")
ImageDrapeauVrai = PhotoImage(file="ImageDrapeauVrai.png")
ImageDrapeauFaux = PhotoImage(file="ImageDrapeauFaux.png")
ImageVert = PhotoImage(file="Vert.png")
ImageRouge = PhotoImage(file="Rouge.png")
ImageBombe = PhotoImage(file="ImageBombe.png")
ImageBombeFaux = PhotoImage(file="ImageBombeFaux.png")
ImagesNuméros = [0]*9
ImagesNuméros[0] = PhotoImage(file="Pic0.png")
ImagesNuméros[1] = PhotoImage(file="Pic1.png")
ImagesNuméros[2] = PhotoImage(file="Pic2.png")
ImagesNuméros[3] = PhotoImage(file="Pic3.png")
ImagesNuméros[4] = PhotoImage(file="Pic4.png")
ImagesNuméros[5] = PhotoImage(file="Pic5.png")
ImagesNuméros[6] = PhotoImage(file="Pic6.png")
ImagesNuméros[7] = PhotoImage(file="Pic7.png")
ImagesNuméros[8] = PhotoImage(file="Pic8.png")

#Génération du tableau
def Start():
    Compteur = 0

    for ligne in range(LargeurGrille):
        for colonne in range(LargeurGrille):

            Bse_donnee[Compteur] = Case(Compteur, colonne, ligne, 0)
            Bse_Case[Compteur] = Button(TableauDémineur, image = ImageBlanc, state = "active", command = lambda Compteur=Compteur:fonction(Bse_donnee[Compteur].compteur))
            Bse_Case[Compteur].grid(row=ligne, column=colonne)
            Compteur += 1
    #Nombre de cases révélées (pour savoir où l'on en est dans la partie
    CasesRévélées = 0

    #Si la valeur du drapeau est 0, alors le drapeau n'est pas activé (Rouge). Si c'est 0, alors il est activé (Vert).

    ValeurDrapeau = 0
    #Partie Gaganée ou Perdue
    statut = ""
    SETBOMBE(NBBOMBES)
    DetectBombe()
Start()

#Génération du menu latéral droit

BoutonDrapeau = Button(TableauDémineur, image = ImageDrapeau, command = ClicDrapeau)
BoutonDrapeau.grid(row = 1, column = LargeurGrille)
IndicateurDrapeau = Label(TableauDémineur, image = ImageRouge)
IndicateurDrapeau.grid(row = 1, column = LargeurGrille + 1)
Resolveur = Button(TableauDémineur, text='Résoudre', command=Resolve)
Resolveur.grid(row = 3, column = LargeurGrille + 1 )
Suite = Button(TableauDémineur, text='Coins', command=ResolveCoin)
Suite.grid(row = 5, column = LargeurGrille + 1 )

Resolveur bugué non fini sans explications.py


#!/usr/bin/env python
"""
this is the settings file for the lighttpd config generator
"""

#required settings
BASE_PATH='/opt/dp'
DOMAIN='example.com'

ADMIN_MEDIA_PATH="/usr/share/pyshared/django/contrib/admin/media"

#per-project settings
EXTRA_CONFIG={
    'my_django_project':{
        'domain':r'^(www\.)?awesomeproject.com$'
    },
    'other_project':{
    }
}


from typing import List
from collections import deque

class Solution:
    def uniquePathsIII(self, grid: List[List[int]]) -> int:

        row_n, col_n = len(grid), len(grid[0])
        to_check, results = list(), list()
        starting, ending = list(), tuple()
        directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
        for x in range(row_n):
            for y in range(col_n):
                if grid[x][y] == 0:
                    to_check.append((x, y))
                elif grid[x][y] == 1:
                    starting = [(x, y)]
                elif grid[x][y] == 2:
                    ending = (x, y)

        walk_length = len(to_check) + 1

        def search(visited=None):
            if visited is None:
                visited = starting
            x, y = visited[-1]

            for dx, dy in directions:
                nx, ny = x+dx, y+dy
                if (nx, ny) in to_check and (nx, ny) not in visited:
                    search(visited + [(nx, ny)])
            if len(visited) == walk_length:
                for dx, dy in directions:
                    nx, ny = x + dx, y+dy
                    if 0 <= nx < row_n and 0 <= ny < col_n and (nx, ny) == ending:
                        results.append(visited)
        search()
        return len(results)

if __name__ == "__main__":
    ex = Solution()

    assert ex.uniquePathsIII([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, -1]]) == 2
    assert ex.uniquePathsIII([[0, 1], [2, 0]]) == 0
    assert ex.uniquePathsIII([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 2]]) == 4
    assert ex.uniquePathsIII([[1], [2]]) == 1
    assert ex.uniquePathsIII(
        [[1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 2, -1, 0, 0]]) == 2


from django.shortcuts import render_to_response
from django.template.context import RequestContext
from property.models import Property, City
from realestate.settings import MEDIA_URL

def searchView(request):
    pass

def searchResult(request):
    if request.POST:
        searchQ = request.POST.copy()
        if request.POST['buyorlet'] == "Rent":
            searchQ['buyorlet'] = "LE"

        results = Property.objects.filter(city_id__name__iexact=searchQ['search_term'])
        results = results.filter(price__gte=searchQ['price_from']).filter(price__lte=searchQ['price_to'])
        results = results.filter(rooms__gte=searchQ['no_of_rooms'])

        if searchQ['buyorlet'] == "LE":
            results = results.filter(sale_type__iexact=searchQ['buyorlet'])

        return render_to_response(  'search/index.htm',
                                    {'search_results' : results,
                                     'media_url' : MEDIA_URL},
                                    context_instance=RequestContext(request)
                                  )
    else:
        results = []
        return render_to_response(  'search/index.htm',
                                    {'search_results' : results,
                                     'media_url' : MEDIA_URL},
                                    context_instance=RequestContext(request)
                                  )


total = 0
command = "y"
unexpectedChar = list()
while True:
    if command == "y":
        jumlahBarang = int(input("Entrikan jumlah barang yang dibeli: "))
        hargaBarang = int(input("Entrikan harga satuan barang: "))
        total += jumlahBarang * hargaBarang
    elif command == "t":
        print("Total pembayaran: Rp", "{:,}".format(total))
        break
    else:
        unexpectedChar.append(command)
    command = input("apakah ada lagi item barang yang akan dientrikan atau tidak?[y/t]")
a = -1
for b in unexpectedChar:
    for i in b:
        a +=1
        print("Karakter salah indeks ke",str(a), "adalah", b)


import numpy as np
from numba import njit
# import g3read_units as g3u

###----- UNIT HANDLER -----###
class Uregexpr(object):
    def __init__(self, expression):
        self.expression = expression
    def evaluate(self, ureg):
        return ureg.parse_expression(self.expression)
    def __str__(self):
        return 'ureg '+self.expression

# type of input paramters, Uregexpr means the input may be  a string like '1000. kpc'
types={
    "CENTER_X": Uregexpr,
    "CENTER_Y": Uregexpr,
    "CENTER_Z": Uregexpr,
    "IMG_XY_SIZE": Uregexpr,
    "IMG_Z_SIZE": Uregexpr,
    "IMG_SIZE": int,

    }

xyz_keys = ['CENTER_X', 'CENTER_Y', 'CENTER_Z']

def parse_ureg_expressions(kv, to_parse, ureg):
    """
    Reads input values with units (e.g. '3000 kpc') and parses it in a  `pint` value).
    Input values came from the config file and are passed in a dict `kv`.
    `to_parse` is a dictionary that stores the type of the value of a given key (e.g. the number of pixels IMG_SIZE is `int`),
    and `ureg` is a `pint` instance
    """
    res = {}
    for k in to_parse:
        res[k] = kv[k].evaluate(ureg)
    return res

###----- KERNELS -----###
@njit
def WendlandC6_2D(u: float, h_inv: float):
    """
    Evaluate the WendlandC6 spline at position u, where u:= x*h_inv, for a 2D projection.
    Values correspond to 295 neighbours.
    """

    norm2D = 78. / (7. * 3.1415926)

    if u < 1.0:
        n = norm2D * h_inv**2
        u_m1 = (1.0 - u)
        u_m1 = u_m1 * u_m1  # (1.0 - u)^2
        u_m1 = u_m1 * u_m1  # (1.0 - u)^4
        u_m1 = u_m1 * u_m1  # (1.0 - u)^8
        u2 = u*u
        return ( u_m1 * ( 1.0 + 8*u + 25*u2 + 32*u2*u )) * n
    else:
        return 0.

###----- GRID -----###
@njit
def calc_area_weights(dw: np.ndarray,
                masked_x: np.ndarray, masked_y: np.ndarray,
                masked_h: np.ndarray, kernel,
                bin_min: int, delta_bin: float, n_bins: int):

    N = len(masked_x)

    tot_max_bin_spread = 0

    for k in range(N):
        xpx = (masked_x[k]-bin_min)/delta_bin #pos of x in terms of px (from 0 to n_bins-1)
        ypx = (masked_y[k]-bin_min)/delta_bin #pos of y in terms of px
        bin_i = int(xpx) #calculates distance in i-direction from minimum bin
        bin_j = int(ypx) #calculates distance in j-direction
        Hsml = masked_h[k]/delta_bin # in number of px

        max_bin_spread = int(Hsml)

        tot_max_bin_spread+=max_bin_spread
        distr_weight = 0.

        for i in range(bin_i - max_bin_spread, bin_i + max_bin_spread + 1):
            if i>=n_bins or i<0:
                continue
            for j in range(bin_j - max_bin_spread, bin_j + max_bin_spread + 1):
                if j>=n_bins or j<0:
                    continue
                u = ( (i+.5-xpx)**2 + (j+.5-ypx)**2 )**.5 / Hsml # distance of particle to px center
                if u > 1.0:
                    continue

                dx = min(xpx + Hsml, i+1) - max(xpx-Hsml, i)
                dy = min(ypx + Hsml, j+1) - max(ypx-Hsml, j)
                dxdy = dx*dy # area of px

                if Hsml < 1.:
                    wk = dxdy
                else:
                    wk = kernel(u, 1./Hsml) * dxdy

                distr_weight += wk

        dw[k] += distr_weight
    if N>0:
        return tot_max_bin_spread/N
    else:
        return np.nan

@njit
def add_to_grid(final_image_t: np.ndarray, weight_image: np.ndarray,
                masked_x: np.ndarray, masked_y: np.ndarray,
                masked_h: np.ndarray, masked_w: np.ndarray, masked_q: np.ndarray,
                dz: float, kernel, distr_weight: np.ndarray,
                bin_min: int, delta_bin: float, n_bins: int):
    """
    This routine adds a chunk of particles with sky positions `masked_x, masked_y`,
    smoothing length  `masked_h,` and value `masked_w` (e.g. paticle mass) to a FIT buffer `finalt_image_t`.
    Data is inserted in chunks in order to be able to process objects that do not fit into memory.
    """

    N = len(masked_x)

    tot_max_bin_spread = 0

    for k in range(N):
        xpx = (masked_x[k]-bin_min)/delta_bin #pos of x in terms of px (from 0 to n_bins-1)
        ypx = (masked_y[k]-bin_min)/delta_bin #pos of y in terms of px
        bin_i = int(xpx) #calculates distance in i-direction from minimum bin
        bin_j = int(ypx) #calculates distance in j-direction
        Hsml = masked_h[k]/delta_bin # in number of px

        max_bin_spread = int(Hsml)
        temp =0

        kernel_norm = 3.1415926 * Hsml**2 # area of particle in px^2

        tot_max_bin_spread+=max_bin_spread
        q = masked_q[k]

        if q == 0:
            continue

        for i in range(bin_i - max_bin_spread, bin_i + max_bin_spread + 1):
            if i>=n_bins or i<0:
                continue
            for j in range(bin_j - max_bin_spread, bin_j + max_bin_spread + 1):
                if j>=n_bins or j<0:
                    continue
                u = ( (i+.5-xpx)**2 + (j+.5-ypx)**2 )**.5 / Hsml # distance of particle to px center
                if u > 1.0:
                    continue

                dx = min(xpx + Hsml, i+1) - max(xpx - Hsml, i)
                dy = min(ypx + Hsml, j+1) - max(ypx - Hsml, j)
                dxdy = dx*dy # area of px

                if Hsml < 1.:
                    wk = dxdy
                else:
                    wk = kernel(u, 1./Hsml) * dxdy

                temp += wk

                area_norm = kernel_norm / distr_weight[k] * masked_w[k] * dz[k] / delta_bin
                px_weight = area_norm * wk
                # print(f"xpx = {xpx:.3f}, ypx = {ypx:.3f},\nbin_i = {bin_i}, bin_j = {bin_j},\ndx = {dx}, dy = {dy},\nmax_bin_spread = {max_bin_spread},\ni = {i}, j = {j},\nHsml = {Hsml}, u = {u:.3f},\nwk = {wk:.3f}, temp = {temp:.6f}\npx_weight = {px_weight:.3f},\nkernel_norm = {kernel_norm:.3f},\ndistr_weight[k] = {distr_weight[k]:.6f}")
                # input()
                final_image_t[j][i] += q * px_weight
                weight_image[j][i] += px_weight
                #Implement different contributions based on bin distance (kernels)... Basic idea would be to see how large the contribution of each particle is to each pixel is
    if N>0:
        return tot_max_bin_spread/N
    else:
        return np.nan

def mapping2D(pos: np.ndarray, hsml: np.ndarray,
              qty: np.ndarray, weights: np.ndarray,
              mapParam: dict, kernel = WendlandC6_2D):
    """
    here we read input data `kv`, read chunks of particles and send them to `add_to_grid`
    """
    #set the snapshots' scalefactor and hubble factor into units.
    # units = g3u.get_units(mapParam['SNAP_PATH'])
    #produce a set of pint units from the snapshots data
    # ureg = units.get_u()

    img_xy_size = mapParam['IMG_XY_SIZE']
    img_z_size  = mapParam['IMG_Z_SIZE']
    img_pxsize = mapParam['IMG_PXSIZE'] # number of pixels per side
    img_center = np.array(mapParam['IMG_CENTER'])

    n_bins = [img_pxsize]*2
    final_image_t = np.zeros(n_bins)
    weight_image = np.zeros(n_bins)
    dw = np.zeros_like(qty)

    bins = [np.linspace(-.5,.5,img_pxsize+1), np.linspace(-.5, .5, img_pxsize+1)]

    N_part_type = len(qty)
    print(N_part_type)

    if N_part_type == 0:
        raise ValueError("Quantity array is empty... Abort")

    rel_poses = pos - img_center

    pos_x = rel_poses[:,0]
    pos_y = rel_poses[:,1]
    pos_z = rel_poses[:,2]

    # Convert into pixel position
    norm_x = (pos_x/img_xy_size)#.to('').magnitude
    norm_y = (pos_y/img_xy_size)#.to('').magnitude
    norm_z = (pos_z/img_z_size)#.to('').magnitude
    norm_h = (hsml/img_xy_size)#.to('').magnitude

    # Select indeces for cube around center based on image size
    mask = (norm_x<=.5)&(norm_x>=-.5)&(norm_y<=.5)&(norm_y>=-.5)&(norm_z<=.5)&(norm_z>=-.5)

    masked_x = norm_x[mask]
    masked_y = norm_y[mask]
    masked_h = norm_h[mask]
    masked_w = weights[mask]
    dz       = 4./3.* masked_h
    masked_q = qty[mask]#(qty[mask]).to(mapParam['RESULT_UNITS']).magnitude
    print(f"'g2D': sum of qty_arr = {np.sum(masked_q):.2e}")
    print(f"'g2D': sum of qty_arr * V_arr = {np.sum(masked_q*4/3*3.1415926*hsml[mask]**3.):.2e}")

    avg_bin_spread = calc_area_weights(dw,masked_x,masked_y,masked_h,kernel,bins[0][0], bins[0][1]-bins[0][0], img_pxsize)

    avg_bin_spread = add_to_grid(final_image_t, weight_image, masked_x, masked_y, masked_h, masked_w, masked_q, dz, kernel, dw, bins[0][0], bins[0][1]-bins[0][0], img_pxsize)
    print ('# avg bin spread ', avg_bin_spread)

    final_image = np.nan_to_num(final_image_t)

    return final_image, weight_image

def mappingParam(center: list[3], xy_size: float, Npx: int):
    mapPar = {
        "IMG_CENTER"    : center,
        "IMG_XY_SIZE"   : xy_size,
        "IMG_Z_SIZE"    : xy_size,
        "IMG_PXSIZE"    : Npx,
        "LEN_PER_PX"    : xy_size/Npx
    }
    return mapPar


# coding:utf-8

import json
import os
import random
import string
from model.file_log import FileLog
from view import route, url_for, View, LoginView, AjaxLoginView, AjaxView

@route('/j/upload', name='j_upload')
class UploadHandler(AjaxLoginView):
    def post(self):
        file1 = self.request.files['file'][0]
        original_fname = file1['filename']
        extension = os.path.splitext(original_fname)[1]
        fname = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(24))
        final_filename = fname + extension
        output_file = open("static/uploads/" + final_filename, 'wb')
        output_file.write(file1['body'])
        fl = FileLog.new(final_filename, original_fname, self.current_user())
        self.finish(json.dumps(fl.to_dict()))

@route('/j/upload_file_lst', name='j_upload_file_lst')
class UploadHandler(AjaxLoginView):
    def post(self):
        self.finish(json.dumps(FileLog.get_list()))


# -*- coding: utf-8 -*-
"""
Created on 2016/10/13 17:06

@author: qiding
"""

import numpy as np
import statsmodels.api as sm

def main():
    data_len = 100000
    std_err = 0.1

    x_var = gen_x_var(data_len, std=1)
    error = gen_error(data_len, std=std_err)
    y_var = func(x_var, error)

    model = ModelLogNormal(y_var, x_var)
    model.fit()

    data_len_oos = 1000
    x_var_oos = gen_x_var(data_len_oos, std=1)
    error_oos = gen_error(data_len_oos, std=std_err)
    y_var_oos = func(x_var_oos, error_oos)
    y_predict_log, y_predict_with_var_raw_y, y_predict_with_var_err, y_predict_without_var = model.predict(x_var_oos)

    r_sq_without_var = model.report_r_sq(y_var_oos, y_predict_without_var)
    r_sq_with_var_raw = model.report_r_sq(y_var_oos, y_predict_with_var_raw_y)
    r_sq_with_var_err = model.report_r_sq(y_var_oos, y_predict_with_var_err)
    r_sq_log = model.report_r_sq(np.log(y_var_oos), y_predict_log)

    # y_predict_log, y_predict_with_var, y_predict_without_var = model.predict(x_var)
    #
    # r_sq_without_var = model.report_r_sq(y_var, y_predict_without_var)
    # r_sq_with_var = model.report_r_sq(y_var, y_predict_with_var)
    # r_sq_log = model.report_r_sq(np.log(y_var), y_predict_log)

    r_sq_in_sample = model.report_r_sq(y_real=np.log(y_var), y_predict=model.y_var_predict_log_in_sample)

    s = 'without: {}, with_raw: {}, with_err: {}, log: {}, in_sample: {}, in_sample2: {}'.format(
        r_sq_without_var, r_sq_with_var_raw, r_sq_with_var_err, r_sq_log, r_sq_in_sample, model.param_reg.rsquared
    )

    print(s)

class ModelLogNormal:
    def __init__(self, y_var, x_var):
        self.y_var = y_var
        self.x_var = x_var
        self.y_var_log = np.log(y_var)
        self.x_var_log = np.log(x_var)

        self.y_var_predict_log_in_sample = None
        self.error_in_sample = None

        self.model = None
        self.param_reg = None

    def fit(self):
        self.model = sm.OLS(endog=self.y_var_log, exog=sm.add_constant(self.x_var_log))
        self.param_reg = self.model.fit()
        self.y_var_predict_log_in_sample = self.predict_log(self.x_var_log)
        self.error_in_sample = self.y_var_log - self.y_var_predict_log_in_sample

    def predict_log(self, x_var_oos_log):
        exog = sm.add_constant(x_var_oos_log)
        y_predict_log = self.model.predict(params=self.param_reg.params, exog=exog)
        return y_predict_log

    def predict(self, x_var_oos):
        x_var_oos_log = np.log(x_var_oos)
        y_predict_log = self.predict_log(x_var_oos_log)
        y_predict_with_var_raw_y = np.exp(y_predict_log + 1 / 2 * (self.y_var_log.std() ** 2))
        y_predict_with_var_err = np.exp(y_predict_log + 1 / 2 * (self.error_in_sample.std() ** 2))
        y_predict_without_var = np.exp(y_predict_log)
        return y_predict_log, y_predict_with_var_raw_y, y_predict_with_var_err, y_predict_without_var

    @classmethod
    def report_r_sq(cls, y_real, y_predict):
        err = y_real - y_predict
        msr = (err * err).mean()
        err2 = y_real - y_real.mean()
        mse = (err2 * err2).mean()
        r_sq = 1 - msr / mse
        return r_sq

def gen_x_var(data_len, std):
    normal_data = np.random.normal(size=data_len, scale=std)
    exp_normal_data = np.exp(normal_data)
    return exp_normal_data

def gen_error(data_len, std):
    err = np.random.normal(scale=std, size=data_len)
    return err

def func(x_var, error, a=.8, b=.4):
    log_x = np.log(x_var)
    log_y = a * log_x + b + error
    y_exp = np.exp(log_y)
    return y_exp

if __name__ == '__main__':
    main()


import os
import random

from wheels import *

def gmap(height=3, width=3):

	def __randsym(syms):
		return syms[random.randint(0, len(syms) - 1)]

	def __randy():
		return random.randint(0, height - 1)

	def __randx():
		return random.randint(0, width - 1)

	retmap = []
	for y in range(height):
		retmap.append([])
		for x in range(width):
			retmap[y].append( __randsym(['.', 'X', '.', '.']))

	start_y, start_x = __randy(), __randx()
	while True:
		end_y, end_x = __randy(), __randx()
		if end_y != start_y or end_x != start_x:
			break

	retmap[start_y][start_x] = 'S'
	retmap[end_y][end_x] = 'D'

	return retmap, random.randint(0, height * width)

def ginput(inmap, time):
	height = len(inmap)
	width = len(inmap[0])

	infile = open(DEFAULT_INPUT_FILE, "w")
	infile.write("%d %d %d\n"%( height, width, time))
	for line in inmap:
		for sym in line:
			infile.write("%c"%sym)
		infile.write("\n")
	infile.close()

if __name__ == "__main__":
	os.chdir("..")

	def ginput2():
		inmap, time = gmap()
		ginput(inmap, time)

	simple_test_2(
		"cat %s | ./b.out"%DEFAULT_INPUT_FILE,
		"cat %s | ./a.out"%DEFAULT_INPUT_FILE,
		ginput2);


# -*- coding: utf-8 -*-
#
# Licensed under the terms of the BSD 3-Clause or the CeCILL-B License
# (see codraft/__init__.py for details)

"""Curve fitting dialog widgets"""

# pylint: disable=invalid-name  # Allows short reference names like x, y, ...

import numpy as np
from guidata.configtools import get_icon
from guiqwt.widgets.fit import FitDialog, FitParam

from codraft.config import _
from codraft.core.computation import fit
from codraft.core.computation.signal import xpeak
from codraft.utils.qthelpers import exec_dialog
from codraft.utils.tests import get_default_test_name

def guifit(
    x,
    y,
    fitfunc,
    fitparams,
    fitargs=None,
    fitkwargs=None,
    wintitle=None,
    title=None,
    xlabel=None,
    ylabel=None,
    param_cols=1,
    auto_fit=True,
    winsize=None,
    winpos=None,
    parent=None,
    name=None,
):
    """GUI-based curve fitting tool"""
    win = FitDialog(
        edit=True,
        wintitle=wintitle,
        icon=None,
        toolbar=True,
        options=dict(title=title, xlabel=xlabel, ylabel=ylabel),
        parent=parent,
        param_cols=param_cols,
        auto_fit=auto_fit,
    )
    if name is None:
        name = get_default_test_name()
    win.setObjectName(name)
    win.set_data(x, y, fitfunc, fitparams, fitargs, fitkwargs)
    win.autofit()  # TODO: [P3] make this optional
    if parent is None:
        win.setWindowIcon(get_icon("codraft.svg"))
    if winsize is not None:
        win.resize(*winsize)
    if winpos is not None:
        win.move(*winpos)
    win.get_plot().do_autoscale()
    if exec_dialog(win):
        return win.get_values()
    return None

# --- Polynomial fitting curve -------------------------------------------------
def polynomialfit(x, y, degree, parent=None, name=None):
    """Compute polynomial fit

    Returns (yfit, params), where yfit is the fitted curve and params are
    the fitting parameters"""
    ivals = np.polyfit(x, y, degree)

    params = []
    for index in range(degree + 1):
        val = ivals[index]
        vmax = max(1.0, np.abs(val))
        param = FitParam(f"c{(len(ivals) - index - 1):d}", val, -2 * vmax, 2 * vmax)
        params.append(param)

    def fitfunc(x, params):
        return np.polyval(params, x)

    values = guifit(
        x, y, fitfunc, params, parent=parent, wintitle=_("Polymomial fit"), name=name
    )
    if values:
        return fitfunc(x, values), params

# --- Gaussian fitting curve ---------------------------------------------------
def gaussianfit(x, y, parent=None, name=None):
    """Compute Gaussian fit

    Returns (yfit, params), where yfit is the fitted curve and params are
    the fitting parameters"""
    dx = np.max(x) - np.min(x)
    dy = np.max(y) - np.min(y)
    sigma = dx * 0.1
    amp = fit.GaussianModel.get_amp_from_amplitude(dy, sigma)

    a = FitParam(_("Amplitude"), amp, 0.0, amp * 1.2)
    b = FitParam(_("Base line"), np.min(y), np.min(y) - 0.1 * dy, np.max(y))
    sigma = FitParam(_("Std-dev") + " (σ)", sigma, sigma * 0.2, sigma * 10)
    mu = FitParam(_("Mean") + " (μ)", xpeak(x, y), np.min(x), np.max(x))

    params = [a, sigma, mu, b]

    def fitfunc(x, params):
        return fit.GaussianModel.func(x, *params)

    values = guifit(
        x, y, fitfunc, params, parent=parent, wintitle=_("Gaussian fit"), name=name
    )
    if values:
        return fitfunc(x, values), params

# --- Lorentzian fitting curve -------------------------------------------------
def lorentzianfit(x, y, parent=None, name=None):
    """Compute Lorentzian fit

    Returns (yfit, params), where yfit is the fitted curve and params are
    the fitting parameters"""
    dx = np.max(x) - np.min(x)
    dy = np.max(y) - np.min(y)
    sigma = dx * 0.1
    amp = fit.LorentzianModel.get_amp_from_amplitude(dy, sigma)

    a = FitParam(_("Amplitude"), amp, 0.0, amp * 1.2)
    b = FitParam(_("Base line"), np.min(y), np.min(y) - 0.1 * dy, np.max(y))
    sigma = FitParam(_("Std-dev") + " (σ)", sigma, sigma * 0.2, sigma * 10)
    mu = FitParam(_("Mean") + " (μ)", xpeak(x, y), np.min(x), np.max(x))

    params = [a, sigma, mu, b]

    def fitfunc(x, params):
        return fit.LorentzianModel.func(x, *params)

    values = guifit(
        x, y, fitfunc, params, parent=parent, wintitle=_("Lorentzian fit"), name=name
    )
    if values:
        return fitfunc(x, values), params

# --- Voigt fitting curve ------------------------------------------------------
def voigtfit(x, y, parent=None, name=None):
    """Compute Voigt fit

    Returns (yfit, params), where yfit is the fitted curve and params are
    the fitting parameters"""
    dx = np.max(x) - np.min(x)
    dy = np.max(y) - np.min(y)
    sigma = dx * 0.1
    amp = fit.VoigtModel.get_amp_from_amplitude(dy, sigma)

    a = FitParam(_("Amplitude"), amp, 0.0, amp * 1.2)
    b = FitParam(_("Base line"), np.min(y), np.min(y) - 0.1 * dy, np.max(y))
    sigma = FitParam(_("Std-dev") + " (σ)", sigma, sigma * 0.2, sigma * 10)
    mu = FitParam(_("Mean") + " (μ)", xpeak(x, y), np.min(x), np.max(x))

    params = [a, sigma, mu, b]

    def fitfunc(x, params):
        return fit.VoigtModel.func(x, *params)

    values = guifit(
        x, y, fitfunc, params, parent=parent, wintitle=_("Voigt fit"), name=name
    )
    if values:
        return fitfunc(x, values), params

# --- Multi-Gaussian fitting curve ---------------------------------------------
def multigaussian(x, *values, **kwargs):
    """Return a 1-dimensional multi-Gaussian function."""
    a_amp = values[0::2]
    a_sigma = values[1::2]
    y0 = values[-1]
    a_x0 = kwargs["a_x0"]
    y = np.zeros_like(x) + y0
    for amp, sigma, x0 in zip(a_amp, a_sigma, a_x0):
        y += amp * np.exp(-0.5 * ((x - x0) / sigma) ** 2)
    return y

def multigaussianfit(x, y, peak_indexes, parent=None, name=None):
    """Compute Multi-Gaussian fit

    Returns (yfit, params), where yfit is the fitted curve and params are
    the fitting parameters"""
    params = []
    for index, i0 in enumerate(peak_indexes):
        istart = 0
        iend = len(x) - 1
        if index > 0:
            istart = (peak_indexes[index - 1] + i0) // 2
        if index < len(peak_indexes) - 1:
            iend = (peak_indexes[index + 1] + i0) // 2
        dx = 0.5 * (x[iend] - x[istart])
        dy = np.max(y[istart:iend]) - np.min(y[istart:iend])
        stri = f"{index + 1:02d}"
        params += [
            FitParam(("A") + stri, y[i0], 0.0, dy * 2),
            FitParam("σ" + stri, dx / 10, dx / 100, dx),
        ]

    params.append(
        FitParam(
            _("Y0"), np.min(y), np.min(y) - 0.1 * (np.max(y) - np.min(y)), np.max(y)
        )
    )

    kwargs = dict(a_x0=x[peak_indexes])

    def fitfunc(xi, params):
        return multigaussian(xi, *params, **kwargs)

    param_cols = 1
    if len(params) > 8:
        param_cols = 4
    values = guifit(
        x,
        y,
        fitfunc,
        params,
        param_cols=param_cols,
        winsize=(900, 600),
        parent=parent,
        name=name,
        wintitle=_("Multi-Gaussian fit"),
    )
    if values:
        return fitfunc(x, values), params


import os
from flask_restful import Resource, reqparse

from models.systemuser import SystemUserModel

class Info(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('x-api-key', location='headers', required=True)
        self.api_key = self.parser.parse_args()['x-api-key']

    def get(self):
        if self.api_key != os.environ.get('X_API_KEY'):
            print(os.environ.get('X_API_KEY'))
            return {"error": "Authentication failed."}, 401

        all_users = SystemUserModel.query.all()
        gmail_users = SystemUserModel.query.filter(SystemUserModel.email.endswith('@gmail.com')).all()
        locked_users = SystemUserModel.query.filter_by(account_locked="true").all()
        suspended_users = SystemUserModel.query.filter_by(suspended="true").all()
        activated_users = SystemUserModel.query.filter_by(activated="true").all()

        return {"total": len(all_users),
                "all_users": [i.serialize for i in all_users],
                "gmail_users": [i.serialize for i in gmail_users],
                "locked_users": [i.serialize for i in locked_users],
                "suspended_users": [i.serialize for i in suspended_users],
                "activated_users": [i.serialize for i in activated_users], }


# https://www.hackerrank.com/challenges/greedy-florist/problem
# !/bin/python3

def getMinimumCost(k, c):
    cost = 0
    m = 1

    c.sort(reverse=True)

    for i in range(len(c)):
        cost += c[i] * m
        if (i + 1) % k == 0:
            m += 1

    return cost

if __name__ == '__main__':
    nk = input().split()
    n = int(nk[0])
    k = int(nk[1])
    c = list(map(int, input().rstrip().split()))
    minimumCost = getMinimumCost(k, c)
    print(minimumCost)