"""
Location data from Google Takeout

DEPRECATED: setup my.google.takeout.parser and use my.location.google_takeout instead
"""

REQUIRES = [
    'geopy', # checking that coordinates are valid
    'ijson',
]

from datetime import datetime, timezone
from itertools import islice
from pathlib import Path
from subprocess import Popen, PIPE
from typing import Iterable, NamedTuple, Optional, Sequence, IO, Tuple
import re

# pip3 install geopy
import geopy # type: ignore

from ..core.common import LazyLogger, mcachew
from ..core.cachew import cache_dir
from ..core import kompress

from my.core.warnings import high

high("Please set up my.google.takeout.parser module for better takeout support")

 # otherwise uses ijson
 # todo move to config??
USE_GREP = False

logger = LazyLogger(__name__)

class Location(NamedTuple):
    dt: datetime
    lat: float
    lon: float
    alt: Optional[float]

TsLatLon = Tuple[int, int, int]

def _iter_via_ijson(fo) -> Iterable[TsLatLon]:
    # ijson version takes 25 seconds for 1M items (without processing)
    # todo extract to common?
    try:
        # pip3 install ijson cffi
        import ijson.backends.yajl2_cffi as ijson # type: ignore
    except:
        import warnings
        warnings.warn("Falling back to default ijson because 'cffi' backend isn't found. It's up to 2x faster, you might want to check it out")
        import ijson # type: ignore

    for d in ijson.items(fo, 'locations.item'):
        yield (
            int(d['timestampMs']),
            d['latitudeE7' ],
            d['longitudeE7'],
        )

# todo ugh. fragile, not sure, maybe should do some assert in advance?
def _iter_via_grep(fo) -> Iterable[TsLatLon]:
    # grep version takes 5 seconds for 1M items (without processing)
    x = [-1, -1, -1]
    for i, line in enumerate(fo):
        if i > 0 and i % 3 == 0:
            yield tuple(x) # type: ignore[misc]
        n = re.search(b': "?(-?\\d+)"?,?$', line) # meh. somewhat fragile...
        assert n is not None
        j = i % 3
        x[j] = int(n.group(1).decode('ascii'))
    # make sure it's read what we expected
    assert (i + 1) % 3 == 0
    yield tuple(x) # type: ignore[misc]

# todo could also use pool? not sure if that would really be faster...
# search thread could process 100K at once?
# would need to find out a way to know when to stop? process in some sort of sqrt progression??

def _iter_locations_fo(fit) -> Iterable[Location]:
    total = 0
    errors = 0

    for tsMs, latE7, lonE7 in fit:
        dt = datetime.fromtimestamp(tsMs / 1000, tz=timezone.utc)
        total += 1
        if total % 10000 == 0:
            logger.info('processing item %d %s', total, dt)

        try:
            lat = float(latE7 / 1e7)
            lon = float(lonE7 / 1e7)
            # note: geopy is quite slow..
            point = geopy.Point(lat, lon) # kinda sanity check that coordinates are ok
        except Exception as e:
            logger.exception(e)
            errors += 1
            if float(errors) / total > 0.01:
                # todo make defensive?
                raise RuntimeError('too many errors! aborting')
            else:
                continue

        # todo support later
        # alt = j.get("altitude", None)
        alt = None
        yield Location(
            dt=dt,
            lat=lat,
            lon=lon,
            alt=alt,
        )

_LOCATION_JSON = 'Takeout/Location History/Location History.json'

# todo if start != 0, disable cache? again this is where nicer caching would come handy
# TODO hope they are sorted... (could assert for it)
# todo configure cache automatically?
@mcachew(cache_dir(), logger=logger)
def _iter_locations(path: Path, start=0, stop=None) -> Iterable[Location]:
    ctx: IO[str]
    if path.suffix == '.json':
        # todo: to support, should perhaps provide it as input= to Popen
        raise RuntimeError("Temporary not supported")
        ctx = path.open('r')
    else: # must be a takeout archive
        # todo CPath? although not sure if it can be iterative?
        ctx = kompress.open(path, _LOCATION_JSON)

    if USE_GREP:
        unzip = f'unzip -p "{path}" "{_LOCATION_JSON}"'
        extract = "grep -E '^    .(timestampMs|latitudeE7|longitudeE7)'"
        with Popen(f'{unzip} | {extract}', shell=True, stdout=PIPE) as p:
            out = p.stdout; assert out is not None
            fit = _iter_via_grep(out)
            fit = islice(fit, start, stop)
            yield from _iter_locations_fo(fit)
    else:
        with ctx as fo:
            # todo need to open as bytes
            fit = _iter_via_ijson(fo)
            fit = islice(fit, start, stop)
            yield from _iter_locations_fo(fit)
    # todo wonder if old takeouts could contribute as well??

def locations(**kwargs) -> Iterable[Location]:
    # NOTE: if this import isn't lazy, tests/tz.py breaks because it can't override config
    # very weird, as if this function captures the values of globals somehow?? investigate later.
    from ..google.takeout.paths import get_last_takeout
    last_takeout = get_last_takeout(path=_LOCATION_JSON)
    if last_takeout is None:
        return []

    return _iter_locations(path=last_takeout, **kwargs)

from ..core.common import stat, Stats
def stats() -> Stats:
    return stat(locations)

# todo add dataframe

# todo deprecate?
def get_locations(*args, **kwargs) -> Sequence[Location]:
    return list(locations(*args, **kwargs))


from app import views
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static

app_name='app'

urlpatterns = [

    path('', views.home, name='home'),
    path('bar-generate/', views.generate_bar_view, name='generate-bar-view'),
    path('bar-generated/', views.generated_bar_view, name='generated-bar-view'),
    path('qr-generate/', views.generate_qr_view, name='generate-qr-view'),
    path('qr-generated/', views.generated_qr_view, name='generated-qr-view'),

]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


# -*- coding: utf-8 -*-
import base
class Host(base.BaseHost):
    dev_mode = True
    short_key = 'k4'
    long_key  = 'keep4u'
    host='keep4u.ru'
    action = 'http://keep4u.ru/'
    form = {
            'disable_effects':'on',
            'preview':'yes',
            'sbmt':'',
            'Submit': '',
            }
    def as_file(self, _file):
        return {'pfile': _file }
    def thumb_size(self, _thumb_size):
        return { 'preview_size': _thumb_size, }
    def postload(self ):
        _src =  self.response.body
        _url = self.findall( 'value=\"\[img\]http://keep4u.ru/imgs/b/(.*?)\[/img\]\"', _src)[0]
        self.img_url = 'http://keep4u.ru/imgs/b/%s'%_url
        self.img_thumb_url = 'http://keep4u.ru/imgs/s/%s'%_url

if __name__ == '__main__':
    h= Host()
    h.test_file()
    h.test_url()


from openerp.osv import fields, osv
from openerp import tools
from openerp.tools.translate import _
from openerp import netsvc
from datetime import datetime, timedelta

class purchase_order(osv.osv):
    _inherit = 'purchase.order'

    def search(self, cr, uid, args, offset=0, limit=None, order=None,
            context=None, count=False):
        if context is None:
            context = {}
        IDS =[]

        if context.get('search_order_lines', False):
            order_line_ids = context.get('search_order_lines')
            order_line_obj = self.pool.get('purchase.order.line')

            IDS = [lines.order_id.id for lines in order_line_obj.browse(cr,uid, order_line_ids,context=context)]

            if IDS:
                args += [('id', 'in', IDS)]

        return super(purchase_order, self).search(cr, uid, args, offset, limit,
                order, context=context, count=count)

    def copy(self, cr, uid, id, default=None, context=None):
        if default is None:
            default = {}
        default = default.copy()
        default.update({'internal_number':'/'})
        return super(purchase_order, self).copy(cr, uid, id,
                default, context=context)


import re
import sys
import unicodedata

#https://stackoverflow.com/questions/1707890/fast-way-to-filter-illegal-xml-unicode-chars-in-python
_illegal_unichrs = [(0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F),
                        (0x7F, 0x84), (0x86, 0x9F),
                        (0xFDD0, 0xFDDF), (0xFFFE, 0xFFFF)]
if sys.maxunicode >= 0x10000:  # not narrow build
        _illegal_unichrs.extend([(0x1FFFE, 0x1FFFF), (0x2FFFE, 0x2FFFF),
                                 (0x3FFFE, 0x3FFFF), (0x4FFFE, 0x4FFFF),
                                 (0x5FFFE, 0x5FFFF), (0x6FFFE, 0x6FFFF),
                                 (0x7FFFE, 0x7FFFF), (0x8FFFE, 0x8FFFF),
                                 (0x9FFFE, 0x9FFFF), (0xAFFFE, 0xAFFFF),
                                 (0xBFFFE, 0xBFFFF), (0xCFFFE, 0xCFFFF),
                                 (0xDFFFE, 0xDFFFF), (0xEFFFE, 0xEFFFF),
                                 (0xFFFFE, 0xFFFFF), (0x10FFFE, 0x10FFFF)])

_illegal_ranges = ["%s-%s" % (chr(low), chr(high))
                   for (low, high) in _illegal_unichrs]
_illegal_xml_chars_RE = re.compile('[%s]' % ''.join(_illegal_ranges))

_ends_in_num = re.compile(r'\W*\d+$')

def remove_badxml(s):
    return _illegal_xml_chars_RE.sub('', s)

_ws_runs_RE = re.compile(r'([\r\n\t]| \$b)+')

def sanitize_ws(s):
    return _ws_runs_RE.sub(u' ', s)

def sanitize_line(s):
    return unicodedata.normalize('NFC', remove_badxml(sanitize_ws(s)).strip())

def remove_author_junk(authname):
    if 'ORCID:' in authname:
        authname = authname.split('ORCID:')[0].strip()
    return _ends_in_num.sub('', authname)


import logging
from mongolog.handlers import MongoHandler
log = logging.getLogger('demo')
log.setLevel(logging.DEBUG)
log.addHandler(MongoHandler.to(db='mongolog', collection='log'))

log.debug("1 - debug message")
log.info("2 - info message")
log.warn("3 - warn message")
log.error("4 - error message")
log.critical("5 - critical message")


# This file is part of the materials accompanying the book
# "Mathematical Logic through Python" by Gonczarowski and Nisan,
# Cambridge University Press. Book site: www.LogicThruPython.org
# (c) Yannai A. Gonczarowski and Noam Nisan, 2017-2022
# File name: propositions/semantics.py

"""Semantic analysis of propositional-logic constructs."""

from typing import AbstractSet, Iterable, Iterator, Mapping, Sequence, Tuple

from propositions.syntax import *
from propositions.proofs import *

from itertools import product

#: A model for propositional-logic formulas, a mapping from variable names to
#: truth values.
Model = Mapping[str, bool]

def is_model(model: Model) -> bool:
    """Checks if the given dictionary is a model over some set of variable
    names.

    Parameters:
        model: dictionary to check.

    Returns:
        ``True`` if the given dictionary is a model over some set of variable
        names, ``False`` otherwise.
    """
    for key in model:
        if not is_variable(key):
            return False
    return True

def variables(model: Model) -> AbstractSet[str]:
    """Finds all variable names over which the given model is defined.

    Parameters:
        model: model to check.

    Returns:
        A set of all variable names over which the given model is defined.
    """
    assert is_model(model)
    return model.keys()

def evaluate(formula: Formula, model: Model) -> bool:
    """Calculates the truth value of the given formula in the given model.

    Parameters:
        formula: formula to calculate the truth value of.
        model: model over (possibly a superset of) the variable names of the
            given formula, to calculate the truth value in.

    Returns:
        The truth value of the given formula in the given model.

    Examples:
        >>> evaluate(Formula.parse('~(p&q76)'), {'p': True, 'q76': False})
        True

        >>> evaluate(Formula.parse('~(p&q76)'), {'p': True, 'q76': True})
        False
    """
    assert is_model(model)
    assert formula.variables().issubset(variables(model))
    if is_constant(formula.root):
        return formula.root == "T"
    if is_variable(formula.root):
        return model[formula.root]
    if is_unary(formula.root):
        assert formula.first is not None
        return not evaluate(formula.first, model)
    if is_binary(formula.root):
        assert formula.first is not None and formula.second is not None
        if formula.root == "&":
            return evaluate(formula.first, model) and evaluate(formula.second, model)
        if formula.root == "|":
            return evaluate(formula.first, model) or evaluate(formula.second, model)
        else:
            a, b = evaluate(formula.first, model), evaluate(formula.second, model)
            z = (a,b)
            if z == (True, False):
                return False
            else:
                return True
    # Task 2.1

def all_models(variables: Sequence[str]) -> Iterable[Model]:
    """Calculates all possible models over the given variable names.

    Parameters:
        variables: variable names over which to calculate the models.

    Returns:
        An iterable over all possible models over the given variable names. The
        order of the models is lexicographic according to the order of the given
        variable names, where False precedes True.

    Examples:
        >>> list(all_models(['p', 'q']))
        [{'p': False, 'q': False}, {'p': False, 'q': True}, {'p': True, 'q': False}, {'p': True, 'q': True}]

        >>> list(all_models(['q', 'p']))
        [{'q': False, 'p': False}, {'q': False, 'p': True}, {'q': True, 'p': False}, {'q': True, 'p': True}]
    """
    for v in variables:
        assert is_variable(v)
    allm = [dict(zip(variables, posibles)) for posibles in product([False,True], repeat=len(variables))]
    return allm
    # Task 2.2

def truth_values(formula: Formula, models: Iterable[Model]) -> Iterable[bool]:
    """Calculates the truth value of the given formula in each of the given
    models.

    Parameters:
        formula: formula to calculate the truth value of.
        models: iterable over models to calculate the truth value in.

    Returns:
        An iterable over the respective truth values of the given formula in
        each of the given models, in the order of the given models.

    Examples:
        >>> list(truth_values(Formula.parse('~(p&q76)'), all_models(['p', 'q76'])))
        [True, True, True, False]
    """
    res = [evaluate(formula, modelito) for modelito in models]
    return res
    # Task 2.3

def print_truth_table(formula: Formula) -> None:
    """Prints the truth table of the given formula, with variable-name columns
    sorted alphabetically.

    Parameters:
        formula: formula to print the truth table of.

    Examples:
        >>> print_truth_table(Formula.parse('~(p&q76)'))
        | p | q76 | ~(p&q76) |
        |---|-----|----------|
        | F | F   | T        |
        | F | T   | T        |
        | T | F   | T        |
        | T | T   | F        |
    """
    def printBool(val:bool)->str:
        """
        Correcta impresion de cada booleano.\n
        True -> "T"\n
        False -> "F"
        """
        if val:
            return 'T'
        else:
            return 'F'
    longitudes = [len(vari) for vari in formula.variables()] + [len(str(formula))]
    #Dibujo de la primera línea
    primeralinea = ""
    for elem in formula.variables():
        primeralinea += "| " + elem + " "
    primeralinea += "| " + str(formula) + " |"
    #Dibujo de la barra espaciadora
    barra = ""
    for elem in longitudes:
        barra += "|" + '-'*(elem+2)
    barra += "|"
    print(primeralinea)
    print(barra)
    # Hacemos cada modelo
    modelos = all_models(formula.variables())
    #cogemos un modelo
    for mode in  modelos:
        #evaluamos la formula en este modelo y lo convertimos en un string
        resfor = evaluate(formula, mode)
        # Cogemos los valores de los modelos, los metemos en una lista y al final el resultado de evaluar
        lista = [printBool(elem) for elem in mode.values()] + [printBool(resfor)]
        nueva_linea = ""
        for i in range(len(lista)):
            nueva_linea += "| " + lista[i] + " "*longitudes[i]
        nueva_linea += "|"
        print(nueva_linea)
    # Task 2.4

def is_tautology(formula: Formula) -> bool:
    """Checks if the given formula is a tautology.

    Parameters:
        formula: formula to check.

    Returns:
        ``True`` if the given formula is a tautology, ``False`` otherwise.
    """
    for modelo in  all_models(formula.variables()):
        if evaluate(formula, modelo) == False:
            return False
    return True
    # Task 2.5a

def is_contradiction(formula: Formula) -> bool:
    """Checks if the given formula is a contradiction.

    Parameters:
        formula: formula to check.

    Returns:
        ``True`` if the given formula is a contradiction, ``False`` otherwise.
    """
    for modelo in  all_models(formula.variables()):
        if evaluate(formula, modelo):
            return False
    return True
    # Task 2.5b

def is_satisfiable(formula: Formula) -> bool:
    """Checks if the given formula is satisfiable.

    Parameters:
        formula: formula to check.

    Returns:
        ``True`` if the given formula is satisfiable, ``False`` otherwise.
    """
    for modelo in  all_models(formula.variables()):
        if evaluate(formula, modelo):
            return True
    return False
    # Task 2.5c

def _synthesize_for_model(model: Model) -> Formula:
    """Synthesizes a propositional formula in the form of a single conjunctive
    clause that evaluates to ``True`` in the given model, and to ``False`` in
    any other model over the same variable names.

    Parameters:
        model: model over a nonempty set of variable names, in which the
            synthesized formula is to hold.

    Returns:
        The synthesized formula.
    """
    assert is_model(model)
    assert len(model.keys()) > 0
    lista = list(zip(model.keys(), model.values()))
    lista_formulas = []
    for elem in lista:
        if elem[1]:
            f = Formula(elem[0])
        else:
            f = Formula('~', Formula(elem[0]))
        lista_formulas.append(f)
    f = lista_formulas[0]
    for formu in lista_formulas[1:]:
        f = Formula("&", f, formu)
    return f
    # Task 2.6

def synthesize(variables: Sequence[str], values: Iterable[bool]) -> Formula:
    """Synthesizes a propositional formula in DNF over the given variable names,
    that has the specified truth table.

    Parameters:
        variables: nonempty set of variable names for the synthesized formula.
        values: iterable over truth values for the synthesized formula in every
            possible model over the given variable names, in the order returned
            by `all_models`\ ``(``\ `~synthesize.variables`\ ``)``.

    Returns:
        The synthesized formula.

    Examples:
        >>> formula = synthesize(['p', 'q'], [True, True, True, False])
        >>> for model in all_models(['p', 'q']):
        ...     evaluate(formula, model)
        True
        True
        True
        False
    """
    assert len(variables) > 0
    modelos = all_models(variables)
    print(modelos)
    # Task 2.7

def _synthesize_for_all_except_model(model: Model) -> Formula:
    """Synthesizes a propositional formula in the form of a single disjunctive
    clause that evaluates to ``False`` in the given model, and to ``True`` in
    any other model over the same variable names.

    Parameters:
        model: model over a nonempty set of variable names, in which the
            synthesized formula is to not hold.

    Returns:
        The synthesized formula.
    """
    assert is_model(model)
    assert len(model.keys()) > 0
    # Optional Task 2.8

def synthesize_cnf(variables: Sequence[str], values: Iterable[bool]) -> Formula:
    """Synthesizes a propositional formula in CNF over the given variable names,
    that has the specified truth table.

    Parameters:
        variables: nonempty set of variable names for the synthesized formula.
        values: iterable over truth values for the synthesized formula in every
            possible model over the given variable names, in the order returned
            by `all_models`\ ``(``\ `~synthesize.variables`\ ``)``.

    Returns:
        The synthesized formula.

    Examples:
        >>> formula = synthesize_cnf(['p', 'q'], [True, True, True, False])
        >>> for model in all_models(['p', 'q']):
        ...     evaluate(formula, model)
        True
        True
        True
        False
    """
    assert len(variables) > 0
    # Optional Task 2.9

def evaluate_inference(rule: InferenceRule, model: Model) -> bool:
    """Checks if the given inference rule holds in the given model.

    Parameters:
        rule: inference rule to check.
        model: model to check in.

    Returns:
        ``True`` if the given inference rule holds in the given model, ``False``
        otherwise.

    Examples:
        >>> evaluate_inference(InferenceRule([Formula('p')], Formula('q')),
        ...                    {'p': True, 'q': False})
        False

        >>> evaluate_inference(InferenceRule([Formula('p')], Formula('q')),
        ...                    {'p': False, 'q': False})
        True
    """
    assert is_model(model)
    # Comprobar las variables de la regla están dentro de las del modelo

    eval_premisas_model = True
    for premisa in rule.assumptions:
        jj = evaluate(premisa, model)
        eval_premisas_model = eval_premisas_model and jj

    # Comprobamos que las premisas evaluadas en el modelos son ciertas.
    res = evaluate(rule.conclusion, model)

    # Comprobamos que la conclusión evaluada en el modelo no es cierta.
    return  not (eval_premisas_model and not res)
    # Task 4.2

def is_sound_inference(rule: InferenceRule) -> bool:
    """Checks if the given inference rule is sound, i.e., whether its
    conclusion is a semantically correct implication of its assumptions.

    Parameters:
        rule: inference rule to check.

    Returns:
        ``True`` if the given inference rule is sound, ``False`` otherwise.
    """
    # Extraemos todas las variables de la regla y calculamos todos los modelos posibles
    modelos = all_models(rule.variables())

    # comprobamos que la regla es cierta para cada uno de los modelos creados
    for modelito in modelos:
        if not evaluate_inference(rule, modelito):
            return False
    return True
    # Task 4.3


#!/usr/bin/env python3

import tkinter
win = tkinter.Tk()
win.title("tkinter 图形编程")
win.geometry("400x200+200+20")

# entry: 输入控件,用于显示简单的文本内容
#   show="*"
e = tkinter.Variable()      # 绑定变量
entry = tkinter.Entry(win, textvariable=e)
entry.pack()

# e 就代表输入框这个对象
e.set("hello python")           # 设置值
print(e.get())                  # 取值
print(entry.get())              # 取值

win.mainloop()


import argparse
import os
import logging
import subprocess
import shutil
import re

log_level = os.environ.get('LOGGING', default="INFO")
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=log_level)

main_desc = "Script to rebrand nano-node as new block chain." \
            "Example: " \
            "rebrand.py"

# Initiate the parser
parser = argparse.ArgumentParser(description=main_desc)

# debug
parser.add_argument("--debug", help="Enable debug", action="store_true")

# version arg
parser.add_argument("-V", "--version", help="Shows version", action="store_true")

# Read arguments from the command line
args = parser.parse_args()

# Check for --version or -V
if args.version:
    print("V22.0_0.0.1")

def remove_prefix(text, prefix):
    return text[len(prefix):] if text.startswith(prefix) else text

def cwd(directory="./"):
    logging.debug(directory)
    if os.environ.get("CI") == "true" and os.environ.get("DRONE") == "true":
        directory = "/drone/src/"
    return directory

def get_env_variable(env):
    if not os.environ.get(env, None):
        return logging.error("%s is not defined!" % env)
    else:
        logging.debug("%s properly set." % env)
        return os.environ.get(env)

def key_create(a):
    lines = []
    proc = subprocess.Popen(['%snano-node-22.0.0-Linux/bin/nano_node' % cwd(), '--key_create'], stdout=subprocess.PIPE)
    while True:
        line = proc.stdout.readline()
        if not line:
            break
        lines.append(str(line.rstrip()))

    private = lines[0].split(": ")[1].rstrip("'")
    public = lines[1].split(": ")[1].rstrip("'")
    account = lines[2].split(": ")[1].rstrip("'").replace("nano_", a)

    return print('''{
    "private": "%s",
    "public": "%s",
    "account": "%s"
}
    ''' % (private, public, account))

def is_ignored(f, w_list):
    #if args.debug:
    #    print("f: %s" % f)
    #    print("Ignored words: %s" % w_list)

    if w_list is not None:
        if re.compile('|'.join(w_list)).search(f):
            return True
        else:
            return False
    else:
        return False

def find_and_replace(filename, find, replace):
    with open(filename, "rb") as orig_file_obj:
        with open("%s.tmp" % filename, "wb") as new_file_obj:
            orig_text = orig_file_obj.read()
            new_text = orig_text.replace(find, replace)
            new_file_obj.write(new_text)

    shutil.copyfile("%s.tmp" % filename, filename)
    os.remove("%s.tmp" % filename)

def replace_all(data, ignore_list, subdir):
    for dirname, dirs, files in os.walk(cwd()+subdir):
        for file_name in files:
            filepath = os.path.join(dirname, file_name)

            for x in data:
                if is_ignored(filepath, ignore_list):
                    logging.debug("IGNORED %s" % filepath)
                else:
                    find_and_replace(filepath, x[0], x[1])

# rename directories
def rename_dirs(dirs):
    for d in dirs:
        if os.path.exists(d[0]):
            os.rename(d[0], d[1])


import chardet

# 파일 경로
file_path = 'data/perfume_data.csv'

# 파일의 실제 인코딩 확인
with open(file_path, 'rb') as file:
    result = chardet.detect(file.read())

# 확인된 인코딩 출력
print(f"파일의 실제 인코딩: {result['encoding']}, 신뢰도: {result['confidence']}")

# 파일을 확인된 인코딩(Windows-1254)으로 읽어오기
with open(file_path, 'r', encoding=result['encoding'], errors='replace') as file:
    content = file.read()

# 새로운 파일이 저장될 경로 (UTF-8로 저장할 파일)
new_file_path = 'data/perfume_data_new.csv'

# 파일 내용을 'UTF-8'로 인코딩하여 저장
with open(new_file_path, 'w', encoding='utf-8') as file:
    file.write(content)


# -*- coding: utf-8 -*-
from typing import List

class Solution:
    def findArguments(self, f, z):
        def binSearch(x, y):
            left = 1
            right = y - 1
            while left <= right:
                mid = (left + right) // 2
                if f(x, mid) == z:  return mid
                elif f(x, mid) < z: left = mid + 1
                else: right = mid - 1
            return -1

        x = 1
        y = 2 ** 32 - 1
        res = []
        while f(x, 1) <= z:
            y = binSearch(x, y)
            if y != -1: res.append([x, y])
            else: y = 2 ** 32 - 1
            x += 1
        return res

if __name__ == '__main__':
    solution = Solution()
    res = solution.findArguments(lambda x, y: x + 5 * y, 17)
    print(res)


import os
import unittest
import sys
sys.path.append("..")

from FileWriter import FileWriter

####################################################################################################################
# Test
####################################################################################################################
class TestFileWriter(unittest.TestCase):

    TEST_FILE = "myTest.txt"

    def tearDown(self):
        os.remove(self.TEST_FILE)

    def testNormal(self):
        with FileWriter(self.TEST_FILE) as f:
            f.WriteLn("a").IncIndent()
            f.WriteLn("b").DecIndent().WriteLn("c")

        with open(self.TEST_FILE) as file:
            lines = file.readlines()
        self.assertEqual("a\n", lines[0])
        self.assertEqual("\tb\n", lines[1])
        self.assertEqual("c\n", lines[2])

    def testRemoveFromLastLine(self):
        with FileWriter(self.TEST_FILE) as f:
            f.WriteLn("abc")
            f.WriteLn("def")
            f.RemoveFromLastLine(1)
            f.WriteLn("123")

        with open(self.TEST_FILE) as file:
            lines = file.readlines()
        self.assertEqual("abc\n", lines[0])
        self.assertEqual("de\n", lines[1])
        self.assertEqual("123\n", lines[2])


import os

import pytest

from bpp_plugins.import_dbf.util import (
    addslashes,
    dbf2sql,
    exp_add_spacing,
    exp_parse_str,
    xls2dict,
    exp_split_poz_str,
)

def test_util_addslashes():
    assert addslashes(None) is None
    assert addslashes(1) == 1
    assert addslashes("foo'") == "foo''"

def test_util_import_dbf():
    dbf2sql(os.path.join(os.path.dirname(__file__), "test.dbf"))
    open(os.path.join(os.path.dirname(__file__), "test.dbf") + ".sql")

@pytest.mark.parametrize(
    "input, output",
    [
        (
            "#204$ #a$ Zachowania zdrowotne dzieci w wieku szkolnym - badania wstępne #b$ #c$ #d$ #e$ s.184-191 "
            "#f$ ryc., tab., bibliogr., streszcz.",
            {
                "id": 204,
                "a": "Zachowania zdrowotne dzieci w wieku szkolnym - badania wstępne",
                "b": "",
                "c": "",
                "d": "",
                "e": "s.184-191",
                "f": "ryc., tab., bibliogr., streszcz.",
            },
        ),
        (
            "#102$ #a$ Autologous hematopoietic stem cell transplant for progressive"
            " diffuse systemic sclerosis: procedural "
            "success and clinical outcome in 5-year follow-up #b$ #c$ #d$",
            {
                "id": 102,
                "a": "Autologous hematopoietic stem cell transplant for progressive diffuse systemic sclerosis: "
                "procedural success and clinical outcome in 5-year follow-up",
                "b": "",
                "c": "",
                "d": "",
            },
        ),
        (
            "#150$ #a$ Badania nad wpływem selenu na integralność chromatyny plemnikowej w przypadkach mężczyzn z "
            "upośledzoną płodnością #b$ #c$ #d$",
            {
                "id": 150,
                "a": "Badania nad wpływem selenu na integralność chromatyny plemnikowej w przypadkach mężczyzn "
                "z upośledzoną płodnością",
                "b": "",
                "c": "",
                "d": "",
            },
        ),
        (
            "#150$ #a$Neurologia #c$Howard L. Weiner, Lawrence P. Levitt	",
            {"id": 150, "a": "Neurologia", "c": "Howard L. Weiner, Lawrence P. Levitt"},
        ),
        (
            "#103$#a$ Abstracts of the 5-th World Congress on Heart Failure - Mechanisms and Managment. "
            "Washinfton, USA, 11-14 May, 1997",
            {
                "id": 103,
                "a": "Abstracts of the 5-th World Congress on Heart Failure - Mechanisms and Managment. "
                "Washinfton, USA, 11-14 May, 1997",
            },
        ),
    ],
)
def test_util_exp_parse_str(input, output):
    assert exp_parse_str(input) == output

@pytest.mark.parametrize(
    "input,output",
    [
        (
            "#153$ #a$ 162 s. #b$ bibliogr. #c$\r\n#154$ #a$|0000004804#b$ #c$\r\n"
            "nr 154 #d$ #e$\r\n#155$ #a$ ISBN 978-83-66066-86-1#988$ #a$|0000\r\n"
            "006505#b$|0000006506#991$ #a$ 10.34616/23.19.146\r\n#995$ #a$ http\r\n"
            "s://www.bibliotekacyfrowa.pl/publication/108240\r\n               ",
            [
                "#153$ #a$ 162 s. #b$ bibliogr. #c$",
                "#154$ #a$|0000004804#b$ #c$nr 154 #d$ #e$",
                "#155$ #a$ ISBN 978-83-66066-86-1",
                "#988$ #a$|0000006505#b$|0000006506",
                "#991$ #a$ 10.34616/23.19.146",
                "#995$ #a$ https://www.bibliotekacyfrowa.pl/publication/108240               ",
            ],
        )
    ],
)
def test_util_exp_split_poz_str(input, output):
    assert output == list(exp_split_poz_str(input))

def test_util_exp_parse_str_raises():
    bad = (
        "#105$ Electrophysiological estimation of the peripheral nerves conduction "
        "parameters and the autonomic nervous system function in the course"
        " of amyotrophic lateral sclerosis #b$"
    )
    with pytest.raises(ValueError):
        exp_parse_str(bad)

def test_util_exp_add_spacing():
    assert exp_add_spacing(" te  st (fa. ) ") == " te st (fa.) "

def test_xls2dict():
    ret = list(xls2dict(os.path.join(os.path.dirname(__file__), "test_chf.xlsx")))
    assert ret[0]["skrot"] == "PAA"


from tqdm import tqdm
from src.services.parser import Parser
from src.services.picker import Picker
from src.models.storage import Storage

class Controller:
    def __init__(self, capacity):
        self.storage = Storage(capacity)

    def run(self, input):
        parser = Parser(input)
        try:
            designs, flowers = parser.parse()
        except Exception as err:
            print("Error: {}".format(err))
            return

        picker = Picker(designs, self.storage)

        bouquets = []
        with tqdm(total=len(flowers)) as pbar:
            for i, flower in enumerate(flowers):
                pbar.update(1)
                try:
                    picker.handle(flower)
                    bouquet = picker.pick_up()
                    if bouquet:
                        bouquets.append(repr(bouquet))
                except Exception as err:
                    print("Error: {} parsing flowers' input at {} position".format(err, i))
                    return

        return '\n'.join(bouquets)


import os
from os.path import join
import numpy as np
import cv2

import sys
sys.path.append('..')
from config import cfg

def read_annotation():
    data = dict()
    images = []
    bboxes = []
    labelfile = open(cfg.path_wider_bbx_gt, 'r')
    while True:
        # image path
        imagepath = labelfile.readline().strip('\n')
        if not imagepath:
            break
        imagepath = join(cfg.path_wider_imgs, imagepath)
        images.append(imagepath)
        # face numbers
        nums = labelfile.readline().strip('\n')
        # im = cv2.imread(imagepath)
        # h, w, c = im.shape
        one_image_bboxes = []
        for i in range(int(nums)):
            # text = ''
            # text = text + imagepath
            bb_info = labelfile.readline().strip('\n').split(' ')
            # only need x, y, w, h
            face_box = [float(bb_info[i]) for i in range(4)]
            # text = text + ' ' + str(face_box[0] / w) + ' ' + str(face_box[1] / h)
            xmin = face_box[0]
            ymin = face_box[1]
            xmax = xmin + face_box[2]
            ymax = ymin + face_box[3]
            # text = text + ' ' + str(xmax / w) + ' ' + str(ymax / h)
            one_image_bboxes.append([xmin, ymin, xmax, ymax])
            # f.write(text + '\n')
        bboxes.append(one_image_bboxes)

    data['images'] = images#all image pathes
    data['bboxes'] = bboxes#all image bboxes
    # f.close()
    return data

def read_and_write_annotation(base_dir, dir):
    """
    read label file
    :param dir: path
    :return:
    """
    data = dict()
    images = []
    bboxes = []
    labelfile = open(dir, 'r')
    f = open('/home/thinkjoy/data/mtcnn_data/imagelists/train.txt', 'w')
    while True:
        # image path
        imagepath = labelfile.readline().strip('\n')
        if not imagepath:
            break
        imagepath = base_dir + '/WIDER_train/images/' + imagepath
        images.append(imagepath)
        # face numbers
        nums = labelfile.readline().strip('\n')
        im = cv2.imread(imagepath)
        h, w, c = im.shape
        one_image_bboxes = []
        for i in range(int(nums)):
            text = ''
            text = text + imagepath
            bb_info = labelfile.readline().strip('\n').split(' ')
            # only need x, y, w, h
            face_box = [float(bb_info[i]) for i in range(4)]
            text = text + ' ' + str(face_box[0] / w) + ' ' + str(face_box[1] / h)
            xmin = face_box[0]
            ymin = face_box[1]
            xmax = xmin + face_box[2] - 1
            ymax = ymin + face_box[3] - 1
            text = text + ' ' + str(xmax / w) + ' ' + str(ymax / h)
            one_image_bboxes.append([xmin, ymin, xmax, ymax])
            f.write(text + '\n')
        bboxes.append(one_image_bboxes)

    data['images'] = images
    data['bboxes'] = bboxes
    f.close()
    return data

def get_path(base_dir, filename):
    return os.path.join(base_dir, filename)

def IoU(box, bboxes):
    """
    Caculate IoU between detect and ground truth boxes
    :param crop_box:numpy array (4, )
    :param bboxes:numpy array (n, 4):x1, y1, x2, y2
    :return:
    numpy array, shape (n, ) Iou
    """
    box_area = (box[2] - box[0] + 1) * (box[3] - box[1] + 1)
    areas = (bboxes[:, 2] - bboxes[:, 0] + 1) * (bboxes[:, 3] - bboxes[:, 1] + 1)
    xx1 = np.maximum(box[0], bboxes[:, 0])
    yy1 = np.maximum(box[1], bboxes[:, 1])
    xx2 = np.minimum(box[2], bboxes[:, 2])
    yy2 = np.minimum(box[3], bboxes[:, 3])

    # compute the width and height of the bounding box
    w = np.maximum(0, xx2 - xx1 + 1)
    h = np.maximum(0, yy2 - yy1 + 1)

    inter = w * h
    over = inter / (box_area + areas - inter)

    return over

if __name__ == '__main__':
    pass


# LIBRARY IMPORTS

# Standard Library imports:
from time import time
import random

# External Imports:

# Internal Imports:
from system_settings import ARENAS
from save_handler import save_generation, init_arenas, log_data
from cython_floor_gen import FloorGenerator
import Inheritance

arenas = []
generation = 0
dead_arenas = []
floor_maker = None
active_arenas = ARENAS
printed = False
calc_needed_for = 0

def main():
    global arenas, generation, floor_maker, dead_arenas, printed, active_arenas

    arenas, generation, floor_maker = init_arenas()

    while True:
        dead_arenas = []
        print("\nStarting generation {}".format(generation))

        # Show inital scores for generations
        score = floor_maker.get_score()
        print("Current score is ", score, ", ", len(arenas), " active arenas")
        printed = True

        # initialize/reset local scores to track current generation
        active_arenas = len(arenas)
        start_time = time()
        # Perform one generation
        while active_arenas > 0:
            floor_maker.next_frame()
            active_arenas = advance_arenas_one_frame()
            show_current_progress()

        print("generation took ", (time()-start_time))
        generate_next_generation()

def generate_next_generation() -> None:
    global floor_maker, arenas, generation
    log_data(generation, floor_maker.get_score())

    starting_score = max(floor_maker.get_score() - 750, 0)
    floor_maker = FloorGenerator(seed=random.random() * 1000, starting_diff=starting_score)
    start_time = time()
    arenas = Inheritance.generate_next_gen(arenas + dead_arenas, floor_maker)
    print("Inheritance took ", (time() - start_time))

    generation += 1
    if generation % 30 == 0:
        save_generation(arenas, generation, to_folder=generation)
    save_generation(arenas, generation)

def show_current_progress() -> None:
    global printed, arenas
    score = floor_maker.get_score()

    if not printed and score % 100 == 0:
        print("Current score is ", score, ", ", len(arenas), " active arenas")
        printed = True
    elif printed and score % 100 == 1:
        printed = False

def advance_arenas_one_frame():
    global active_arenas, arenas, calc_needed_for, dead_arenas
    global calc_needed_for
    # if there are no holes in jumping distance of the agents,
    # it's not necessary to calculate their inputs

    for i in range(6):
        if floor_maker.floor[1 + i] == 0.0:
            calc_needed_for = 6

    for arena in arenas:
        if arena.running:
            arena.next_frame()
            #if calc_needed_for > 3:
            arena.apply_network()

        if not arena.running:
            dead_arenas.append(arena)
            arenas.remove(arena)
            active_arenas -= 1
    calc_needed_for -= 1
    return active_arenas

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("Starting to save neural networks...")
        save_generation(arenas, generation)


#Dizide Tekrar Eden Değerleri Silme

def removeDuplicates(liste):
    removed_list = []
    if liste:
        for item in liste:
            if item not in removed_list:
                removed_list.append(item)
    else:
        return liste
    print("Fazlalıklardan kurtulmuş yeni dizi: {}".format(removed_list))

liste = [1,2,2,3,4,1,7,4,8,7,3]
removeDuplicates(liste)


from google.appengine.ext import webapp
from google.appengine.api import urlfetch
import urllib2
import time
import logging, datetime

def remove_www(handler):
    if handler.request.url.startswith('http://www.'):
        handler.redirect(handler.request.url.replace('http://www.', 'http://'))

def makeStatic(template_name, context={}):
    class Static(webapp.RequestHandler):
        def get(self):
            remove_www(self)
            self.response.headers['Content-Type'] = 'text/html'
            self.response.out.write(
                render(template_name, context)
            )
    return Static

import re
# Allow 'abc' and 'abc.def' but not '.abc' or 'abc.'
valid_callback = re.compile('^\w+(\.\w+)*$')

from BeautifulSoup import BeautifulSoup

class twitpicapi(webapp.RequestHandler):
    user = ""
    ids = []
    def get(self):
        self.response.headers['Content-Type'] = 'text/javascript'
        callback = self.request.get('callback', default_value='')
        page = self.request.get('page', default_value='0')
        self.user = self.request.path[1:]

        self.loadTwitPicPage(page)

        json = []
        for j in self.ids:
            json.append("{ id : '%s', url : '%s', twitpic_url : '%s', date : '%s', title : '%s' }" % (j['id'], j['url'], j['twitpic_url'], j['date'], re.escape(j['title'])))

        # json = u"{ works : false, user : '%s', id_size : %s }" % (self.user, len(self.ids))
        json = '[%s]' % (",\n".join(json))
        if callback and valid_callback.match(callback):
            json = '%s(%s)' % (callback, json)
        self.response.out.write(json)

    def loadTwitPicPage(self, page):
        url = ""
        if page > 1:
            url = 'http://twitpic.com/photos/%s?page=%s' % (self.user, page)
        else:
            url = 'http://twitpic.com/photos/%s' % (self.user)

        # self.response.out.write('Grabbing from ' + url + "\n")
        contents = urllib2.urlopen(url)
        soup = BeautifulSoup(contents)
        for photowrapper in soup('div', {"class":"profile-photo-img"}):
            json = {}
            anchor = photowrapper.find('a')
            json['id'] = anchor['href'][1:]
            json['twitpic_url'] = 'http://twitpic.com/show/large/' + json['id']

            image = urlfetch.fetch(url=json['twitpic_url'], follow_redirects=False)
            if image.status_code == 302:
                json['url'] = image.headers['location']
            else:
                json['url'] = json['twitpic_url']

            # required to get the date - sucks that they don't maintain the date on the image URL
            twitpicPage = urllib2.urlopen('http://twitpic.com/' + json['id'])
            twitpicPageSoup = BeautifulSoup(twitpicPage)
            meta = twitpicPageSoup.find('div', { "id" : "photo-info" }).find('div').contents[0].strip() # grab the first nest div
            date = time.strptime(meta,"Posted on %B %d, %Y")
            json['date'] = time.strftime("%Y-%m-%d", date)

            json['title'] = ''
            if (twitpicPageSoup.find('div', { 'id' : 'view-photo-caption' }) is not None):
                json['title'] = twitpicPageSoup.find('div', { 'id' : 'view-photo-caption' }).contents[0].strip()

            self.ids.append(json)

        # if soup.find(text=re.compile("OLDER")):
        #     href = soup.find(text=re.compile("OLDER")).parent['href']
        #     m = re.search('(\d+?)$', href)
        #     if m is not None:
        #         self.loadTwitPicPage(m.group(0))

class Http404Page(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        self.error(404)
        self.response.out.write(render('index.html', {
            'path': self.request.path,
        }))

def main():
    logging.getLogger().setLevel(logging.DEBUG)
    from wsgiref.handlers import CGIHandler
    application = webapp.WSGIApplication([
        ('/', makeStatic('index.html')),
        (r'/[a-z0-9]{1,15}$', twitpicapi),
        ('/.*$', Http404Page),
    ], debug=True)
    CGIHandler().run(application)

import os
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
from google.appengine.ext.webapp import template
def render(template_name, context={}):
    path = os.path.join(template_dir, template_name)
    return template.render(path, context)

if __name__ == "__main__":
    main()


#Adapted from https://github.com/keras-team/keras-applications/blob/master/keras_applications/densenet.py

import keras
from keras import layers, backend, models

def dense_block(x, blocks, width, name=None):
    for i in range(blocks):
        x = conv_block(x, width, name=name + '_block' + str(i + 1))
    return x

def transition_block(x, reduction, name):
    bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1
    x = layers.BatchNormalization(axis=bn_axis, epsilon=1.001e-5,
                                  name=name + '_bn')(x)
    x = layers.Activation('relu', name=name + '_relu')(x)
    x = layers.Conv2D(int(backend.int_shape(x)[bn_axis] * reduction), 1,
                      use_bias=False,
                      name=name + '_conv')(x)
    x = layers.AveragePooling2D(2, strides=2, name=name + '_pool')(x)
    return x

def conv_block(x, growth_rate, name):
    bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1
    x1 = layers.BatchNormalization(axis=bn_axis,
                                   epsilon=1.001e-5,
                                   name=name + '_0_bn')(x)
    x1 = layers.Activation('relu', name=name + '_0_relu')(x1)
    x1 = layers.Conv2D(4 * growth_rate, 1,
                       use_bias=False,
                       name=name + '_1_conv')(x1)
    x1 = layers.BatchNormalization(axis=bn_axis, epsilon=1.001e-5,
                                   name=name + '_1_bn')(x1)
    x1 = layers.Activation('relu', name=name + '_1_relu')(x1)
    x1 = layers.Conv2D(growth_rate, 3,
                       padding='same',
                       use_bias=False,
                       name=name + '_2_conv')(x1)
    x = layers.Concatenate(axis=bn_axis, name=name + '_concat')([x, x1])
    return x

def DenseNet(blocks, input_shape, num_classes, width):
    img_input = layers.Input(shape=input_shape)

    bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1

    x = layers.ZeroPadding2D(padding=((3, 3), (3, 3)))(img_input)
    x = layers.Conv2D(2 * width, 7, strides=2, use_bias=False, name='conv1/conv')(x)
    x = layers.BatchNormalization(
        axis=bn_axis, epsilon=1.001e-5, name='conv1/bn')(x)
    x = layers.Activation('relu', name='conv1/relu')(x)
    x = layers.ZeroPadding2D(padding=((1, 1), (1, 1)))(x)
    x = layers.MaxPooling2D(3, strides=2, name='pool1')(x)

    x = dense_block(x, blocks[0], width, name='conv2')
    x = transition_block(x, 0.5, name='pool2')
    x = dense_block(x, blocks[1], width, name='conv3')
    x = transition_block(x, 0.5, name='pool3')
    x = dense_block(x, blocks[2], width, name='conv4')
    x = transition_block(x, 0.5, name='pool4')
    x = dense_block(x, blocks[3], width, name='conv5')

    x = layers.BatchNormalization(
        axis=bn_axis, epsilon=1.001e-5, name='bn')(x)
    x = layers.Activation('relu', name='relu')(x)

    x = layers.GlobalAveragePooling2D(name='avg_pool')(x)
    x = layers.Dense(num_classes, activation='softmax', name='fc1000')(x)

    # Create model.
    if blocks == [6, 12, 24, 16]:
        model = models.Model(img_input, x, name='densenet121')
    elif blocks == [6, 12, 32, 32]:
        model = models.Model(img_input, x, name='densenet169')
    elif blocks == [6, 12, 48, 32]:
        model = models.Model(img_input, x, name='densenet201')
    else:
        model = models.Model(img_input, x, name='densenet')

    return model

def DenseNet121(input_shape, num_classes, width):
    return DenseNet([6, 12, 24, 16], input_shape, num_classes, width)


#!/usr/bin/env python3
from functools import reduce
import csv

actions = ("Random Walk", "Extinguish Fire", "Resupply Water")
states = [("W", 2), ("F", 2)]
sum_states = [1 if i == len(states) - 1 else sum(map(lambda x: x[1], states[i+1:])) for i in range(len(states))]

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("csv_file", help="put the csv file path")
    args = parser.parse_args()
    csv_path = args.csv_file
    out_path = csv_path.replace(".csv", ".tex")

    n_states = reduce(lambda x,y: x*y, map(lambda x: x[1], states))
    n_actions = len(actions)

    table = [[0 for i in range(n_actions)] for j in range(n_states)]
    with open(csv_path) as csvfile:
        reader = csv.reader(csvfile)
        for i, row in enumerate(reader):
            if i < n_states:
                for j, val in enumerate(row[:-1]):
                    table[i][j] = val

    lines = [["" for i in range(len(states) + len(actions))] for j in range(n_states)]
    sep = [r"\hline" for i in range(n_states)]

    for i in range(n_states):
        for j, (state, _) in enumerate(states):
            if i % sum_states[j] == 0:
                if _ == 2:
                    text = "${}{}$".format(r'\neg ' if (i // sum_states[j]) % 2 == 0  else '', state)
                else:
                    text = "${} = {}$".format(state, (i // sum_states[j]) % _)
                lines[i][j] = r"\multirow{" + str(sum_states[j]) + r"}{*}{" + text + r"}"
                if j != len(states) - 1 and sep[i] == r"\hline":
                    sep[i] = r'\cline{' + str(j + 2)  + '-' + str(len(lines[0])) + '}'
                else:
                    lines[i][j] = text

        for j, val in enumerate(table[i]):
            lines[i][len(states) + j] = "{:.3f}".format(float(val))

    header = [' '] * len(states) + list(actions)

    indent = "  "
    tex = ""
    # tex = r"\begin{code}" + "\n"
    tex += r"\begin{center}" + "\n"
    tex += r"\begin{tabular}{|" + "|".join(['c' for i in range(len(lines[0]))]) + "|}\n"
    tex += indent + r"\hline" + "\n"
    tex += ' & '.join(header) + r"\\" + "\n"
    tex += indent + r"\hline" + "\n"
    for i in range(n_states):
        tex += indent + " & ".join(lines[i]) + r"\\" + "\n"
        if i != n_states - 1:
            tex += indent + sep[i] + "\n"
    tex += indent + r"\hline" + "\n"
    tex += r"\end{tabular}" + "\n"
    tex += r"\end{center}" + "\n"
    # tex += r"\end{code}"

    open(out_path, 'w').write(tex)


# -*- coding: utf-8 -*-
"""
Created on Wed Jan 18 16:21:48 2023

@author: Md.Jahidul Islam
"""

try:
    import tkinter as tk                # python 3
    from tkinter import font as tkfont  # python 3

except ImportError:
    import Tkinter as tk     # python 2
    import tkFont as tkfont  # python 2
from tkinter import filedialog
import tkinter.messagebox
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import fitz
from PIL import Image
import os
import shutil

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        #Main Frame
        self.title("PDF To TIFF OFFLINE CONVERTER")
        MainFrame= tk.Frame(self,bd=10, width=1100, height=400,relief= tk.RIDGE, bg='cadet blue')
        MainFrame.pack(fill=tk.BOTH,expand=1)
        MainFrame.pack_propagate(0)

        #Panedwindow Botton and Editor
        BE_pan=tk.PanedWindow(MainFrame,orient=tk.HORIZONTAL)

        #Page Frame --Left side of Main Frame
        Page_Frame2= tk.Frame(BE_pan,bd=8, width=800, height=200,relief= tk.RIDGE, bg='AliceBlue')
        Page_Frame2.pack(side="left", fill=tk.BOTH)
        BE_pan.add(Page_Frame2)

        #Main ELEMENT Frame --Right side of Main Frame
        Main_ELEMENT_Frame5= tk.Frame(BE_pan,bd=8, width=50, height=200,relief= tk.RIDGE, bg='AliceBlue')
        Main_ELEMENT_Frame5.pack(side="right")
        Main_ELEMENT_Frame5.pack_propagate(0)

        BE_pan.add(Main_ELEMENT_Frame5)

        BE_pan.pack(fill = tk.BOTH, expand = True)

        # This method is used to show sash
        BE_pan.configure(sashrelief = tk.RAISED)

        #Panedwindow Element and display
        ED_pan=tk.PanedWindow(Page_Frame2,orient=tk.VERTICAL)
        #Page Frame --top side of Main Frame
        Page_Frame1= tk.Frame(ED_pan,bd=8, width=800, height=100,relief= tk.RIDGE, bg='cadet blue')
        Page_Frame1.pack(side="top", fill=tk.BOTH)
        ED_pan.add(Page_Frame1)

        #Main ELEMENT Frame --bottom side of Main Frame
        Frame5= tk.Frame(ED_pan,bd=8, width=800, height=100,relief= tk.RIDGE, bg='cadet blue')
        Frame5.pack(side="bottom")
        Frame5.pack_propagate(0)

        ED_pan.add(Frame5)
        ED_pan.pack(fill = tk.BOTH, expand = True)
        ED_pan.configure(sashrelief = tk.RAISED)

        Fact = """\nHere We Can Get The Update Of The Runing Process."""
        #=============function============
        def Open():
            global path
            path= filedialog.askopenfilenames(title="Select PDF FIles",filetypes=(("PDF Files","*.pdf"),("Excel Files","*.xlsx"),("CSV Files","*.csv"),("All Files","*.*")))
            nb_file="\nNumber of files selected: "+str(len(path))
            T.insert(tk.END,nb_file)
            for i in path:
                filename = i.split('/')[len(i.split('/'))-1]
                filename =filename.replace(".pdf","")
                filename1="\n  "+filename
                T.insert(tk.END,filename1)

        #Location to Save the the report
        def saving():
            global save_only
            save_only= filedialog.askdirectory(title="Select the output folder")
            T.insert(tk.END,f"\nSelected Folder To Save The TIFF File:{save_only}")

        def slider_changed(event):
            pass

        def start():
            for pdf1 in path:
                #Creat Forlder
                dpi = DPI.get()
                zoom = dpi / Zoom.get()
                magnify = fitz.Matrix(zoom, zoom)
                doc = fitz.open(pdf1)
                filename = pdf1.split('/')[len(pdf1.split('/'))-1]
                filename =filename.replace(".pdf","")
                filename1="\n    Start Converting For:"+filename
                T.insert(tk.END,filename1)

                # path
                path_mak = os.path.join(save_only, filename)
                try:
                    os.mkdir(path_mak)
                except OSError as error:
                    tkinter.messagebox.showerror('Error', 'Error: Please Select The location To Save The Files!')

                add=[]
                for index, page in enumerate(doc):
                    pix = page.get_pixmap(matrix=magnify)
                    pix.save(f"{path_mak}/page-{page.number}.tiff")
                    im1 = Image.open(f"{path_mak}/page-{page.number}.tiff")
                    if index==0:
                        pass
                    else:
                        add.append(im1)

                im1 = Image.open(f"{path_mak}/page-0.tiff")
                output_tiff=f"{save_only}/{filename}.tiff"
                im1.save(output_tiff, save_all=True, append_images=add, compression='tiff_lzw', tiffinfo={317: 2})
                T.insert(tk.END,f"\n{filename} Is Converted")
                # removing directory
                shutil.rmtree(path_mak, ignore_errors=False)
            os.startfile(save_only)
            tkinter.messagebox.showinfo("PDF TO TIFF","ALL The Pdfs Are Converted Successfully")

        #===========Button=========
        pdf_button= tk.Button(Main_ELEMENT_Frame5,font =('Bahnschrift Light SemiCondensed', 12, 'bold'),text="SELECT PDFs", bd =5, command= Open).pack(fill=tk.BOTH, expand=1)
        Save_button= tk.Button(Main_ELEMENT_Frame5,font =('Bahnschrift Light SemiCondensed', 12, 'bold'),text="SELECT THE LOCATION TO SAVE", bd =5, command= saving).pack(fill=tk.BOTH, expand=1)
        Convert_button= tk.Button(Main_ELEMENT_Frame5,font =('Bahnschrift Light SemiCondensed', 12, 'bold'),text="Start Converting", cursor="plus",activeforeground='#58D68D',activebackground='#5D6D7E', bd =5, command= start).pack(fill=tk.BOTH, expand=1)
        #===========text=======
        # Create text widget and specify size.
        T = tk.Text(Frame5)
        T.insert(tk.END, Fact)
        T.pack(fill=tk.BOTH, expand=1)
        #================ scorol bar========
        DPI= tk.Scale(Page_Frame1,from_= 300, to=600,orient='horizontal',command=slider_changed)
        DPI.pack(fill=tk.BOTH, expand=1)
        DPIlable=tk.Label(Page_Frame1, text= "Please Select DPI  Value\n Default value: 300", bd =2)
        DPIlable.pack(fill=tk.BOTH, expand=1)
        Zoom= tk.Scale(Page_Frame1,from_= 72, to=200,orient='horizontal',command=slider_changed)
        Zoom.pack(fill=tk.BOTH, expand=1)
        Zoomlable=tk.Label(Page_Frame1, text= "Please Select Zoom Factor Value\nDefault value: 72\nSelect 120-180 for best output", bd =2)
        Zoomlable.pack(fill=tk.BOTH, expand=1)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()


"""
    Napisz dwie niezalezne funkcje rozwiazujace nastepujace problemy:
    a) count_digits powinno zliczac ilosc cyfr w liczbie calkowitej,
       ktora zostanie podana jako argument,
    b) count_zeros powinno zliczac ilosc zer w liczbie calkowitej, ktora zostanie
       podana jako argument.
    Przyklady:
    >> x = count_digits(1234)
    >> print(x)
    4
    >> x = count_zeros(1000)
    >> print(x)
    3
    Zadania mozna rozwiazac w sposob "matematyczny", ale rowniez
    wykorzystujac uproszczenia Pythona.
    Podpowiedz: a gdyby tak liczbe rzutowac na napis?
"""

def count_digits1(num):
    num
    count = 0

    while num != 0:
        num //= 10
        count += 1

    return str(count)

def count_digits(number):
    """Zlicza ilosc cyfr w liczbie.

    :param number: pewna liczba calkowita
    :return: ilosc cyfr w liczbie (int).

    """
    return len(str(number))

def count_zeros(number):
    """Zlicza zera w liczbie number.

    :param number: pewna liczba calkowita
    :return:
    """
    return str(number).count("0")

def digits(n):
    count = 0
    if n == 0:
        return 1

    if n < 0:
        n *= -1

    while (n >= 10 ** count):
        count += 1
        n += n % 10

    return count

if __name__=="__main__":
    print(count_digits1(123456))
    print(count_digits(123456))
    print(count_zeros(1000))
    print(digits(123456))


import sys
import cv2
import argparse
import os

print("OpenCV version"+cv2.__version__)

def variance_of_laplacian(image):
    """
    compute the Laplacian of the image and return the focus measure
    """
    return cv2.Laplacian(image, cv2.CV_64F).var()

parser = argparse.ArgumentParser()
parser._action_groups.pop()
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
required.add_argument("-p", "--path", type=str, default="",
                      help="path to the video file", required=True)
optional.add_argument("-t", "--threshold", type=float, default=100.0,
                      help="default threshold is 100.0. Use 10-30 for motion")
optional.add_argument("-s", "--step", type=int,
                      default=1, help="frame step size")
optional.add_argument("--save", default= "", type= str, help= "path to save the frames in a directory")
args = vars(parser.parse_args())

if not args["path"]:
    sys.exit("Please supply a video file '-p <path>'")

vidcap = cv2.VideoCapture(args["path"])

success, image = vidcap.read()
count = 0
blurryFrame = 0
savedFrame = 0
frameStep = 0
step = args["step"]

print("Working...")

while success:
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    fm = variance_of_laplacian(gray)

    if frameStep == step:
        if fm > args["threshold"]:
            savedFrame += 1
            image_path = os.path.join(args["save"], "frame%d.png" % count)
            cv2.imwrite(image_path, image)
        frameStep = 0

    if fm < args["threshold"]:
        blurryFrame += 1

    success, image = vidcap.read()
    count += 1
    frameStep += 1

sys.exit("Done!")


from ice.evaluation.evaluate_recipe_result import RecipeResult
from ice.metrics.gold_standards import get_gold_standard
from ice.metrics.gold_standards import list_experiments
from ice.paper import Paper
from ice.recipe import Recipe

class AllQuotesRecipe(Recipe):
    # Used to view paper parses
    # and to test whether the gold standard quotes we're looking for
    # are actually in the parses
    question_short_name_to_test = "placebo"

    async def run(self, paper: Paper):
        experiments = list_experiments(document_id=paper.document_id)

        results: list[RecipeResult] = []
        for experiment in experiments:
            gold_standard = get_gold_standard(
                document_id=paper.document_id,
                question_short_name=self.question_short_name_to_test,
                experiment=experiment,
            )

            if gold_standard:
                results.append(
                    RecipeResult(
                        experiment=experiment,
                        question_short_name=self.question_short_name_to_test,
                        document_id=paper.document_id,
                        answer="",
                        classifications=[],
                        excerpts=[
                            paragraph.__str__() for paragraph in paper.paragraphs
                        ],
                    )
                )

        self.maybe_add_to_results(results)

        return results


import pygame, sys
from button import Button
import random
pygame.init()

SCREEN = pygame.display.set_mode((1280, 720))
pygame.display.set_caption("Menu")

#variables
BG = pygame.image.load("Background.png")
blue = pygame.image.load("BlueSprite.png")
cyan = pygame.image.load("CyanSprite.png")
green = pygame.image.load("GreenSprite.png")
orange = pygame.image.load("OrangeSprite.png")
pink = pygame.image.load("PinkSprite.png")
red = pygame.image.load("RedSprite.png")
yellow = pygame.image.load("YellowSprite.png")
direction = 1
clock = pygame.time.Clock()
player_rect_blue = blue.get_rect(midbottom = (80,100))
player_rect_cyan = cyan.get_rect(midbottom = (80,200))
player_rect_green = green.get_rect(midbottom = (80,300))
player_rect_orange = orange.get_rect(midbottom = (80,400))
player_rect_pink = pink.get_rect(midbottom = (80,500))
player_rect_red = red.get_rect(midbottom = (80,600))
player_rect_yellow = yellow.get_rect(midbottom = (80,700))

#definition for the font
def get_font(size): # Returns Press-Start-2P in the desired size
    return pygame.font.Font("font.ttf", size)

#play screen
def play():
    while True:
        PLAY_MOUSE_POS = pygame.mouse.get_pos()
        keys = pygame.key.get_pressed()
        SCREEN.fill("black")
        speed_x = 1
        if keys[pygame.K_SPACE]:
            print('jump')

        PLAY_TEXT = get_font(45).render("This is the PLAY screen.", True, "White")
        PLAY_RECT = PLAY_TEXT.get_rect(center=(640, 260))

        SCREEN.blit(PLAY_TEXT, PLAY_RECT)
        SCREEN.blit(blue, player_rect_blue)
        SCREEN.blit(cyan, player_rect_cyan)
        SCREEN.blit(green, player_rect_green)
        SCREEN.blit(orange, player_rect_orange)
        SCREEN.blit(pink, player_rect_pink)
        SCREEN.blit(red, player_rect_red)
        SCREEN.blit(yellow, player_rect_yellow)
        direction = 1
        direction *=-1
        #if player_rect_blue.right >=80 or player_rect_blue.right >=1280:
            #player_rect_blue.x = random.randint(0,8) * direction
            #player_rect_blue.y = random.randint(0.8) * direction
                #if player_rect_blue.bottom >=720:
                    #player_rect_blue.x +=1
                    #player_rect_blue.y = 0

        PLAY_BACK = Button(image=None, pos=(640, 460),
                            text_input="BACK", font=get_font(75), base_color="White", hovering_color="Green")

        PLAY_BACK.changeColor(PLAY_MOUSE_POS)

        PLAY_BACK.update(SCREEN)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if PLAY_BACK.checkForInput(PLAY_MOUSE_POS):
                    return
            if event.type == pygame.KEYDOWN:
                print('key down')
            if event.type == pygame.KEYUP:
                print("key up")

        pygame.display.update()

#option screen
def options():
    while True:
        OPTIONS_MOUSE_POS = pygame.mouse.get_pos()

        SCREEN.fill("white")

        OPTIONS_TEXT = get_font(45).render("This is the OPTIONS screen.", True, "Black")
        OPTIONS_RECT = OPTIONS_TEXT.get_rect(center=(640, 260))
        SCREEN.blit(OPTIONS_TEXT, OPTIONS_RECT)

        OPTIONS_BACK = Button(image=None, pos=(640, 460),
                            text_input="BACK", font=get_font(75), base_color="Black", hovering_color="Green")

        OPTIONS_BACK.changeColor(OPTIONS_MOUSE_POS)
        OPTIONS_BACK.update(SCREEN)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if OPTIONS_BACK.checkForInput(OPTIONS_MOUSE_POS):
                    return

        pygame.display.update()

#main menu screen
while True:
    SCREEN.blit(BG, (0, 0))

    MENU_MOUSE_POS = pygame.mouse.get_pos()

    MENU_TEXT = get_font(100).render("TEAM ORANGE", True, "#b68f40")
    MENU_RECT = MENU_TEXT.get_rect(center=(640, 100))

    PLAY_BUTTON = Button(image=pygame.image.load("Play Rect.png"), pos=(640, 250),
                            text_input="PLAY", font=get_font(75), base_color="#d7fcd4", hovering_color="Black")
    OPTIONS_BUTTON = Button(image=pygame.image.load("Options Rect.png"), pos=(640, 400),
                            text_input="OPTIONS", font=get_font(75), base_color="#d7fcd4", hovering_color="Black")
    QUIT_BUTTON = Button(image=pygame.image.load("Quit Rect.png"), pos=(640, 550),
                            text_input="QUIT", font=get_font(75), base_color="#d7fcd4", hovering_color="Black")

    SCREEN.blit(MENU_TEXT, MENU_RECT)

    for button in [PLAY_BUTTON, OPTIONS_BUTTON, QUIT_BUTTON]:
        button.changeColor(MENU_MOUSE_POS)
        button.update(SCREEN)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if PLAY_BUTTON.checkForInput(MENU_MOUSE_POS):
                play()
            if OPTIONS_BUTTON.checkForInput(MENU_MOUSE_POS):
                    options()
            if QUIT_BUTTON.checkForInput(MENU_MOUSE_POS):
                pygame.quit()
                sys.exit()

    pygame.display.update()


# ======================================================================
# Radioisotope Thermoelectric Generators
#   Advent of Code 2016 Day 11 -- Eric Wastl -- https://adventofcode.com
#
# Python implementation by Dr. Dean Earl Wright III
# ======================================================================

# ======================================================================
#                    t e s t _ s o l v e r . p y
# ======================================================================
"Test solver for Advent of Code 2016 day 11, Radioisotope Thermoelectric Generators"

# ----------------------------------------------------------------------
#                                                                 import
# ----------------------------------------------------------------------
import unittest

import aoc_11
import solver

# ----------------------------------------------------------------------
#                                                              constants
# ----------------------------------------------------------------------
EXAMPLE_TEXT = """
The first floor contains a hydrogen-compatible microchip and a lithium-compatible microchip.
The second floor contains a hydrogen generator.
The third floor contains a lithium generator.
The fourth floor contains nothing relevant.
"""

PART_ONE_TEXT = EXAMPLE_TEXT
PART_TWO_TEXT = ""

PART_ONE_RESULT = 11
PART_TWO_RESULT = None

# ======================================================================
#                                                             TestSolver
# ======================================================================

class TestSolver(unittest.TestCase):  # pylint: disable=R0904
    "Test Solver object"

    def test_empty_init(self):
        "Test the default Solver creation"

        # 1. Create default Solver object
        myobj = solver.Solver()

        # 2. Make sure it has the default values
        self.assertEqual(myobj.part2, False)
        self.assertEqual(myobj.text, None)

    def test_text_init(self):
        "Test the Solver object creation from text"

        # 1. Create Solver object from text
        myobj = solver.Solver(text=aoc_11.from_text(EXAMPLE_TEXT))

        # 2. Make sure it has the expected values
        self.assertEqual(myobj.part2, False)
        self.assertEqual(len(myobj.text), 4)

        # 3. Check methods
        self.assertEqual(myobj.number_moves(), 11)

    def test_part_one(self):
        "Test part one example of Solver object"

        # 1. Create Solver object from text
        myobj = solver.Solver(text=aoc_11.from_text(PART_ONE_TEXT))

        # 2. Check the part one result
        self.assertEqual(myobj.part_one(verbose=False), PART_ONE_RESULT)

    def test_part_two(self):
        "Test part two example of Solver object"

        # 1. Create Solver object from text
        myobj = solver.Solver(part2=True, text=aoc_11.from_text(PART_TWO_TEXT))

        # 2. Check the part two result
        self.assertEqual(myobj.part_two(verbose=False), PART_TWO_RESULT)

# ----------------------------------------------------------------------
#                                                  module initialization
# ----------------------------------------------------------------------
if __name__ == '__main__':
    pass

# ======================================================================
# end                   t e s t _ s o l v e r . p y                  end
# ======================================================================


#!/usr/bin/env python

# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Xinlei Chen, based on code from Ross Girshick
# --------------------------------------------------------

"""
Demo script showing detections in sample images.

See README.md for installation instructions before running.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os

import cv2
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from lib.config import config as cfg
from lib.utils.nms_wrapper import nms
from lib.utils.test import im_detect
#from nets.resnet_v1 import resnetv1
from lib.nets.vgg16 import vgg16
from lib.utils.timer import Timer
import lib.config.config as cf

CLASSES = ('__background__', 'defect')

NETS = {'vgg16': ('vgg16_faster_rcnn_iter_30000.ckpt',), 'res101': ('res101_faster_rcnn_iter_110000.ckpt',)}
DATASETS = {'pascal_voc': ('voc_2007_trainval',), 'pascal_voc_0712': ('voc_2007_trainval+voc_2012_trainval',)}

def load_image_set_index():
    """
    Load the indexes listed in this dataset's image set file.
    """
    # Example path to image set file:
     # self._devkit_path/VOC2007/ImageSets/Main/trainval.txt
    image_set_file = os.path.join(cf.FLAGS2["root_dir"],'DateSet','RSDDs_dataset_LJ','RSDDsTest','VOCDevkit2007',"VOC2007",'ImageSets','Main','test.txt')

    assert os.path.exists(image_set_file), \
        'Path does not exist: {}'.format(image_set_file)
    with open(image_set_file) as f:
            # f.read()把整个文件内容读进一个字符串
            # f.readline()读一行
            # f.readlines()把整个文件让你读入一个字符串列表，每一行为一个字符串
         image_index = [x.strip() for x in f.readlines()]
    return image_index

def image_path_from_index(index):
    """
    Construct an image path from the image's "index" identifier.
    """
    image_path = os.path.join(cf.FLAGS2["root_dir"],'DateSet','RSDDs_dataset_LJ','RSDDsTest','VOCdevkit2007','VOC2007','JPEGImages',
                                  index + ".jpg")
    assert os.path.exists(image_path), \
            'Path does not exist: {}'.format(image_path)
    return image_path

def vis_detections(im, class_name, dets,image_name,outputPath, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))  #figure来设置窗口尺寸
    # 在ax子图中绘制im图像
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]
        # 在子图中添加块
        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
        )
        #在指定位置添加文本
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')
    # 设置子图标题
    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                 fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw()
    image_name=os.path.join(outputPath,image_name+'.jpg')
    plt.savefig(image_name)

def demo(sess, net, image_name,output_path):
    """Detect object classes in an image using pre-computed object proposals."""

    # Load the demo image
    image_path=image_path_from_index(image_name)
    im = cv2.imread(image_path)

    # Detect all object classes and regress object bounds
    timer = Timer()
    timer.tic()
    # 此处的boxes是经过bbox_pre修正过的Bbox的位置坐标，并且对于预测的每一个类别，都有一个预测的Bbox坐标
    scores, boxes = im_detect(sess, net, im)
    timer.toc()
    print('Detection took {:.3f}s for {:d} object proposals'.format(timer.total_time, boxes.shape[0]))

    # Visualize detections for each class
    CONF_THRESH = 0.1
    NMS_THRESH = 0.1
    #对每个类别进行一次画图,这里只有一个类别defect
    for cls_ind, cls in enumerate(CLASSES[1:]):
        cls_ind += 1  # because we skipped background
        cls_boxes = boxes[:, 4 * cls_ind:4 * (cls_ind + 1)]
        cls_scores = scores[:, cls_ind]
        dets = np.hstack((cls_boxes,
                          cls_scores[:, np.newaxis])).astype(np.float32)
        #利用非极大值抑制，从300个proposal中剔除掉与更大得分的proposal的IOU大于0.1的proposal
        keep = nms(dets, NMS_THRESH)
        dets = dets[keep, :]

        vis_detections(im, cls, dets,image_name,output_path,thresh=CONF_THRESH)

def parse_args():
    """Parse input arguments."""
    parser = argparse.ArgumentParser(description='Tensorflow Faster R-CNN demo')
    parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16 res101]',
                        choices=NETS.keys(), default='vgg16')
    # choices： 参数的取值范围  default：  参数的默认值  help：参数的说明信息
    # dest： 添加对象的属性名，由parse_Args()返回
    parser.add_argument('--dataset', dest='dataset', help='Trained dataset [pascal_voc pascal_voc_0712]',
                        choices=DATASETS.keys(), default='pascal_voc')
    args = parser.parse_args()

    return args

#以双下划线“__”开头和结尾的是python的内置属性
#当作为导入模块使用时，模块__name__属性值为模块的主名，当作为顶层模块直接使用时，__name__属性值为__main__
if __name__ == '__main__':
    #模块独立执行，所以执行下面的代码
    args = parse_args()

    # model path
    demonet = args.demo_net
    dataset = args.dataset

    #加载训练好的模型的路径
    #dataset为键值=pascal_voc，DATASETS[dataset]=('voc_2007_trainval',)，是一个集合，所以[0]是下标
    #DATASETS[dataset][0]='voc_2007_trainval'
    tfmodel = os.path.join(cf.FLAGS2["root_dir"], 'Module', 'LJModule', 'Faster RCNN', demonet, 'RSDDs_1', 'default', NETS[demonet][0])

    if not os.path.isfile(tfmodel + '.meta'):
        print(tfmodel)
        raise IOError(('{:s} not found.\nDid you download the proper networks from '
                       'our server and place them properly?').format(tfmodel + '.meta'))

    # set config
    tfconfig = tf.ConfigProto(allow_soft_placement=True)
    tfconfig.gpu_options.allow_growth = True

    # init session
    sess = tf.Session(config=tfconfig)
    # load network
    if demonet == 'vgg16':
        net = vgg16(batch_size=1)
    # elif demonet == 'res101':
        # net = resnetv1(batch_size=1, num_layers=101)
    else:
        raise NotImplementedError

    n_classes = len(CLASSES)
    # create the structure of the net having a certain shape (which depends on the number of classes)
    '''
    self._predictions["bbox_pred"] *= stds
    self._predictions["bbox_pred"] += means
    '''
    net.create_architecture(sess, "TEST", n_classes,
                            tag='default', anchor_scales=[8, 16, 32])
    saver = tf.train.Saver()
    saver.restore(sess, tfmodel)

    print('Loaded network {:s}'.format(tfmodel))

    output_path='G:\DeepLearning\Project\LJProject\Faster-RCNN\Faster-RCNN-TensorFlow-Python3-master-RSDDs\demo_output\\vgg16\RSDDs_train_test'
    print("save result in  {:s}".format(output_path))
    if not os.path.isdir(output_path):
         os.mkdir(output_path)
    image_index=load_image_set_index()

    for i in range(len(image_index)):
         demo(sess, net, image_index[i],output_path)


from django.conf.urls import patterns, url

from user_bizz import views

urlpatterns = patterns('',
  url(r'^$', views.book_list, name='book_list'),
  url(r'^new$', views.book_create, name='book_new'),
  url(r'^edit/(?P<pk>\d+)$', views.book_update, name='book_edit'),
  url(r'^delete/(?P<pk>\d+)$', views.book_delete, name='book_delete'),
  url(r'^export/csv/$', views.export_users_csv, name='export_users_csv'),
)


#!/usr/bin/python3
# _*_ coding: utf-8 _*_

"""
El nostre programa ha d'escriure una seqüència numèrica que comenci amb el número 'inici' i que compti de 'salt' en 'salt' fins al número 'final'
sense passar-s'hi de llarg.
"""

__author__ = "Unai Cervantes"

import sys

def main(inici,final,salt):
    """
    Doctest
    >>> main(10,18,2)
    '10, 12, 14, 16, 18'
    >>> main(10,17,2)
    '10, 12, 14, 16'
    >>> main(18,10,-2)
    '18, 16, 14, 12, 10'
    >>> main(-10,2,0)
    Traceback (most recent call last):
    ...
    ValueError: El valor del salt no pot ser 0
    >>> main(-10,2,3)
    '-10, -7, -4, -1, 2'
    """
    resultat = ''
    if salt == 0:
        raise ValueError ("El valor del salt no pot ser 0")
    if salt >= 1:
        final += 1
    else:
        final -= 1
    for index in range(inici,final,salt):
        if index > inici or index < inici:
            resultat += ', ' + str(index)
        else:
            resultat += str(index)
    return resultat
if __name__ == "__main__":
    print(main(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])))


N, K = map(int, input().split())

friends = []
for i in range(N):
    A, B = map(int, input().split())
    friends.append([A, B])

friends.sort()

now_village = 0

# まずK円分進む
now_village += K

# 進んだ村の間に友達がいるか確認する
# いたら、友達からお金をもらう
# お金をもらった分先に進むことができる
for i in range(N):
    friend_village = friends[i][0]
    friend_money = friends[i][1]

    if friend_village < now_village:
        now_village += friend_money
    else:
        break

print(now_village)


import ctypes
import platform

from functools import lru_cache

import pygame

import vars

class Screen:
    """Object containing information about the current display

    Used by draw functions"""

    def __init__(self):
        # Constants
        self.FULLSCREEN = vars.options["fullscreen"]
        self.FRAMERATE = vars.options["framerate"]
        self.DEFAULT_SIZE = (vars.options["resolution_x"], vars.options["resolution_y"])

        # If running Windows, disable high DPI scaling
        if platform.system() == "Windows":
            ctypes.windll.user32.SetProcessDPIAware()

        # Units for drawing the board to the screen
        self.LAST_BOARD_SIZE = None

        self.rescale_window(self.DEFAULT_SIZE, self.FULLSCREEN)

        # Theme to be used for screen drawing
        self.theme = None

        # Pygame
        self.clock = pygame.time.Clock()

        pygame.display.set_caption("Battleships")
        pygame.display.set_icon(pygame.image.load("assets/icon.ico"))

        pygame.font.init()

    def rescale_window(self, size, fullscreen):
        """
        Rescale the window to size
        :param size: (int width, int height)
        :param fullscreen: bool
        """

        if fullscreen is None:
            fullscreen = self.FULLSCREEN

        self.FULLSCREEN = fullscreen

        if self.FULLSCREEN:
            size = pygame.display.list_modes()[0]
            self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN | pygame.HWACCEL)
        else:
            self.screen = pygame.display.set_mode(size, pygame.RESIZABLE)

        self.SIZE = size
        self.WIDTH, self.HEIGHT = self.SIZE
        self.MID = (self.WIDTH / 2, self.HEIGHT / 2)

        # Units for drawing to the screen
        self.UNIT = min(self.SIZE)
        self.BORDER_SIZE = self.UNIT / 20
        self.MARGIN_SIZE = int(self.UNIT / 300)

        # Font settings
        self.FONT_SCALE = self.UNIT / 1000

        # Force text to be rescaled
        self.render_text.cache_clear()

        if self.LAST_BOARD_SIZE:
            self.calc_board_spacing(self.LAST_BOARD_SIZE)

    def toggle_fullscreen(self):
        """
        Toggles fullscreen mode
        """

        if self.FULLSCREEN:
            self.rescale_window(self.DEFAULT_SIZE, False)
        else:
            self.rescale_window(self.DEFAULT_SIZE, True)

    def calc_board_spacing(self, board_size):
        """
        Calculates spacing for boards on screen
        :param board_size: int
        """

        self.LAST_BOARD_SIZE = board_size

        self.CELL_SIZE = int(((vars.screen.UNIT - vars.screen.BORDER_SIZE * 3)
                              / 2 - (board_size + 1) * self.MARGIN_SIZE) / board_size)
        self.CELL_DOT_SIZE = int(self.CELL_SIZE / 4)

        self.BOARD_SIZE = self.CELL_SIZE * board_size + self.MARGIN_SIZE * (board_size + 1)

    def set_theme(self, theme):
        """Sets the theme"""

        self.theme = theme

    @lru_cache(maxsize=32)
    def get_font(self, name, size):
        """Returns a font object given a name and size"""

        return pygame.font.Font(name, size)

    @lru_cache(maxsize=32)
    def render_text(self, size, text, text_color):
        """Returns a text object given a name, size and text to render"""

        # Adjust size of font for screen size
        size = int(self.FONT_SCALE * size)

        # Get font
        font = self.get_font(self.theme.FONT, size)

        # Render text
        text = font.render(text, True, text_color)

        return text

    def draw(self):
        """Draws to the screen"""

        self.clock.tick(self.FRAMERATE)
        pygame.display.flip()

        # print(self.clock.get_fps())


from dataloader import*
# from model import*
# from train import*
# from run import*
net1=torch.load('charmodel')
#net2=torch.load('charrnnmodel')

def predict(net, char, h=None, top_k=None):
    ''' Given a character, predict the next character.
        Returns the predicted character and the hidden state.
    '''

    # tensor inputs
    x = np.array([[net.char2int[char]]])
    x = one_hot_encode(x, len(net.chars))
    inputs = torch.from_numpy(x)
    train_on_gpu = torch.cuda.is_available()
    if (train_on_gpu):
         inputs = inputs.cuda()

    # detach hidden state from history
    h = tuple([each.data for each in h])
    # get the output of the model
    out, h = net(inputs, h)

    # get the character probabilities
    p = F.softmax(out, dim=1).data
    # train_on_gpu = torch.cuda.is_available()
    if (train_on_gpu):
        p = p.cpu()  # move to cpu

    # get top characters
    if top_k is None:
        top_ch = np.arange(len(net.chars))
    else:
        p, top_ch = p.topk(top_k)
        top_ch = top_ch.numpy().squeeze()

    # select the likely next character with some element of randomness
    p = p.numpy().squeeze()
    char = np.random.choice(top_ch, p=p / p.sum())

    # return the encoded value of the predicted char and the hidden state
    return net.int2char[char], h
def sample(net, size, prime='B', top_k=None):
    # Check if GPU is available
    train_on_gpu = torch.cuda.is_available()

    if(train_on_gpu):
        net.cuda()
    else:
        net.cpu()

    net.eval() # eval mode

    # First off, run through the prime characters
    chars = [ch for ch in prime]
    h = net.init_hidden(1)
    for ch in prime:
        char, h = predict(net, ch, h, top_k=top_k)

    chars.append(char)

    # Now pass in the previous character and get a new one
    for ii in range(size):
        char, h = predict(net, chars[-1], h, top_k=top_k)
        chars.append(char)

    return ''.join(chars)

# Generating new text
print(sample(net1, 1000, prime='B', top_k=5))


import sys
import math

n = [8,10,16,4,5,21,11,7,1,3]
print("Uneti niz je: \n", n)

def maxHeapify(A, i, heapSize):
    l = 2*i + 1
    r = 2*i + 2
    if(l <= heapSize and A[l]> A[i]):
        largest = l
    else:
        largest = i

    if(r <= heapSize and A[r] > A[largest]):
        largest = r

    if (largest != i):
        temp = A[i]
        A[i] = A[largest]
        A[largest] = temp

#A[i],A[largest] = A[largest],A[i] -- mala pomoc
        maxHeapify(A, largest, heapSize)

def buildMaxHeap(A, heapSize):
    i = 1
    for i in range(int(math.floor(len(A)/2))-1, -1, -1):
        maxHeapify(A, i, heapSize)

def heapSort(A, heapSize):
    buildMaxHeap(A, heapSize)
    for i in range(len(A)-1, 0, -1):
        A[0],A[i] = A[i],A[0]
        #temp = A[0]
        #A[0] = A[i]
        #A[i] = temp
        heapSize = heapSize - 1
        maxHeapify(A, 0, heapSize)

def heapMax(A):
    return A[1]

def heapExtractMax(A, heapSize):
    if (heapSize < 0):
        print("Heap Underflow")
        return

    max = A[0]
    temp = A[heapSize]
    A.remove(A[heapSize])
    A[0] = temp
    heapSize = heapSize - 1
    maxHeapify(A, 0, heapSize)
    return max

def maxHeapInsert(A, key, heapSize):
    heapSize = heapSize + 1
    #A = -math.inf
    #A.insert(heapSize, key)
    A.append(-(sys.maxsize)) #-- ovo je za beskonacno
    heapIncreaseKey(A, heapSize, key)

def heapIncreaseKey(A, i, key):
    if(key < A[i]):
        print("New key is smaller than current key")

    A[i] = key
    while(i > 1 and A[math.floor((i - 1)/2)] < A[i]):
        A[i],A[math.floor((i - 1)/2)] = A[math.floor((i - 1)/2)],A[i]
        i = math.floor((i - 1)/2)

heapSize = len(n)-1
buildMaxHeap(n, heapSize)
print("Posle Build Max Heap: \n", n)

heapSort(n, heapSize)
print("Posle Heap Sort: \n", n)

#heapExtractMax(n, heapSize)
#print("Posle Heap Extract Max: \n", n)

maxHeapInsert(n, 5, heapSize)
print("Posle Max Heap Insert: \n", n)


import tkinter as tk

janela = tk.Tk()

var_promocoes = tk.IntVar()
chekbox_promocoes = tk.Checkbutton(text='Deseja receber e-mail promocionais?', variable=var_promocoes)
chekbox_promocoes.grid(row=0, column=0)

var_politicas = tk.IntVar()
checkbox_politicas = tk.Checkbutton(text='Aceitar Termos de Uso e Políticas de Privacidade', variable=var_politicas)
checkbox_politicas.grid(row=1, column=0)

def enviar():
    if var_promocoes.get():
        print(f'Usuário deseja receber promoções')
    else:
        print(f'Usuário NÃO deseja receber promoções')
    if var_politicas.get():
        print(f'Usuário concordou com Termos de Uso e Políticas de Privacidade')
    else:
        print(f'Usuário NÃO concordou')

botao_enviar = tk.Button(text='Enviar', command=enviar)
botao_enviar.grid(row=2, column=0)

janela.mainloop()


import sys
import math
import numpy as np
import time
import sounddevice as sd
import soundfile as sf
import subprocess
from multiprocessing import Process
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

PLAYER_FRAME_DURATION = 0.2
PLAYER_FRAME_SHIFT = 0.1
PLAYER_N_PLOTS = 20
PLAYER_UPDATE_INTERVAL = 0.05

PLAYER_SAMPLERATE = 16000  # samplerate is fixed value
PLAYER_NYQUIST = PLAYER_SAMPLERATE // 2

PLAYER_LIM_FREQ = 5000
PLAYER_LENFREQ = ((int(PLAYER_SAMPLERATE * PLAYER_FRAME_DURATION) >> 1) + 1) // (PLAYER_NYQUIST // PLAYER_LIM_FREQ)

def calc_specgrams(waveform, samplerate):
    specgrams = []

    left = 0
    right = PLAYER_FRAME_DURATION * samplerate

    while right < len(waveform):
        wframe = waveform[int(left):int(right)]

        hanningwindow = np.hanning(len(wframe))
        wframe = hanningwindow * wframe

        specgrams.append(np.log(np.abs(np.fft.rfft(wframe))))

        left += PLAYER_FRAME_SHIFT * samplerate
        right += PLAYER_FRAME_SHIFT * samplerate

    return specgrams

class Player():
    def __init__(self, filename, q):
        super(Player, self).__init__()

        waveform, samplerate = sf.read(sys.argv[1], dtype='float32')

        if samplerate != PLAYER_SAMPLERATE:
            print("ERROR in player: input wav file's sampling rate must be equal to 16,000")
            sys.exit(1)

        self.waveform = waveform

        self.filename = filename
        self.specgrams = calc_specgrams(waveform, samplerate)

        self.readed = 0

        q.put(0)

    def play(self, q):
        self.specgrams = calc_specgrams(self.waveform, PLAYER_SAMPLERATE)

        # playback start
        self.started = time.time()

        def playback(filename):
            # This requires SoX
            subprocess.call(['play', '-q', filename])

        pb = Process(target=playback, args=(self.filename,))
        pb.start()

        while 1:
            time.sleep(PLAYER_UPDATE_INTERVAL)

            elapsed = time.time() - self.started

            if elapsed >= (self.readed + 1) * PLAYER_FRAME_SHIFT:
                self.readed += 1

                if self.readed >= len(self.specgrams):
                    break

                # put latest specgram to queue
                q.put(self.specgrams[self.readed][:PLAYER_LENFREQ])

def player_main(filename, q):
    p = Player(filename, q)
    p.play(q)


import tensorflow as tf
import tensorflow.contrib as tc
from tensorflow.contrib.layers import variance_scaling_initializer as contrib_W_init

act_dict = {

    'RELU': tf.nn.relu,
    'LEAKY_RELU': tf.nn.leaky_relu,
    'SIGMOID': tf.nn.sigmoid,
    'SOFTMAX': tf.nn.softmax,
    'IDENTITY': tf.identity,
    'TANH': tf.nn.tanh,
    'ELU': tf.nn.elu
}

class Model(object):
    def __init__(self, name, scope):
        self.name = name
        self.scope = scope

    @property
    def vars(self):
        return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.scope + '/' + self.name)

    @property
    def trainable_vars(self):
        return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.scope + '/' + self.name)

    @property
    def perturbable_vars(self):
        return [var for var in self.trainable_vars if 'LayerNorm' not in var.name]

class Actor(Model):
    def __init__(self, net_config, nb_actions, action_low, action_high, scope='', name='actor', layer_norm=0):
        super(Actor, self).__init__(name=name, scope=scope)
        self.nb_actions = nb_actions
        self.layer_norm = layer_norm
        self.net_config = net_config
        self.action_low = action_low
        self.action_high = action_high

    def __call__(self, obs, reuse=False):
        with tf.variable_scope(self.name) as scope:
            if reuse:
                scope.reuse_variables()
            x = obs
            last_act = None
            for config in self.net_config:
                use_bias = not (config['B_INIT_VALUE']) == 'None'
                if config['TYPE'] == 'DENSE':
                    x = tf.layers.dense(x,
                                        config['N_UNITS'],
                                        kernel_initializer=contrib_W_init(),
                                        bias_initializer=tf.constant_initializer(value=config['B_INIT_VALUE']),
                                        use_bias=use_bias)
                else:
                    raise NotImplementedError("Not support this type layer: %s" % config['TYPE'])
                if self.layer_norm == 1 and config['NAME'] != 'OUTPUT':
                    x = tc.layers.layer_norm(x, center=True, scale=True)
                if act_dict[config['ACT']] is None:
                    raise NotImplementedError("Not support this type activation function: %s" % config['ACT'])
                else:
                    x = act_dict[config['ACT']](x)
                    last_act = config['ACT']
            if last_act == "TANH":
                x = (x + 1.0) / 2.0 * (self.action_high - self.action_low) + self.action_low
            elif last_act == 'SIGMOID':
                x = x * (self.action_high - self.action_low) + self.action_low
            else:
                raise ValueError('Change last act to tanh or sigmoid')
        return x

class Critic(Model):
    def __init__(self, net_config, scope, name='critic', layer_norm=0):
        super(Critic, self).__init__(name=name, scope=scope)
        self.layer_norm = layer_norm
        self.net_config = net_config

    def __call__(self, obs, action, reuse=False):

        with tf.variable_scope(self.name) as scope:
            if reuse:
                scope.reuse_variables()

            x = obs
            y = action
            count = 0
            for config in self.net_config:
                if count == 0:
                    x = tf.layers.dense(x,
                                        config['N_UNITS'],
                                        kernel_initializer=contrib_W_init(),
                                        bias_initializer=tf.constant_initializer(value=config['B_INIT_VALUE']))
                    y = tf.layers.dense(y,
                                        config['N_UNITS'],
                                        kernel_initializer=contrib_W_init(),
                                        bias_initializer=tf.constant_initializer(value=config['B_INIT_VALUE']))
                    x = tf.concat([x, y], axis=1)
                    count += 1
                else:
                    if config['TYPE'] == 'DENSE':
                        x = tf.layers.dense(x,
                                            config['N_UNITS'],
                                            kernel_initializer=contrib_W_init(),
                                            bias_initializer=tf.constant_initializer(value=config['B_INIT_VALUE']))
                    else:
                        raise NotImplementedError("Not support this type layer: %s" % config['TYPE'])
                    if self.layer_norm == 1 and config['NAME'] != 'OUTPUT':
                        x = tc.layers.layer_norm(x, center=True, scale=True)
                    if act_dict[config['ACT']] is None:
                        raise NotImplementedError("Not support this type activation function: %s" % config['ACT'])
                    else:
                        x = act_dict[config['ACT']](x)
                    count += 1
        return x

    @property
    def output_vars(self):
        output_vars = [var for var in self.trainable_vars if 'output' in var.name]
        return output_vars