from django.db import models
from django.utils.translation import ugettext as _

class Gallery(models.Model):
    id = models.BigIntegerField(editable=False, primary_key=True)
    name = models.CharField(max_length=255, editable=False)
    description = models.TextField(blank=True, editable=False)
    cover_photo = models.TextField(editable=False, default='')
    count = models.IntegerField(editable=False)
    album_type = models.CharField(max_length=255, choices=[('profile', 'Profile'),
        ('mobile', 'Mobile'),
        ('wall', 'Wall'),
        ('normal', 'Normal'),
        ('album', 'Album'),], editable=False)
    created_time = models.DateTimeField(editable=False)
    updated_time = models.DateTimeField(editable=False)
    published = models.BooleanField(default=False, blank=True)

    class Meta:
        verbose_name = _('Gallery')
        verbose_name_plural = _('Galleries')
        ordering = ["created_time", "updated_time", "name"]

    def __unicode__(self):
        return self.name

    @models.permalink
    def get_absolute_url(self):
        return ('show_gallery', (), {'pk': str(self.id)})

    def publish(self):
        self.published = True
        self.save()
        return self

    def unpublish(self):
        self.published = False
        self.save()
        return self

    def get_cover_photo(self):
        if self.cover_photo:
            return self.cover_photo
        elif self.image_set.count() > 0:
            return self.image_set.all()[0].thumbnail
        else:
            return None

class Image(models.Model):
    id = models.BigIntegerField(editable=False, primary_key=True)
    gallery = models.ForeignKey(Gallery, editable=False)
    thumbnail = models.TextField(editable=False)
    image = models.TextField(editable=False)


from ast import arg
from asyncio.windows_events import NULL
from cmath import sqrt

from math import fabs
import math
import re
from sre_constants import SUCCESS
from unittest import result
import numpy as np
import scipy.optimize
import time
from numpy import random
import json

import DifferentiablePhysicsEngine

import os.path
from os import path

class OptimizationResult:
    newData = NULL
    elapsedTime = 0
    cost = 0
    cuadraticError = 0
    cuadraticErrorConstant = 0
    parameterDeviation = 0

def Average(lst):
    return sum(lst) / len(lst)

def QuadraticError(estimated, actual, nVerts):
    nSteps = len(estimated)
    G = 0
    for i in range(nSteps):
        G += np.sum(abs(actual[i].x - estimated[i].x) ** 2)

    if math.isnan(G):
        print("It's too much")
        return float("inf")

    return math.sqrt(G/(nVerts*nSteps))

def g(p, nSteps, forwardSubSteps, h, m_numDoFs, initialState, targets):
    print("Deprecated!")
    global lastP
    lastP = p

    steps = []
    current = initialState
    steps.append(initialState)

    for i in range(nSteps - 1):
        current = DifferentiablePhysicsEngine.forward(current.x, current.v, p, h)
        steps.append(current)

    g = np.sum(targets[nSteps - 1].x - steps[nSteps - 1].x) ** 2

    return g

def G(p, nSteps, forwardSubSteps, h, m_numDoFs, initialState, targets, settings):

    steps = [initialState] + DifferentiablePhysicsEngine.forwardLoop(
        initialState.x, initialState.v, p, settings, h, nSteps - 1, forwardSubSteps
    )

    G = 0
    history = []
    for i in range(nSteps):  # cambiar a steps
        G += np.sum(abs(targets[i].x - steps[i].x) ** 2)
        history.append(G)
    # G = G / nSteps

    if math.isnan(G):
        print(history)
        G = float("inf")

    return G

def dGdp(p, nSteps, forwardSubSteps, h, m_numDoFs, initialState, targets, settings):

    steps = [initialState] + DifferentiablePhysicsEngine.forwardLoop(
        initialState.x, initialState.v, p, settings, h, nSteps - 1, forwardSubSteps
    )

    _dGdp = np.full(p.size, 0.0)
    _dGdx = []
    _dGdv = []

    for i in range(nSteps):
        """if i == nSteps - 1:
            _dGdx.append(2.0 * (targets[nSteps - 1].x - steps[nSteps - 1].x))
        else:
            _dGdx.append(np.full(m_numDoFs, 0.0))

        _dGdv.append(np.full(m_numDoFs, 0.0))"""

        _dGdx.append(2.0 * (targets[i].x - steps[i].x))

        # _dGdx.append(2.0 * (targets[i].x - steps[i].x))
        _dGdv.append(np.full(m_numDoFs, 0.0))

    i = nSteps - 2
    while i >= 0:
        backward = DifferentiablePhysicsEngine.backward(
            steps[i].x,
            steps[i].v,
            steps[i + 1].x,
            steps[i + 1].v,
            p,
            settings,
            _dGdx[i + 1],
            _dGdv[i + 1],
            h,
        )

        _dGdp += backward.dGdp
        _dGdx[i] += backward.dGdx
        _dGdv[i] += backward.dGdv

        i -= 1

    return _dGdp

def Minimize(data, method="L-BFGS-B", costFunction=G, jacobian=dGdp, cuadraticErrorFrames=0, printResult=True):

    # scipy.optimize.show_options(solver="minimize", method=method, disp=True)

    # read data as json
    data_dict = json.loads(data)

    # PARAMETERS

    nSteps = data_dict["optimizationIterations"]
    forwardSubSteps = data_dict["forwardSubSteps"]
    h = data_dict["delta"]

    p = []

    settings = ""

    for o in data_dict["objects"]:

        _settings = o["optimizationSettings"]
        massMode = _settings[0]
        stiffnessMode = _settings[1]

        if massMode == "L":
            p += o["vertMass"]
        elif massMode == "G":
            p += [Average(o["vertMass"])]

        if stiffnessMode == "L":
            p += o["springStiffness"]
        elif stiffnessMode == "G":
            p += [Average(o["springStiffness"])]

        settings += _settings

    desiredParameter = np.array(p)

    # INITIALIZATION
    initialState = DifferentiablePhysicsEngine.initialize(data, settings)

    m_numDoFs = initialState.x.size

    # CALCULATING TARGET
    targets = [initialState] + DifferentiablePhysicsEngine.forwardLoop(
        initialState.x,
        initialState.v,
        np.full(0, 0,),
        "nn" * len(data_dict["objects"]),
        h,
        nSteps - 1,
        forwardSubSteps
    )

    p0 = np.full(desiredParameter.size, 0.0001)  # initial parameter value
    args = (nSteps, forwardSubSteps, h, m_numDoFs, initialState,
            targets, settings)  # extra info
    bnds = [(0.0001, 10000)] * p0.size  # parameter bounds

    # G(desiredParameter, nSteps, h, m_numDoFs, initialState, targets)
    # dGdp(desiredParameter, nSteps, h, m_numDoFs, initialState, targets)

    start = time.time()
    res = scipy.optimize.minimize(
        costFunction,
        p0,
        jac=jacobian,  # jacobian "2-point" "3-point" "cs"
        method=method,
        args=args,
        bounds=bnds,
        callback=ShowProgress,
    )
    end = time.time()

    # WRITING RESULTS TO NEW FILE
    offset = 0
    for o in data_dict["objects"]:

        settings_ = o["optimizationSettings"]
        massMode = settings_[0]
        stiffnessMode = settings_[1]

        nVerts = len(o["vertMass"])
        nSprings = len(o["springStiffness"])

        if massMode in {"L", "l"}:
            o["vertMass"] = res.x[offset: nVerts + offset].tolist()
            offset += nVerts
        elif massMode in {"G", "g"}:
            o["vertMass"] = [res.x[offset]] * nVerts
            offset += 1

        if stiffnessMode in {"L", "l"}:
            o["springStiffness"] = res.x[offset: nSprings + offset].tolist()
            offset += nSprings
        elif stiffnessMode in {"G", "g"}:
            o["springStiffness"] = [res.x[offset]] * nSprings
            offset += 1

    newData = json.dumps(data_dict)

    # Measure time
    elapsedTime = round((end - start), 1)

    # Cost at end
    cost = round(res.fun, 2)

    # Parameter deviation
    parameterDeviation = round(np.sum(
        abs(abs(desiredParameter - res.x)/desiredParameter)*100)/len(res.x), 2)

    # Error with n steps
    steps = [initialState] + DifferentiablePhysicsEngine.forwardLoop(
        initialState.x, initialState.v, res.x, settings, h, len(
            targets)-1, forwardSubSteps
    )
    cuadraticError = round(QuadraticError(steps, targets, len(res.x)), 2)

    # Error with constant steps
    targets = [initialState] + DifferentiablePhysicsEngine.forwardLoop(
        initialState.x,
        initialState.v,
        np.full(0, 0,),
        "nn" * len(data_dict["objects"]),
        h,
        cuadraticErrorFrames - 1 if cuadraticErrorFrames > 0 else nSteps - 1,
        forwardSubSteps
    )

    steps = [initialState] + DifferentiablePhysicsEngine.forwardLoop(
        initialState.x, initialState.v, res.x, settings, h, len(
            targets)-1, forwardSubSteps
    )

    cuadraticErrorConstantSteps = round(
        QuadraticError(steps, targets, len(res.x)), 2)

    # Error with average parameters
    # avg = np.full(1, Average(data_dict["objects"][0]["springStiffness"]),)

    if printResult:
        title = data_dict["title"]

        log = f"{'-'*20}{title}{'-'*20}\n"
        log += f"Settings: {settings}\n"
        log += f"Simulation steps: {nSteps}\n"
        log += f"Substeps: {forwardSubSteps}\n"
        log += f"Timestep: {round(h, 3)}\n"
        log += f"No. parameters: {len(desiredParameter)}\n\n"

        log += f"Success: {res.success}\n"
        log += f"Message: {res.message}\n"
        log += f"Time elapsed: {elapsedTime}s\n\n"

        log += f"Cost: {round(res.fun,2)}\n"
        log += f"Cuadratic error: {cuadraticError}\n"
        log += f"Fixed cuadratic error: {cuadraticErrorConstantSteps}\n"
        log += f"Parameter deviation: {parameterDeviation}%\n\n"

        # log += f"nfev: {res.nfev}\n"
        # log += f"nit: {res.nit}\n"
        # log += f"njev: {res.njev}\n\n"

        print(log)

        print("Sample:")
        for i in range(min(10, len(desiredParameter))):
            print(f" {round(desiredParameter[i], 4)} --> {round(res.x[i], 4)}")

        log_file = open("log.txt", "a+")
        log_file.write(log)
        log_file.close()

    result = OptimizationResult()
    result.newData = newData
    result.parameterDeviation = parameterDeviation
    result.cost = cost
    result.cuadraticError = cuadraticError
    result.cuadraticErrorConstant = cuadraticErrorConstantSteps
    result.elapsedTime = elapsedTime

    return result

currentProgress = 0

def ShowProgress(p):
    global currentProgress
    progress = ["-", "/", "|", "\\"]
    print(progress[currentProgress], end="\r")
    currentProgress += 1
    if currentProgress >= len(progress):
        currentProgress = 0

# https://gist.github.com/yuyay/3067185
# python -m pip install "../DifferentiablePhysicsEngine"


#!/usr/bin/env python3

#
#  All rights reserved (c) 2014-2022 CEA/DAM.
#
#  This file is part of Phobos.
#
#  Phobos is free software: you can redistribute it and/or modify it under
#  the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation, either version 2.1 of the License, or
#  (at your option) any later version.
#
#  Phobos is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
#  along with Phobos. If not, see <http://www.gnu.org/licenses/>.
#

"""Unit tests for phobos.ldm"""

import errno
import os
import subprocess
import unittest
import re

from phobos.core.admin import Client as AdminClient
from phobos.core.const import PHO_LIB_SCSI # pylint: disable=no-name-in-module

# Conventional lib device for phobos tests
LIB_TEST_DEV = "/dev/changer"

class LdmTest(unittest.TestCase):
    """
    This test case issue requests to the DSS to stress the python bindings.
    """

    # XXX: refactor this test to split the code in subfunctions
    # pylint: disable=too-many-branches,too-many-locals,too-many-statements
    def test_lib_scan(self):
        """Test LdmAdapter.scan() against mtx output"""
        if not os.access(LIB_TEST_DEV, os.W_OK):
            self.skipTest("%s not writable or absent" % (LIB_TEST_DEV,))

        # Check that mtx is available
        try:
            subprocess.check_call(["mtx"])
        except OSError as exc:
            if exc.errno == errno.ENOENT:
                self.skipTest("mtx not available")

        # Ensure a tape is loaded
        subprocess.call(
            ["mtx", "-f", LIB_TEST_DEV, "load", "1"],
            # Silence output (it should not be verbose enough to stall)
            stderr=subprocess.PIPE, stdout=subprocess.PIPE,
        )

        # Retrieve mtx output
        mtx = subprocess.Popen(
            ["mtx", "-f", LIB_TEST_DEV, "status"],
            stdout=subprocess.PIPE,
        )
        mtx_output, _ = mtx.communicate()

        # Parse mtx output:
        #   Storage Changer /dev/changer:4 Drives, 24 Slots ( 4 Import/Export )
        # Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = P00001L5 # pylint: disable=line-too-long
        # Data Transfer Element 1:Empty
        # ...
        #       Storage Element 1:Empty
        #       Storage Element 2:Full :VolumeTag=P00002L5
        # ...
        #       Storage Element 21 IMPORT/EXPORT:Empty
        rel_addr_re =\
            re.compile(r".*Element (?P<rel_addr>\d+)(?: IMPORT/EXPORT)?:.*")
        rel_addr_loaded_re =\
            re.compile(r".*Storage Element (?P<rel_addr>\d+) Loaded.*")
        volume_re = re.compile(r".*:VolumeTag ?= ?(?P<volume>\w+).*")

        mtx_elts = {}
        imp_exp_base_addr = None
        for line in mtx_output.splitlines():
            line = line.strip().decode('utf-8')
            # Ignore lines we don't want to parse
            if " Element " not in line:
                continue
            full = ":Full" in line
            # mtx has its own way of displaying scsi addresses of the lib
            # components, the obscure address translations done here tries to
            # normalize it
            rel_addr = int(rel_addr_re.match(line).group("rel_addr"))

            if "Data Transfer Element" in line:
                elt_type = u"drive"
            elif "Storage Element" in line:
                if "IMPORT/EXPORT" in line:
                    if imp_exp_base_addr is None:
                        imp_exp_base_addr = rel_addr
                    rel_addr -= imp_exp_base_addr
                    elt_type = u"import/export"
                else:
                    # slot numbers start at 1
                    rel_addr -= 1
                    elt_type = u"slot"

            elt = {"full": full, "rel_addr": rel_addr}
            rel_addr_loaded_m = rel_addr_loaded_re.match(line)
            if rel_addr_loaded_m:
                # slot numbers start at 1
                elt["rel_addr_loaded"] =\
                    int(rel_addr_loaded_m.group("rel_addr")) - 1
            volume_m = volume_re.match(line)
            if volume_m:
                elt["volume"] = str(volume_m.group("volume"))
            mtx_elts.setdefault(elt_type, []).append(elt)

        # Retrieve data as seen by ldm_lib_scan
        with AdminClient(lrs_required=False) as adm:
            raw_lib_data = adm.lib_scan(PHO_LIB_SCSI, LIB_TEST_DEV)

        # Find the base address for each type to the first address seen (they
        # should be sorted)
        base_addrs = {}
        for lib_elt in raw_lib_data:
            base_addrs.setdefault(lib_elt["type"], lib_elt["address"])

        # Reshape data to be comparable to mtx
        lib_elts = {}
        for lib_elt in raw_lib_data:
            elt = {
                "full": lib_elt["full"],
                "rel_addr": lib_elt["address"] - base_addrs[lib_elt["type"]],
            }
            if "volume" in lib_elt:
                elt["volume"] = lib_elt["volume"]
            # Source address is not supported for slots in mtx
            if lib_elt["type"] != "slot" and "source_address" in lib_elt:
                elt["rel_addr_loaded"] =\
                    lib_elt["source_address"] - base_addrs["slot"]
            lib_elts.setdefault(lib_elt["type"], []).append(elt)

        # Check lib_elts conformity
        self.maxDiff = None # pylint: disable=invalid-name
        self.assertGreaterEqual(len(lib_elts.pop("arm")), 1)
        self.assertEqual(mtx_elts, lib_elts)

if __name__ == '__main__':
    unittest.main(buffer=True)


import sys
import heapq
input=sys.stdin.readline
arr=[]
N=int(input())
for _ in range(N):
    x=int(input())
    if x==0 and len(arr)==0:
        print(0)
    elif x==0:
        print(heapq.heappop(arr))
    else:
        heapq.heappush(arr,x)


import os, argparse

import numpy as np
from tqdm import tqdm
import sparse

def main(INPUT_DIR, ND_CH0_ADC, ND_CH3_STACKED, ND_CH4_FIRSTTRIGGER, ND_CH5_WIREDISTANCE):
    max_adcs, max_num_stacked, max_num_firsttriggers, max_wiredistance = [], [], [], []
    min_adcs, min_num_stacked, min_num_firsttriggers, min_wiredistance = [], [], [], []

    for entry in tqdm(os.scandir(INPUT_DIR)):
        arr = sparse.load_npz(entry.path).todense()

        if ND_CH0_ADC:
            max_adcs.append(np.max(arr[0]))
            min_adcs.append(np.min(arr[0]))

        if ND_CH3_STACKED:
            max_num_stacked.append(np.max(arr[3]))
            min_num_stacked.append(np.min(arr[3]))

        if ND_CH4_FIRSTTRIGGER:
            max_num_firsttriggers.append(np.max(arr[4]))
            min_num_firsttriggers.append(np.min(arr[4]))

        if ND_CH5_WIREDISTANCE:
            max_wiredistance.append(np.max(arr[5]))
            min_wiredistance.append(np.min(arr[5]))

    if ND_CH0_ADC:
        print("min adc = {}, max adc = {}".format(min(min_adcs), max(max_adcs)))
        print("1/max = {}\n".format(1/max(max_adcs)))

    if ND_CH3_STACKED:
        print("min num stacked = {}, max num stacked = {}".format(min(min_num_stacked), max(max_num_stacked)))
        print("1/max = {}\n".format(1/max(max_num_stacked)))

    if ND_CH4_FIRSTTRIGGER:
        print("min num first triggers = {}, max num first triggers = {}".format(min(min_num_firsttriggers), max(max_num_firsttriggers)))
        print("1/max = {}\n".format(1/max(max_num_firsttriggers)))

    if ND_CH5_WIREDISTANCE:
        print("min wire distance = {}, max wire distance = {}".format(min(min_wiredistance), max(max_wiredistance)))
        print("1/max = {}\n".format(1/max(max_wiredistance)))

def parse_arguments():
    parser = argparse.ArgumentParser()

    parser.add_argument("input_dir")

    parser.add_argument("--nd_ch0_adc", action='store_true')
    parser.add_argument("--nd_ch3_stacked", action='store_true')
    parser.add_argument("--nd_ch4_firsttrigger", action='store_true')
    parser.add_argument("--nd_ch5_wiredistance", action='store_true')

    args = parser.parse_args()

    return (args.input_dir, args.nd_ch0_adc, args.nd_ch3_stacked, args.nd_ch4_firsttrigger, args.nd_ch5_wiredistance)

if __name__ == "__main__":
    arguments = parse_arguments()
    main(*arguments)


import re

# Inserir entradas
inserirEntrada = "A1 A2B1"
# Gerar Lista de entradas
entrada = re.split("\s", inserirEntrada)
# Verifica a quantidade de entradas
numeroEntradas = len(entrada)

print("=======//=======//=======//=======")

while (numeroEntradas>0):
    lerPosicaoEntrada = len(entrada) - numeroEntradas
    pcaracter = 0
    scaracter = pcaracter + 1

    # Gerar Lista de elementos
    element = list(entrada[lerPosicaoEntrada])
    # Verifica quantidade de elementos
    numeroElemento = len(element)
    tamanhoElemento = len(element)

    # Analisar entradas
    #fatorEntrada = ""
    #if numeroEntradas>1:
    #    fatorEntrada = "<list>"
    print("Entrada: ", entrada[lerPosicaoEntrada])
    print("<list>::= <element> <list>")

    numeroEntradas = numeroEntradas - 1
    resultadoElementos = ""

    while (numeroElemento>0):

        lerPosicaoElemento = len(element) - numeroElemento
        numeroElemento = numeroElemento - 1
        # Analisar elementos
        fatorElemento = " "
        if numeroElemento >=1:
            fatorElemento = "<element>"
        # Construir Fator Geral
        #fatorGeral = fatorElemento + fatorEntrada
        fatorGeral = fatorElemento
        # Verificar Elemento

        # Verificar Tipo de Elemento
        tipoElemento = ""
        # Verifica se são pares de elementos
        if (tamanhoElemento%2 != 0):
            print("ERRO: Não satisfaz as regras")
            break

        # verifica o primeiro e o segundo elemento conforme regra de negocio
        primeiroCaracter = re.match(r"[A-C]",element[pcaracter])
        segundoCaracter = re.match(r"[1-4]",element[scaracter])
        # Regra de negócio
        letra = re.match(r"[A-C]",element[lerPosicaoElemento])
        numero = re.match(r"[1-4]", element[lerPosicaoElemento])

        # Organiza quem é o primeiro e o segundo elemento
        if (tamanhoElemento > (pcaracter+2)):
            pcaracter = scaracter + 1
            scaracter = pcaracter + 1

        if (not primeiroCaracter):
            print("ERRO: Não satisfaz as regras")
            break
        else:
            if (not segundoCaracter):
                print("ERRO: Não satisfaz as regras")
                break
            else:
                if(letra):
                    tipoElemento = "<letter>"
                else:
                    if(numero):
                        tipoElemento = "<digit>"
                    else:
                        print("ERRO: Não satisfaz as regras")
                        break
        print(resultadoElementos+tipoElemento+fatorGeral)
        resultadoElementos = resultadoElementos + element[lerPosicaoElemento]
        print(resultadoElementos+fatorGeral)
    print ("=======//=======//=======//=======")


try:
  import sentlex.negdetect as neg
except Exception:
  import negdetect as neg

import sys,os
import unittest

#####
#
# Unit Testing for negation detection
#
####

# data for tests - ignore POS tags
STR_NONEGATION = 'this/DT example/DT contains/DT only/DT positive/DT remarks/DT !/DT'
STR_UNTAGGED = 'this example does not contain any tags. algorithm will assume one.'
STR_NEGATION = 'this/DT example/DT does/DT not/DT cause/DT the/DT algorithm/DT to/DT detect/DT something/DT positive/DT ./DT'
STR_DOUBLE = 'this/DT example/DT does/DT not/DT mean/DT there/DT are/DT no/DT negations/DT ./DT'
STR_PSEUDO = 'not/DT only/DT this/DT example/DT contains/DT a/DT double/DT ./DT it/DT is/DT no/DT wonder/DT language/DT is/DT a/DT problem/DT ./DT'
STR_WINDOW = 'with/DT no/DT certainty/DT this/DT will/DT negate/DT as/DT far/DT as/DT the/DT window/DT allows/DT'
STR_OTHERTAG = 'in_DT this_DT example_DT nothing_DT means_DT the_DT algorithm_DT still_DT works_DT'

# T0 - Edge cases
class T0_edgecases(unittest.TestCase):
    def runTest(self):
        # empty list
        self.assertEqual(neg.getNegationArray([], 4, True), [], 'Failed to deal with empty list')

        # untagged - processes as normal
        self.assertTrue(neg.getNegationArray(STR_UNTAGGED.split(), 4, True), 'Unable to process untagged doc')

        # string should raise an error
        self.assertRaises(AssertionError, neg.getNegationArray, STR_UNTAGGED, 4, True)

# T1 - Negation algorithm
class T1_negationalgo(unittest.TestCase):
    def runTest(self):
        # no negation
        A = neg.getNegationArray(STR_NONEGATION.split(), 4, True)
        self.assertEqual(sum(A), 0, 'No negation string failed')

        # simple negation
        A = neg.getNegationArray(STR_NEGATION.split(), 4, True)
        self.assertTrue(sum(A)>0, 'Negation algo failed on STR_NEGATION')

        # double negation
        A = neg.getNegationArray(STR_DOUBLE.split(), 4, True)
        self.assertTrue(sum(A)>0, 'Negation algo failed on STR_DOUBLE')

        # pseudo
        A = neg.getNegationArray(STR_PSEUDO.split(), 4, True)
        self.assertTrue(sum(A)==0, 'Negation algo failed on STR_PSEUDO')

        # other tag
        A = neg.getNegationArray(STR_OTHERTAG.split(), 4, True)
        self.assertTrue(sum(A)>0, 'Negation algo failed on STR_OTHERTAG')

# T2 - window
class T2_negationwindow(unittest.TestCase):
    def runTest(self):
        # loop increasing window sizes
        negatedsums = []
        for i in range(1,6):
            A = neg.getNegationArray(STR_WINDOW.split(), i, False)
            negatedsums.append(sum(A))
        for i in range(4):
            self.assertTrue(negatedsums[i] < negatedsums[i+1], 'Something wrong with window size %d'%i)

#
# Runs unit testing if module is called directly
#
if __name__ == "__main__":

   # Run those guys
   unittest.main()


import os, os.path
import shutil
# import tensorflow as tf
# import facenet
# import facenet.align.align_dataset_mtcnn as MTCNN

RAW_DATASET = 'data/progvar_raw'
OUTPUT_DATASET = 'data/progvar_aligned'

def main():
    dir_path = os.path.dirname(os.path.realpath(__file__))

    # clean output dataset
    raw_path = os.path.join(dir_path, RAW_DATASET)
    output_path = os.path.join(dir_path, OUTPUT_DATASET)

    if os.path.exists(output_path):
        print('Cleaning ' + output_path)
        shutil.rmtree(output_path)

    # generate aligned images
    facenet_align = os.path.join('facenet/align/align_dataset_mtcnn.py')
    args = ['python', facenet_align, raw_path, output_path,
        '--gpu_memory_fraction', '0.68']
    os.system(' '.join(args))
    # MTCNN.main(MTCNN.parse_arguments(args))

if __name__ == '__main__':
    main()


"""Use a função map() para aplicar uma função em cada elemento de uma lista"""
print('--------------map-----------------\n')
# usando loop
my_list = [1, 2, 3, 4, 5]
new_list = []
for element in my_list:
    new_list.append(element**2)
print(new_list)

# usando map
my_list = [1, 2, 3, 4, 5]
new_list = list(map(lambda x: x**2, my_list))
print(new_list)

print('\n--------------zip------------------\n')

"""Use a função zip para iterar em multiplas listas em paralelo"""

# usando loop
list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
for i in range(len(list1)):
    for j in range(len(list2)):
        if i == j:
            print(list1[i], list2[j])

# usando a função zip
list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
for item1, item2 in zip(list1, list2):
    print(item1, item2)

"""Slicing para malipular listas
- Extrair
- Manipular
- Criar novas listas a partir de outra existente
"""

print('\n--------------slicing------------------\n')

# usando loop
my_list = [1, 2, 3, 4, 5]
new_list = []
for i in range(1, len(my_list) - 1):
    new_list.append(my_list[i])
print(new_list)

# usando slicing
my_list = [1, 2, 3, 4, 5]
new_list = my_list[1: -1]
print(new_list)


import os
import unittest
from envok import manager

class TestUpdateEnv(unittest.TestCase):
    def test_update_env(self):
        '''Test updating an environment configuration'''
        cwd = os.getcwd()
        path = os.path.join(cwd, 'tests/env.json')
        m = manager.EnvManager(path)
        env = m.update_env('dev', {
            'my_param': 'baz'
        })
        self.assertDictContainsSubset({
            'dev': {
                'account_id': '1223334444',
                'region': 'us-west-2',
                'my_param': 'baz'
            }
        }, env)

if __name__ == '__main__':
    unittest.main()


def make4(ip):
    more = 4 - len(ip)
    if more:
        return '0' * more + ip
    return ip

ip6 = input().split(':')
if ip6[0] == '':
    ip6.pop(0)
elif ip6[-1] == '':
    ip6.pop(-1)

ans = []
for ip in ip6:
    if ip == '':
        for _ in range(8 - len(ip6) + 1):
            ans.append('0000')
    else:
        ans.append(make4(ip))

print(':'.join(ans))


#탭을 4개의 공백으로 바꾸기\
#터미널에서 처음 입력시 python use.p a.txt b.txt #argv[1] = a.txt, argv[2] = b.txt
import sys
src = sys.argv[1]
dst = sys.argv[2]

f = open(src)
tab_content = f.read() #전부 읽어서 tab_content 변수에 넣음
f.close()

space_content = tab_content.replace("\t"," "*4) #space_content는 tab_con에서 tab을 space*4로만 바꾼 변수임
print(space_content)

f = open(dst, 'w')
f.write(space_content)
f.close() #space_content를 dst에 써줌.


# -*- encoding: utf-8 -*-
"""
冒泡排序
当某次冒泡操作已经没有数据交换时，说明已经达到完全有序，不用再继续执行后续的冒泡操作。

算法复杂度：N^2
稳定排序：重复元素排序完后仍然保持原来的相对位置。
"""
from algorithms.c02_sort.base.template import SortTemplate

class BubbleSort(SortTemplate):

    def sort(self):
        le = len(self.seq)
        for i in range(le):
            # 提前退出排序的标志，本次循环是否有数据交换
            has_exchange = False
            for j in range(0, le - i - 1):
                if self.seq[j] > self.seq[j + 1]:
                    self.seq[j], self.seq[j + 1] = self.seq[j + 1], self.seq[j]
                    has_exchange = True  # 表示有数据交换
            if not has_exchange:
                break

if __name__ == '__main__':
    bubble_sort = BubbleSort([4, 2, 5, 1, 6, 3])
    bubble_sort.main()


import numpy as np
#from hypatie.transform import sph2car
from hypatie.simbad import sql2df as simbad_sql2df
from gaiadr3 import sql2df as gaia_sql2df

def in_radius(ra, dec, r):
    s = "CONTAINS(POINT('ICRS', ra, dec), " + \
        f"CIRCLE('ICRS', {ra}, {dec}, {r})) = 1"
    return s

def count(ra, dec, radius, database='gaia', where=None):

    if database.lower()[:4]=='gaia':
        table = 'gaiadr3.gaia_source'
        idcol = 'source_id'
    elif database.lower()=='simbad':
        table = 'basic'
        idcol = 'main_id'
    else:
        raise Exception('Database unknown!')

    where = '' if where is None else ' AND '+where
    s = f'SELECT COUNT({idcol}) AS num FROM {table} '
    s = s + f'WHERE {in_radius(ra, dec, radius)}' + where

    if database.lower()[:4]=='gaia':
        try:
            df,_ = gaia_sql2df(s)
            return df['num'].iloc[0]
        except:
            print('Error in retrieving from server! Try here:')
            print('https://gea.esac.esa.int/archive/\n')
            print(s)

    if database.lower()=='simbad':
        try:
            df = simbad_sql2df(s)
            return int(df['num'].iloc[0])
        except:
            print('Error in retrieving from server! Try here:')
            print('https://simbad.cds.unistra.fr/simbad/sim-tap\n')
            print(s)

def gaia_to_simbad(source_id):
    # ex: gaia_to_simbad(1870117138241890432)
    s1 = "SELECT b.main_id FROM ids AS i "
    s2 = "LEFT JOIN basic AS b ON b.oid=i.oidref "
    s3 = f"WHERE ids LIKE '%Gaia DR3 {source_id}%'"
    df = simbad_sql2df(s1+s2+s3)
    return df


import os

from input_file_reader.input_file_reader import InputFileReader

class CarburizationData:
    def __init__(self, time, temperature, carbon):
        self.time = time
        self.temperature = temperature
        self.carbon = carbon

class TemperatureData:
    def __init__(self, time, temperature, interaction_property_name):
        self.time = time
        self.temperature = temperature
        self.interaction_property_name = interaction_property_name

class QuenchingData:
    def __init__(self, time, temperature, oil_name):
        self.time = time
        self.temperature = temperature
        self.oil_name = oil_name

class CaseHardeningToolbox:
    def __init__(self, name, include_file_name, include_file_directory):
        """
        :param name:  All input files will get the name Toolbox_Simulation_name.inp
                      where simulation is 'Carbon',
        :param include_file_name:
        """
        self._include_file_directory = include_file_directory + '/'

        self.name = name
        self.include_file_name = include_file_name

        self.input_file_reader = InputFileReader()

        self.material = 'U925062'

        self.initial_temperature = 20.
        self.initial_carbon = 0.0022

        self.diffusion_file = None
        self.interaction_property_file = None

        self.heating_data = CarburizationData(time=None, temperature=self.initial_temperature,
                                              carbon=self.initial_carbon)
        self.carburization_steps = []
        self.furnace_interaction_property = 'FURNACE'
        self.hot_air_interaction_property = 'HOT_AIR'
        self.cool_air_interaction_property = 'AIR_COOL'
        self.transfer_data = TemperatureData(time=60., temperature=650., interaction_property_name=None)
        self.quenching_data = QuenchingData(time=None, temperature=None, oil_name='QUENCHWAY125B_Used_0mps')
        self.cooldown_data = TemperatureData(time=600, temperature=80., interaction_property_name=None)
        self.tempering_data = TemperatureData(time=None, temperature=None, interaction_property_name=None)

        self.carbon_file_lines = None
        self.thermal_file_lines = None
        self.mechanical_file_lines = None

        self.total_time = 0.
        self.thermal_step_counter = 1

        self.dante_file = '/scratch/users/erik/Dante/Abaqus_Link/DANTE_Library/dante3_7f_pr1/abq2018_linux/' \
                          'dante3_7f_pr1-std.o'
        self.abaqus_path = '/scratch/users/erik/SIMULIA/CAE/2018/linux_a64/code/bin/ABQLauncher'
        self.dante_path = '/scratch/users/erik/Dante/'

        self.write_env_file = True
        self.write_run_file = True

        self.write_dctrl_file = False
        self.max_temp_inc = 30
        self.max_vf_inc = 0.05
        self.max_carb_inc = 0.0005

    def _init_carbon_file_lines(self):
        return ['**',
                '**',
                '** Autogenerated input file created by Case Hardening Simulation Toolbox, version 0.8.1',
                '** Written by Niklas Melin and Erik Olsson',
                '**',
                '*Heading',
                '\t Case Hardening Simulation Toolbox - Carburization - Niklas Melin 2012',
                '*Preprint, echo=NO, model=NO, history=NO, contact=NO',
                '**',
                '** ----------------------------------------------------------------',
                '** Load required include files',
                '**',
                '**   Load geometry',
                '*INCLUDE, INPUT = ' + self._include_file_directory + '/Toolbox_Carbon_' +
                self.include_file_name + '_geo.inc',
                '** Load geometry set definitions',
                '*INCLUDE, INPUT = ' + self._include_file_directory + self.include_file_name + '_sets.inc',
                '**',
                '** ----------------------------------------------------------------',
                '**',
                '**   Define material properties',
                '**',
                '*Solid Section, elset=All_Elements, material=' + self.material,
                '\t1.0',
                '*Hourglass Stiffness',
                '\t225.0, 0.0, 0.0',
                '**',
                '** DEFINE MATERIAL PROPERTIES',
                '**',
                '*Material, name=' + self.material,
                '\t*Density',
                '\t\t7.83e-06,',
                '\t*Diffusivity',
                '\t\t*INCLUDE, INPUT = ' + self._include_file_directory + self.diffusion_file,
                '\t*Solubility',
                '\t\t1.0',
                '**',
                '**',
                '*INITIAL CONDITIONS, TYPE=CONCENTRATION',
                '\tAll_Nodes , ' + str(self.initial_carbon),
                '*INITIAL CONDITIONS, TYPE=TEMPERATURE',
                '\tAll_Nodes , ' + str(self.initial_temperature),
                '**']

    def _init_thermal_lines(self):
        return ['**',
                '**',
                '** Autogenerated input file created by Case Hardening Simulation Toolbox, version 0.8.1',
                '** Written by Niklas Melin and Erik Olsson',
                '**',
                '*Heading',
                '\t Case Hardening Simulation Toolbox - Thermal - Niklas Melin 2012',
                '*Preprint, echo=NO, model=NO, history=NO, contact=NO',
                '**',
                '** ----------------------------------------------------------------',
                '** Load required include files',
                '**',
                '**   Load geometry',
                '*INCLUDE, INPUT = ' + self._include_file_directory +
                'Toolbox_Thermal_' + self.include_file_name + '_geo.inc',
                '** Load geometry set definitions',
                '*INCLUDE, INPUT = ' + self._include_file_directory + self.include_file_name + '_sets.inc',
                '**',
                '** ----------------------------------------------------------------',
                '**',
                '**   Define material properties',
                '**',
                '*Solid Section, elset=All_Elements, material=' + self.material,
                '\t1.0',
                '*Hourglass Stiffness',
                '\t225.0, 0.0, 0.0',
                '**',
                '** DEFINE MATERIAL PROPERTIES',
                '**',
                '*Material, name=' + self.material,
                '\t*Density',
                '\t\t7.83e-06,',
                '\t*Depvar',
                '\t\t100,',
                '\t\t1,  CARBON,       VOLUME FRACTION of CARBON',
                '\t\t2,  HARDNESS,     Hardness in Rockwell C',
                '\t\t21, AUSTENITE,    VOLUME FRACTION of AUSTENITE',
                '\t\t34, FERRITE,      VOLUME FRACTION of FERRITE',
                '\t\t47, PEARLITE,     VOLUME FRACTION of PEARLITE',
                '\t\t60, UBAINITE,     VOLUME FRACTION of UPPER BAINITE',
                '\t\t73, LBAINITE,     VOLUME FRACTION of LOWER BAINITE',
                '\t\t86, Q_MARTENSITE, VOLUME FRACTION of QUENCHED MARTENSITE',
                '\t\t99, T_MARTENSITE, VOLUME FRACTION of TEMPERED MARTENSITE',
                '\t*User Material, constants=8, type=THERMAL',
                '\t\t7.83e-06, 0, 0.50, 0.50, 0.00, 0.00, 0.00, 0.00',
                '**',
                '** ----------------------------------------------------------------',
                '*INCLUDE, INPUT = ' + self._include_file_directory + self.interaction_property_file,
                '** ----------------------------------------------------------------',
                '** Set initial temperature',
                '*INITIAL CONDITIONS, TYPE=TEMPERATURE',
                '\tALL_NODES , ' + str(self.initial_temperature),
                '**',
                '** Set initial carbon content',
                '*INITIAL CONDITIONS, TYPE=FIELD, VAR=1',
                '\tALL_NODES , ' + str(self.initial_carbon),
                '**',
                '** Set analysis kinematics type to -8, (2 heating up kinetics, -2 cooling kinetics without tempering',
                '*INITIAL CONDITIONS, TYPE=FIELD, VAR=2',
                '\tALL_NODES , -8',
                '**']

    def _init_mechanical_lines(self):
        return ['**',
                '**',
                '** Autogenerated input file created by Case Hardening Simulation Toolbox, version 0.8.1',
                '** Written by Niklas Melin and Erik Olsson',
                '**',
                '*Heading',
                '\t Case Hardening Simulation Toolbox - Mechanical - Niklas Melin 2012',
                '*Preprint, echo=NO, model=NO, history=NO, contact=NO',
                '**',
                '** ----------------------------------------------------------------',
                '** Load required include files',
                '**',
                '**   Load geometry',
                '*INCLUDE, INPUT = ' + self._include_file_directory + 'Toolbox_Mechanical_'
                + self.include_file_name + '_geo.inc',
                '** Load geometry set definitions',
                '*INCLUDE, INPUT = ' + self._include_file_directory + self.include_file_name + '_sets.inc',
                '**',
                '** ----------------------------------------------------------------',
                '**',
                '**   Define material properties',
                '**',
                '*Solid Section, elset=All_Elements, material=' + self.material,
                '\t1.0',
                '*Hourglass Stiffness',
                '\t225.0, 0.0, 0.0',
                '**',
                '** DEFINE MATERIAL PROPERTIES',
                '**',
                '*Material, name=' + self.material,
                '\t*Density',
                '\t\t7.83e-06,',
                '\t*Depvar',
                '\t\t100,',
                '\t\t1,  CARBON,       VOLUME FRACTION of CARBON',
                '\t\t2,  HARDNESS,     Hardness in Rockwell C',
                '\t\t5,  PLASTIC STRAIN, EFFECTIVE PLASTIC STRAIN',
                '\t\t21, AUSTENITE,    VOLUME FRACTION of AUSTENITE',
                '\t\t34, FERRITE,      VOLUME FRACTION of FERRITE',
                '\t\t47, PEARLITE,     VOLUME FRACTION of PEARLITE',
                '\t\t60, UBAINITE,     VOLUME FRACTION of UPPER BAINITE',
                '\t\t73, LBAINITE,     VOLUME FRACTION of LOWER BAINITE',
                '\t\t86, Q_MARTENSITE, VOLUME FRACTION of QUENCHED MARTENSITE',
                '\t\t99, T_MARTENSITE, VOLUME FRACTION of TEMPERED MARTENSITE',
                '\t*User Material, constants=8, type=MECHANICAL',
                '\t\t1, 0, 0.50, 0.50, 0.00, 0.00, 0.00, 0.00',
                '**',
                '** Set initial temperature',
                '*INITIAL CONDITIONS, TYPE=TEMPERATURE',
                '\tALL_NODES , ' + str(20.),
                '**',
                '** Set initial carbon content',
                '*INITIAL CONDITIONS, TYPE=FIELD, VAR=1',
                '\tALL_NODES , ' + str(self.initial_carbon),
                '**',
                '** Set analysis kinematics type to -8, (2 heating up kinetics, -2 cooling kinetics without tempering',
                '*INITIAL CONDITIONS, TYPE=FIELD, VAR=2',
                '\tALL_NODES , -8',
                '**',
                '*INCLUDE, INPUT = ' + self._include_file_directory + self.include_file_name + '_BC.inc']

    def _write_carburization_step(self, step_name, t1, t2, carbon):
        self.carbon_file_lines.append('*STEP,NAME=' + step_name + ', INC=10000')
        self.carbon_file_lines.append('\t' + step_name + ' - Total time: ' + str(t1) + ' - ' +
                                      str(t2) + 's, Carbon: ' + str(carbon) + '%')
        self.carbon_file_lines.append('\t*MASS DIFFUSION, DCMAX=0.001')
        self.carbon_file_lines.append('\t\t0.2,  ' + str(t2 - t1) + ', 1e-05,  10000')
        self.carbon_file_lines.append('\t*TEMPERATURE, AMPLITUDE=TEMP_AMPLITUDE')
        self.carbon_file_lines.append('\t\tAll_Nodes')
        self.carbon_file_lines.append('\t*BOUNDARY')
        self.carbon_file_lines.append('\t\tEXPOSED_NODES, 11, 11, ' + str(carbon / 100))
        self.carbon_file_lines.append('\t*MONITOR, NODE=monitor_node, DOF=11, FREQ=1')
        self.carbon_file_lines.append('\t*Output, field, frequency=1')
        self.carbon_file_lines.append('\t\t*Node Output')
        self.carbon_file_lines.append('\t\t\tNNC, NT')
        self.carbon_file_lines.append('\t\t*Element Output, directions=YES')
        self.carbon_file_lines.append('\t\t\tCONC')
        self.carbon_file_lines.append('\t\t*Element Output, directions=YES,  POSITION=NODES')
        self.carbon_file_lines.append('\t\t\tCONC')
        self.carbon_file_lines.append('*END STEP')
        self.carbon_file_lines.append('**')

        self.thermal_file_lines.append('*STEP,NAME=' + step_name + ', INC=10000')
        self.thermal_file_lines.append('\t*HEAT TRANSFER, DELTMX=10.0, END=PERIOD')
        self.thermal_file_lines.append('\t\t0.01,  ' + str(t2 - t1) + ', 1e-05,  10000')
        self.thermal_file_lines.append('\t*CONTROLS, PARAMETERS = LINE SEARCH')
        self.thermal_file_lines.append('\t\t6,')
        self.thermal_file_lines.append('\t*CONTROLS, PARAMETERS = TIME INCREMENTATION')
        self.thermal_file_lines.append('\t\t20, 30')
        self.thermal_file_lines.append('\t*CONTROLS, FIELD = TEMPERATURE, PARAMETERS = FIELD')
        self.thermal_file_lines.append('\t\t0.05, 0.05')
        self.thermal_file_lines.append('\t*SFILM, OP = NEW, AMPLITUDE=TEMP_AMPLITUDE')
        self.thermal_file_lines.append('\t\tEXPOSED_SURFACE, F, 1.000000, ' + self.furnace_interaction_property)
        self.thermal_file_lines.append('\t*MONITOR, NODE = MONITOR_NODE, DOF=11, FREQ=1')
        self.thermal_file_lines.append('\t*RESTART, WRITE, FREQ=1000')
        self.thermal_file_lines.append('\t*OUTPUT, FIELD, FREQ=1')
        self.thermal_file_lines.append('\t\t*ELEMENT OUTPUT')
        self.thermal_file_lines.append('\t\t\tSDV1, SDV21, SDV34, SDV47, SDV60, SDV73, SDV86, HFL')
        self.thermal_file_lines.append('\t*OUTPUT, FIELD, FREQ=1')
        self.thermal_file_lines.append('\t\t*NODE OUTPUT')
        self.thermal_file_lines.append('\t\t\tNT')
        self.thermal_file_lines.append('\t*EL FILE, FREQUENCY=0')
        self.thermal_file_lines.append('\t*NODE FILE, FREQUENCY=1')
        self.thermal_file_lines.append('\t\tNT')
        self.thermal_file_lines.append('\t*EL PRINT, FREQ=0')
        self.thermal_file_lines.append('\t*NODE PRINT, FREQ=0')
        self.thermal_file_lines.append('*END STEP')
        self.thermal_file_lines.append('**')

        self.mechanical_file_lines.append('*STEP,NAME=' + step_name + ', INC=10000')
        self.mechanical_file_lines.append('\tMechanical simulation')
        self.mechanical_file_lines.append('\t*STATIC')
        self.mechanical_file_lines.append('\t\t0.01,  ' + str(t2 - t1) + ', 1e-05,  10000')
        self.mechanical_file_lines.append('\t*TEMPERATURE, FILE=Toolbox_Thermal_' + self.name + '.odb, '
                                          'BSTEP=' + str(self.thermal_step_counter) + ', ESTEP=' +
                                          str(self.thermal_step_counter))
        self.mechanical_file_lines.append('\t** Add convergence control parameters')
        self.mechanical_file_lines.append('\t*CONTROLS, PARAMETERS = LINE  SEARCH')
        self.mechanical_file_lines.append('\t\t6,')
        self.mechanical_file_lines.append('\t*CONTROLS, PARAMETERS = TIME INCREMENTATION')
        self.mechanical_file_lines.append('\t\t20, 30')
        self.mechanical_file_lines.append('\t*CONTROLS, FIELD = DISPLACEMENT, PARAMETERS = FIELD')
        self.mechanical_file_lines.append('\t\t0.05, 0.05')
        self.mechanical_file_lines.append('\t** Add output variables')
        self.mechanical_file_lines.append('\t*RESTART, WRITE, FREQ = 1000')
        self.mechanical_file_lines.append('\t*MONITOR, NODE = MONITOR_NODE, DOF = 1, FREQ = 1')
        self.mechanical_file_lines.append('\t*OUTPUT, FIELD, FREQ = 10')
        self.mechanical_file_lines.append('\t\t*ELEMENT OUTPUT, directions = YES')
        self.mechanical_file_lines.append('\t\t\tS, E')
        self.mechanical_file_lines.append('\t*OUTPUT, FIELD, FREQ = 10')
        self.mechanical_file_lines.append('\t\t*ELEMENT OUTPUT')
        self.mechanical_file_lines.append('\t\t\tSDV1, SDV2, SDV5, SDV21, SDV34, SDV47, SDV60, SDV73, SDV86, SDV99')
        self.mechanical_file_lines.append('\t*OUTPUT, FIELD, FREQ = 10')
        self.mechanical_file_lines.append('\t\t*NODE OUTPUT')
        self.mechanical_file_lines.append('\t\t\tNT, U')
        self.mechanical_file_lines.append('*END  STEP')
        self.mechanical_file_lines.append('**')
        self.thermal_step_counter += 1

    def add_carburization_steps(self, times, temperatures, carbon_levels):
        for t, temp, carbon in zip(times, temperatures, carbon_levels):
            self.carburization_steps.append(CarburizationData(time=t*60, temperature=temp, carbon=carbon))

    @staticmethod
    def _thermal_step_data(step_name, step_description, step_time, surface_temperature, interaction_property,
                           kinematic_mode, output_frequency=5, step_amp='STEP'):
        return ['*STEP,NAME=' + step_name + ' , INC=10000, AMP=' + step_amp,
                '\t' + step_description,
                '\t*HEAT TRANSFER, DELTMX=10.0, END=PERIOD',
                '\t\t0.01,  ' + str(step_time) + ', 1e-09,  1000.',
                '\t*FIELD, OP=NEW, VAR = 2',
                '\t\tAll_Nodes, ' + str(kinematic_mode),
                '\t*SFILM, OP=NEW',
                '\t\tEXPOSED_SURFACE,F, ' + str(surface_temperature) + ', ' + interaction_property,
                '\t*MONITOR, NODE=MONITOR_NODE, DOF=11, FREQ=1',
                '\t*CONTROLS, PARAMETERS=LINE SEARCH',
                '\t\t 6,',
                '\t*CONTROLS, PARAMETERS=TIME INCREMENTATION',
                '\t\t20, 30, 9, 16, 10, 4, 12, 20',
                '\t*CONTROLS, FIELD=TEMPERATURE, PARAMETERS=FIELD',
                '\t\t0.05, 0.05',
                '\t*RESTART, WRITE, FREQ=1000',
                '\t*OUTPUT, FIELD, FREQ=' + str(output_frequency),
                '\t\t*ELEMENT OUTPUT',
                '\t\t\tSDV1,SDV2,SDV21,SDV34,SDV47,SDV60,SDV73,SDV86,SDV99,HFL',
                '\t*OUTPUT, FIELD, FREQ=' + str(output_frequency),
                '\t\t*NODE OUTPUT',
                '\t\t\tNT',
                '\t\t*EL FILE, FREQUENCY=0',
                '\t\t*NODE FILE, FREQUENCY=1',
                '\t\t\tNT',
                '\t\t*EL PRINT, FREQ=0',
                '\t\t*NODE PRINT, FREQ=0',
                '*END STEP',
                '**']

    def _mechanical_step_data(self, step_name, step_description, step_time, kinematic_mode, output_frequency=5,
                              max_increment=1000., step_amp='STEP'):
        return ['*STEP, NAME=' + step_name + ', inc=10000, AMP=' + step_amp,
                '\t' + step_description,
                '\t*STATIC',
                '\t\t0.01,  ' + str(step_time) + ', 1e-05,  ' + str(max_increment),
                '\t*FIELD, OP=NEW, VAR=2',
                '\t\tAll_Nodes,  ' + str(kinematic_mode),
                '\t*TEMPERATURE, FILE=Toolbox_Thermal_' + self.name + '.odb, BSTEP = ' +
                str(self.thermal_step_counter) + ', ESTEP = ' + str(self.thermal_step_counter),
                '\t*CONTROLS, PARAMETERS=LINE SEARCH',
                '\t\t 6,',
                '\t*CONTROLS, PARAMETERS=TIME INCREMENTATION',
                '\t\t20, 30',
                '\t*CONTROLS, FIELD=DISPLACEMENT, PARAMETERS=FIELD',
                '\t\t0.05, 0.05',
                '\t*RESTART, WRITE, FREQ=1000',
                '\t*MONITOR, NODE=MONITOR_NODE, DOF=1, FREQ=1',
                '\t*OUTPUT, FIELD, FREQ=' + str(output_frequency),
                '\t\t*ELEMENT OUTPUT, directions=YES',
                '\t\t\tS, E',
                '\t*OUTPUT, FIELD, FREQ=' + str(output_frequency),
                '\t\t*ELEMENT OUTPUT',
                '\t\t\tSDV1,SDV2,SDV5,SDV21,SDV34,SDV47,SDV60,SDV73,SDV86,SDV99',
                '\t*OUTPUT, FIELD, FREQ=' + str(output_frequency),
                '\t\t*NODE OUTPUT',
                '\t\t\tNT,U',
                '*END STEP',
                '**']

    def _add_add_carbon_step(self):
        step_lines = self._mechanical_step_data(step_name='Add carbon',
                                                step_description='Import carbon content from mass diffusion simulation',
                                                step_time=1.0,
                                                kinematic_mode=-8,
                                                output_frequency=10, step_amp='RAMP')

        step_lines[6] = '\t*FIELD, VAR=1,  INPUT=Toolbox_Carbon_' + self.name + '.nod'
        self.mechanical_file_lines += step_lines

    def _add_transfer_step(self):
        step_name = 'Transfer'
        step_description = 'Transfer from furnace to quench tank in air'
        interaction_property = self.hot_air_interaction_property
        if self.transfer_data.interaction_property_name is not None:
            interaction_property = self.transfer_data.interaction_property_name

        step_lines = self._thermal_step_data(step_name=step_name,
                                             step_description=step_description,
                                             step_time=self.transfer_data.time,
                                             surface_temperature=self.transfer_data.temperature,
                                             interaction_property=interaction_property,
                                             kinematic_mode=-8,
                                             output_frequency=10)

        step_lines.insert(4, '\t*FIELD, VAR=1,  INPUT=Toolbox_Carbon_' + self.name + '.nod')

        self.thermal_file_lines += step_lines

        self.mechanical_file_lines += self._mechanical_step_data(step_name=step_name,
                                                                 step_description=step_description,
                                                                 step_time=self.transfer_data.time,
                                                                 kinematic_mode=-8,
                                                                 output_frequency=10)
        self.thermal_step_counter += 1

    def _add_quenching_step(self):
        step_name = 'Quenching'
        step_description = 'Quenching in oil ' + self.quenching_data.oil_name
        self.thermal_file_lines += self._thermal_step_data(step_name=step_name,
                                                           step_description=step_description,
                                                           step_time=self.quenching_data.time,
                                                           surface_temperature=self.quenching_data.temperature,
                                                           interaction_property=self.quenching_data.oil_name,
                                                           kinematic_mode=-8,
                                                           output_frequency=1)

        self.mechanical_file_lines += self._mechanical_step_data(step_name=step_name,
                                                                 step_description=step_description,
                                                                 step_time=self.quenching_data.time,
                                                                 kinematic_mode=-8,
                                                                 output_frequency=10)

        self.thermal_step_counter += 1

    def _add_cooldown_step(self, step_name, kinematic_mode, time, temperature):
        step_description = 'Cooling'
        interaction_property = self.cool_air_interaction_property
        if self.cooldown_data.interaction_property_name is not None:
            interaction_property = self.cooldown_data.interaction_property_name

        self.thermal_file_lines += self._thermal_step_data(step_name=step_name,
                                                           step_description=step_description,
                                                           step_time=time,
                                                           surface_temperature=temperature,
                                                           interaction_property=interaction_property,
                                                           kinematic_mode=kinematic_mode,
                                                           output_frequency=1)

        self.mechanical_file_lines += self._mechanical_step_data(step_name=step_name,
                                                                 step_description=step_description,
                                                                 step_time=time,
                                                                 kinematic_mode=kinematic_mode,
                                                                 output_frequency=10)

        self.thermal_step_counter += 1

    def _add_tempering_step(self):
        step_name = 'Tempering'
        step_description = 'Tempering'
        interaction_property = self.cool_air_interaction_property
        if self.tempering_data.interaction_property_name is not None:
            interaction_property = self.tempering_data.interaction_property_name

        self.thermal_file_lines += self._thermal_step_data(step_name=step_name,
                                                           step_description=step_description,
                                                           step_time=self.tempering_data.time,
                                                           surface_temperature=self.tempering_data.temperature,
                                                           interaction_property=interaction_property,
                                                           kinematic_mode=-3,
                                                           output_frequency=1)

        self.mechanical_file_lines += self._mechanical_step_data(step_name=step_name,
                                                                 step_description=step_description,
                                                                 step_time=self.tempering_data.time,
                                                                 kinematic_mode=-3,
                                                                 output_frequency=10,
                                                                 max_increment=50)
        self.thermal_step_counter += 1

    def write_files(self):
        self.carbon_file_lines = self._init_carbon_file_lines()
        self.thermal_file_lines = self._init_thermal_lines()
        self.mechanical_file_lines = self._init_mechanical_lines()

        for line_set in [self.carbon_file_lines, self.thermal_file_lines]:
            line_set.append('*AMPLITUDE, NAME=TEMP_AMPLITUDE, TIME=TOTAL TIME, VALUE=ABSOLUTE')
            line_set.append('\t ' + str(0.) + ', \t ' + str(self.initial_temperature))
            total_time = 0.
            if self.heating_data.time is not None:
                line_set.append('\t ' + str(60.) + ', \t ' + str(self.heating_data.temperature))
                line_set.append('\t ' + str(self.heating_data.time*60) + ', \t ' +
                                str(self.heating_data.temperature))
                total_time = self.heating_data.time*60

            for carb_step in self.carburization_steps:
                line_set.append('\t ' + str(total_time + 60.) + ', \t ' + str(carb_step.temperature))
                line_set.append('\t ' + str(total_time + carb_step.time) + ', \t ' + str(carb_step.temperature))
                total_time += carb_step.time
            line_set.append('**')

        # Add a heating step
        if self.heating_data.time is not None:
            self._write_carburization_step('Heating', self.total_time, self.total_time + self.heating_data.time*60,
                                           self.heating_data.carbon)
            self.total_time += self.heating_data.time*60

        # Add the carburization steps
        for i, carburization_step in enumerate(self.carburization_steps):
            step_name = 'Carburization - ' + str(i+1)
            self._write_carburization_step(step_name, self.total_time, self.total_time + carburization_step.time,
                                           carburization_step.carbon)
            self.total_time += carburization_step.time

        # Add the add carbon step to the mechanical input file
        self._add_add_carbon_step()

        # Add step for transfer from oven to quench bath
        if self.transfer_data.time is not None and self.transfer_data.time > 0.:
            self._add_transfer_step()

        if self.quenching_data.time is not None and self.quenching_data.time > 0.:
            self._add_quenching_step()

        if self.cooldown_data.time is not None and self.cooldown_data.time > 0.:
            self._add_cooldown_step('Cooldown_1', kinematic_mode=-8, time=self.cooldown_data.time,
                                    temperature=self.cooldown_data.temperature)

        if self.tempering_data.time is not None and self.tempering_data.time > 0:
            self._add_cooldown_step('Heating_tempering', kinematic_mode=1, time=3600.,
                                    temperature=self.tempering_data.temperature)
            self._add_tempering_step()

        self._add_cooldown_step('Cooldown_3', kinematic_mode=1, time=3600,
                                temperature=self.cooldown_data.temperature)

        for name, lines in zip(['Carbon', 'Thermal', 'Mechanical'],
                               [self.carbon_file_lines, self.thermal_file_lines, self.mechanical_file_lines]):
            with open('Toolbox_' + name + '_' + self.name + '.inp', 'w+') as inp_file:
                for line in lines:
                    inp_file.write(line + '\n')
                inp_file.write('**EOF')

        if self.write_env_file:
            self._write_env_file()

        if self.write_run_file:
            self._write_run_file()

        if self.write_dctrl_file:
            self._write_dctrl_file()

    def _write_env_file(self):
        file_lines = ['# Settings for dante',
                      'usub_lib_dir=\'' + os.path.dirname(self.dante_file) + '\'',
                      '',
                      'ask_delete = OFF'
                      '# MPI Configuration',
                      'mp_mode = MPI']

        with open('abaqus_v6.env', 'w') as env_file:
            for line in file_lines:
                env_file.write(line + '\n')

    def _write_run_file(self):
        file_lines = ['#!/bin/bash',
                      '#PBS -V',
                      '#PBS -z',
                      '#PBS -l select=1:ncpus=8',
                      'cd $PBS_O_WORKDIR',
                      'export LD_PRELOAD=\"\"',
                      'abq=' + self.abaqus_path,
                      'usersub_dir=' + self.dante_file,
                      'export DANTE_PATH=\'' + self.dante_path + '/DANTEDB3_6\'',
                      '',
                      'sim_name=' + self.name,
                      'carbon_exp_script=' + self.dante_path + '/python/carbonFieldExport.py',
                      '${abq} j=Toolbox_Carbon_${sim_name} cpus=8 interactive',
                      '${abq} python ${carbon_exp_script} odbFileName=Toolbox_Carbon_${sim_name}.odb '
                      'carbonFileName=Toolbox_Carbon_${sim_name}.nod',
                      '${abq} j=Toolbox_Thermal_${sim_name} cpus=8 interactive user=${usersub_dir}',
                      '${abq} j=Toolbox_Mechanical_${sim_name} cpus=8 interactive user=${usersub_dir}']

        with open('run_heat_treatment_sim.sh', 'w') as shell_file:
            for line in file_lines:
                shell_file.write(line + '\n')

    def _write_dctrl_file(self):
        file_lines = ['## line1: ADVANCED DANTE CONTROL FILE FOR LIMITING CHANGES OF',
                      '## line2: TEMPERATURE, VOLUME FRACTION AND CARBON IN ONE INCREMENT',
                      '## line3: THE FILE FORMAT IS NOT ALLOWED TO CHANGE',
                      '## line4: maximum temperature change in one increment (default 30.0)',
                      str(self.max_temp_inc),
                      '## line6: maximum VF change in one increment (default: 0.20)',
                      str(self.max_vf_inc),
                      '## line8: maximum carbon change in one increment (default: 0.0005)',
                      str(self.max_carb_inc),
                      '## line10: end of file']

        with open('DCTRL.CTL', 'w') as ctl_file:
            for line in file_lines:
                ctl_file.write(line + '\n')

def write_geometry_files_for_dante(geometry_data_file, directory_to_write, dante_include_file_name,
                                   str_to_remove_from_set_names=''):
    input_file_reader = InputFileReader()
    input_file_reader.read_input_file(geometry_data_file)
    if not os.path.isdir(directory_to_write):
        os.makedirs(directory_to_write)

    input_file_reader.write_geom_include_file(directory_to_write + '/Toolbox_Carbon_' +
                                              dante_include_file_name + '_geo.inc',
                                              simulation_type='Carbon')

    input_file_reader.write_geom_include_file(directory_to_write + '/Toolbox_Thermal_' +
                                              dante_include_file_name + '_geo.inc',
                                              simulation_type='Thermal')

    input_file_reader.write_geom_include_file(directory_to_write + '/Toolbox_Mechanical_' +
                                              dante_include_file_name + '_geo.inc',
                                              simulation_type='Mechanical')

    surfaces = [('EXPOSED_SURFACE', 'EXPOSED_ELEMENTS')]
    input_file_reader.write_sets_file(directory_to_write + dante_include_file_name + '_sets.inc',
                                      str_to_remove_from_setname=str_to_remove_from_set_names,
                                      surfaces_from_element_sets=surfaces)


# rice cake cutter
# there is an array of rice cakes
# cutter cuts rice cakes at height H
# sum of the cut off cakes' length must be greater than equal to M

# find the max height to cut to get at least M number of rice cakes
from bisect import bisect_right

n, m = map(int, input().split())
rice = list(map(int,input().split()))

# rice.sort()
# mid = len(rice) // 2
# prev_mid = len(rice)
# greatest = 0
# while True:
#     total = 2 * len(rice) - bisect_right(rice, rice[mid])
#     if total >= m:
#         if total < greatest:
#             break
#         greatest = total
#         h = rice[mid]
#     elif not mid:
#         h = -1
#         break

#     if total >= m:
#         prev_mid = mid
#         mid = mid + (prev_mid - mid) // 2
#         if mid == prev_mid:
#             break
#     else:
#         prev_mid = mid
#         mid = prev_mid // 2

# if h < 0:
#     h = min(rice) - 1
# print(h)

start = 0
end = max(rice)
greatest = 0
while start <= end:
    mid = (start + end) // 2
    total = 0
    for i in rice:
        if i > mid:
            total += i - mid
    if total >= m:
        greatest = mid
        start = mid + 1
    else:
        end = mid - 1
print(greatest)


import io
from module import Text, Replace, Shift, ReplaceNum, Type
import pytest

@pytest.mark.parametrize("test_input,line,author",
                         [("1; abc; I\n", 'abc', 'I'), ("2; hello; Roma; 3\n", 'hello', 'Roma')])
def test_read_from(test_input, line, author):
    text = Text()
    text.read_from(test_input)

    assert text.line_symbol == line
    assert text.author == author

@pytest.mark.parametrize("line,author",
                         [('abcde', 'Boris'), ('test2', 'Arkasha')])
def test_write_to(line, author):
    output = io.StringIO()
    text = Text()
    text.line_symbol = line
    text.author = author
    text.key = Type.replacement
    text.obj = Replace()
    text.obj.read_from(text.line_symbol)
    length = text.number_of_symbols()
    text.write_to(output)

    output.seek(0)

    test_str = f'[Replacement method]\n' \
               f'String: {line}\n' \
               f'Author: {author}\n' \
               f'String length: {length}\n' \
               f'Encrypt message: {text.obj.encrypt_line}\n'

    assert output.read() == test_str

@pytest.mark.parametrize("line,author,meth",
                         [('abcde', 'Boris', Type.replacement), ('test2', 'Arkasha', Type.shift)])
def test_write_to_replace(line, author, meth):
    output = io.StringIO()
    text = Text()
    text.line_symbol = line
    text.author = author
    if meth == Type.replacement:
        text.key = meth
        text.obj = Replace()
        text.obj.read_from(text.line_symbol)
    else:
        text.key = 0
        text.obj = Shift()

    length = text.number_of_symbols()
    text.write_to_replace(output)
    test_str = ''
    output.seek(0)
    if meth == Type.replacement:
        test_str = f'[Replacement method]\n' \
                   f'String: {line}\n' \
                   f'Author: {author}\n' \
                   f'String length: {length}\n' \
                   f'Encrypt message: {text.obj.encrypt_line}\n'

    assert output.read() == test_str

@pytest.mark.parametrize('mes, count', [
    ('hello world', 11),
    ('it is secret', 12),
    ('abcds', 5),
])
def test_number_sym(mes, count):
    text = Text()
    text.line_symbol = mes
    assert text.number_of_symbols() == count


from tkinter import *
from functools import partial  # To prevent unwanted windows

import random

class Converter:
    def __init__(self, parent):

        # Formatting Variables
        background_colour = '#2883F4'

        # List to Hold Calculation History
        self.all_calc_list = []

        # Converter Frame
        self.converter_frame = Frame(bg=background_colour, pady=10)
        self.converter_frame.grid()

        # Temperature Converter Heading
        self.temp_heading_label = Label(self.converter_frame, text="Temperature Converter",
                                        font=('Arial', '19', 'bold'), bg=background_colour,
                                        padx=10, pady=10)
        self.temp_heading_label.grid(row=0)

        # User Instructions
        self.temp_instructions_label = Label(self.converter_frame, text="Type in the amount to be converted "
                                             "and then push one of the buttons below:", wrap=290, padx=10,
                                             pady=10, font=('Arial', '10', 'italic'), justify=LEFT,
                                             bg=background_colour)
        self.temp_instructions_label.grid(row=1)

        # Temperature Entry Box
        self.to_convert_entry = Entry(self.converter_frame, width=20, font=('Arial', '14', 'bold'))
        self.to_convert_entry.grid(row=2)

        # Conversion Buttons Frame
        self.conversion_buttons_frame = Frame(self.converter_frame)
        self.conversion_buttons_frame.grid(row=3, pady=10)

        self.to_c_button = Button(self.conversion_buttons_frame, text="To Centigrade", bg="#FC8621",
                                  font=('Arial', '10', 'bold'), padx=10, pady=10,
                                  command=lambda: self.temp_convert(-459))
        self.to_c_button.grid(row=0, column=0)

        self.to_f_button = Button(self.conversion_buttons_frame, text="To Fahrenheit", bg="#FC8621",
                                  font=('Arial', '10', 'bold'), padx=10, pady=10,
                                  command=lambda: self.temp_convert(-273))
        self.to_f_button.grid(row=0, column=1)

        # Answer Label
        self.converted_label = Label(self.converter_frame, font=("Arial", "12", "bold"), fg="purple",
                                     bg=background_colour, pady=10)
        self.converted_label.grid(row=4)

        # History + Help Button Frame
        self.hist_help_frame = Frame(self.converter_frame)
        self.hist_help_frame.grid(row=5, pady=10)

        self.history_button = Button(self.hist_help_frame, font=("Arial", "12", "bold"), width=15,
                                     text="Calculation History", command=lambda: self.history(self.all_calc_list))
        self.history_button.grid(row=0, column=0)

        if len(self.all_calc_list) == 0:
            self.history_button.config(state=DISABLED)

        self.help_button = Button(self.hist_help_frame, font=("Arial", "12", "bold"), width=5,
                                  text="Help")
        self.help_button.grid(row=0, column=1)

    def temp_convert(self, low):
        error = "#ffafaf"

        # Retrieve amount in text box
        to_convert = self.to_convert_entry.get()

        # Check amount is valid
        try:
            to_convert = float(to_convert)
            has_errors = "no"

            # Convert to F
            if low == -273 and to_convert >= low:
                fahrenheit = (to_convert * 9/5) + 32
                to_convert = self.rounding(to_convert)
                fahrenheit = self.rounding(fahrenheit)
                answer = "{} degrees C is {} degrees F" .format(to_convert, fahrenheit)

            # Convert to C
            elif low == -459 and to_convert >= low:
                celsius = (to_convert - 32) * 5/9
                to_convert = self.rounding(to_convert)
                celsius = self.rounding(celsius)
                answer = "{} degrees F is {} degrees C" .format(to_convert, celsius)

            else:
                # Input is too cold
                answer = "Too Cold!"
                has_errors = "yes"

            # Display Answer
            if has_errors == "no":
                self.converted_label.configure(text=answer, fg="blue")
                self.to_convert_entry.configure(bg="white")

            else:
                self.converted_label.configure(text=answer, fg="red")
                self.to_convert_entry.configure(bg=error)

            # Add answer to list
            if has_errors != "yes":
                self.all_calc_list.append(answer)
                self.history_button.config(state=NORMAL)

        # Store Answer

        except ValueError:
            self.converted_label.configure(text="Please enter a number!", fg="red")
            self.to_convert_entry.configure(bg=error)

    def rounding(self, to_round):
        if to_round % 1 == 0:
            rounded = int(to_round)

        else:
            rounded = round(to_round, 1)

        return rounded

    def history(self, calc_history):
        History(self, calc_history)

class History:
    def __init__(self, partner, calc_history):

        background = "orange"

        # Disable History Button
        partner.history_button.config(state=DISABLED)

        # Set up child window (history box)
        self.history_box = Toplevel()

        # Release History Button if cross is used
        self.history_box.protocol('WM_DELETE_WINDOW', partial(self.close_history, partner))

        # Set up GUI Frame
        self.history_frame = Frame(self.history_box, bg=background, width=300)
        self.history_frame.grid()

        # History Heading
        self.history_heading = Label(self.history_frame, text="Calculation History",
                                     font=("Arial", "10", "bold"), bg=background)
        self.history_heading.grid(row=0)

        # History Text
        self.history_text = Label(self.history_frame, text="Here are you most recent calculations. "
                                                           "Use the export button to create a txt file of all "
                                                           "your calculations for this session.", wrap=250,
                                  font=("arial", "10", "italic"), justify=LEFT, width=40, bg=background)
        self.history_text.grid(row=1)

        # Generate string from Calculation List
        history_string = ""

        if len(calc_history) > 7:
            for item in range(0, 7):
                history_string += calc_history[len(calc_history) - item - 1] + "\n"
        else:
            for item in calc_history:
                history_string += calc_history[len(calc_history) - calc_history.index(item) - 1] + "\n"

                self.history_text.config(text="Here is your calculation history. You can use the export data to save "
                                              "this data to a txt file if desired.")

        # Display Calc History
        self.calc_label = Label(self.history_frame, text=history_string, bg=background,
                                font=("arial", "12"), justify=LEFT)
        self.calc_label.grid(row=2)

        # Export / Dismiss Button Frame
        self.export_dismiss_frame = Frame(self.history_frame)
        self.export_dismiss_frame.grid(row=3, pady=10)

        # Export Button
        self.export_button = Button(self.export_dismiss_frame, text="Export", font=("arial", "12", "bold"))
        self.export_button.grid(row=0, column=0)

        # Dismiss Button
        self.dismiss_button = Button(self.export_dismiss_frame, text="Dismiss", font=("arial", "12", "bold"),
                                     command=partial(self.close_history, partner))
        self.dismiss_button.grid(row=0, column=1)

    def close_history(self, partner):

        # Put history button back to normal
        partner.history_button.config(state=NORMAL)
        self.history_box.destroy()

# main routine
if __name__ == "__main__":
    root = Tk()
    root.title("Temperature Convertor")
    something = Converter(root)
    root.mainloop()


import http.client
import json
from pprint import pprint
from datetime import datetime, date
import time
import datetime
import math
from espncricinfo.summary import Summary

def diff(stime):
    a = time.strptime(stime[:19], '%Y-%m-%dT%H:%M:%S')
    t = datetime.datetime.utcnow()
    ISO_8601_time = t.isoformat()
    b = time.strptime(str(ISO_8601_time)[:19], '%Y-%m-%dT%H:%M:%S')
    a = time.mktime(a)
    b = time.mktime(b)
    d = a - b
    days = int(d) / 86400
    hours = int(d) // 3600 % 24
    minutes = math.ceil(int(d) / 60 % 60)
    seconds = int(d) % 60
    h = str(hours)
    m = str(minutes)
    if hours < 10:
        h = '0' + h
    if minutes < 10:
        m = '0' + m
    return [h, m]

def local(t):
    h = t[:2]
    m = t[3:]
    mins = int(h) * 60 + int(m) + 330
    h = mins // 60
    m = mins % 60
    m = str(m)
    return str(h) + ':' + (('0' + m) if len(m) == 1 else m)

def getCKTMatches(flag):
    conn = http.client.HTTPSConnection("hs-consumer-api.espncricinfo.com")

    payload = ""

    headers = {
        'authority': "hs-consumer-api.espncricinfo.com",
        'pragma': "no-cache",
        'cache-control': "no-cache",
        'sec-ch-ua': "^\^Chromium^^;v=^\^94^^, ^\^Google"
        }

    conn.request("GET", "/v1/pages/matches/current?lang=en&latest=true", payload, headers)

    res = conn.getresponse()
    data = res.read()

    # print(data.decode("utf-8"))
    jsonDict = json.loads(data)
    # print(jsonDict)
    ret = dict()
    i = "1"
    series = ['Indian Premier League', 'Syed Mushtaq Ali Trophy', 'Ranji Trophy', 'Vijay Hazare Trophy']
    teams = ['Sydney Thunder Women', 'Sydney Sixers Women', 'Melbourne Renegades Women', 'Hobart Hurricanes Women', 'Brisbane Heat Women']
    url_head = 'https://www.espncricinfo.com/series/'
    if flag == 0:
        for e in jsonDict['matches']:
            url = url_head + e['series']['slug'] + '-' + str(e['series']['objectId']) + '/' + e['slug'] + '-' + str(e['objectId']) + '/full-scorecard'
            if str(date.today()) == e['startDate'][:10] and ((e["teams"][0]['team']['longName'].find('India') != -1 or e["teams"][1]['team']['longName'].find('India') != -1 or e['series']['description'].find('India') != -1) or (e['series']['longName'] in series) or (e['teams'][0]['team']['longName'] in teams) or (e['teams'][1]['team']['longName'] in teams)):
            # if str(date.today()) == e['startTime'][:10] :
                # pprint(e['teams'][1]['team']['id'])
                id1 = e['teams'][0]['team']['id']
                id2 = e['teams'][1]['team']['id']
                win = 0
                if 'winnerTeamId' in e and e['winnerTeamId'] != None:
                    idw = e['winnerTeamId']
                    if idw == id1:
                        win = 1
                    elif idw == id2:
                        win = 2
                score1 = '' if e['teams'][0]['score'] == None else (e['teams'][0]['score'] + ('' if e['teams'][0]['scoreInfo'] == None else ('(' + e['teams'][0]['scoreInfo'] + ')')))
                score2 = '' if e['teams'][1]['score'] == None else (e['teams'][1]['score'] + ('' if e['teams'][1]['scoreInfo'] == None else ('(' + e['teams'][1]['scoreInfo'] + ')')))
                # print(e['teams'][0]['score'])
                stxt = e['statusText']
                if e['statusText'] == 'Match starts in {{MATCH_START_HOURS}} {{MATCH_START_MINS}}':
                    h, m = diff(e['startTime'])
                    stxt = 'Match starts in ' + h + ' hours ' + m + ' minutes'
                ret[i] = [e['series']['longName'], e['title'] + ', ' + e['ground']['smallName'] + ' - ' + e['format'], ('Started at ' if (e['state'] == 'LIVE' or e['stage'] == 'FINISHED' or e['status'] == 'RESULT') else 'Starts at ') + local(e['startTime'][11:16]) + ', ' + ('Match ended' if e['status'] == 'RESULT' else ('-' if e['status'][0] == '{' else e['status'].upper())), e["teams"][0]['team']['longName'], e["teams"][1]['team']['longName'], score1, score2, 'Updates only' if stxt == None else stxt, e['objectId'], url, win];
                i = str(int(i) + 1)
    else:
        for e in jsonDict['matches']:
            url = url_head + e['series']['slug'] + '-' + str(e['series']['objectId']) + '/' + e['slug'] + '-' + str(e['objectId']) + '/full-scorecard'
            if e['state'] == 'LIVE' and ((e["teams"][0]['team']['longName'].find('India') != -1 or e["teams"][1]['team']['longName'].find('India') != -1 or e['series']['description'].find('India') != -1) or (e['series']['longName'] in series) or (e['teams'][0]['team']['longName'] in teams) or (e['teams'][1]['team']['longName'] in teams)):

                score1 = '' if e['teams'][0]['score'] == None else (e['teams'][0]['score'] + ('' if e['teams'][0]['scoreInfo'] == None else ('(' + e['teams'][0]['scoreInfo'] + ')')))
                score2 = '' if e['teams'][1]['score'] == None else (e['teams'][1]['score'] + ('' if e['teams'][1]['scoreInfo'] == None else ('(' + e['teams'][1]['scoreInfo'] + ')')))
                # print(e['teams'][0]['score'])
                stxt = e['statusText']
                if e['statusText'] == 'Match starts in {{MATCH_START_HOURS}} {{MATCH_START_MINS}}':
                    h, m = diff(e['startTime'])
                    stxt = 'Match starts in ' + h + ' hours ' + m + ' minutes'
                ret[i] = [e['series']['longName'], e['title'] + ', ' + e['ground']['smallName'] + ' - ' + e['format'], ('Started at ' if (e['state'] == 'LIVE' or e['stage'] == 'FINISHED' or e['status'] == 'RESULT') else 'Starts at ') + local(e['startTime'][11:16]) + ', ' + ('Match ended' if e['status'] == 'RESULT' else ('-' if e['status'][0] == '{' else e['status'].upper())), e["teams"][0]['team']['longName'], e["teams"][1]['team']['longName'], score1, score2, 'Updates only' if stxt == None else stxt, e['objectId'], url];
                i = str(int(i) + 1)
    return ret

# def main():
#     match_id=1254115
#     url= "https://www.espncricinfo.com/matches/engine/match/{0}.json".format(str(match_id))
#     response=requests.get(url)
#     j_son=response.json()
#     return (j_son)

# pprint(getCKTMatches(0))


import cli
from backup.backups import backup, remote

from .path import Path

def setup():
    script_assets = Path.script_assets.relative_to(Path.HOME)
    remote.Backup(folder=script_assets, quiet=False).pull()
    backup.Backup.after_pull()

    move_files(Path.assets / "root")
    move_files(Path.assets / "home", Path.HOME)
    move_crontab()
    # trust_keyboard()
    # seems to work without this command for now

def move_files(src_root, dst_root=Path("/")):
    for src in src_root.rglob("*"):
        if src.is_file():
            dst = dst_root / src.relative_to(src_root)
            commands = (
                [f"unzip -o '{src}' -d '{dst.parent}'"]
                if src.suffix == ".zip"
                else [f"mkdir -p '{dst.parent}'", f"cp -f '{src}' '{dst}'"]
            )

            cli.run_commands(*commands, root=dst.is_root, capture_output=True)

def move_crontab():
    src = Path.assets / "crontab" / "crontab"
    cli.run("crontab -", input=src.text)

def trust_keyboard():
    keyboard = cli.get("bluetoothctl devices | grep Keyboard", shell=True)
    cli.run("bluetoothctl trust", keyboard, wait=False)  # blocks if not found

if __name__ == "__main__":
    setup()


import os
import sys
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import accuracy_score, roc_auc_score, roc_curve, precision_score, f1_score
import xgboost as xgb
import mlflow
import mlflow.sklearn

def eval_metrics(y_true, y_pred):
    accuracy = round(accuracy_score(y_true, y_pred), 3)
    precision = round(precision_score(y_true, y_pred), 3)
    f1 = round(f1_score(y_true, y_pred), 3)
    auc = round(roc_auc_score(y_true, y_pred), 3)

    return accuracy, precision, f1, auc

if __name__ == "__main__":
    warnings.filterwarnings('ignore')

    parser = argparse.ArgumentParser()
    parser.add_argument("--n_estimators")
    parser.add_argument("--learning_rate")
    args = parser.parse_args()

    df = pd.read_csv("Marketing-Customer-Value-Analysis.csv")

    features_collected = ['Customer Lifetime Value',
                          'Income',
                          'Monthly Premium Auto',
                          'Months Since Policy Inception',
                          'Total Claim Amount']
    label = 'Response'

    df['Response'] = df['Response'].map(lambda x: 1 if x == "Yes" else 0)

    X = df[features_collected]
    y = df['Response']

    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.2)

    n_estimators = int(args.n_estimators)
    learning_rate = float(args.learning_rate)

    with mlflow.start_run():
        xgb_clf = xgb.XGBClassifier(random_state = 42,
                                  learning_rate=learning_rate,
                                  n_estimators=n_estimators)

        xgb_model = xgb_clf.fit(X_train, y_train)

        yhat = xgb_model.predict(X_test)

        (accuracy, precision, f1, auc) = eval_metrics(y_test, yhat)

        print("XGBClassifier model (learning_rate={}, n_estimators={})".format(learning_rate, n_estimators))
        print("Accuracy: {}".format(accuracy))
        print("Precision: {}".format(precision))
        print("F1 score: {}".format(f1))
        print("AUC: {}".format(auc))

        mlflow.log_param("learning_rate", learning_rate)
        mlflow.log_param("n_estimators", n_estimators)

        mlflow.log_metric("accuracy", accuracy)
        mlflow.log_metric("precision", precision)
        mlflow.log_metric("f1", f1)
        mlflow.log_metric("auc", auc)

        mlflow.sklearn.log_model(xgb_model, "XGBModel")


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

####李运辰  2021-01-04
import requests
from stylecloud import gen_stylecloud
import jieba
####视频https://www.bilibili.com/video/BV1nX4y1u7BH?from=search&seid=13601446070722236862
####弹幕https://api.bilibili.com/x/v1/dm/list.so?oid=266851015
headers = {
     'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0'
}
def jieba_cloud(file_name, icon):
    with open(file_name, 'r', encoding='utf8') as f:
        word_list = jieba.cut(f.read())
        result = " ".join(word_list)  # 分词用 隔开
        # 制作中文云词
        icon_name = ""
        if icon == "1":
            icon_name = ''
        elif icon == "2":
            icon_name = 'fas fa-dragon'
        elif icon == "3":
            icon_name = 'fas fa-dog'
        elif icon == "4":
            icon_name = 'fas fa-cat'
        elif icon == "5":
            icon_name = 'fas fa-dove'
        elif icon == "6":
            icon_name = 'fab fa-qq'
        """
        # icon_name='',#国旗
        # icon_name='fas fa-dragon',#翼龙
        #icon_name='fas fa-dog',#狗
        # icon_name='fas fa-cat',#猫
        # icon_name='fas fa-dove',#鸽子
        # icon_name='fab fa-qq',#qq
        """
        picp = file_name.split('.')[0] + str(icon) + '.png'
        if icon_name is not None and len(icon_name) > 0:
            gen_stylecloud(text=result, icon_name=icon_name, font_path='simsun.ttc', output_name=picp)  # 必须加中文字体，否则格式错误
        else:
            gen_stylecloud(text=result, font_path='simsun.ttc', output_name=picp)  # 必须加中文字体，否则格式错误

    return picp

url="https://api.bilibili.com/x/v1/dm/list.so?oid=266851015"
r = requests.get(url, headers=headers)
r.encoding = 'utf-8'
list_s = r.text.split("<d p=")
list_s = list_s[1:]
with open("commit.txt","a+",encoding='utf-8') as f:
    for i in list_s:
          i = (i.split(">"))[1].replace("</d","")
          #print(i)
          i = i.replace("？","").replace("。","").replace("，","").replace("+","").replace("！","").replace("....","").replace(".......","")
          f.write(str(i)+"\n")

jieba_cloud("t2.txt","1")
jieba_cloud("t2.txt","3")
jieba_cloud("t2.txt","4")
jieba_cloud("t2.txt","5")
jieba_cloud("t2.txt","6")