from tkinter import *

root = Tk()

root.title("Calculator")

entry_box = Entry(root,width=35,font=('Century Schoolbook', 12))
entry_box.grid(row=0,column=0,columnspan=4,padx=10,pady=20,ipady=5)

answer = 0
val1=""

operands=['+','-','*','/','=']

def button_click(number):
    current = entry_box.get()
    if number in operands:
        if current[-1] not in operands:
            entry_box.delete(0,END)
            entry_box.insert(0,str(current)+str(number))

    elif number == '.':
        flag = 1
        l = len(current)
        i = -1
        while(i>=-l):
            if current[i] == '.':
                flag = 0
                break
            elif current[i] in operands:
                flag = 1
                break
            i=i-1
        if(flag == 1):
            entry_box.delete(0,END)
            entry_box.insert(0,str(current)+str(number))

    else:
        entry_box.delete(0,END)
        entry_box.insert(0,str(current)+str(number))

def button_clear():
    entry_box.delete(0,END)

#def operations(op):

def button_equal():
    current = entry_box.get()
    if current[-1] not in operands:
        entry_box.delete(0,END)
        entry_box.insert(0,str(current)+"=")
        current = entry_box.get()
        op = '+'
        val1=""
        answer=0.00
        for i in range(len(current)):
            if current[i] in operands:
                if op == '+':
                    answer = answer + float(val1)
                if op == '-':
                    answer = answer - float(val1)
                if op == '*':
                    answer = answer * float(val1)
                if op == '/':
                    answer = answer / float(val1)
                val1=""
                op = current[i]
            else:
                val1 = val1 + current[i]
            i=i+1
        entry_box.delete(0,END)
        entry_box.insert(0,answer)

def button_back():
    current=entry_box.get()
    entry_box.delete(0,END)
    entry_box.insert(0,current[0:-1])

#def operations:

back_button = Button(root,text="←",width=20,height=2,command=button_back)
back_button.grid(row=1,column=0,columnspan=2,padx=5,pady=5)

clear_button = Button(root,text="Clear",width=20,height=2,command=button_clear)
clear_button.grid(row=1,column=2,columnspan=2,padx=5,pady=5)

button_7 = Button(root,text="7",width=7,height=2,command=lambda:button_click(7))
button_7.grid(row=2,column=0,padx=5,pady=5)

button_8 = Button(root,text="8",width=7,height=2,command=lambda:button_click(8))
button_8.grid(row=2,column=1,padx=5,pady=5)

button_9 = Button(root,text="9",width=7,height=2,command=lambda:button_click(9))
button_9.grid(row=2,column=2,padx=5,pady=5)

button_add = Button(root,text="+",width=7,height=2,command=lambda:button_click('+'))
button_add.grid(row=2,column=3,padx=5,pady=5)

button_4 = Button(root,text="4",width=7,height=2,command=lambda:button_click(4))
button_4.grid(row=3,column=0,padx=5,pady=5)

button_5 = Button(root,text="5",width=7,height=2,command=lambda:button_click(5))
button_5.grid(row=3,column=1,padx=5,pady=5)

button_6 = Button(root,text="6",width=7,height=2,command=lambda:button_click(6))
button_6.grid(row=3,column=2,padx=5,pady=5)

button_sub = Button(root,text="-",width=7,height=2,command=lambda:button_click('-'))
button_sub.grid(row=3,column=3,padx=5,pady=5)

button_1 = Button(root,text="1",width=7,height=2,command=lambda:button_click(1))
button_1.grid(row=4,column=0,padx=5,pady=5)

button_2 = Button(root,text="2",width=7,height=2,command=lambda:button_click(2))
button_2.grid(row=4,column=1,padx=5,pady=5)

button_3 = Button(root,text="3",width=7,height=2,command=lambda:button_click(3))
button_3.grid(row=4,column=2,padx=5,pady=5)

button_mul = Button(root,text="*",width=7,height=2,command=lambda:button_click('*'))
button_mul.grid(row=4,column=3,padx=5,pady=5)

button_0 = Button(root,text="0",width=20,height=2,command=lambda:button_click(0))
button_0.grid(row=5,column=0,columnspan=2,padx=5,pady=5)

button_dec = Button(root,text=".",width=7,height=2,command=lambda:button_click("."))
button_dec.grid(row=5,column=2,padx=5,pady=5)

button_div = Button(root,text="/",width=7,height=2,command=lambda:button_click('/'))
button_div.grid(row=5,column=3,padx=5,pady=5)

button_equal = Button(root,text="=",width=43,height=2,command=button_equal)
button_equal.grid(row=6,column=0,columnspan=4,padx=5,pady=5)

root.mainloop()


from django.shortcuts import render
from .models import Product
from .forms import ProductForm
from django.http import HttpResponse

def list(request):
    products = Product.objects.all()
    context = {'products': products}
    return render(request, 'product/list.html', context)

def save_product(request):
    if(request.method == 'POST'):
        product = ProductForm(request.POST)
        if product.is_valid:
            product.save()

            products = Product.objects.all()
            context = {'products': products, 'product': products}
            return render(request, 'product/list.html', context)

    else:
        return render(request, 'layout/create.html', {'product': product})

def create(request):
    form = ProductForm()
    context = {'form': form}
    return render(request, 'product/create.html', context)

def delete(request, id):
    if(request.method == 'GET'):
        product = Product.objects.get(id=id)
        product.delete()

        products = Product.objects.all()
        context = {'products': products}
        return render(request, 'product/list.html', context)

def update(request, id):
    product = Product.objects.get(id=id)
    if(request.method == 'GET'):
        form = ProductForm(instance=product)
        context = {'form': form, 'id': id}
        return render(request, 'product/update.html', context)

    if(request.method == 'POST'):
        form = ProductForm(request.POST, instance=product)
        if form.is_valid():
            form.save()

            products = Product.objects.all()
            context = {'products': products}
            return render(request, 'product/list.html', context)


import librosa,librosa.display
import matplotlib.pyplot as plt
import numpy as np

file="your-summer-day-5448.wav"

#waveform
signal,sr=librosa.load(file,sr=22050) #signal will be a numpy array which will have no.of values=sr*duration of sound track
librosa.display.waveplot(signal,sr=sr) #visualizing the wave
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.show()

#time domain->frequency domain(fourier tranform)
fft=np.fft.fft(signal) #np array

magnitude= np.abs(fft) #indicates contrib of each frequency to the sound
frequency=np.linspace(0,sr,len(magnitude))
left_frequency=frequency[:int(len(frequency)/2)]
left_magnitude=magnitude[:int(len(magnitude)/2)]
plt.plot(left_frequency,left_magnitude)
plt.xlabel("Frequency")
plt.ylabel("Magnitude")
plt.show()

#get spectogram(amplitude as function of freq and time)
n_fft=2048 #no.of sample in each fft
hop_length=512 #amount of shift to next fft to the right
stft=librosa.core.stft(signal,hop_length=hop_length,n_fft=n_fft)
spectrogram=np.abs(stft)
log_spectrogram=librosa.amplitude_to_db(spectrogram) #converting amplitude to decibel

librosa.display.specshow(log_spectrogram,sr=sr,hop_length=hop_length) #specshow helps to visualize spectogram like data(x axis, y axis and color label)
plt.xlabel("Time")
plt.ylabel("Frequency")
plt.colorbar() #amplitude will be displayed by color
plt.show()

#mfccs
MFCCS=librosa.feature.mfcc(signal,n_fft=n_fft,hop_length=hop_length,n_mfcc=13)
librosa.display.specshow(MFCCS,sr=sr,hop_length=hop_length) #specshow helps to visualize spectogram like data(x axis, y axis and color label)
plt.xlabel("Time")
plt.ylabel("MFCC")
plt.colorbar() #amplitude will be displayed by color
plt.show()


import sys
import re
import os

# nagios exit code
STATUS_OK = 0
STATUS_WARNING = 1
STATUS_ERROR = 2
STATUS_UNKNOWN = 3

def main():
    try:
        with open('/proc/drbd') as f:
            for line in f:
                match = re.search('^\ *(.*): cs:(.*) ro:([^\ ]*) ds:([^\ ]*) .*$', line)
                if match:
                    id = match.group(1)
                    cs = match.group(2)
                    ro = match.group(3)
                    ds = match.group(4)
                    res = id

                    for root, dirs, files in os.walk('/dev/drbd/by-res/'):
                        for f in files:
                            if f == id:
                                res = os.path.basename(root)

                    error_msg='DRBD %s (drbd%s) state is %s (ro:%s, ds:%s)' % (res, id, cs, ro, ds)

                    if cs not in ('Connected', 'SyncSource', 'SyncTarget') or 'Unknown' in ro or 'Unknown' in ds:
                        print(error_msg)
                        return STATUS_ERROR
                    if cs == 'SyncTarget':
                        print(error_msg)
                        return STATUS_WARNING

            print('DRDB is OK')
            return STATUS_OK
    except IOError as e:
        print(e)
        return STATUS_UNKNOWN

if __name__ == "__main__":
    sys.exit(main())


import telebot
from config import TOKEN, keys
from extensions import ExchangeException, Exchange

bot = telebot.TeleBot(TOKEN)

# Обработка команды /start
@bot.message_handler(commands=['start'])
def start(message):
    start = "Привет! Я бот, который может вернуть цену на определенное количество валюты.\n\n" \
                   "Пример использования: <имя валюты, цену которой вы хотите узнать> " \
                   "<имя валюты, в которой нужно узнать цену первой валюты> <количество первой валюты>\n\n" \
                   "Команды:\n" \
                   "/start - выводит инструкции по применению бота\n" \
                   "/help - выводит список команд бота\n" \
                   "/values - выводит информацию о всех доступных валютах\n\n" \
                   "Пример запроса: Рубль доллар 100"
    bot.reply_to(message, start)

# Обработка команды /help
@bot.message_handler(commands=['help'])
def help(message):
    help = "/start - выводит инструкции по применению бота\n" \
           "/help - выводит список команд бота\n" \
           "/values - выводит информацию о всех доступных валютах\n\n" \
           "Регистр значения не имеет.\n\n" \
           "Пример запроса: Рубль доллар 100"
    bot.reply_to(message,help)

# Обработка команды /values
@bot.message_handler(commands=['values'])
def values(message: telebot.types.Message):
    text = 'Доступные валюты:'
    for key in keys.keys():
        text = '\n'.join((text, key,))
    bot.reply_to(message, text)

# Обработка текстовых сообщений от пользователя
@bot.message_handler(content_types=['text'])
def get_price(message: telebot.types.Message):
    try:
        values = message.text.lower().split(' ')  # преобразование в нижний регистр регистр

        if len(values) != 3:
            raise ExchangeException('Введите команду или 3 параметра')

        quote, base, amount = values
        total_base = Exchange.get_price(quote, base, amount)
    except ExchangeException as e:
        bot.reply_to(message, f'Ошибка пользователя.\n{e}')
    except Exception as e:
        bot.reply_to(message, f'Что-то пошло не так с {e}')
    else:
        text = f'Переводим {quote} в {base}\n{amount} {quote} = {total_base} {base}'
        bot.send_message(message.chat.id, text)

bot.polling()


# main.py

from project.scraper import Scraper
from project.database import Database

def main():
    """
    main function
    """
    #Initialize the scraper
    scraper = Scraper()

    #Get the data
    response = scraper.scrape_data()

    data = scraper.parse_response(response)

    #Connect to the database
    db = Database()
    db.connect()

    #Store the data
    db.store_data(data)

    #Close connection
    db.close()

if __name__ == "__main__":
    main()


import collections
from collections import abc
import getpass
import io
import itertools
import logging
import os
import socket
import struct
import sys
import threading
import time
import timeit
import traceback
import types
import warnings

from absl import flags
from absl.logging import converter

try:
  from typing import NoReturn
except ImportError:
  pass

FLAGS = flags.FLAGS

# Logging levels.
FATAL = converter.ABSL_FATAL
ERROR = converter.ABSL_ERROR
WARNING = converter.ABSL_WARNING
WARN = converter.ABSL_WARNING  # Deprecated name.
INFO = converter.ABSL_INFO
DEBUG = converter.ABSL_DEBUG

# Regex to match/parse log line prefixes.
ABSL_LOGGING_PREFIX_REGEX = (
    r'^(?P<severity>[IWEF])'
    r'(?P<month>\d\d)(?P<day>\d\d) '
    r'(?P<hour>\d\d):(?P<minute>\d\d):(?P<second>\d\d)'
    r'\.(?P<microsecond>\d\d\d\d\d\d) +'
    r'(?P<thread_id>-?\d+) '
    r'(?P<filename>[a-zA-Z<][\w._<>-]+):(?P<line>\d+)')

# Mask to convert integer thread ids to unsigned quantities for logging purposes
_THREAD_ID_MASK = 2 ** (struct.calcsize('L') * 8) - 1

# Extra property set on the LogRecord created by ABSLLogger when its level is
# CRITICAL/FATAL.
_ABSL_LOG_FATAL = '_absl_log_fatal'
# Extra prefix added to the log message when a non-absl logger logs a
# CRITICAL/FATAL message.
_CRITICAL_PREFIX = 'CRITICAL - '

# Used by findCaller to skip callers from */logging/__init__.py.
_LOGGING_FILE_PREFIX = os.path.join('logging', '__init__.')

# The ABSL logger instance, initialized in _initialize().
_absl_logger = None
# The ABSL handler instance, initialized in _initialize().
_absl_handler = None

_CPP_NAME_TO_LEVELS = {
    'debug': '0',  # Abseil C++ has no DEBUG level, mapping it to INFO here.
    'info': '0',
    'warning': '1',
    'warn': '1',
    'error': '2',
    'fatal': '3'
}

_CPP_LEVEL_TO_NAMES = {
    '0': 'info',
    '1': 'warning',
    '2': 'error',
    '3': 'fatal',
}

class _VerbosityFlag(flags.Flag):
  """Flag class for -v/--verbosity."""

  def __init__(self, *args, **kwargs):
    super(_VerbosityFlag, self).__init__(
        flags.IntegerParser(),
        flags.ArgumentSerializer(),
        *args, **kwargs)

  @property
  def value(self):
    return self._value

  @value.setter
  def value(self, v):
    self._value = v
    self._update_logging_levels()

  def _update_logging_levels(self):
    """Updates absl logging levels to the current verbosity.

    Visibility: module-private
    """
    if not _absl_logger:
      return

    if self._value <= converter.ABSL_DEBUG:
      standard_verbosity = converter.absl_to_standard(self._value)
    else:
      # --verbosity is set to higher than 1 for vlog.
      standard_verbosity = logging.DEBUG - (self._value - 1)

    # Also update root level when absl_handler is used.
    if _absl_handler in logging.root.handlers:
      # Make absl logger inherit from the root logger. absl logger might have
      # a non-NOTSET value if logging.set_verbosity() is called at import time.
      _absl_logger.setLevel(logging.NOTSET)
      logging.root.setLevel(standard_verbosity)
    else:
      _absl_logger.setLevel(standard_verbosity)

class _LoggerLevelsFlag(flags.Flag):
  """Flag class for --logger_levels."""

  def __init__(self, *args, **kwargs):
    super(_LoggerLevelsFlag, self).__init__(
        _LoggerLevelsParser(),
        _LoggerLevelsSerializer(),
        *args, **kwargs)

  @property
  def value(self):
    # For lack of an immutable type, be defensive and return a copy.
    # Modifications to the dict aren't supported and won't have any affect.
    # While Py3 could use MappingProxyType, that isn't deepcopy friendly, so
    # just return a copy.
    return self._value.copy()

  @value.setter
  def value(self, v):
    self._value = {} if v is None else v
    self._update_logger_levels()

  def _update_logger_levels(self):
    # Visibility: module-private.
    # This is called by absl.app.run() during initialization.
    for name, level in self._value.items():
      logging.getLogger(name).setLevel(level)

class _LoggerLevelsParser(flags.ArgumentParser):
  """Parser for --logger_levels flag."""

  def parse(self, value):
    if isinstance(value, abc.Mapping):
      return value

    pairs = [pair.strip() for pair in value.split(',') if pair.strip()]

    # Preserve the order so that serialization is deterministic.
    levels = collections.OrderedDict()
    for name_level in pairs:
      name, level = name_level.split(':', 1)
      name = name.strip()
      level = level.strip()
      levels[name] = level
    return levels

class _LoggerLevelsSerializer(object):
  """Serializer for --logger_levels flag."""

  def serialize(self, value):
    if isinstance(value, str):
      return value
    return ','.join(
        '{}:{}'.format(name, level) for name, level in value.items())

class _StderrthresholdFlag(flags.Flag):
  """Flag class for --stderrthreshold."""

  def __init__(self, *args, **kwargs):
    super(_StderrthresholdFlag, self).__init__(
        flags.ArgumentParser(),
        flags.ArgumentSerializer(),
        *args, **kwargs)

  @property
  def value(self):
    return self._value

  @value.setter
  def value(self, v):
    if v in _CPP_LEVEL_TO_NAMES:
      # --stderrthreshold also accepts numeric strings whose values are
      # Abseil C++ log levels.
      cpp_value = int(v)
      v = _CPP_LEVEL_TO_NAMES[v]  # Normalize to strings.
    elif v.lower() in _CPP_NAME_TO_LEVELS:
      v = v.lower()
      if v == 'warn':
        v = 'warning'  # Use 'warning' as the canonical name.
      cpp_value = int(_CPP_NAME_TO_LEVELS[v])
    else:
      raise ValueError(
          '--stderrthreshold must be one of (case-insensitive) '
          "'debug', 'info', 'warning', 'error', 'fatal', "
          "or '0', '1', '2', '3', not '%s'" % v)

    self._value = v

flags.DEFINE_boolean('logtostderr',
                     False,
                     'Should only log to stderr?', allow_override_cpp=True)
flags.DEFINE_boolean('alsologtostderr',
                     False,
                     'also log to stderr?', allow_override_cpp=True)
flags.DEFINE_string('log_dir',
                    os.getenv('TEST_TMPDIR', ''),
                    'directory to write logfiles into',
                    allow_override_cpp=True)
flags.DEFINE_flag(_VerbosityFlag(
    'verbosity', -1,
    'Logging verbosity level. Messages logged at this level or lower will '
    'be included. Set to 1 for debug logging. If the flag was not set or '
    'supplied, the value will be changed from the default of -1 (warning) to '
    '0 (info) after flags are parsed.',
    short_name='v', allow_hide_cpp=True))
flags.DEFINE_flag(
    _LoggerLevelsFlag(
        'logger_levels', {},
        'Specify log level of loggers. The format is a CSV list of '
        '`name:level`. Where `name` is the logger name used with '
        '`logging.getLogger()`, and `level` is a level name  (INFO, DEBUG, '
        'etc). e.g. `myapp.foo:INFO,other.logger:DEBUG`'))
flags.DEFINE_flag(_StderrthresholdFlag(
    'stderrthreshold', 'fatal',
    'log messages at this level, or more severe, to stderr in '
    'addition to the logfile.  Possible values are '
    "'debug', 'info', 'warning', 'error', and 'fatal'.  "
    'Obsoletes --alsologtostderr. Using --alsologtostderr '
    'cancels the effect of this flag. Please also note that '
    'this flag is subject to --verbosity and requires logfile '
    'not be stderr.', allow_hide_cpp=True))
flags.DEFINE_boolean('showprefixforinfo', True,
                     'If False, do not prepend prefix to info messages '
                     'when it\'s logged to stderr, '
                     '--verbosity is set to INFO level, '
                     'and python logging is used.')

def get_verbosity():
  """Returns the logging verbosity."""
  return FLAGS['verbosity'].value

def set_verbosity(v):
  """Sets the logging verbosity.

  Causes all messages of level <= v to be logged,
  and all messages of level > v to be silently discarded.

  Args:
    v: int|str, the verbosity level as an integer or string. Legal string values
        are those that can be coerced to an integer as well as case-insensitive
        'debug', 'info', 'warning', 'error', and 'fatal'.
  """
  try:
    new_level = int(v)
  except ValueError:
    new_level = converter.ABSL_NAMES[v.upper()]
  FLAGS.verbosity = new_level

def set_stderrthreshold(s):
  """Sets the stderr threshold to the value passed in.

  Args:
    s: str|int, valid strings values are case-insensitive 'debug',
        'info', 'warning', 'error', and 'fatal'; valid integer values are
        logging.DEBUG|INFO|WARNING|ERROR|FATAL.

  Raises:
      ValueError: Raised when s is an invalid value.
  """
  if s in converter.ABSL_LEVELS:
    FLAGS.stderrthreshold = converter.ABSL_LEVELS[s]
  elif isinstance(s, str) and s.upper() in converter.ABSL_NAMES:
    FLAGS.stderrthreshold = s
  else:
    raise ValueError(
        'set_stderrthreshold only accepts integer absl logging level '
        'from -3 to 1, or case-insensitive string values '
        "'debug', 'info', 'warning', 'error', and 'fatal'. "
        'But found "{}" ({}).'.format(s, type(s)))

def fatal(msg, *args, **kwargs):
  # type: (Any, Any, Any) -> NoReturn
  """Logs a fatal message."""
  log(FATAL, msg, *args, **kwargs)

def error(msg, *args, **kwargs):
  """Logs an error message."""
  log(ERROR, msg, *args, **kwargs)

def warning(msg, *args, **kwargs):
  """Logs a warning message."""
  log(WARNING, msg, *args, **kwargs)

def warn(msg, *args, **kwargs):
  """Deprecated, use 'warning' instead."""
  warnings.warn("The 'warn' function is deprecated, use 'warning' instead",
                DeprecationWarning, 2)
  log(WARNING, msg, *args, **kwargs)

def info(msg, *args, **kwargs):
  """Logs an info message."""
  log(INFO, msg, *args, **kwargs)

def debug(msg, *args, **kwargs):
  """Logs a debug message."""
  log(DEBUG, msg, *args, **kwargs)

def exception(msg, *args, **kwargs):
  """Logs an exception, with traceback and message."""
  error(msg, *args, **kwargs, exc_info=True)

# Counter to keep track of number of log entries per token.
_log_counter_per_token = {}

def _get_next_log_count_per_token(token):
  """Wrapper for _log_counter_per_token. Thread-safe.

  Args:
    token: The token for which to look up the count.

  Returns:
    The number of times this function has been called with
    *token* as an argument (starting at 0).
  """
  # Can't use a defaultdict because defaultdict isn't atomic, whereas
  # setdefault is.
  return next(_log_counter_per_token.setdefault(token, itertools.count()))

def log_every_n(level, msg, n, *args):
  """Logs ``msg % args`` at level 'level' once per 'n' times.

  Logs the 1st call, (N+1)st call, (2N+1)st call,  etc.
  Not threadsafe.

  Args:
    level: int, the absl logging level at which to log.
    msg: str, the message to be logged.
    n: int, the number of times this should be called before it is logged.
    *args: The args to be substituted into the msg.
  """
  count = _get_next_log_count_per_token(get_absl_logger().findCaller())
  log_if(level, msg, not (count % n), *args)

# Keeps track of the last log time of the given token.
# Note: must be a dict since set/get is atomic in CPython.
# Note: entries are never released as their number is expected to be low.
_log_timer_per_token = {}

def _seconds_have_elapsed(token, num_seconds):
  """Tests if 'num_seconds' have passed since 'token' was requested.

  Not strictly thread-safe - may log with the wrong frequency if called
  concurrently from multiple threads. Accuracy depends on resolution of
  'timeit.default_timer()'.

  Always returns True on the first call for a given 'token'.

  Args:
    token: The token for which to look up the count.
    num_seconds: The number of seconds to test for.

  Returns:
    Whether it has been >= 'num_seconds' since 'token' was last requested.
  """
  now = timeit.default_timer()
  then = _log_timer_per_token.get(token, None)
  if then is None or (now - then) >= num_seconds:
    _log_timer_per_token[token] = now
    return True
  else:
    return False

def log_every_n_seconds(level, msg, n_seconds, *args):
  """Logs ``msg % args`` at level ``level`` iff ``n_seconds`` elapsed since last call.

  Logs the first call, logs subsequent calls if 'n' seconds have elapsed since
  the last logging call from the same call site (file + line). Not thread-safe.

  Args:
    level: int, the absl logging level at which to log.
    msg: str, the message to be logged.
    n_seconds: float or int, seconds which should elapse before logging again.
    *args: The args to be substituted into the msg.
  """
  should_log = _seconds_have_elapsed(get_absl_logger().findCaller(), n_seconds)
  log_if(level, msg, should_log, *args)

def log_first_n(level, msg, n, *args):
  """Logs ``msg % args`` at level ``level`` only first ``n`` times.

  Not threadsafe.

  Args:
    level: int, the absl logging level at which to log.
    msg: str, the message to be logged.
    n: int, the maximal number of times the message is logged.
    *args: The args to be substituted into the msg.
  """
  count = _get_next_log_count_per_token(get_absl_logger().findCaller())
  log_if(level, msg, count < n, *args)

def log_if(level, msg, condition, *args):
  """Logs ``msg % args`` at level ``level`` only if condition is fulfilled."""
  if condition:
    log(level, msg, *args)

def log(level, msg, *args, **kwargs):
  """Logs ``msg % args`` at absl logging level ``level``.

  If no args are given just print msg, ignoring any interpolation specifiers.

  Args:
    level: int, the absl logging level at which to log the message
        (logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbose logging
        level constants are also supported, callers should prefer explicit
        logging.vlog() calls for such purpose.

    msg: str, the message to be logged.
    *args: The args to be substituted into the msg.
    **kwargs: May contain exc_info to add exception traceback to message.
  """
  if level > converter.ABSL_DEBUG:
    # Even though this function supports level that is greater than 1, users
    # should use logging.vlog instead for such cases.
    # Treat this as vlog, 1 is equivalent to DEBUG.
    standard_level = converter.STANDARD_DEBUG - (level - 1)
  else:
    if level < converter.ABSL_FATAL:
      level = converter.ABSL_FATAL
    standard_level = converter.absl_to_standard(level)

  # Match standard logging's behavior. Before use_absl_handler() and
  # logging is configured, there is no handler attached on _absl_logger nor
  # logging.root. So logs go no where.
  if not logging.root.handlers:
    logging.basicConfig()

  _absl_logger.log(standard_level, msg, *args, **kwargs)

def vlog(level, msg, *args, **kwargs):
  """Log ``msg % args`` at C++ vlog level ``level``.

  Args:
    level: int, the C++ verbose logging level at which to log the message,
        e.g. 1, 2, 3, 4... While absl level constants are also supported,
        callers should prefer logging.log|debug|info|... calls for such purpose.
    msg: str, the message to be logged.
    *args: The args to be substituted into the msg.
    **kwargs: May contain exc_info to add exception traceback to message.
  """
  log(level, msg, *args, **kwargs)

def vlog_is_on(level):
  """Checks if vlog is enabled for the given level in caller's source file.

  Args:
    level: int, the C++ verbose logging level at which to log the message,
        e.g. 1, 2, 3, 4... While absl level constants are also supported,
        callers should prefer level_debug|level_info|... calls for
        checking those.

  Returns:
    True if logging is turned on for that level.
  """

  if level > converter.ABSL_DEBUG:
    # Even though this function supports level that is greater than 1, users
    # should use logging.vlog instead for such cases.
    # Treat this as vlog, 1 is equivalent to DEBUG.
    standard_level = converter.STANDARD_DEBUG - (level - 1)
  else:
    if level < converter.ABSL_FATAL:
      level = converter.ABSL_FATAL
    standard_level = converter.absl_to_standard(level)
  return _absl_logger.isEnabledFor(standard_level)

def flush():
  """Flushes all log files."""
  get_absl_handler().flush()

def level_debug():
  """Returns True if debug logging is turned on."""
  return get_verbosity() >= DEBUG

def level_info():
  """Returns True if info logging is turned on."""
  return get_verbosity() >= INFO

def level_warning():
  """Returns True if warning logging is turned on."""
  return get_verbosity() >= WARNING

level_warn = level_warning  # Deprecated function.

def level_error():
  """Returns True if error logging is turned on."""
  return get_verbosity() >= ERROR

def get_log_file_name(level=INFO):
  """Returns the name of the log file.

  For Python logging, only one file is used and level is ignored. And it returns
  empty string if it logs to stderr/stdout or the log stream has no `name`
  attribute.

  Args:
    level: int, the absl.logging level.

  Raises:
    ValueError: Raised when `level` has an invalid value.
  """
  if level not in converter.ABSL_LEVELS:
    raise ValueError('Invalid absl.logging level {}'.format(level))
  stream = get_absl_handler().python_handler.stream
  if (stream == sys.stderr or stream == sys.stdout or
      not hasattr(stream, 'name')):
    return ''
  else:
    return stream.name

def find_log_dir_and_names(program_name=None, log_dir=None):
  """Computes the directory and filename prefix for log file.

  Args:
    program_name: str|None, the filename part of the path to the program that
        is running without its extension.  e.g: if your program is called
        ``usr/bin/foobar.py`` this method should probably be called with
        ``program_name='foobar`` However, this is just a convention, you can
        pass in any string you want, and it will be used as part of the
        log filename. If you don't pass in anything, the default behavior
        is as described in the example.  In python standard logging mode,
        the program_name will be prepended with ``py_`` if it is the
        ``program_name`` argument is omitted.
    log_dir: str|None, the desired log directory.

  Returns:
    (log_dir, file_prefix, symlink_prefix)

  Raises:
    FileNotFoundError: raised in Python 3 when it cannot find a log directory.
    OSError: raised in Python 2 when it cannot find a log directory.
  """
  if not program_name:
    # Strip the extension (foobar.par becomes foobar, and
    # fubar.py becomes fubar). We do this so that the log
    # file names are similar to C++ log file names.
    program_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]

    # Prepend py_ to files so that python code gets a unique file, and
    # so that C++ libraries do not try to write to the same log files as us.
    program_name = 'py_%s' % program_name

  actual_log_dir = find_log_dir(log_dir=log_dir)

  try:
    username = getpass.getuser()
  except KeyError:
    # This can happen, e.g. when running under docker w/o passwd file.
    if hasattr(os, 'getuid'):
      # Windows doesn't have os.getuid
      username = str(os.getuid())
    else:
      username = 'unknown'
  hostname = socket.gethostname()
  file_prefix = '%s.%s.%s.log' % (program_name, hostname, username)

  return actual_log_dir, file_prefix, program_name

def find_log_dir(log_dir=None):
  """Returns the most suitable directory to put log files into.

  Args:
    log_dir: str|None, if specified, the logfile(s) will be created in that
        directory.  Otherwise if the --log_dir command-line flag is provided,
        the logfile will be created in that directory.  Otherwise the logfile
        will be created in a standard location.

  Raises:
    FileNotFoundError: raised in Python 3 when it cannot find a log directory.
    OSError: raised in Python 2 when it cannot find a log directory.
  """
  # Get a list of possible log dirs (will try to use them in order).
  if log_dir:
    # log_dir was explicitly specified as an arg, so use it and it alone.
    dirs = [log_dir]
  elif FLAGS['log_dir'].value:
    # log_dir flag was provided, so use it and it alone (this mimics the
    # behavior of the same flag in logging.cc).
    dirs = [FLAGS['log_dir'].value]
  else:
    dirs = ['/tmp/', './']

  # Find the first usable log dir.
  for d in dirs:
    if os.path.isdir(d) and os.access(d, os.W_OK):
      return d
  raise FileNotFoundError(
      "Can't find a writable directory for logs, tried %s" % dirs)

def get_absl_log_prefix(record):
  """Returns the absl log prefix for the log record.

  Args:
    record: logging.LogRecord, the record to get prefix for.
  """
  created_tuple = time.localtime(record.created)
  created_microsecond = int(record.created % 1.0 * 1e6)

  critical_prefix = ''
  level = record.levelno
  if _is_non_absl_fatal_record(record):
    # When the level is FATAL, but not logged from absl, lower the level so
    # it's treated as ERROR.
    level = logging.ERROR
    critical_prefix = _CRITICAL_PREFIX
  severity = converter.get_initial_for_level(level)

  return '%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] %s' % (
      severity,
      created_tuple.tm_mon,
      created_tuple.tm_mday,
      created_tuple.tm_hour,
      created_tuple.tm_min,
      created_tuple.tm_sec,
      created_microsecond,
      _get_thread_id(),
      record.filename,
      record.lineno,
      critical_prefix)

def skip_log_prefix(func):
  """Skips reporting the prefix of a given function or name by :class:`~absl.logging.ABSLLogger`.

  This is a convenience wrapper function / decorator for
  :meth:`~absl.logging.ABSLLogger.register_frame_to_skip`.

  If a callable function is provided, only that function will be skipped.
  If a function name is provided, all functions with the same name in the
  file that this is called in will be skipped.

  This can be used as a decorator of the intended function to be skipped.

  Args:
    func: Callable function or its name as a string.

  Returns:
    func (the input, unchanged).

  Raises:
    ValueError: The input is callable but does not have a function code object.
    TypeError: The input is neither callable nor a string.
  """
  if callable(func):
    func_code = getattr(func, '__code__', None)
    if func_code is None:
      raise ValueError('Input callable does not have a function code object.')
    file_name = func_code.co_filename
    func_name = func_code.co_name
    func_lineno = func_code.co_firstlineno
  elif isinstance(func, str):
    file_name = get_absl_logger().findCaller()[0]
    func_name = func
    func_lineno = None
  else:
    raise TypeError('Input is neither callable nor a string.')
  ABSLLogger.register_frame_to_skip(file_name, func_name, func_lineno)
  return func

def _is_non_absl_fatal_record(log_record):
  return (log_record.levelno >= logging.FATAL and
          not log_record.__dict__.get(_ABSL_LOG_FATAL, False))

def _is_absl_fatal_record(log_record):
  return (log_record.levelno >= logging.FATAL and
          log_record.__dict__.get(_ABSL_LOG_FATAL, False))

# Indicates if we still need to warn about pre-init logs going to stderr.
_warn_preinit_stderr = True

class PythonHandler(logging.StreamHandler):
  """The handler class used by Abseil Python logging implementation."""

  def __init__(self, stream=None, formatter=None):
    super(PythonHandler, self).__init__(stream)
    self.setFormatter(formatter or PythonFormatter())

  def start_logging_to_file(self, program_name=None, log_dir=None):
    """Starts logging messages to files instead of standard error."""
    FLAGS.logtostderr = False

    actual_log_dir, file_prefix, symlink_prefix = find_log_dir_and_names(
        program_name=program_name, log_dir=log_dir)

    basename = '%s.INFO.%s.%d' % (
        file_prefix,
        time.strftime('%Y%m%d-%H%M%S', time.localtime(time.time())),
        os.getpid())
    filename = os.path.join(actual_log_dir, basename)

    self.stream = open(filename, 'a', encoding='utf-8')

    # os.symlink is not available on Windows Python 2.
    if getattr(os, 'symlink', None):
      # Create a symlink to the log file with a canonical name.
      symlink = os.path.join(actual_log_dir, symlink_prefix + '.INFO')
      try:
        if os.path.islink(symlink):
          os.unlink(symlink)
        os.symlink(os.path.basename(filename), symlink)
      except EnvironmentError:
        # If it fails, we're sad but it's no error.  Commonly, this
        # fails because the symlink was created by another user and so
        # we can't modify it
        pass

  def use_absl_log_file(self, program_name=None, log_dir=None):
    """Conditionally logs to files, based on --logtostderr."""
    if FLAGS['logtostderr'].value:
      self.stream = sys.stderr
    else:
      self.start_logging_to_file(program_name=program_name, log_dir=log_dir)

  def flush(self):
    """Flushes all log files."""
    self.acquire()
    try:
      self.stream.flush()
    except (EnvironmentError, ValueError):
      # A ValueError is thrown if we try to flush a closed file.
      pass
    finally:
      self.release()

  def _log_to_stderr(self, record):
    """Emits the record to stderr.

    This temporarily sets the handler stream to stderr, calls
    StreamHandler.emit, then reverts the stream back.

    Args:
      record: logging.LogRecord, the record to log.
    """
    # emit() is protected by a lock in logging.Handler, so we don't need to
    # protect here again.
    old_stream = self.stream
    self.stream = sys.stderr
    try:
      super(PythonHandler, self).emit(record)
    finally:
      self.stream = old_stream

  def emit(self, record):
    """Prints a record out to some streams.

    1. If ``FLAGS.logtostderr`` is set, it will print to ``sys.stderr`` ONLY.
    2. If ``FLAGS.alsologtostderr`` is set, it will print to ``sys.stderr``.
    3. If ``FLAGS.logtostderr`` is not set, it will log to the stream
        associated with the current thread.

    Args:
      record: :class:`logging.LogRecord`, the record to emit.
    """
    # People occasionally call logging functions at import time before
    # our flags may have even been defined yet, let alone even parsed, as we
    # rely on the C++ side to define some flags for us and app init to
    # deal with parsing.  Match the C++ library behavior of notify and emit
    # such messages to stderr.  It encourages people to clean-up and does
    # not hide the message.
    level = record.levelno
    if not FLAGS.is_parsed():  # Also implies "before flag has been defined".
      global _warn_preinit_stderr
      if _warn_preinit_stderr:
        sys.stderr.write(
            'WARNING: Logging before flag parsing goes to stderr.\n')
        _warn_preinit_stderr = False
      self._log_to_stderr(record)
    elif FLAGS['logtostderr'].value:
      self._log_to_stderr(record)
    else:
      super(PythonHandler, self).emit(record)
      stderr_threshold = converter.string_to_standard(
          FLAGS['stderrthreshold'].value)
      if ((FLAGS['alsologtostderr'].value or level >= stderr_threshold) and
          self.stream != sys.stderr):
        self._log_to_stderr(record)
    # Die when the record is created from ABSLLogger and level is FATAL.
    if _is_absl_fatal_record(record):
      self.flush()  # Flush the log before dying.

      # In threaded python, sys.exit() from a non-main thread only
      # exits the thread in question.
      os.abort()

  def close(self):
    """Closes the stream to which we are writing."""
    self.acquire()
    try:
      self.flush()
      try:
        # Do not close the stream if it's sys.stderr|stdout. They may be
        # redirected or overridden to files, which should be managed by users
        # explicitly.
        user_managed = sys.stderr, sys.stdout, sys.__stderr__, sys.__stdout__
        if self.stream not in user_managed and (
            not hasattr(self.stream, 'isatty') or not self.stream.isatty()):
          self.stream.close()
      except ValueError:
        # A ValueError is thrown if we try to run isatty() on a closed file.
        pass
      super(PythonHandler, self).close()
    finally:
      self.release()

class ABSLHandler(logging.Handler):
  """Abseil Python logging module's log handler."""

  def __init__(self, python_logging_formatter):
    super(ABSLHandler, self).__init__()

    self._python_handler = PythonHandler(formatter=python_logging_formatter)
    self.activate_python_handler()

  def format(self, record):
    return self._current_handler.format(record)

  def setFormatter(self, fmt):
    self._current_handler.setFormatter(fmt)

  def emit(self, record):
    self._current_handler.emit(record)

  def flush(self):
    self._current_handler.flush()

  def close(self):
    super(ABSLHandler, self).close()
    self._current_handler.close()

  def handle(self, record):
    rv = self.filter(record)
    if rv:
      return self._current_handler.handle(record)
    return rv

  @property
  def python_handler(self):
    return self._python_handler

  def activate_python_handler(self):
    """Uses the Python logging handler as the current logging handler."""
    self._current_handler = self._python_handler

  def use_absl_log_file(self, program_name=None, log_dir=None):
    self._current_handler.use_absl_log_file(program_name, log_dir)

  def start_logging_to_file(self, program_name=None, log_dir=None):
    self._current_handler.start_logging_to_file(program_name, log_dir)

class PythonFormatter(logging.Formatter):
  """Formatter class used by :class:`~absl.logging.PythonHandler`."""

  def format(self, record):
    """Appends the message from the record to the results of the prefix.

    Args:
      record: logging.LogRecord, the record to be formatted.

    Returns:
      The formatted string representing the record.
    """
    if (not FLAGS['showprefixforinfo'].value and
        FLAGS['verbosity'].value == converter.ABSL_INFO and
        record.levelno == logging.INFO and
        _absl_handler.python_handler.stream == sys.stderr):
      prefix = ''
    else:
      prefix = get_absl_log_prefix(record)
    return prefix + super(PythonFormatter, self).format(record)

class ABSLLogger(logging.getLoggerClass()):
  """A logger that will create LogRecords while skipping some stack frames.

  This class maintains an internal list of filenames and method names
  for use when determining who called the currently executing stack
  frame.  Any method names from specific source files are skipped when
  walking backwards through the stack.

  Client code should use the register_frame_to_skip method to let the
  ABSLLogger know which method from which file should be
  excluded from the walk backwards through the stack.
  """
  _frames_to_skip = set()

  def findCaller(self, stack_info=False, stacklevel=1):
    """Finds the frame of the calling method on the stack.

    This method skips any frames registered with the
    ABSLLogger and any methods from this file, and whatever
    method is currently being used to generate the prefix for the log
    line.  Then it returns the file name, line number, and method name
    of the calling method.  An optional fourth item may be returned,
    callers who only need things from the first three are advised to
    always slice or index the result rather than using direct unpacking
    assignment.

    Args:
      stack_info: bool, when True, include the stack trace as a fourth item
          returned.  On Python 3 there are always four items returned - the
          fourth will be None when this is False.  On Python 2 the stdlib
          base class API only returns three items.  We do the same when this
          new parameter is unspecified or False for compatibility.

    Returns:
      (filename, lineno, methodname[, sinfo]) of the calling method.
    """
    f_to_skip = ABSLLogger._frames_to_skip
    # Use sys._getframe(2) instead of logging.currentframe(), it's slightly
    # faster because there is one less frame to traverse.
    frame = sys._getframe(2)  # pylint: disable=protected-access

    while frame:
      code = frame.f_code
      if (_LOGGING_FILE_PREFIX not in code.co_filename and
          (code.co_filename, code.co_name,
           code.co_firstlineno) not in f_to_skip and
          (code.co_filename, code.co_name) not in f_to_skip):
        sinfo = None
        if stack_info:
          out = io.StringIO()
          out.write(u'Stack (most recent call last):\n')
          traceback.print_stack(frame, file=out)
          sinfo = out.getvalue().rstrip(u'\n')
        return (code.co_filename, frame.f_lineno, code.co_name, sinfo)
      frame = frame.f_back

  def critical(self, msg, *args, **kwargs):
    """Logs ``msg % args`` with severity ``CRITICAL``."""
    self.log(logging.CRITICAL, msg, *args, **kwargs)

  def fatal(self, msg, *args, **kwargs):
    """Logs ``msg % args`` with severity ``FATAL``."""
    self.log(logging.FATAL, msg, *args, **kwargs)

  def error(self, msg, *args, **kwargs):
    """Logs ``msg % args`` with severity ``ERROR``."""
    self.log(logging.ERROR, msg, *args, **kwargs)

  def warn(self, msg, *args, **kwargs):
    """Logs ``msg % args`` with severity ``WARN``."""
    warnings.warn("The 'warn' method is deprecated, use 'warning' instead",
                  DeprecationWarning, 2)
    self.log(logging.WARN, msg, *args, **kwargs)

  def warning(self, msg, *args, **kwargs):
    """Logs ``msg % args`` with severity ``WARNING``."""
    self.log(logging.WARNING, msg, *args, **kwargs)

  def info(self, msg, *args, **kwargs):
    """Logs ``msg % args`` with severity ``INFO``."""
    self.log(logging.INFO, msg, *args, **kwargs)

  def debug(self, msg, *args, **kwargs):
    """Logs ``msg % args`` with severity ``DEBUG``."""
    self.log(logging.DEBUG, msg, *args, **kwargs)

  def log(self, level, msg, *args, **kwargs):
    """Logs a message at a cetain level substituting in the supplied arguments.

    This method behaves differently in python and c++ modes.

    Args:
      level: int, the standard logging level at which to log the message.
      msg: str, the text of the message to log.
      *args: The arguments to substitute in the message.
      **kwargs: The keyword arguments to substitute in the message.
    """
    if level >= logging.FATAL:
      # Add property to the LogRecord created by this logger.
      # This will be used by the ABSLHandler to determine whether it should
      # treat CRITICAL/FATAL logs as really FATAL.
      extra = kwargs.setdefault('extra', {})
      extra[_ABSL_LOG_FATAL] = True
    super(ABSLLogger, self).log(level, msg, *args, **kwargs)

  def handle(self, record):
    """Calls handlers without checking ``Logger.disabled``.

    Non-root loggers are set to disabled after setup with :func:`logging.config`
    if it's not explicitly specified. Historically, absl logging will not be
    disabled by that. To maintaining this behavior, this function skips
    checking the ``Logger.disabled`` bit.

    This logger can still be disabled by adding a filter that filters out
    everything.

    Args:
      record: logging.LogRecord, the record to handle.
    """
    if self.filter(record):
      self.callHandlers(record)

  @classmethod
  def register_frame_to_skip(cls, file_name, function_name, line_number=None):
    """Registers a function name to skip when walking the stack.

    The :class:`~absl.logging.ABSLLogger` sometimes skips method calls on the
    stack to make the log messages meaningful in their appropriate context.
    This method registers a function from a particular file as one
    which should be skipped.

    Args:
      file_name: str, the name of the file that contains the function.
      function_name: str, the name of the function to skip.
      line_number: int, if provided, only the function with this starting line
          number will be skipped. Otherwise, all functions with the same name
          in the file will be skipped.
    """
    if line_number is not None:
      cls._frames_to_skip.add((file_name, function_name, line_number))
    else:
      cls._frames_to_skip.add((file_name, function_name))

def _get_thread_id():
  """Gets id of current thread, suitable for logging as an unsigned quantity.

  If pywrapbase is linked, returns GetTID() for the thread ID to be
  consistent with C++ logging.  Otherwise, returns the numeric thread id.
  The quantities are made unsigned by masking with 2*sys.maxint + 1.

  Returns:
    Thread ID unique to this process (unsigned)
  """
  thread_id = threading.get_ident()
  return thread_id & _THREAD_ID_MASK

def get_absl_logger():
  """Returns the absl logger instance."""
  return _absl_logger

def get_absl_handler():
  """Returns the absl handler instance."""
  return _absl_handler

def use_python_logging(quiet=False):
  """Uses the python implementation of the logging code.

  Args:
    quiet: No logging message about switching logging type.
  """
  get_absl_handler().activate_python_handler()
  if not quiet:
    info('Restoring pure python logging')

_attempted_to_remove_stderr_stream_handlers = False

def use_absl_handler():
  """Uses the ABSL logging handler for logging.

  This method is called in :func:`app.run()<absl.app.run>` so the absl handler
  is used in absl apps.
  """
  global _attempted_to_remove_stderr_stream_handlers
  if not _attempted_to_remove_stderr_stream_handlers:
    # The absl handler logs to stderr by default. To prevent double logging to
    # stderr, the following code tries its best to remove other handlers that
    # emit to stderr. Those handlers are most commonly added when
    # logging.info/debug is called before calling use_absl_handler().
    handlers = [
        h for h in logging.root.handlers
        if isinstance(h, logging.StreamHandler) and h.stream == sys.stderr]
    for h in handlers:
      logging.root.removeHandler(h)
    _attempted_to_remove_stderr_stream_handlers = True

  absl_handler = get_absl_handler()
  if absl_handler not in logging.root.handlers:
    logging.root.addHandler(absl_handler)
    FLAGS['verbosity']._update_logging_levels()  # pylint: disable=protected-access
    FLAGS['logger_levels']._update_logger_levels()  # pylint: disable=protected-access

def _initialize():
  """Initializes loggers and handlers."""
  global _absl_logger, _absl_handler

  if _absl_logger:
    return

  original_logger_class = logging.getLoggerClass()
  logging.setLoggerClass(ABSLLogger)
  _absl_logger = logging.getLogger('absl')
  logging.setLoggerClass(original_logger_class)

  python_logging_formatter = PythonFormatter()
  _absl_handler = ABSLHandler(python_logging_formatter)

_initialize()


from trainer import image_classifier, augmentation_pipeline,GCSHelper
import argparse

def str2bool(v):
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

def run(data_directory, output_directory, project_id,augment_flag,augment_samples,nr_epochs,drop_out,val_split,model,batch_size,check_overfit):
    image_classifier.check_input(project_id=project_id, data_dir=data_directory, output_dir=output_directory,
                                 validation_split=val_split, num_epochs=nr_epochs, dropout=drop_out,
                                 augmentation_samples=augment_samples)

    print('AUGMENTING IMAGES...')
    if augment_flag:
        augmentation_pipeline.augmentImages(project_id=project_id, data_dir=data_directory, sample_size=augment_samples,cloudML=True)
    print('AUGMENTING IMAGES DONE!')
    print('TRAINING MODEL...')
    image_classifier.retrain(project_id, data_directory, batch_size=batch_size, model=model, dropout=drop_out, num_epochs=nr_epochs,
                             validation_split=val_split, output_dir=output_directory, cloud_mode=True,check_overfit=check_overfit)

parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, help='directory of data')
parser.add_argument('--output_dir', type=str, help='directory of output model')
parser.add_argument('--project_id', type=str, default="trainer-cl", help='Google cloud projectID')
parser.add_argument('--aug_flag', type=str2bool, default=False, help='True if augmentation is done on images')
parser.add_argument('--aug_samples', type=int, default=1, help='extra augmentation samples that are added per category')
parser.add_argument('--nr_epochs', type=int, default=1, help='extra augmentation samples that are added per category')
parser.add_argument('--drop_out', type=float, default=0.1, help='Amount of droppout to prevent overfitting')
parser.add_argument('--val_split', type=float, default=0.1, help='Percentage of data used for validation')
parser.add_argument('--model', type=str, default="MobileNet", help='Used model architecture')
parser.add_argument('--batch_size', type=int, default=16, help='Batch size used for model training')
parser.add_argument('--check_overfit', type=str2bool, default=True, help='Add early stopping check')

args = parser.parse_args()

try:
    run(args.data_dir,args.output_dir,args.project_id,args.aug_flag,args.aug_samples,args.nr_epochs,args.drop_out,args.val_split,args.model,args.batch_size,args.check_overfit)
    GCSHelper.uploadClosingStatusFilesToGCS(args.project_id,[],'done.txt',args.output_dir)
except Exception as e:
    GCSHelper.uploadClosingStatusFilesToGCS(args.project_id,[str(e)], 'wrong.txt', args.output_dir)


from flask import Flask, jsonify, request
from flask_cors import CORS
from flask_jwt_extended import create_access_token, JWTManager
from flask_mysqldb import MySQL
from dotenv import load_dotenv
import os
from datetime import datetime

app = Flask(__name__)

load_dotenv()

app.config['MYSQL_HOST'] = os.environ.get('MYSQL_HOST')
app.config['MYSQL_USER'] = os.environ.get('MYSQL_USER')
app.config['MYSQL_PASSWORD'] = os.environ.get('MYSQL_PASSWORD')
app.config['MYSQL_DB'] = os.environ.get('MYSQL_DB')

mysql = MySQL(app)

CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)

@app.route('/coords', methods=["GET"])
def get_coords():
    try:
        cursor = mysql.connection.cursor()
        cursor.execute("SELECT latitude, longitude FROM sample")
        results = cursor.fetchall()
        cursor.close()

        coords = [{'lat': row[0], 'lng': row[1]} for row in results]

        return jsonify({'coords': coords})

    except Exception as e:
        return jsonify({'error': str(e)}), 500


from PIL import Image
from os import listdir, mkdir

def PrepareChars5x7(jmeno, mezX, mezY):
    im = Image.open(jmeno)
    Pixels = im.load()
    for x in range(13):
        for y in range(4):
            imnew = Image.new(mode="RGB", size=(5, 7))
            pole = imnew.load()
            print(pole[1, 1], imnew.size)
            for x2 in range(5):
                for y2 in range(7):
                    pole[x2, y2] = Pixels[x2 + (5 + mezX) * x, y2 + (7 + mezY) * y]

            imnew.save("Characters/ch" + str(x + 13 * y) + ".png")

def Roztrid():
    seznam = listdir("Characters")

    for polozka in seznam:
        im = Image.open("Characters/" + polozka)
        pixels = im.load()

        hodnota = 0
        for x in range(5):
            for y in range(7):
                if pixels[x,y][0] != 0:
                    hodnota += 1

        if str(hodnota) not in listdir("Characters"):
            mkdir("Characters/" + str(hodnota))

        im.save("Characters/" + str(hodnota) + "//" + polozka)


# Merge k Sorted Linked Lists and return in form of Array

class Node:
    def __init__(self, head):
        self.head = head
        self.next = None

def merge(self, left, right):
    if left is None:
        return right

    if right is None:
        return left

    ans = Node(-1)
    temp = ans

    while left and right:
        if left.data <= right.data:
            temp.next = left
            temp = left
            left = left.next
        else:
            temp.next = right
            temp = right
            right = right.next

    while left:
        temp.next = left
        temp = left
        left = left.next

    while right:
        temp.next = right
        temp = right
        right = right.next

    return ans.next

def mergeKLists(self, arr ,k):

    for i in range(0, k - 1):
        temp = self.merge(arr[i], arr[i + 1])
        arr[i + 1] = temp

    return arr[k - 1]

# Runtime Error

# Optimal Solution using Priority Queue


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Picture',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('image', models.ImageField(null=True, upload_to=b'media/product_pictures', blank=True)),
                ('description', models.CharField(max_length=140, null=True, blank=True)),
                ('default_picture', models.BooleanField(default=False)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Product',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=140)),
                ('description', models.TextField(null=True, blank=True)),
                ('total_number_of_tickets', models.IntegerField()),
                ('tickets_sold', models.IntegerField()),
                ('end_time', models.DateTimeField()),
                ('start_time', models.DateTimeField()),
                ('pricing_per_ticket', models.DecimalField(max_digits=8, decimal_places=2)),
                ('winning_ticket_number', models.IntegerField()),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Ticket',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('ticket_number', models.IntegerField()),
                ('product', models.ForeignKey(related_name='tickets', to='ticketing.Product')),
                ('user', models.ForeignKey(related_name='tickets', to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='picture',
            name='product',
            field=models.ForeignKey(related_name='pictures', to='ticketing.Product'),
            preserve_default=True,
        ),
    ]


#!/usr/bin/env python3
#_*_ coding: utf8 _*_

#------------------------------------------------------------
#-----            GUILLOTINE                           -----|
# ----            FINDER HTTP SECURITY HEADERS          ----|
# ----            Gohanckz                              ----|
# ----            Contact : igonzalez@pwnsec.cl         ----|
# ----            Version : 2.0                         ----|
#------------------------------------------------------------
try:
    from banner import banner
    from prettytable import PrettyTable
    import requests
    import argparse
    from urllib3.exceptions import InsecureRequestWarning
except ImportError as err:
    print("Some libraries are missing:")
    print(err)

parser = argparse.ArgumentParser(description="Finder Security Headers")
parser.add_argument("-t","--target",help="Show http security headers enabled and missing")
parser.add_argument("-v","--verbose",action="store_true",help="Show full response")
parser = parser.parse_args()

try:
    requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
    url = requests.get(url=parser.target, verify=False)

    security_headers = [
        "Strict-Transport-Security",
        "X-Frame-Options",
        "X-Content-Type-Options",
        "Content-Security-Policy",
        "X-Permitted-Cross-Domain-Policies",
        "Referrer-Policy",
        "Clear-Site-Data",
        "Cross-Origin-Embedder-Policy",
        "Cross-Origin-Opener-Policy",
        "Cross-Origin-Resource-Policy",
        "Cache-Control"
    ]

    info_headers = []
    headers_site = []
    security_headers_site = []
    missing_headers = []

    headers = dict(url.headers)

    for i in headers:
        headers_site.append(i)

    for i in headers:
        info_headers.append(headers[i])

    for i in headers_site:
        if i in security_headers:
            security_headers_site.append(i)

    for j in security_headers:
        if not j in [h for h in headers_site]:
            missing_headers.append(j)

    table = PrettyTable()
    table.add_column("Header",headers_site)
    table.add_column("Information",info_headers)
    table.align="l"

    while len(security_headers_site) < len(missing_headers):
        security_headers_site.append(" ")

    while len(security_headers_site) > len(missing_headers):
        missing_headers.append(" ")

    count = 0
    for i in security_headers_site:
        if i != " ":
            count += 1

    count_m = 0
    for j in missing_headers:
        if j != " ":
            count_m +=1

    s_table = PrettyTable()
    s_table.add_column("Enabled Security Header",security_headers_site)
    s_table.add_column("Missing Security Header",missing_headers)
    s_table.align="l"
except:
    print("[!] time out, unable to connect to site.")

def main():
    banner()
    try:
        print("\n[*] Analyzing target : ",parser.target)
        print("[*] Security headers enabled :", count)
        print("[*] Missing Security Headers :",count_m)
    except:
        print("[!] Syntax Error.")
        print("[+] Usage: python3 guillotine.py -t http://example.site")
def target():
    try:
        print(s_table)
    except:
        pass
def verbose():
    try:
        print(table)
    except:
        pass
if __name__ == '__main__':
    main()
    if parser.verbose:
        verbose()
    elif parser.target:
        target()


# 导入所需的库
import jieba
import docx
from docx import Document
from docx.shared import Inches
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS

# 读取文档内容
filter_words = ['', '','','','','','','']
document = Document('221.docx')
text = ''
text= jieba.cut(text)
text = ''.join(str(x) for x in text)
for paragraph in document.paragraphs:
    text += paragraph.text + ' '
for word in filter_words:
    text = text.replace(word, '')

# 创建停用词集合
stopwords = set(STOPWORDS)
stopwords = ['同志们', '二','三','四','五','一','六','七','八','九','十','']
# 创建词云对象，并设置参数
wordcloud = WordCloud(
    font_path="simhei.ttf",
    width=1200, height=800,
    background_color='white',
    stopwords=stopwords,
    min_font_size=10).generate(text)

# 绘制词云图
plt.figure(figsize=(8, 8), facecolor=None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad=0)
plt.show()
# 创建需要过滤的词汇列表

# 加载需要过滤的文本
text = 'I hate this bad movie, it is so ugly and boring.'

# 使用字符串函数 replace() 进行替换

print(text)


import time
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait

import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import service

#driver = webdriver.Chrome(executable_path="G:\driver\chromedriver_win32\chromedriver.exe") #my computer
driver=webdriver.Chrome()
driver.implicitly_wait(40)
driver.get("https://www.facebook.com/")
driver.find_element(By.XPATH,'//a[@role="button"and@data-testid="open-registration-form-button"]').click()
time.sleep(2)
driver.find_element(By.XPATH,'//input[@name="firstname"and@aria-label="First name"]').send_keys('pavithran')
time.sleep(2)
driver.find_element(By.XPATH,'//input[@name="lastname"and@aria-label="Surname"]').send_keys('sethu')
time.sleep(2)
driver.find_element(By.XPATH,'//input[@aria-label="Mobile number or email address"]').send_keys('9784561524')
driver.find_element(By.XPATH,'//input[@id="password_step_input"and@type="password"]').send_keys('Passcode')
time.sleep(2)
print("--------days-------")
days_elements=driver.find_element(By.ID,"day")#assign the id
days=Select(days_elements)#selecting the all elements
#giving the values manually to the dropdownlist
days.select_by_visible_text("17")#text method
time.sleep(2)
days.select_by_index(2)#index method
time.sleep(2)
days.select_by_value("6")#value method
time.sleep(2)
days_elements.send_keys("25")#send my value to days dropdown box NORMAL METHOD
print("get attribute method the value sent to the dropbox:",days_elements.get_attribute('value')) #get my value from dropbox
time.sleep(2)
totaloptions=len(days.options)#to find total options available in days
print("Total options in day dropdownlist:",totaloptions)#31 options are there
opsd=days.options#to get all options
print("total options")#just for heading
for option in opsd:#for loop
    print("option text is-{}-option value is={}".format(option.text,option.get_attribute("value")))
print("--using range--")
for x in range(0,30):
    print(opsd[x].text)
print("--days after 20th\n--")
for x in opsd:
    y=x.get_attribute("value")
    z=int(y)
    if z>=20:
        print(x.text)

print("--days between 10 to 25\n--")
for x in opsd:
    y=x.get_attribute("value")
    z=int(y)
    if z>=10 and z<=25:
         print(x.text)

print('-----month-----')
#month

month_element=driver.find_element(By.ID,'month')
months=Select(month_element)
months.select_by_value("2")#feb
time.sleep(2)
months.select_by_index(4)
time.sleep(2)
months.select_by_visible_text("Aug")
month_length=len(months.options)
print("total months options are available in facebook\n:",month_length)
ops=months.options
for option in ops:
   print("option text is-{}-option value is={}".format(option.text, option.get_attribute("value")))
#using range printing text
print("--using range--")
for x in range(0,12):
    print(ops[x].text)

print("----last 3 months---\n")
for x in ops:
    y=(x.get_attribute('value'))
    z=int(y)
    if z>=10:
        print(x.text)
print("----between months:----\n")
for x in ops:
    y=(x.get_attribute('value'))
    z=int(y)
    if z>=2 and z<=10:
        print(x.text)
print("---1st 3 months\n---")
for x in ops:
    y=(x.get_attribute('value'))
    z=int(y)
    if z<=3:
        print(x.text)

print("-------year--------")
year_elements=driver.find_element(By.ID,"year")
years=Select(year_elements)
years.select_by_visible_text("1997")
time.sleep(3)
years.select_by_value("1996")
time.sleep(3)
years.select_by_index(1)#2021
totalyears=len(years.options)
print("total no of options in year:",totalyears)#118
opsy=years.options
for x in opsy:
   print("year is={} year value is={}".format(x.text,x.get_attribute("value")))
print("--using range--")
for x in range(0,30):
    print(opsy[x].text)
print("--years above 1997\n--")
for x in opsy:
    y=x.get_attribute("value")
    z=int(y)
    if z>=1997:
        print(x.text)
print("--years between 2000 to 1990\n--")
for x in opsy:
    y=x.get_attribute("value")
    z=int(y)
    if z<=2000 and z>=1990:
        print(x.text)

print(type(y))
print(type(z))

#gender selection
gender_f=driver.find_element(By.XPATH,'(//input[@type="radio"and@name="sex"])[1]').click()
status=driver.find_element(By.XPATH,'(//input[@type="radio"and@name="sex"])[1]').is_selected()
print(status)
time.sleep(3)
gender_m=driver.find_element(By.XPATH,'(//input[@type="radio"and@name="sex"])[2]').click()
status=driver.find_element(By.XPATH,'(//input[@type="radio"and@name="sex"])[2]').is_selected()
print(status)
time.sleep(3)
gender_c=driver.find_element(By.XPATH,'(//input[@type="radio"and@name="sex"])[3]').click()
status=driver.find_element(By.XPATH,'(//input[@type="radio"and@name="sex"])[3]').is_selected()
print(status)
custom=driver.find_element(By.XPATH,'//select[@aria-label="Select your pronoun"]')
custom_s=Select(custom)
custom_s.select_by_value("1")
time.sleep(2)
custom_s.select_by_value("2")
time.sleep(2)
customs=custom_s.options
for x in customs:
    print(x.text)
driver.find_element(By.XPATH,'//input[@name="custom_gender"]').send_keys("they")

driver.find_element(By.XPATH,'//button[text()="Sign Up"]').click()
time.sleep(5)
driver.close()


import torch
import torch.nn as nn
from torch_geometric.loader import DataLoader
from torch_geometric.data import Data, Batch
from torch.utils.data import Dataset
import torch_geometric.transforms as T
from torch_geometric.nn import GATConv
import torch.nn.functional as F

class GATNet(torch.nn.Module):
    def __init__(self, num_graph_node_features, num_boundary_node_features):
        super(GATNet, self).__init__()

        self.graph_conv1 = GATConv(num_graph_node_features, 32, heads=4)

        input_of_conv2   = num_graph_node_features + 32*4
        self.graph_conv2 = GATConv(input_of_conv2, 32, heads=8)

        input_of_conv3   = num_graph_node_features + 32*8
        self.graph_conv3 = GATConv(input_of_conv3, 64, heads=8)

        input_of_conv4   = num_graph_node_features + 64*8
        self.graph_conv4 = GATConv(input_of_conv4, 128, heads=8)

        shape_of_graphs_befor_concatination = num_graph_node_features + 128*8

        self.boundary_conv1 = GATConv(num_boundary_node_features, 32, heads=4)
        input_of_boundary_conv2 = 32*4 + num_boundary_node_features
        self.boundary_conv2 = GATConv(input_of_boundary_conv2, 32, heads=8)

        shape_of_boundary_befor_concatination = num_boundary_node_features + 32 * 8

        # Output of graph_conv8 + output of boundary_conv5 + 2 step connection from real nodes and boundary nodes
        inputs_concatination = shape_of_graphs_befor_concatination + shape_of_boundary_befor_concatination
        self.Concatination1  = GATConv(inputs_concatination, 128, heads=8)

        self.width_layer1  = nn.Linear(128*8, 128)
        self.height_layer1 = nn.Linear(128*8, 128)

        self.width_output  = nn.Linear(128, 1)
        self.height_output = nn.Linear(128, 1)

        self.dropout = torch.nn.Dropout(0.2)

    def forward(self, graph, boundary):
        x_graph, g_edge_index, g_edge_attr, g_batch = graph.x.to(torch.float32), graph.edge_index, graph.edge_attr, graph.batch
        x_boundary, b_edge_indexy, b_edge_attr, b_batch = boundary.x.to(torch.float32), boundary.edge_index, boundary.edge_attr, boundary.batch

        NUM_OF_NODES = x_graph.shape[0]
        # During testing, as we input only one graph.
        if g_batch == None:
            g_batch = torch.zeros(x_graph.shape[0], dtype=torch.long)
        if b_batch == None:
            b_batch = torch.zeros(x_boundary.shape[0], dtype=torch.long)

        x_graph_res = x_graph
        x_boundary_res = x_boundary

        # Passing the graph throught a message passing to embed its features
        x_graph = F.leaky_relu(self.graph_conv1(x_graph, g_edge_index, g_edge_attr))
        x_graph = self.dropout(x_graph) # Concatinate with step connection from real values.
        x_graph = torch.cat([x_graph, x_graph_res], dim=1)

        x_graph = F.leaky_relu(self.graph_conv2(x_graph, g_edge_index, g_edge_attr))
        x_graph = self.dropout(x_graph)
        x_graph = torch.cat([x_graph, x_graph_res], dim=1)

        x_graph = F.leaky_relu(self.graph_conv3(x_graph, g_edge_index))
        x_graph = self.dropout(x_graph)
        x_graph = torch.cat([x_graph, x_graph_res], dim=1)

        x_graph = F.leaky_relu(self.graph_conv4(x_graph, g_edge_index))
        x_graph = self.dropout(x_graph)
        x_graph = torch.cat([x_graph, x_graph_res], dim=1)

        # Passing the boundary throught a message passing to embed its features
        x_boundary = F.leaky_relu(self.boundary_conv1(x_boundary, b_edge_indexy, b_edge_attr))
        x_boundary = self.dropout(x_boundary)
        x_boundary = torch.cat([x_boundary, x_boundary_res], dim=1)

        x_boundary = F.leaky_relu(self.boundary_conv2(x_boundary, b_edge_indexy, b_edge_attr))
        x_boundary = self.dropout(x_boundary)
        x_boundary = torch.cat([x_boundary, x_boundary_res], dim=1)

        # Pooling the bounadry to 1D vector by getting max value in each feature for all nodes.
        x_boundary_pooled = F.max_pool1d(x_boundary.transpose(0, 1), kernel_size=x_boundary.shape[0]).view(1, -1)

        # Concatinating the graph & the boundary
        x = torch.cat([x_graph, x_boundary_pooled.repeat(NUM_OF_NODES, 1)], dim=1)
        x = F.leaky_relu(self.Concatination1(x, g_edge_index))
        x = self.dropout(x)

        width = F.leaky_relu(self.width_layer1(x))
        width = self.dropout(width)
        width = self.width_output(width)

        height = F.leaky_relu(self.height_layer1(x))
        height = self.dropout(height)
        height = self.height_output(height)

        return width.squeeze(), height.squeeze()

def load_model(checkpoint_path, device):
    model = GATNet(9, 3)
    model = model.to(device)

    checkpoint = torch.load(checkpoint_path)

    model.load_state_dict(checkpoint['model_state_dict'])
    model.eval()

    return model


import os
import requests
from app import Processing
import nltk
from moviepy.editor import *
from pexels_api import API
from pathlib import Path
import time
import pyttsx3

# configurations of paths, output URL, file structure
# 16:9 ratios possible for upright smartphone usage
# 1080, 1920 --> FullHD resolution
# 540, 960 --> 1/4 data size compared to FullHD
# 270, 480 --> 1/8 data size compared to FullHD
WIDTH_OUT = 540/2
HEIGHT_OUT = 960/2
screensize = (WIDTH_OUT, HEIGHT_OUT)

FONT = "Helvetica-Bold"
FONTSIZE_MAIN = WIDTH_OUT * 0.1
FONTSIZE_SUB = WIDTH_OUT * 0.03
FONT_COLOUR = "white"
PADDING = WIDTH_OUT * 0.1

readingSpeed = 0.2

audio_dir_emotional = "static/music/emotional.mp3"
audio_dir_promo = "static/music/promo.mp3"
audio_dir_neutral = "static/music/neutral.mp3"

audio_emotional = AudioFileClip(audio_dir_emotional, fps=44100)
audio_neutral = AudioFileClip(audio_dir_neutral, fps=44100)
audio_promo = AudioFileClip(audio_dir_promo, fps=44100)

ABS_PATH = os.path.abspath(__file__)  # "/app.py"
BASE_DIR = os.path.dirname(ABS_PATH)  # "/"

Path(os.path.join(BASE_DIR, "downloads")).mkdir(parents=True, exist_ok=True)
OUTPUT = os.path.join(BASE_DIR, "downloads")

# API setups
PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
api = API(PEXELS_API_KEY)

def dl_img(url, filename):
    print(filename)
    r = requests.get(url, allow_redirects=True)
    open(filename, 'wb').write(r.content)
    return filename

def pexels_fetch(to_download):
    downloaded_files = []
    n = 0

    for i in to_download:
        api.search(" ".join(i), page=1, results_per_page=1)
        dl = api.get_entries()
        print(dl)
        img = [
            dl_img(dl[0].large, os.path.join(OUTPUT, str("image_downloaded_" + str(n) + ".jpg"))),
            dl[0].photographer
               ]
        downloaded_files.append(img)
        n += 1
    return downloaded_files

def zoom(file, t):
    f = (ImageClip(file)
         .resize(height=screensize[1])
         .resize(lambda t: 1 + 0.02 * t)
         .set_position(('center', 'center'))
         .set_duration(t)
         )
    f = resize_to_ouput_size(f)
#    cvc = ImageClip(f, t)
    return f

def resize_to_ouput_size(f):
    if f.w < WIDTH_OUT:
        f = f.resize(width=WIDTH_OUT)
    if f.h < HEIGHT_OUT:
        f = f.resize(height=HEIGHT_OUT)
    f = f.crop(x_center=f.w / 2, y_center=f.h / 2, width=WIDTH_OUT, height=HEIGHT_OUT)
    return f

'''
# voiceover functionality deprecated due to non-existent espeak support on heroku

def voiceover(textSnippet, i):
    engine = pyttsx3.init()
    print(f"inside voiceover func, processing: {textSnippet} \nIsBusy is set to {engine.isBusy()}")
    audioFileName = f"voiceover text segment no. {i}.mp3"
    engine.save_to_file(textSnippet, audioFileName)
    engine.runAndWait()
#    engine.stop()
    print(f"text to speech worked correctly? \nisBusy is set to {engine.isBusy()}")

    return audioFileName
'''

def overlay_text(file, i):
    overlay = TextClip(file.text_segmented[i],
                       size=(WIDTH_OUT * 0.9, HEIGHT_OUT),
                       color=FONT_COLOUR,
                       method="caption",
                       align="East",
                       fontsize=FONTSIZE_MAIN,
                       font=FONT
                       )
    combined = CompositeVideoClip([overlay, overlay_attribution(file.downloaded_items[i][1])])

# voiceover functionality deprecated
#    if file.voiceover == True or file.voiceover == "true" or file.voiceover == "True":
#        audio_clip_temp = AudioFileClip(voiceover(file.text_segmented[i], i), fps=44100)
#        combined = combined.set_audio(audio_clip_temp)

    combined = combined.set_duration(file.text_timing[i])

    return combined

def overlay_attribution(text):
    attribution = TextClip(f"Image from www.pexels.com by: {text}",
                           size=(WIDTH_OUT, HEIGHT_OUT * 0.95),
                           color=FONT_COLOUR,
                           fontsize=FONTSIZE_SUB,
                           align="south",
                           method="caption",
                           font=FONT
                           )
    attribution = attribution.set_position((0, 0.97), relative=True)
    return attribution

def create_kopfkino(content):
    file = Processing(user_input=content.get("user_input"), style=content.get("style"), voiceover=content.get("voiceover"))
    print(f"voiceover from content JSON is set to: {file.voiceover}")
    nlp_testing_2(file)
    print(file.downloaded_items)
    print(file.text_searchwords)
    file.downloaded_items = pexels_fetch(file.text_searchwords)

    for i in range(0, len(file.downloaded_items)):
        file.footage.append(zoom(file.downloaded_items[i][0], file.text_timing[i]))
    for i in range(0, len(file.text_segmented)):
        clip = overlay_text(file, i)
        combined = CompositeVideoClip([file.footage[i], clip])
        file.footage_and_text.append(combined)

    file.export_file = concatenate(file.footage_and_text)

    if file.style == "neutral":
        file.export_file = file.export_file.set_audio(audio_neutral.set_duration(file.export_file.duration))
    elif file.style == "emotional":
        file.export_file = file.export_file.set_audio(audio_emotional.set_duration(file.export_file.duration))
    elif file.style == "promo":
        file.export_file = file.export_file.set_audio(audio_promo.set_duration(file.export_file.duration))
    else:
        file.export_file = file.export_file.set_audio(audio_neutral.set_duration(file.export_file.duration))

    file.export_file.write_videofile(os.path.join(OUTPUT, f"Kopfkino_export_in workerinstance.mp4"), codec='libx264',
                                     audio_codec='aac', fps=24)
    with open(os.path.join(OUTPUT, f"Kopfkino_export_in workerinstance.mp4"), "rb") as trans:
        result = trans.read()

    return result

def nlp_testing_2(file):
    text_raw = file.user_input
    print(text_raw)
    file.text_segmented = nltk.sent_tokenize(text_raw)
    for i in range(0, len(file.text_segmented)):
        n = 0
        for c in file.text_segmented[i]:
            n += 1
        n = round(n * readingSpeed, 1)
        if n < 5:
            n = 5
        file.text_timing.append(n)
        text_segmented_to_words = nltk.word_tokenize(file.text_segmented[i])
        file.text_searchwords.append([])
        print(f"POS Tags{nltk.pos_tag(text_segmented_to_words)}")
        for p in nltk.pos_tag(text_segmented_to_words):
            if p[1] in {"JJ", "NN", "NNS", "VB"}:
                print(f"found word {p} and put it to the searchwords")
                file.text_searchwords[i].append(p[0])

    for x in file.text_searchwords:
        if len(x) == 0:
            x.append("error")
            print("-------> ERROR HANDLING NEEDED: No searchword left: appended full sentence OR error")

    return f"\nsegmented: {file.text_segmented}, \ntimings: {file.text_timing} \nsearchwords: {file.text_searchwords}"


import pandas as pd

dataset = pd.read_csv('iris.csv')

data = dataset.iloc[ : 99 , :]

target = data.iloc[ : , -1: ]

y = []

for x in target.values:
    if x == 'Iris-setosa':
        y.append(1)
    else:
        y.append(0)

x = data.iloc[ : , : -1]
x = x.values.tolist()

from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
import numpy as np

shuffle(x, y)

x_train = []
x_test = []
y_train = []
y_test = []

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.1)

x_train = np.array(x_train)
y_train = np.array(y_train)
x_test = np.array(x_test)
y_test = np.array(y_test)

from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression

clf = LogisticRegression()
clf.fit(x_train,y_train)
y_pred = clf.predict(x_test)
print(accuracy_score(y_test,y_pred))


import copy
import json
import logging
import os
from threading import Thread

import requests
import six
import yaml
from toscaparser.tosca_template import ToscaTemplate
from yaml import Loader

from configuration_tool.common.tosca_reserved_keys import IMPORTS, DEFAULT_ARTIFACTS_DIRECTORY, \
    EXECUTOR, NAME, TOSCA_ELEMENTS_MAP_FILE, TOSCA_ELEMENTS_DEFINITION_FILE, TOPOLOGY_TEMPLATE, TYPE, \
    TOSCA_ELEMENTS_DEFINITION_DB_CLUSTER_NAME, NODE_TEMPLATES, RELATIONSHIP_TEMPLATES
from configuration_tool.common import utils
from configuration_tool.common.configuration import Configuration
from configuration_tool.configuration_tools.ansible.instance_model.instance_model import update_instance_model
from configuration_tool.configuration_tools.combined.combine_configuration_tools import get_configuration_tool_class
from configuration_tool.providers.common.provider_configuration import ProviderConfiguration
from configuration_tool.providers.common.tosca_template import ProviderToscaTemplate

REQUIRED_CONFIGURATION_PARAMS = (TOSCA_ELEMENTS_DEFINITION_FILE, DEFAULT_ARTIFACTS_DIRECTORY, TOSCA_ELEMENTS_MAP_FILE)

REQUIRED_CONFIGURATION_PARAMS = (TOSCA_ELEMENTS_DEFINITION_FILE, DEFAULT_ARTIFACTS_DIRECTORY, TOSCA_ELEMENTS_MAP_FILE)

def load_to_db(node_templates, relationship_templates, config, database_api_endpoint, template, cluster_name):
    definitions = {}
    all_templates = node_templates
    all_templates = utils.deep_update_dict(all_templates, relationship_templates)
    def_cluster = config.get_section(config.MAIN_SECTION).get(TOSCA_ELEMENTS_DEFINITION_DB_CLUSTER_NAME)
    for key, value in all_templates.items():
        type = value[TYPE]
        r = requests.get(utils.get_url_for_getting_dependencies(def_cluster, database_api_endpoint, type))
        try:
            response = r.json()
        except Exception:
            raise Exception("Failed to parse json response from db")
        if response['status'] != 200:
            raise Exception("Error in db! Status code: %s, msg: %s" % (response['status'], response['message']))
        definitions = utils.deep_update_dict(definitions, response['result'])
    with open(os.path.join(utils.get_tmp_clouni_dir(), 'template.yaml'), "w") as f:
        template = utils.deep_update_dict(template, definitions)
        del template[IMPORTS]
        print(yaml.dump(template, Dumper=utils.NoAliasDumper), file=f)
    with open(os.path.join(utils.get_tmp_clouni_dir(), 'template.yaml'), "r") as f:
        files = {'file': f}
        res = requests.post(utils.get_url_for_loading_to_db(cluster_name, database_api_endpoint), files=files)
        try:
            response = res.json()
        except Exception:
            raise Exception("Failed to parse json response from db on loading template")
        if response['status'] != 200:
            raise Exception("Error in db! Status code: %s, msg: %s" % (response['status'], response['message']))

def translate(provider_template, validate_only, configuration_tool, cluster_name, is_delete=False,
              extra=None, log_level='info', debug=False, host_ip_parameter='public_address',
              database_api_endpoint=None, grpc_cotea_endpoint=None):
    log_map = dict(
        debug=logging.DEBUG,
        info=logging.INFO,
        warning=logging.WARNING,
        error=logging.ERROR,
        critical=logging.ERROR
    )

    logging_format = "%(asctime)s %(levelname)s %(message)s"
    logging.basicConfig(filename='.clouni-configuration-tool.log', filemode='a', level=log_map[log_level],
                        format=logging_format, datefmt='%Y-%m-%d %H:%M:%S')

    config = Configuration()

    template = yaml.load(provider_template, Loader=Loader)
    topology_template = template.get(TOPOLOGY_TEMPLATE)

    # tmp version - provider gets from first node template (can't use different providers in template)
    provider = None
    for key in topology_template.get('node_templates').keys():
        provider_template_name = key
        tosca_type = topology_template.get('node_templates').get(provider_template_name).get('type')
        (provider, _, _) = utils.tosca_type_parse(tosca_type)
        if provider in ['openstack', 'amazon', 'kubernetes']: # TODO: make config prividers file!
            break

    provider_config = ProviderConfiguration(provider)
    for sec in REQUIRED_CONFIGURATION_PARAMS:
        if sec not in config.get_section(config.MAIN_SECTION).keys():
            logging.error('Provider configuration parameter "%s" is missing in configuration file' % sec)
            raise Exception('Provider configuration parameter "%s" is missing in configuration file' % sec)

    def_files = config.get_section(config.MAIN_SECTION).get(TOSCA_ELEMENTS_DEFINITION_FILE)
    if isinstance(def_files, six.string_types):
        def_files = [def_files]
    provider_def_files = provider_config.get_section(config.MAIN_SECTION).get(TOSCA_ELEMENTS_DEFINITION_FILE)
    if isinstance(provider_def_files, six.string_types):
        provider_def_files = [provider_def_files]
    default_import_files = []
    for def_file in def_files:
        default_import_files.append(os.path.join(utils.get_project_root_path(), def_file))
    for def_file in provider_def_files:
        default_import_files.append(os.path.join(utils.get_project_root_path(), 'configuration_tool', 'providers',
                                                 provider, def_file))
    logging.info("Default TOSCA template definition file to be imported \'%s\'" % json.dumps(default_import_files))

    # Add default import of normative TOSCA types to the template
    template[IMPORTS] = template.get(IMPORTS, [])
    for i in range(len(template[IMPORTS])):
        if isinstance(template[IMPORTS][i], dict):
            for import_key, import_value in template[IMPORTS][i].items():
                if isinstance(import_value, six.string_types):
                    template[IMPORTS][i] = import_value
                elif isinstance(import_value, dict):
                    if import_value.get('file', None) is None:
                        logging.error("Imports %s doesn't contain \'file\' key" % import_key)
                        raise Exception("Imports %s doesn't contain \'file\' key" % import_key)
                    else:
                        template[IMPORTS][i] = import_value['file']
                    if import_value.get('repository', None) is not None:
                        logging.warning("Clouni doesn't support imports \'repository\'")
    template[IMPORTS].extend(default_import_files)
    for i in range(len(template[IMPORTS])):
        template[IMPORTS][i] = os.path.abspath(template[IMPORTS][i])
    if template.get(TOPOLOGY_TEMPLATE):
        tmpl = template.get(TOPOLOGY_TEMPLATE)
        if database_api_endpoint:
            if not tmpl.get(NODE_TEMPLATES):
                tmpl[NODE_TEMPLATES] = {}
            if not tmpl.get(RELATIONSHIP_TEMPLATES):
                tmpl[RELATIONSHIP_TEMPLATES] = {}
            load_to_db(tmpl[NODE_TEMPLATES], tmpl[RELATIONSHIP_TEMPLATES], config, database_api_endpoint, template, cluster_name)
        else:
            if tmpl.get(NODE_TEMPLATES):
                node_templates = tmpl.get(NODE_TEMPLATES)
                for elem in node_templates:
                    update_instance_model(cluster_name, node_templates[elem], node_templates[elem][TYPE], elem, [], [], is_delete, init=True)
            if tmpl.get(RELATIONSHIP_TEMPLATES):
                rel_templates = tmpl.get(RELATIONSHIP_TEMPLATES)
                for elem in rel_templates:
                    update_instance_model(cluster_name, rel_templates[elem], rel_templates[elem][TYPE], elem, [], [], is_delete, init=True)

    copy_of_template = copy.deepcopy(template)
    try:
        tosca_parser_template_object = ToscaTemplate(yaml_dict_tpl=copy_of_template)
    except Exception as e:
        logging.exception("Got exception from OpenStack tosca-parser: %s" % e)
        raise Exception("Got exception from OpenStack tosca-parser: %s" % e)

    # After validation, all templates are imported
    if validate_only:
        msg = 'The input "%(template_file)s" successfully passed validation. \n' \
              % {'template_file': 'TOSCA template'}
        return msg

    tosca = ProviderToscaTemplate(template, provider, configuration_tool, cluster_name,
                                  host_ip_parameter, is_delete, grpc_cotea_endpoint)

    tool = get_configuration_tool_class(configuration_tool)(provider)

    default_artifacts_directory = config.get_section(config.MAIN_SECTION).get(DEFAULT_ARTIFACTS_DIRECTORY)

    configuration_content = tool.to_dsl(provider, tosca.provider_operations, tosca.reversed_provider_operations,
                                        tosca.cluster_name, is_delete, target_directory=default_artifacts_directory,
                                        extra=extra, debug=debug,
                                        grpc_cotea_endpoint=grpc_cotea_endpoint)
    return configuration_content


# 46__method_chaining
class Car:
    def turn_on(self):
        print("You started the engine")
        turned_on = "turned on"
        return self
    def turn_off(self):
        print("You turned of the engine")
        return self
    def brake(self):
        print("You stepped on the brake")
        return self
    def drive(self):
        print("You drive the car")
        print("You have previously")
        return self

car = Car()

# Tidigare med två rader
# car.turn_on()
# car.drive()

car.turn_on().drive()

print("-------")

car.brake().turn_off()

print("---------")
car.turn_on().drive().brake().turn_off()


from django.db import models

class Vehicles(models.Model):

    class Meta:
        ordering = [ 'year']

    id = models.AutoField(
        primary_key = True
    )

    year_min = 1900
    year_max = 2100
    year = models.IntegerField(
        'Year',
    )

    man_max_len = 50
    manufacturer = models.CharField(
        'Manufacturer',
        max_length = man_max_len,
    )

    model_max_len = 100
    model = models.CharField(
        'model',
        max_length = model_max_len
    )

    sn_max_len = 15
    serial_no = models.CharField(
        'Serial Number',
        unique = True,
        max_length = sn_max_len
    )


from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('api/songs', views.SongsView.as_view(), name='songs'),
    path('api/songs/<int:song_id>', views.SongInfoView.as_view(), name='song_info'),
    path('api/songs/search/', views.SongSearchView.as_view(), name='song_search'),
    path('api/artists', views.ArtistsView.as_view(), name='artists'),
    path('api/artists/<int:artist_id>', views.ArtistInfoView.as_view(), name='artist_info'),
    path('api/albums', views.AlbumsView.as_view(), name='albums'),
    path('api/albums/<int:album_id>', views.AlbumInfoView.as_view(), name='album_info'),
]


import PySimpleGUI as sg
import numpy as np
import cv2
import matplotlib.pyplot as plt
from Baysian_Mat import Bayesian_Matte
from PIL import Image, ImageOps
import time  # Execution TIme imports
import psutil

from laplac import Laplacianmatting
from compositing import compositing
from QualityTest import mse2d
from QualityTest import sad2d
from QualityTest import psnr2d
from smooth import smooth

# Import your Bayesian_Matte, Laplacianmatting, compositing, mse2d, sad2d, and psnr2d functions here

# Define the PySimpleGUI layout
layout = [
    [sg.Text("Select image file")],
    [sg.Input(key="-IMAGE_FILE-"), sg.FileBrowse()],
    [sg.Text("Select trimap file")],
    [sg.Input(key="-TRIMAP_FILE-"), sg.FileBrowse()],
    [sg.Text("Select GT file")],
    [sg.Input(key="-GT_FILE-"), sg.FileBrowse()],
    [sg.Button("Submit")],
    [sg.Output(size=(60, 2))]
]

# Create the PySimpleGUI window
window = sg.Window("Alpha Matte Calculation", layout)

# Start time for computing the execution time
st = time.time()

# Get initial memory usage
Memstart = psutil.Process().memory_info().rss / (1024 ** 2)

# Event loop
while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    if event == "Submit":
        # Get the file paths from the input fields
        image_path = values["-IMAGE_FILE-"]
        trimap_path = values["-TRIMAP_FILE-"]
        gt_path = values["-GT_FILE-"]

        # Read the image, trimap, and GT files
        image = np.array(Image.open(image_path))
        image_trimap = np.array(Image.open(trimap_path))
        GT = np.array(Image.open(gt_path))

        # Step 2 : Calculating Bayesian Matte for the given trimap
        alpha, pixel_count = Bayesian_Matte(image, image_trimap)

        # Step 3 : Making it back to range (0-255) for display purpose
        alpha_disp = alpha * 255
        alpha_int8 = np.array(alpha, dtype=int)

        et = time.time()
        elapsed_time = et - st

        # Step 4 : End to End testing - 1 : Calculating the Laplacian Matting
        Lalpha = Laplacianmatting(image, image_trimap)

        # Step 5 : Compositing Function Display
        background = np.array(Image.open(
            'C:/Users/aduttagu/Desktop/Main/Bayesian-Matting-Implementation/bayesian-Matting-Python/background.png'))
        comp_Bay = compositing(image, alpha_disp, background)

        # Step 6 : Smoothening ALpha Methods
        smooth_alpha = smooth(alpha_disp)

        # Step 7 : Displaying THe Bayesian, Laplacian and GT.
        fig, axes = plt.subplots(nrows=2, ncols=2)
        axes[0, 0].imshow(alpha_disp, cmap='gray')
        axes[0, 0].set_title('Bayesian - Alpha Matte')
        axes[0, 1].imshow(Lalpha, cmap='gray')
        axes[0, 1].set_title('Laplacian - Alpha Matte')
        axes[1, 0].imshow(GT, cmap='gray')
        axes[1, 0].set_title('Ground Truth')
        axes[1, 1].imshow(smooth_alpha, cmap='gray')
        axes[1, 1].set_title('Smoothed Alpha')
        plt.show()

        plt.imshow(comp_Bay)
        plt.show()

# Close the PySimpleGUI window
window.close()

# Part of End to End testing - 1 : Performance Comparision between Laplacian and Bayesian.
Bay_MSE = mse2d(alpha_disp, GT)
Lap_MSE = mse2d(Lalpha, GT)
print("The MSE between the Ground Truth and Bayesian Alpha Matte is :", Bay_MSE)
print("The MSE between the Ground Truth and Laplacian Alpha Matte is :", Lap_MSE)

Bay_SAD = sad2d(alpha_disp, GT)
Lap_SAD = sad2d(Lalpha, GT)
print("The SAD between the Ground Truth and Bayesian Alpha Matte is :", Bay_SAD)
print("The SAD between the Ground Truth and Laplacian Alpha Matte is :", Lap_SAD)

Bay_PSNR = psnr2d(alpha_disp, GT)
Lap_PSNR = psnr2d(Lalpha, GT)
print("The PSNR between the Ground Truth and Bayesian Alpha Matte is :", Bay_PSNR)
print("The PSNR between the Ground Truth and Laplacian Alpha Matte is :", Lap_PSNR)

print('Execution time for Bayesian Matting: {:.3f} seconds'.format(
elapsed_time))

# get usage after completion of code
Memend = psutil.Process().memory_info().rss / (1024 ** 2)
Memuse = Memend - Memstart
print("Total memory consumed in execution of this program : ", Memuse, "MB's")


import os
import cv2
import pytesseract
import numpy as np
from tqdm import tqdm

INPUT_PATH: str = "inputs_control/"
OUTPUT_PATH: str = "text_pred_control/"
#CONFIG: str = "--psm 6 --oem 1"
CONFIG: str = "--psm 7 --oem 1"

def pipeline(file) -> str:

    path: str = f"{INPUT_PATH}{file}"
    img: np.ndarray = cv2.imread(path)
    text: str = pytesseract.image_to_string(img, config=CONFIG)

    iterator: str = file.split(".")[0]
    with open(OUTPUT_PATH + f"{iterator}.txt", 'w') as f:
        f.write(text)

    return text

def main() -> int:

    files = os.listdir(INPUT_PATH)

    for file in tqdm(files):
        pipeline(file)

    return 0

if __name__ == "__main__":
    main()