import time
from datetime import datetime, timedelta, timezone
import logging
import sys
import math

if (len(sys.argv) < 2):
	exit()
now = datetime.now()
zone_cn = timezone(timedelta(hours=8))
now_cn = now.astimezone(zone_cn)
logging.warning(f'服务器时间：{now}, 北京时间：{now_cn}')
logging.warning(now_cn.hour)
target_hour = -1
hour = now_cn.hour
if (len(sys.argv) == 2 and "-" in sys.argv[1]):
	hs = sys.argv[1].split("-")
	if hour+1 >= int(hs[0]) and hour+1 <= int(hs[1]):
		target_hour = hour+1
else :
	for i in range(1, len(sys.argv)):
		if (hour < int(sys.argv[i])):
			target_hour = int(sys.argv[i])
			break

if target_hour == -1:
	logging.error(f'木有匹配到对应的参数: {sys.argv[1:]}')
	exit()
logging.warning(f'匹配到的参数为: {target_hour}')

if target_hour == 24:
	target_hour = 0
target_time = now_cn.replace(hour=target_hour,minute=0, second=0, microsecond=0)
if target_hour == 0:
	target_time = target_time + timedelta(days=1)
logging.warning(f'当前时间: {now_cn}, 目标时间: {target_time}')

td = target_time - now_cn
if td.seconds > 3600:
	logging.error('时间差大于1小时，退出')
	exit()
logging.warning(f'需要沉睡：{td.seconds}秒')
wait = td.seconds+math.floor(td.microseconds/1000)/1000
time.sleep(wait)
logging.warning(f'当前北京时间：{datetime.now().astimezone(zone_cn)}')


while True:
    x = (input("Üye mi olmak istiyorsunuz Giriş yapmak mı?"))
    #Üyelik kısmı
    if x=="Üye" or x=="Üye olmak" or x=="üye" or x=="üye olmak":

        ad = (input("Ad ve Soyadınızı giriniz"))
        sifre = (input("Şifrenizi belirleyiniz"))
        mail = (input("E-mailinizi giriniz"))
    bilgiler =[ad,sifre,mail]

    #Giriş kısmı
    if x=="Giriş" or x=="Giriş yapmak" or x=="giriş" or x=="giriş yapmak":
        g_mail = (input("E-mail:"))
        g_sifre = (input("Şifre:"))
        if g_mail == (mail) and g_sifre == (sifre):
                print("Giriş Başarılı . Hoşgeldin",ad)
                break
        elif g_mail != (mail) and g_sifre == (sifre):
            print("E-mail yanlış , giriş başarısız")
        elif g_mail == (mail) and g_sifre != (sifre):
            print("Şifre yanlış , giriş başarısız")
        else:
            print("Giriş başarısız , üye olmaya ne dersin?")


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

import tensorflow as tf
import numpy as np

from vgg16_model import vgg16 as vgg16
import TensorflowUtils as utils
import read_voa_data as scene_parsing
import datetime
import BatchDatasetReader as dataset
from six.moves import xrange
from function import accuracy
from PIL import Image

FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_integer("batch_size", "10", "batch size for training")
tf.flags.DEFINE_string("logs_dir", "logs/", "path to logs directory")
tf.flags.DEFINE_string("data_dir", "dataset/", "path to dataset")
tf.flags.DEFINE_float("learning_rate", "1e-4", "Learning rate for Momentum Optimizer")
tf.flags.DEFINE_bool('debug', "False", "Debug mode: True/ False")
tf.flags.DEFINE_string("model_dir", "Model_zoo/", "Path to vgg model mat")
tf.flags.DEFINE_string('mode', "train", "Mode train/ test/ visualize")
tf.flags.DEFINE_float("momentum", "0.9", "momentum for Momentum Optimizer")
tf.flags.DEFINE_float("weight_decay", "5e-4", "weight_decay for reg_loss")

MAX_ITERATION = int(1e5 + 1)
IMAGE_SIZE = 500

MODEL_URL = "http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-16.mat"

def inference(image, keep_prob):
    """ fcn_8s """
    # load data
    vgg16_object = vgg16()
    print("setting up vgg initialized conv layers ...")
    model_data = utils.get_model_data(FLAGS.model_dir, MODEL_URL)
    mean = model_data['normalization'][0][0][0]
    mean_pixel = np.mean(mean, axis=(0, 1))
    weights = model_data['layers'][0]

    # preprocess
    processed_image = utils.process_image(image, mean_pixel)

    # deconvolution
    with tf.variable_scope("inference"):
        image_net = vgg16_object._vgg16_modified(processed_image, weights)

        pool4, pool3 = image_net["pool4"], image_net["pool3"]

        conv_final_layer = image_net["conv5_3"]

        """ pool5 """
        pool5 = vgg16_object._max_pool(conv_final_layer, 2, 2, 'pool5')

        """ fc6 """
        W6 = utils.weight_variable([7, 7, 512, 4096], name="W6")
        b6 = utils.bias_variable([4096], name="b6")
        fc6 = vgg16_object._conv(pool5, W6, b6, 'fc6')
        relu6 = vgg16_object._relu(fc6, 'relu6')
        fc6 = tf.nn.dropout(relu6, keep_prob)

        """ fc7 """
        W7 = utils.weight_variable([1, 1, 4096, 4096], name="W7")
        b7 = utils.bias_variable([4096], name="b7")
        fc7 = vgg16_object._conv(fc6, W7, b7, 'fc7')
        relu7 = vgg16_object._relu(fc7, 'relu7')
        fc7 = tf.nn.dropout(relu7, keep_prob)

        """ fc8 """
        W8 = utils.weight_variable([1, 1, 4096, 21], name="W8")
        b8 = utils.bias_variable([21], name="b8")
        fc8 = vgg16_object._conv(fc7, W8, b8, 'fc8')

        # upsample and add with pool4(pool4 should pass through a score layer)
        score_w1 = utils.weight_variable([1,1,512,21], name="score_w1")
        score_b1 = utils.weight_variable([21], name="score_b1")
        score1 = vgg16_object._conv(pool4, score_w1, score_b1, 'score1')
        W_t1 = tf.Variable(initial_value=bilinear_init(), name="W_t1")
        b_t1 = tf.Variable(initial_value=tf.constant(0.0, shape=[21]), name="b_t1")
        conv_t1 = vgg16_object.conv2d_transpose_strided(fc8, W_t1, b_t1, output_shape=tf.shape(score1))
        fuse_1 = tf.add(conv_t1, score1, name="fuse_1")

        # upsample and add with pool3(pool3 should pass through a score layer)
        score_w2 = utils.weight_variable([1,1,256,21], name="score_w2")
        score_b2 = utils.weight_variable([21], name="score_b2")
        score2 = vgg16_object._conv(pool3, score_w2, score_b2, 'score2')
        W_t2 = tf.Variable(initial_value=bilinear_init(), name="W_t2")
        b_t2 = tf.Variable(initial_value=tf.constant(0.0, shape=[21]), name="b_t2")
        conv_t2 = vgg16_object.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(score2))
        fuse_2 = tf.add(conv_t2, score2, name="fuse_2")

        shape = tf.shape(processed_image)
        deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], 21])
        W_t3 = tf.Variable(initial_value=bilinear_init(scale=8), name="W_t3")
        b_t3 = tf.Variable(initial_value=tf.constant(0.0, shape=[21]), name="b_t3")
        conv_t3 = vgg16_object.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)

        prediction = tf.argmax(conv_t3, dimension=3, name="prediction")
        return prediction, conv_t3, pool4

#Create bilinear weights in numpy array
def bilinear_init(scale=2, num_classes=21):
    filter_size = (2 * scale - scale % 2)
    bilinear_kernel = np.zeros([filter_size, filter_size], dtype=np.float32)
    scale_factor = (filter_size + 1) // 2
    if filter_size % 2 == 1:
        center = scale_factor - 1
    else:
        center = scale_factor - 0.5
    for x in range(filter_size):
        for y in range(filter_size):
            bilinear_kernel[x,y] = (1 - abs(x - center) / scale_factor) * \
                                   (1 - abs(y - center) / scale_factor)
    weights = np.zeros((filter_size, filter_size, num_classes, num_classes))
    for i in range(num_classes):
        weights[:, :, i, i] = bilinear_kernel

    #assign numpy array to tensor
    bilinear_initial = tf.convert_to_tensor(weights, dtype=tf.float32)
    return bilinear_initial

def train(loss_val, var_list):
    optimizer = tf.train.MomentumOptimizer(FLAGS.learning_rate, FLAGS.momentum)
    grads = optimizer.compute_gradients(loss_val, var_list=var_list)
    if FLAGS.debug:
        # print(len(var_list))
        for grad, var in grads:
            utils.add_gradient_summary(grad, var)
    return optimizer.apply_gradients(grads)

def main(argv=None):
    keep_probability = tf.placeholder(tf.float32, name="keep_probabilty")
    image = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="input_image")
    annotation = tf.placeholder(tf.int32, shape=[None, IMAGE_SIZE, IMAGE_SIZE], name="annotation")

    # TODO
    pred_annotation, logits, c_l_l = inference(image, keep_probability)

    tf.summary.image("input_image", image, max_outputs=20)
    # tf.summary.image("ground_truth", tf.cast(annotation, tf.uint8), max_outputs=20)
    # tf.summary.image("pred_annotation", tf.cast(pred_annotation, tf.uint8), max_outputs=20)
    annotation_onehot = tf.one_hot(annotation, 21, 1.0, 0.0, -1)
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = annotation_onehot, logits = logits))
    # loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=tf.clip_by_value(tf.cast(logits, dtype=tf.float32), 1e-10, 1), labels=tf.cast(annotation, dtype=tf.int32))))
    tf.summary.scalar("entropy", loss)

    trainable_var = tf.trainable_variables()
    if FLAGS.debug:
        for var in trainable_var:
            utils.add_to_regularization_and_summary(var)
        # reg_loss = tf.add_n(tf.get_collection("reg_loss"))
    reg_loss = tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables()])
    loss += FLAGS.weight_decay * reg_loss

    train_op = train(loss, trainable_var)

    print("Setting up summary op...")
    summary_op = tf.summary.merge_all()

    print("Setting up image reader...")
    train_records, valid_records = scene_parsing.read_dataset(FLAGS.data_dir)
    print(len(train_records))
    print(len(valid_records))

    print("Setting up dataset reader")
    image_options = {'resize': False, 'resize_size': IMAGE_SIZE}
    if FLAGS.mode == 'train':
        train_dataset_reader = dataset.BatchDatasetReader(train_records, image_options, FLAGS.data_dir)
        validation_dataset_reader = dataset.BatchDatasetReader(valid_records, image_options, FLAGS.data_dir)

    tf_config = tf.ConfigProto()
    tf_config.gpu_options.per_process_gpu_memory_fraction = 0.7
    sess = tf.Session(config=tf_config)

    print("Setting up Saver...")
    saver = tf.train.Saver()
    summary_writer = tf.summary.FileWriter(FLAGS.logs_dir, sess.graph)

    sess.run(tf.initialize_all_variables())
    # print(sess.run(tf.trainable_variables()))

    ckpt = tf.train.get_checkpoint_state(FLAGS.logs_dir)
    if ckpt and ckpt.model_checkpoint_path:
        saver.restore(sess, ckpt.model_checkpoint_path)
        print("Model restored...")

    if FLAGS.mode == "train":
        for itr in xrange(MAX_ITERATION):
            train_images, train_annotations = train_dataset_reader.read_next_batch(FLAGS.batch_size)
            feed_dict = {image: train_images, annotation: train_annotations, keep_probability: 0.85}

            sess.run(train_op, feed_dict=feed_dict)
            print(sess.run(c_l_l, feed_dict=feed_dict))
            if itr % 10 == 0:
                train_loss, summary_str = sess.run([loss, summary_op], feed_dict=feed_dict)
                print("Step: %d, Train_loss:%g" % (itr, train_loss))
                summary_writer.add_summary(summary_str, itr)

            if itr % 500 == 0:
                valid_images, valid_annotations = validation_dataset_reader.read_next_batch(FLAGS.batch_size)
                valid_loss = sess.run(loss, feed_dict={image: valid_images, annotation: valid_annotations,
                                                       keep_probability: 1.0})
                pred = sess.run(pred_annotation, feed_dict={image: valid_images, annotation: valid_annotations,
                                keep_probability: 1.0})
                valid_accu = accuracy.batch_calc_accuracy(pred, valid_annotations)
                print("%s ---> Validation_accu: %g" % (datetime.datetime.now(), valid_accu))
                print("%s ---> Validation_loss: %g" % (datetime.datetime.now(), valid_loss))
                saver.save(sess, FLAGS.logs_dir + "model.ckpt", itr)

    elif FLAGS.mode == "visualize":
        valid_images, valid_annotations = validation_dataset_reader.get_random_batch(FLAGS.batch_size)
        # pred = sess.run(pred_annotation, feed_dict={image: valid_images, annotation: valid_annotations,
        #                                             keep_probability: 1.0})
        # pred = np.squeeze(pred, axis=3)

        # save the prediction
        pass
        # for itr in range(FLAGS.batch_size):
        #     # save gt
        #     pal = (Image.open('/home/jingyang/Desktop/fcn/fcn_test/dataset/SegmentationClass_tranformed/2007_000032.png')).getpalette()
        #     new_img = Image.fromarray(valid_annotations[itr], mode="P")
        #     new_img.putpalette(pal)
        #     path = "logs/gt_"+ str(5 + itr)+".png"
        #     new_img.save(path)
        #     # save inp
        #     utils.save_image(valid_images[itr].astype(np.uint8), FLAGS.logs_dir, name="inp_" + str(5 + itr))
        #     #utils.save_image(valid_annotations[itr].astype(np.uint8), FLAGS.logs_dir, name="gt_" + str(5 + itr))
        #     # save pred
        #     new_img = Image.fromarray(pred[itr], mode="P")
        #     new_img.putpalette(pal)
        #     path = "logs/pred_"+ str(5 + itr)+".png"
        #     new_img.save(path)
        #     # utils.save_image(pred[itr].astype(np.uint8), FLAGS.logs_dir, name="pred_" + str(5 + itr))
        #     print("Saved image: %d" % itr)

if __name__ == "__main__":
    tf.app.run()


#https://open.kattis.com/problems/textencryption

while True :
    n = int(input())

    if n == 0 :
         break

    message = input()
    message = message.replace(' ','')
    message = message.upper()

    encrypted = [ '' for x in range(len(message)) ]

    for i in range(n) :
        for j in range(i,len(encrypted),n) :
            encrypted[j] = message[0]
            message = message[1:]

    print(''.join(encrypted))


from __future__ import print_function
import argparse
import os
import os.path
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
import glob
import ssl
import traceback
from urllib.request import urlopen
from urllib.error import URLError

def is_windows():
    return sys.platform == 'win32'

def get_linux_distribution_id_like():
    # An example of a line in /etc/os-release is ID_LIKE=ubuntu
    # An example of a line in /etc/os-release is ID=debian
    # See ID, ID_LIKE on https://www.freedesktop.org/software/systemd/man/os-release.html

    id_value = id_like_value = None
    try:
        with open('/etc/os-release') as lines:
            for line in lines:
                if "=" in line:
                    key, value = line.split("=", 1)
                    if key.lower() == "id_like":
                        id_like_value = value.lower()
                    if key.lower() == "id":
                        id_value = value.lower()
            return id_value, id_like_value
    except Exception as e:
        return id_value, id_like_value

def is_ubuntu_or_debian():
    linux_distribution_id, linux_distribution_id_like = get_linux_distribution_id_like()
    return (linux_distribution_id_like and any(x in linux_distribution_id_like for x in ['ubuntu', 'debian'])) or (linux_distribution_id and any(x in linux_distribution_id for x in ['ubuntu', 'debian']))

sudo_cmd = 'sudo'
if is_ubuntu_or_debian():
    if os.geteuid() == 0:
        sudo_cmd = ""

def get_ubuntu_version():
    try:
        with open("/etc/os-release") as f:
            d = {}
            for line in f:
                k, v = line.rstrip().split("=")
                d[k.lower()] = v.strip('"')
        return d["version_id"] if d["name"] == "Ubuntu" else None
    except Exception as e:
        return None

optional_feature_list = ['db (will install cx_Oracle)']

ACCEPT_ALL_DEFAULTS = False

VIRTUALENV_VERSION = '20.6.0'
VIRTUALENV_ARCHIVE = 'virtualenv-{}.pyz'.format(VIRTUALENV_VERSION)
VIRTUALENV_DOWNLOAD_URL = 'https://github.com/pypa/get-virtualenv/blob/{}/public/virtualenv.pyz?raw=true'.format(VIRTUALENV_VERSION)
VIRTUALENV_ARCHIVE_SHA256 = 'a5d9b1f27bc790423f7910876c0e46cf476044f4ebd76d29dc6c06a3ab019e93'

DEFAULT_INSTALL_DIR = os.path.expanduser(os.path.join('~', 'lib', 'oracle-cli'))
DEFAULT_EXEC_DIR = os.path.expanduser(os.path.join('~', 'bin'))
DEFAULT_SCRIPT_DIR = os.path.expanduser(os.path.join('~', 'bin', 'oci-cli-scripts'))
OCI_EXECUTABLE_NAME = 'oci.exe' if is_windows() else 'oci'
DBAAS_SCRIPT_NAME = 'create_backup_from_onprem.exe' if is_windows() else 'create_backup_from_onprem'

USER_BASH_RC = os.path.expanduser(os.path.join('~', '.bashrc'))
USER_BASH_PROFILE = os.path.expanduser(os.path.join('~', '.bash_profile'))
SOURCE_AUTOCOMPLETE_COMMAND_TEMPLATE = '[[ -e "{completion_file_path}" ]] && source "{completion_file_path}"'
RELATIVE_PATH_TO_AUTOCOMPLETE_SCRIPT = os.path.join('oci_cli', 'bin', 'oci_autocomplete.sh')
RELATIVE_PATH_TO_POWERSHELL_AUTOCOMPLETE_SCRIPT = os.path.join('oci_cli', 'bin', 'OciTabExpansion.ps1')
DEFAULT_OPTIONAL_FEATURES = ''  # Default is to not install any optional features during OCI CLI installation

DEFAULT_DEPENDENCY_DIR = 'cli-deps'

ANNOUNCEMENT_MESSAGE = "Announcement\n" \
                       "============\n" \
                       "\033[1m1. Interactive mode now available in CLI\033[0;0m\n" \
                       "Have you tried the new interactive features in OCI CLI yet? You can get started by typing `oci -i`.\n" \
                       "Learn more by watching our informative video on YouTube -> https://www.youtube.com/watch?v=lX29Xw1Te54&ab_channel=OracleLearning\n" \
                       "Also see https://docs.oracle.com/iaas/Content/API/SDKDocs/cliusing_topic-Using_Interactive_Mode.htm\n" \
                       "============"

class CLIInstallError(Exception):
    pass

def print_status(msg='', extra_new_line=False):
    if not extra_new_line:
        print('-- ' + msg)
    else:
        print('\n-- ' + msg)

def prompt_input(msg):
    return input('\n===> ' + msg)

def prompt_input_with_default(msg, default):
    if ACCEPT_ALL_DEFAULTS:
        return default

    if default:
        return prompt_input("{} (leave blank to use '{}'): ".format(msg, default)) or default
    else:
        return prompt_input('{}: '.format(msg))

def prompt_y_n(msg, default=None):
    if default not in [None, 'y', 'n']:
        raise ValueError("Valid values for default are 'y', 'n' or None")
    y = 'Y' if default == 'y' else 'y'
    n = 'N' if default == 'n' else 'n'

    if ACCEPT_ALL_DEFAULTS:
        return default == y.lower()

    while True:
        ans = prompt_input('{} ({}/{}): '.format(msg, y, n))
        if ans.lower() == n.lower():
            return False
        if ans.lower() == y.lower():
            return True
        if default and not ans:
            return default == y.lower()

def exec_command(command_list, cwd=None, env=None):
    print_status('Executing: ' + str(command_list))
    subprocess.check_call(command_list, cwd=cwd, env=env)

def create_tmp_dir():
    tmp_dir = tempfile.mkdtemp()
    return tmp_dir

def create_dir(dir):
    if not os.path.isdir(dir):
        print_status("Creating directory '{}'.".format(dir))
        os.makedirs(dir)

def is_valid_sha256sum(a_file, expected_sum):
    sha256 = hashlib.sha256()
    with open(a_file, 'rb') as f:
        sha256.update(f.read())
    computed_hash = sha256.hexdigest()
    return expected_sum == computed_hash

def download_and_create_virtualenv(tmp_dir, install_dir):
    download_location = os.path.join(tmp_dir, VIRTUALENV_ARCHIVE)
    print_status('Downloading virtualenv package from {}.'.format(VIRTUALENV_DOWNLOAD_URL))

    try:
        response = urlopen(VIRTUALENV_DOWNLOAD_URL)
    except URLError as e:
        if e.reason and isinstance(e.reason, ssl.SSLError):
            traceback.print_exc()
            sys.exit('ERROR: Failed to download virtualenv package. Please check that your trusted certificates are up to date and include the certificates necessary to verify github.com')
        else:
            raise e

    with open(download_location, 'wb') as f:
        f.write(response.read())
    print_status("Downloaded virtualenv package to {}.".format(download_location))
    if is_valid_sha256sum(download_location, VIRTUALENV_ARCHIVE_SHA256):
        print_status("Checksum of {} OK.".format(download_location))
    else:
        raise CLIInstallError("The checksum of the downloaded virtualenv package does not match.")
    working_dir = tmp_dir
    # due to an issue with virtualenv on windows, we need to explicitly copy some dlls into the virtual environment
    # or the python executable in the virtualenv will crash upon invocation
    # for python 3 one possible alternative is to use venv instead of virtualenv
    if is_windows():
        print_status('Copying DLLs into virtualenv.')
        dest_dir = os.path.join(install_dir, 'Scripts')
        os.makedirs(dest_dir)
        src_dir = os.path.dirname(sys.executable)
        for dll in glob.glob(os.path.join(src_dir, '*.dll')):
            print_status('Copying {} to {}'.format(dll, dest_dir))
            shutil.copy(dll, dest_dir)
    cmd = [sys.executable, VIRTUALENV_ARCHIVE, install_dir]
    exec_command(cmd, cwd=working_dir)

def install_python3_venv():
    # This is required because if script is run through root user sudo_cmd value will be empty quote and command subprocess.check_call([ ' ', 'apt-get', 'update' ]) will not work.
    if sudo_cmd == "":
        cmd = ['apt-get', 'update']
    else:
        cmd = [sudo_cmd, 'apt-get', 'update']
    if DRY_RUN:
        print_status('dry-run: Skipping apt-get update, cmd=' + str(cmd))
    else:
        exec_command(cmd)

    print_status('Installing python3-venv.')
    # This is required because if script is run through root user sudo_cmd value will be empty quote and command subprocess.check_call(['', 'apt-get', 'install', 'python3-venv', '-y']) will not work.
    if sudo_cmd == "":
        cmd = ['apt-get', 'install', 'python3-venv', '-y']
    else:
        cmd = [sudo_cmd, 'apt-get', 'install', 'python3-venv', '-y']
    if DRY_RUN:
        print_status('dry-run: Skipping apt-get install python3-venv, cmd=' + str(cmd))
    else:
        exec_command(cmd)

def upgrade_pip_wheel(tmp_dir, install_dir, dependency_dir=DEFAULT_DEPENDENCY_DIR):
    if is_windows():
        path_to_python = os.path.join(install_dir, 'Scripts', 'python.exe')
        path_to_pip = os.path.join(install_dir, 'Scripts', 'pip')
    else:
        path_to_pip = os.path.join(install_dir, 'bin', 'pip')

    if not OFFLINE_INSTALL:
        if is_windows():
            cmd = [path_to_python, '-m', 'pip', 'install', '--upgrade', 'pip']
        else:
            cmd = [path_to_pip, 'install', '--upgrade', 'pip']
    else:
        # Upgrade pip with internal wheel file
        py_ver = 'python' + str(sys.version_info.major) + str(sys.version_info.minor) + '.html'
        if not is_windows():
            cmd = [path_to_pip, 'install', 'pip', '--upgrade', '--find-links', os.path.join(dependency_dir, py_ver), '--no-index']
        else:
            cmd = [path_to_python, '-m', 'pip', 'install', 'pip', '--upgrade', '--find-links', os.path.join(dependency_dir, py_ver),
                   '--no-index']

    if DRY_RUN:
        print_status('dry-run: Skipping pip upgrade, cmd=' + str(cmd))
    else:
        exec_command(cmd)

    if not OFFLINE_INSTALL:
        cmd = [path_to_pip, 'install', '--cache-dir', tmp_dir, 'wheel', '--upgrade']
        if DRY_RUN:
            print_status('dry-run: Skipping wheel upgrade, cmd=' + str(cmd))
        else:
            exec_command(cmd)

def create_virtualenv(tmp_dir, install_dir, dependency_dir):
    # Try to create virtaulenv using python3 venv, if venv is not installed or is having any issue, call download_and_create_virtualenv
    if DRY_RUN:
        print_status('dry-run: Skipping virtualenv setup')
        return
    try:
        # Since Ubuntu and Debian are having issues with python3 venv (mising ensurepip module), install python3-venv
        # package, this doesn't work with the offline installation mode since there is no internet connection
        if is_ubuntu_or_debian() and not OFFLINE_INSTALL:
            install_python3_venv()
        print_status('Trying to use python3 venv.')

        cmd = [sys.executable, '-m', 'venv', install_dir]
        exec_command(cmd)

        upgrade_pip_wheel(tmp_dir, install_dir, dependency_dir)
    except Exception:
        if OFFLINE_INSTALL:
            print_status('System was unable to use venv, Please make sure Python3 venv is installed.')
            exit(1)
        else:
            print_status('System was unable to use venv, is going to download and create virtualenv.')
            download_and_create_virtualenv(tmp_dir, install_dir)

def install_cli(install_dir, tmp_dir, version, optional_features, dependency_dir=DEFAULT_DEPENDENCY_DIR):
    """
    The python installer handles 3 cases:
    1) full install zip bundles -- originally for distributing preview builds
       --oci-cli-version can be used to pick the version of the local whl package
    2) installation from pypi
       --oci-cli-version can be used to pick the version of oci-cli from pypi
    3) offline installation (this is for regions or instances which don't have internet access)
    """
    if is_windows():
        path_to_pip = os.path.join(install_dir, 'Scripts', 'pip')
    else:
        path_to_pip = os.path.join(install_dir, 'bin', 'pip')

    # known issue on python 3 where shebang for scripts install using subprocess.call will not reference python executable from venv
    # fix is to unset this environment variable
    # https://github.com/pypa/virtualenv/issues/845
    env = dict(os.environ)
    if '__PYVENV_LAUNCHER__' in os.environ:
        env.pop('__PYVENV_LAUNCHER__')

    match_wheel = "oci_cli*.whl"
    cli_package_name = 'oci_cli'
    if (optional_features):
        cli_package_name += '[' + optional_features + ']'
    if version:
        cli_package_name += '==' + version
        match_wheel = "oci_cli*" + version + "*.whl"

    # Check if we should install a local full-install bundle.
    oci_cli_whl_files = glob.glob(match_wheel)
    if os.path.exists('./' + dependency_dir) and len(oci_cli_whl_files) > 0:
        print_status("Installing {} from local resources.".format(oci_cli_whl_files[0]))
        cmd = [path_to_pip, 'install', '--cache-dir', tmp_dir, oci_cli_whl_files[0], '--upgrade', '--find-links', dependency_dir]

    elif OFFLINE_INSTALL:
        dependency_dir = DEFAULT_DEPENDENCY_DIR + '/python{}{}.html'.format(sys.version_info.major, sys.version_info.minor)
        cmd = [path_to_pip, 'install', cli_package_name, '--find-links', dependency_dir, '--no-index', '--ignore-requires-python']
    else:
        cmd = [path_to_pip, 'install', '--cache-dir', tmp_dir, cli_package_name, '--upgrade']

    if DRY_RUN:
        print_status('dry-run: Skipping CLI install, cmd=' + str(cmd))
        return
    exec_command(cmd, env=env)

def get_install_dir(allow_spaces):
    install_dir = None
    while not install_dir:
        prompt_message = 'In what directory would you like to place the install?'
        install_dir = prompt_input_with_default(prompt_message, DEFAULT_INSTALL_DIR)
        install_dir = os.path.realpath(os.path.expanduser(install_dir))
        if ' ' in install_dir and not allow_spaces:
            print_status("The install directory '{}' cannot contain spaces.".format(install_dir))
            install_dir = None
        else:
            create_dir(install_dir)
            if os.listdir(install_dir):
                print_status("Install directory '{}' is not empty and may contain a previous installation.".format(install_dir))
                if ACCEPT_ALL_DEFAULTS:
                    # default behavior is to NOT delete an existing directory and re-prompt for install_dir, but we can't re-prompt if ACCEPT_ALL_DEFAULTS is set
                    sys.exit("Refusing to remove existing directory {}. Please remove directory manually and re-run installation script.".format(install_dir))

                ans_yes = prompt_y_n('Remove this directory?', 'n')
                if ans_yes:
                    try:
                        shutil.rmtree(install_dir)
                    except Exception:
                        sys.exit("Failed to remove directory: {}. Please remove directory manually and re-run installation script.".format(install_dir))

                    print_status("Deleted '{}'.".format(install_dir))
                    create_dir(install_dir)
                else:
                    # User opted to not delete the directory so ask for install directory again
                    install_dir = None
    print_status("We will install at '{}'.".format(install_dir))
    return install_dir

def get_exec_dir(install_dir, allow_spaces):
    exec_dir = None
    while not exec_dir:
        prompt_message = "In what directory would you like to place the '{}' executable?".format(OCI_EXECUTABLE_NAME)
        exec_dir = prompt_input_with_default(prompt_message, DEFAULT_EXEC_DIR)
        exec_dir = os.path.realpath(os.path.expanduser(exec_dir))
        if ' ' in exec_dir and not allow_spaces:
            print_status("The executable directory '{}' cannot contain spaces.".format(exec_dir))
            exec_dir = None
            continue

        install_dir_bin_folder = 'Scripts' if is_windows() else 'bin'
        install_bin_dir = os.path.join(install_dir, install_dir_bin_folder)
        if exec_dir == install_bin_dir:
            print_status("The executable directory cannot be the same as the {} directory of the virtualenv. Adding this directory to your PATH could interfere with your system python installation.".format(install_dir_bin_folder))
            exec_dir = None

    create_dir(exec_dir)
    print_status("The executable will be in '{}'.".format(exec_dir))
    return exec_dir

def get_script_dir(install_dir, allow_spaces):
    script_dir = None
    while not script_dir:
        prompt_message = "In what directory would you like to place the OCI scripts?"
        script_dir = prompt_input_with_default(prompt_message, DEFAULT_SCRIPT_DIR)
        script_dir = os.path.realpath(os.path.expanduser(script_dir))
        if ' ' in script_dir and not allow_spaces:
            print_status("The script directory '{}' cannot contain spaces.".format(script_dir))
            script_dir = None
            continue

        install_dir_bin_folder = 'Scripts' if is_windows() else 'bin'
        install_bin_dir = os.path.join(install_dir, install_dir_bin_folder)
        if script_dir == install_bin_dir:
            print_status("The script directory cannot be the same as the {} directory of the virtualenv. Adding this directory to your PATH could interfere with your system python installation.".format(install_dir_bin_folder))
            script_dir = None

    create_dir(script_dir)
    print_status("The scripts will be in '{}'.".format(script_dir))
    return script_dir

def get_optional_features():
    prompt_message = "Currently supported optional packages are: {}\n" \
                     "What optional CLI packages would you like to be installed (comma separated names; press enter if " \
                     "you don't need any optional packages)?".format(optional_feature_list)
    optional_features = prompt_input_with_default(prompt_message, DEFAULT_OPTIONAL_FEATURES)

    print_status("The optional packages installed will be '{}'.".format(optional_features))
    return optional_features

def _backup_rc(rc_file):
    try:
        shutil.copyfile(rc_file, rc_file + '.backup')
        print_status("Backed up '{}' to '{}'".format(rc_file, rc_file + '.backup'))
    except (OSError, IOError):
        pass

def _get_default_rc_file():
    bashrc_exists = os.path.isfile(USER_BASH_RC)
    bash_profile_exists = os.path.isfile(USER_BASH_PROFILE)
    if not bashrc_exists and bash_profile_exists:
        return USER_BASH_PROFILE
    if bashrc_exists and bash_profile_exists and platform.system().lower() == 'darwin':
        return USER_BASH_PROFILE
    return USER_BASH_RC if bashrc_exists else None

def _default_rc_file_creation_step():
    rcfile = USER_BASH_PROFILE if platform.system().lower() == 'darwin' else USER_BASH_RC
    ans_yes = prompt_y_n('Could not automatically find a suitable file to use. Create {} now?'.format(rcfile), default='y')
    if ans_yes:
        open(rcfile, 'a').close()
        return rcfile
    return None

def _find_line_in_file(file_path, search_pattern):
    try:
        with open(file_path, 'r') as search_file:
            for line in search_file:
                if search_pattern in line:
                    return True
    except (OSError, IOError):
        pass
    return False

def _modify_rc(rc_file_path, line_to_add):
    if not _find_line_in_file(rc_file_path, line_to_add):
        with open(rc_file_path, 'a') as rc_file:
            rc_file.write('\n' + line_to_add + '\n')

def get_rc_file_path():
    rc_file = None
    default_rc_file = _get_default_rc_file()
    if not default_rc_file:
        rc_file = _default_rc_file_creation_step()
    rc_file = rc_file or prompt_input_with_default('Enter a path to an rc file to update (file will be created if it does not exist)', default_rc_file)
    if rc_file:
        rc_file_path = os.path.realpath(os.path.expanduser(rc_file))
        if not os.path.isfile(rc_file_path):
            print_status("Automatically created rc file at '{}'".format(rc_file_path))
        return rc_file_path
    return None

def warn_other_oci_on_path(exec_dir, exec_filepath):
    env_path = os.environ.get('PATH')
    conflicting_paths = []
    if env_path:
        for p in env_path.split(':'):
            p_to_oci = os.path.join(p, OCI_EXECUTABLE_NAME)
            if p != exec_dir:
                if os.path.isfile(p_to_oci):
                    conflicting_paths.append(p_to_oci)
    if conflicting_paths:
        print_status("** WARNING: Other '{}' executables are on your $PATH. **".format(OCI_EXECUTABLE_NAME), extra_new_line=True)
        print_status("Conflicting paths: {}".format(', '.join(conflicting_paths)))
        print_status("You can run this installation of the CLI with '{}'.".format(exec_filepath))

def handle_path_and_tab_completion(completion_file_path, exec_filepath, exec_dir, update_path_and_enable_tab_completion,
                                   rc_file_path):
    if DRY_RUN:
        print_status("dry-run: Skipping handle_path_and_tab_completion")
        print_status("dry-run: update_path_and_enable_tab_completion=" + str(update_path_and_enable_tab_completion))
        print_status("dry-run: rc_file_path=" + str(rc_file_path))
        return
    if is_windows():
        if update_path_and_enable_tab_completion:
            ans_yes = True
        else:
            ans_yes = prompt_y_n('Modify PATH to include the CLI and enable tab completion in PowerShell now?', 'y')
        if ans_yes:
            # Add autocomplete to the user's profile. Assume that powershell is on the path
            profile_file_path = subprocess.check_output(['powershell', '-NoProfile', 'echo $profile']).decode(sys.stdout.encoding).strip()
            if not os.path.exists(profile_file_path):
                if not os.path.exists(os.path.dirname(profile_file_path)):
                    os.makedirs(os.path.dirname(profile_file_path))

                with open(profile_file_path, 'w') as f:
                    f.write('. "{}"'.format(completion_file_path))
            else:
                with open(profile_file_path, 'a+') as f:
                    current_file_contents = f.read()

                    if current_file_contents.find(completion_file_path) >= 0:
                        # They have the tab completion script in the place we thought already. No action needed
                        pass
                    elif current_file_contents.find('OciTabExpansion.ps1') >= 0:
                        # They have the tab completion script, but not in the place we thought. Print out a warning
                        # but otherwise take no action on the profile
                        print_status()

                        format_str = "It looks like tab completion for oci is already configured in {profile_file_path}. If you wish to replace this with the tab completion script included in this version of the CLI, please remove any lines containing 'OciTabExpansion.ps1' from {profile_file_path} and then run 'oci setup autocomplete'"
                        print_status(format_str.format(profile_file_path=profile_file_path))
                    else:
                        # They don't have the tab completion script in their profile. Add it
                        f.write('\n. "{}"\n'.format(completion_file_path))

            # powershell one-liner to append the exec_dir to the USER path permanently
            # makes the assumption that powershell is on the PATH already
            command = "powershell -Command \"[Environment]::SetEnvironmentVariable(\\\"PATH\\\", \\\"{};\\\" + (Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Environment' -Name PATH).Path, \\\"User\\\")".format(exec_dir)  # noqa: W605
            subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
            print_status('** Close and re-open PowerShell to reload changes to your PATH **', extra_new_line=True)
            print_status('In order to run the autocomplete script, you may also need to set your PowerShell execution policy to allow for running local scripts (as an Administrator run Set-ExecutionPolicy RemoteSigned in a PowerShell prompt)\n')
        else:
            print_status("If you change your mind, dot source {} in your PowerShell profile and restart your shell to enable tab completion.".format(completion_file_path))
            print_status("You can run the CLI with '{}'.".format(exec_filepath))
    else:
        if update_path_and_enable_tab_completion:
            ans_yes = True
        else:
            ans_yes = prompt_y_n('Modify profile to update your $PATH and enable shell/tab completion now?', 'y')
        if ans_yes:
            if rc_file_path is None:
                rc_file_path = get_rc_file_path()
            if not rc_file_path:
                raise CLIInstallError('No suitable profile file found.')
            _backup_rc(rc_file_path)
            line_to_add = "export PATH={}:$PATH".format(exec_dir)
            _modify_rc(rc_file_path, line_to_add)
            line_to_add = SOURCE_AUTOCOMPLETE_COMMAND_TEMPLATE.format(completion_file_path=completion_file_path)
            _modify_rc(rc_file_path, line_to_add)
            print_status('Tab completion set up complete.')
            print_status("If tab completion is not activated, verify that '{}' is sourced by your shell.".format(rc_file_path))
            warn_other_oci_on_path(exec_dir, exec_filepath)
            print_status('** Run `exec -l $SHELL` to restart your shell. **\n', extra_new_line=True)
        else:
            print_status("If you change your mind, add 'source {}' to your rc file and restart your shell to enable tab completion.".format(completion_file_path))
            print_status("You can run the CLI with '{}'.".format(exec_filepath))

def verify_python_version():
    print_status('Verifying Python version.')
    v = sys.version_info
    valid_version = v >= (3, 6, 0)
    if not valid_version:
        raise CLIInstallError('The CLI does not support Python versions less than 3.6.0.')
    if 'conda' in sys.version:
        raise CLIInstallError("This script does not support the Python Anaconda environment. "
                              "Create an Anaconda virtual environment and install with 'pip'")
    print_status('Python version {}.{}.{} okay.'.format(v.major, v.minor, v.micro))

def verify_install_dir_exec_path_conflict(install_dir, exec_path):
    if install_dir == exec_path:
        raise CLIInstallError("The executable file '{}' would clash with the install directory of '{}'. Choose either a different install directory or directory to place the executable.".format(exec_path, install_dir))

def install_native_dependencies_for_ubuntu():
    ubuntu_version = get_ubuntu_version()
    if ubuntu_version is None or ubuntu_version != "20.04":
        return
    print_status('Installing native dependencies for Ubuntu.')
    is_python3 = sys.version_info[0] == 3
    python_dep = 'python3-dev' if is_python3 else 'python-dev'
    dep_list = ['libssl-dev', 'libffi-dev', python_dep, 'build-essential']
    # This is required because if script is run through root user sudo_cmd value will be empty quote and command subprocess.check_call(['', 'apt-get', '--assume-yes', 'install']) will not work.
    if sudo_cmd == "":
        cmd = ['apt-get', '--assume-yes', 'install']
    else:
        cmd = [sudo_cmd, 'apt-get', '--assume-yes', 'install']
    cmd.extend(dep_list)
    exec_command(cmd)

def main():
    parser = argparse.ArgumentParser(description='Install Oracle Cloud Infrastructure CLI.')
    parser.add_argument('--accept-all-defaults', action='store_true',
                        help='If this flag is specified, no user prompts will be displayed and all default prompt '
                             'responses will be used. This flag can be used in combination with other input '
                             'parameters/flags. When used with other parameters/flags, other parameter values '
                             'mentioned on command line take precedence over default values.')
    parser.add_argument('--offline-install', action='store_true',
                        help='When specified, the script installs CLI without going to the internet.'
                             'This can run only as part of offline installation.')
    parser.add_argument('--dependency-dir',
                        help='When input is specified, CLI install will process dependencies from input relative path')
    parser.add_argument('--optional-features', help="""This input param is used to specify any optional
                         features that need to be installed as part of OCI CLI install .e.g. to run dbaas script
                         'create_backup_from_onprem', users need to install optional "db" feature which will install
                         dependent cxOracle package. Use this optional input param as follows:
                         --optional-features feature1,feature2""")
    parser.add_argument('--install-dir', help='This input parameter allows the user to specify the directory where '
                                              'CLI installation is done.')
    parser.add_argument('--exec-dir', help='This input parameter allows the user to specify the directory where CLI '
                                           'executable is stored.')
    parser.add_argument('--script-dir', help='This input parameter allows the user to specify the directory where CLI '
                                             'scripts are stored.')
    parser.add_argument('--update-path-and-enable-tab-completion', action='store_true',
                        help='If this flag is specified, the PATH environment variable is updated to include CLI '
                             'executable and tab auto completion of CLI commands is enabled. It does require rc '
                             'file path in *NIX systems which can be either given interactively or using the '
                             '--rc-file-path option')
    parser.add_argument('--rc-file-path', help='This input param is used in *NIX systems to update the corresponding '
                                               'shell rc file with command auto completion and modification to '
                                               'PATH environment variable with CLI executable path. It requires '
                                               'shell\'s rc file path. e.g. ~/.bashrc. Ideally, should be used with '
                                               'the --update-path-and-enable-tab-completion option')
    parser.add_argument('--oci-cli-version', help='The pip version of CLI to install.')
    parser.add_argument('--dry-run', action='store_true', help='Do not install virtualenv or CLI but go through the motions.')

    # Get Arguments
    args = parser.parse_args()
    global ACCEPT_ALL_DEFAULTS
    ACCEPT_ALL_DEFAULTS = args.accept_all_defaults
    global OFFLINE_INSTALL
    OFFLINE_INSTALL = args.offline_install
    dependency_dir = args.dependency_dir
    if dependency_dir is None:
        dependency_dir = DEFAULT_DEPENDENCY_DIR
    global DRY_RUN
    DRY_RUN = args.dry_run
    OPTIONAL_FEATURES = args.optional_features
    if OPTIONAL_FEATURES and OFFLINE_INSTALL:
        ans = prompt_y_n("You can not provide optional features with the Offline installation mode, do you want to continue?", "y")
        if not ans:
            exit(1)
        OPTIONAL_FEATURES = ""
    install_dir = args.install_dir
    exec_dir = args.exec_dir
    script_dir = args.script_dir
    cli_version = args.oci_cli_version

    # Check Python Version
    verify_python_version()

    # Create required directories
    tmp_dir = create_tmp_dir()
    allow_spaces = False    # on *nix systems, virtualenv pip does not work properly when there are spaces in the dir.
    if is_windows():
        allow_spaces = True
    if install_dir is None:
        install_dir = get_install_dir(allow_spaces)
    else:
        # Create the install directory provided by the user if it does not exist
        create_dir(install_dir)
    if exec_dir is None:
        exec_dir = get_exec_dir(install_dir, allow_spaces)
    else:
        # Create the executable directory provided by the user if it does not exist
        create_dir(exec_dir)
    if script_dir is None:
        script_dir = get_script_dir(install_dir, allow_spaces)
    else:
        # Create the script directory provided by the user if it does not exist
        create_dir(script_dir)
    if OPTIONAL_FEATURES is None and not OFFLINE_INSTALL:
        OPTIONAL_FEATURES = get_optional_features()

    # Create Path
    oci_exec_path = os.path.join(exec_dir, OCI_EXECUTABLE_NAME)
    dbaas_exec_path = os.path.join(script_dir, DBAAS_SCRIPT_NAME)
    verify_install_dir_exec_path_conflict(install_dir, oci_exec_path)

    # Create Virtual Environment
    create_virtualenv(tmp_dir, install_dir, dependency_dir)
    if OPTIONAL_FEATURES:
        install_native_dependencies_for_ubuntu()
    cli_version = args.oci_cli_version

    # Install OCI CLI
    if cli_version and OFFLINE_INSTALL:
        ans = prompt_y_n("CLI version can't be specified with the Offline installation, do you want to continue?", "y")
        if not ans:
            exit(1)
        cli_version = None
    install_cli(install_dir, tmp_dir, cli_version, OPTIONAL_FEATURES, dependency_dir)

    # Copying Files to executing directories
    if DRY_RUN:
        print_status("dry-run: Skipping copying files to Scripts/bin directories.")
        print_status("dry-run: exec_dir=" + exec_dir)
        print_status("dry-run: script_dir=" + script_dir)
        completion_file_path = None
    elif is_windows():
        venv_python_executable = os.path.join(install_dir, 'Scripts', 'python')
        venv_site_packages_directory = subprocess.check_output([venv_python_executable, '-c', 'from distutils.sysconfig import get_python_lib; print(get_python_lib())']).strip()
        completion_file_path = os.path.join(venv_site_packages_directory.decode(sys.stdout.encoding), RELATIVE_PATH_TO_POWERSHELL_AUTOCOMPLETE_SCRIPT)

        # copy the executable created from the pip install to the bin directory specified by the user
        shutil.copyfile(os.path.join(install_dir, 'Scripts', OCI_EXECUTABLE_NAME), oci_exec_path)
        shutil.copyfile(os.path.join(install_dir, 'Scripts', DBAAS_SCRIPT_NAME), dbaas_exec_path)
    else:
        # copy the executable created from the pip install to the bin directory specified by the user
        shutil.copyfile(os.path.join(install_dir, 'bin', OCI_EXECUTABLE_NAME), oci_exec_path)
        shutil.copyfile(os.path.join(install_dir, 'bin', DBAAS_SCRIPT_NAME), dbaas_exec_path)

        oci_exec_cur_stat = os.stat(oci_exec_path)
        dbaas_exec_cur_stat = os.stat(dbaas_exec_path)
        os.chmod(oci_exec_path, oci_exec_cur_stat.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
        os.chmod(dbaas_exec_path, dbaas_exec_cur_stat.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)

        # find the site-packages directory in the virtual environment where we installed oci
        # and use the autocomplete script contained in the bin/ directory
        venv_python_executable = os.path.join(install_dir, 'bin', 'python')
        venv_site_packages_directory = subprocess.check_output([venv_python_executable, '-c', 'from distutils.sysconfig import get_python_lib; print(get_python_lib())']).strip()
        completion_file_path = os.path.join(venv_site_packages_directory.decode(sys.stdout.encoding), RELATIVE_PATH_TO_AUTOCOMPLETE_SCRIPT)

    try:
        # this function prints out the executable location so we only want to point users to 'oci'
        handle_path_and_tab_completion(completion_file_path, oci_exec_path, exec_dir,
                                       args.update_path_and_enable_tab_completion, args.rc_file_path)
    except Exception as e:
        print_status("Unable to set up tab completion. ERROR: {}".format(str(e)))

    shutil.rmtree(tmp_dir)
    print_status("Installation successful.")
    print('\n' + ANNOUNCEMENT_MESSAGE)
    print_status("Run the CLI with {} --help".format(oci_exec_path), True)

if __name__ == '__main__':
    try:
        main()
    except CLIInstallError as cie:
        print('ERROR: ' + str(cie), file=sys.stderr)
        sys.exit(1)
    except KeyboardInterrupt:
        print('\n\nExiting...')
        sys.exit(1)


from time import sleep

print('Bem vindo ao Posto de combustivel!!')

print('=' * 50)
a = 3.90
g = 4.90

desconto1A = 0.04 * a
desconto2A = 0.06 * a

desconto1g = 0.03 * g
desconto2g = 0.06 * g

combustivel = str(input('Alcool ou gasolina? '))

if combustivel == 'g' or'G':
    print('Ok')

    litros = float(input('Quantos litros ? '))
    print('Abastecendo...')
    sleep(2)

    if litros <= 20:
        a = (g - desconto1g) * litros

        print(f'Voce abasteceu {litros}L e tera 3% de desconto, pagara R$ {a:.2f} ')

    elif litros > 20:
        b = (g - desconto2g) * litros
        print(f'Voce abasteceu {litros}L e tera 6% de desconto, pagara R$ {b - desconto2g:.2f} ')

elif combustivel == 'A' or 'a':
    print('OK')

    litros = float(input('Quantos litros ? '))
    print('Abastecendo...')
    sleep(2)

    if litros <= 20:
        a = (a * desconto1A) * litros
        print(f'Voce abasteceu {litros}L e tera 4% de desconto, pagara R$ {a:.2f} ')

    elif litros > 20:
        b = (a * desconto2A) * litros
        print(f'Voce abasteceu {litros}L e tera 6% de desconto, pagara R$ {b:.2f} ')


# -*- coding: utf-8 -*-
import base64
import json
import hashlib
import hmac
from jsonview.decorators import json_view

from django.conf import settings
from django.http import Http404, HttpResponse
from django.shortcuts import redirect
from django.contrib import messages
from django.template import loader, Context
from django.utils.translation import gettext as _
from django.db.models import Sum
from django.template.loader import render_to_string
from django.views.decorators.csrf import csrf_exempt
from django.core.exceptions import PermissionDenied
from django.db.models import Count
from django.urls import reverse
from django.utils import timezone
from django.utils.dateformat import format

from .forms import CheckoutForm
from .models import Cart, CartItem, CartSet, CartSetItem, Orders, OrderItems, Payment, PaymentRaw, Promo, Phones, \
    NovaPoshtaCities, NovaPoshtaWarehouses, NovaPoshtaRegions
from apps.info.models import Config
from apps.liqpay import LiqPay
from apps.elephants.models import Balance
from apps.helpers import normalize_phone, send_sms, delivery_cost_sum

@json_view
def cart(request):
    cart, created = Cart.objects.get_or_create(session_key=request.session.session_key)
    cart.session = request.session.session_key
    cart.save()

    if not created:
        cart_items = CartItem.objects.filter(cart=cart)
        for c_i in cart_items:
            c_i.bal = Balance.objects.get(item=c_i.item, size=c_i.size).amount
    else:
        cart_items = []

    t = loader.get_template('orders/cart.html')
    c = {'cart': cart, 'cart_items': cart_items}
    html = t.render(c, request)

    return {'html': html}

@json_view
def cart_remove(request, id, set=False):
    cart, created = Cart.objects.get_or_create(session_key=request.session.session_key)

    if not created:
        if set:
            try:
                cart_set = CartSet.objects.get(id=id)
            except:
                raise
                return {'success': False}
            else:
                set_items = CartSetItem.objects.filter(cartset=cart_set)
                for item in set_items:
                    try:
                        cart_item = CartItem.objects.get(item=item.item, size=item.size)
                    except CartItem.DoesNotExist:
                        raise
                        return {'success': False}
                    else:
                        cart_item.amount -= cart_set.amount
                        cart_item.amount_set -= cart_set.amount
                        cart_item.save()

                        if cart_item.amount == 0:
                            cart_item.delete()

                cart_set.delete()

        else:
            try:
                cart_item = CartItem.objects.get(id=id)
            except CartItem.DoesNotExist:
                return {'success': False}
            else:
                cart_item.amount = cart_item.amount_set
                cart_item.save()

                if cart_item.amount == 0:
                    cart_item.delete()
    else:
        return {'success': False}

    cart_items = CartItem.objects.filter(cart=cart)
    for c_i in cart_items:
        c_i.bal = Balance.objects.get(item=c_i.item, size=c_i.size).amount
    t = loader.get_template('orders/cart.html')
    c = {'cart': cart, 'cart_items': cart_items}
    html = t.render(c, request)

    return {'html': html, 'count': cart_items.count()}

@json_view
def cart_plus(request, id, set=False, plus=True):
    cart, created = Cart.objects.get_or_create(session_key=request.session.session_key)
    if not created:
        if not set:
            try:
                cart_item = CartItem.objects.get(id=id)
            except CartItem.DoesNotExist:
                return {'success': False}
            else:
                if plus:
                    cart_item.amount += 1
                else:
                    cart_item.amount -= 1
                cart_item.save()
    else:
        return {'success': False}

    cart_items = CartItem.objects.filter(cart=cart)
    for c_i in cart_items:
        c_i.bal = Balance.objects.get(item=c_i.item, size=c_i.size).amount
    t = loader.get_template('orders/cart.html')
    c = {'cart': cart, 'cart_items': cart_items}
    html = t.render(c, request)

    return {'html': html, 'count': cart_items.count()}

@json_view
def cart_warehouses(request, city_id, warehouse_id):
    warehouses = [(w.id, w.description, w.id == warehouse_id) for w in
                  NovaPoshtaWarehouses.objects.filter(novaposhtacities__id=city_id).order_by('number')]
    return {'success': True, 'warehouses': warehouses}

@json_view
def cart_cities(request, region_id, city_id):
    try:
        region = NovaPoshtaRegions.objects.get(pk=region_id)
    except:
        return {'success': False}
    if city_id == 0:
        cities = [(c.id, c.description, region.areasenter_ref == c.ref) for c in
                  NovaPoshtaCities.objects.filter(novaposhtaregions__id=region_id)]
    else:
        cities = [(c.id, c.description, city_id == c.id) for c in
                  NovaPoshtaCities.objects.filter(novaposhtaregions__id=region_id)]
    return {'success': True, 'cities': cities}

def price_description(request):
    config = Config.objects.get()
    description = ''
    if request.session['valuta']=='grn':
        description = config.price_description
    if request.session['valuta']=='usd':
        description = config.price_description_usd
    if request.session['valuta']=='eur':
        description = config.price_description_eur

    return description

@json_view
def cart_checkout(request):
    cart, created = Cart.objects.get_or_create(session_key=request.session.session_key)

    if created:
        return {'success': False}

    form = CheckoutForm(request.user, cart=cart, language=request.LANGUAGE_CODE)

    no_avail_items = 0

    cart_items = CartItem.objects.filter(cart=cart)

    for item in cart_items:
        if not item.check_avail():
            no_avail_items += 1

    if no_avail_items:

        t = loader.get_template('orders/cart.html')
        c = {'cart': cart, 'cart_items': cart_items}
        html = t.render(c, request)

        return {'form': False, 'html': html}

    if request.method == 'POST':
        form = CheckoutForm(request.user, request.POST, cart=cart, language=request.LANGUAGE_CODE)
        if form.is_valid():

            discount_stocks = int(cart.get_discount())

            discount_promo = 0
            if not discount_stocks:
                if form.cleaned_data['promo']:
                    if discount_stocks == 0:
                        codes = Promo.objects.filter(code=form.cleaned_data['promo'], used=False)
                        if codes:
                            code = codes[0]
                            discount_promo = code.discount
                            code.used = True
                            code.save()

                            message1 = _('Thank you. Your bonus %s percent activated.') % code.discount
                            messages.add_message(
                                request,
                                messages.SUCCESS,
                                message1
                            )
                    else:
                        message1 = _('Your discount on the share is %(sum)s %(dsc)s.
') % {'sum': cart.discount_stocks_val(request), 'dsc': price_description(request)}
                        message1 += _('Your promo-code is not activated.')
                        messages.add_message(
                            request,
                            messages.SUCCESS,
                            message1
                        )

            phone = Phones.objects.filter(phone=normalize_phone(form.cleaned_data['phone']))

            if phone:
                p = phone[0]
                if discount_stocks == 0 and discount_promo == 0 and p.active:
                    discount_promo = settings.DISCOUNT_PHONE

                    message0 = _('Thank you. Your discount is %s percent.
') % settings.DISCOUNT_PHONE
                    messages.add_message(
                        request,
                        messages.SUCCESS,
                        message0
                    )
                p.news = True
                p.save()

            else:
                p = Phones()
                p.phone = normalize_phone(form.cleaned_data['phone'])
                p.lang_code = request.LANGUAGE_CODE
                p.save()

                message0 = _('Thank you. After payment of the order your discount will be %s percent.
') % settings.DISCOUNT_PHONE
                message0 += '%(text)s' % ({'url': reverse('messages_off', args=(p.id,)), 'text': _('Do not recive messages about promotion.')})
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    message0
                )

            delivery_cost = 0
            if form.cleaned_data['delivery'] == 3:
                delivery_cost = delivery_cost_sum(form.cleaned_data['country'], cart)

            order = Orders()
            order.name = form.cleaned_data['name']
            order.last_name = form.cleaned_data['last_name']
            order.phone = normalize_phone(form.cleaned_data['phone'])
            order.email = form.cleaned_data['email']
            order.lang_code = request.LANGUAGE_CODE
            order.payment_method = form.cleaned_data['payment']
            order.delivery_method = form.cleaned_data['delivery']
            order.user_comment = form.cleaned_data['shipping']
            order.delivery_cost = delivery_cost
            order.discount_promo = discount_promo
            order.discount_stocks = cart.discount_stocks
            if form.cleaned_data['payment']==5:
                order.paid = True
                order.ttn = 0
                order.date_of_delivery = timezone.now()
                order.delivered = True
                order.packed = True
            order.save()

            cart_items = CartItem.objects.filter(cart=cart)

            for item in cart_items:
                balance = Balance.objects.get(item=item.item, size=item.size)

                orderitem = OrderItems()
                orderitem.order = order
                orderitem.balance = balance
                orderitem.amount = item.amount
                orderitem.price = item.item.get_actual_price()
                orderitem.save()

            items = OrderItems.objects.filter(order=order)
            sum = 0

            for i in items:
                sum += i.price * i.amount

            order.discount_set = sum - cart.get_total()
            order.save()

            if form.cleaned_data['payment'] == 5:
                p = Payment()
                p.order = order
                p.amount = order.get_total_price_grn()
                p.comment = _('In showroom')
                p.save()

            cart.delete()

            if order.payment_method == 2:
                if order.lang_code == 'en':
                    text = 'Your order #%(number)s has been taken. Card number is %(card)s (%(name)s) and sum is %(sum)s %(dsc)s. CatCult' % {'number': order.get_number(), 'card': settings.PRIVAT_CARD, 'name': settings.PRIVAT_NAME, 'sum': order.get_total_price(request), 'dsc': price_description(request)}
                    text += ' Please indicate your name or order number in the payment order'
                elif order.lang_code == 'ru':
                    text = 'Ваш заказ №%(number)s был принят. Номер карты %(card)s (%(name)s). Сумма к оплате %(sum)s %(dsc)s. CatCult' % {'number': order.get_number(), 'card': settings.PRIVAT_CARD, 'name': settings.PRIVAT_NAME, 'sum': order.get_total_price(request), 'dsc': price_description(request)}
                    text += ' Пожалуйста, укажите в назначении платежа свою фамилию или номер заказа'
                elif order.lang_code == 'uk':
                    text = 'Ваше замовлення №%(number)s було прийняте. Номер картки %(card)s (%(name)s). Сума до оплати %(sum)s %(dsc)s. CatCult' % {'number': order.get_number(), 'card': settings.PRIVAT_CARD, 'name': settings.PRIVAT_NAME, 'sum': order.get_total_price(request), 'dsc': price_description(request)}
                    text += ' Буьласка, вкжіть в призначенні платежу своє прізвище або номер замовлення'
                else:
                    text = ''

                send_sms(order.phone, text)

            elif order.payment_method == 1:
                if order.lang_code == 'en':
                    text = 'Your order #%(number)s has been taken. Card number is %(card)s (%(name)s) and sum is %(sum)s %(dsc)s. CatCult' % {'number': order.get_number(), 'card': settings.MONO_CARD, 'name': settings.MONO_NAME, 'sum': order.get_total_price(request), 'dsc': price_description(request)}
                    text += ' Please indicate your name or order number in the payment order'
                elif order.lang_code == 'ru':
                    text = 'Ваш заказ №%(number)s был принят. Номер карты %(card)s (%(name)s). Сумма к оплате %(sum)s %(dsc)s. CatCult' % {'number': order.get_number(), 'card': settings.MONO_CARD, 'name': settings.MONO_NAME, 'sum': order.get_total_price(request), 'dsc': price_description(request)}
                    text += ' Пожалуйста, укажите в назначении платежа свою фамилию или номер заказа'
                elif order.lang_code == 'uk':
                    text = 'Ваше замовлення №%(number)s було прийняте. Номер картки %(card)s (%(name)s). Сума до оплати %(sum)s %(dsc)s. CatCult' % {'number': order.get_number(), 'card': settings.MONO_CARD, 'name': settings.MONO_NAME, 'sum': order.get_total_price(request), 'dsc': price_description(request)}
                    text += ' Буьласка, вкжіть в призначенні платежу своє прізвище або номер замовлення'
                else:
                    text = ''

                send_sms(order.phone, text)

            else:
                if order.payment_method != 5:
                    if order.lang_code == 'en':
                        text = 'Your order #%(number)s has been taken. Total price is %(sum)s %(dsc)s. CatCult' % {'number': order.get_number(), 'sum': order.get_total_price(request), 'dsc': price_description(request)}
                        text += ' Please indicate your name or order number in the payment order'
                    elif order.lang_code == 'ru':
                        text = 'Ваш заказ №%(number)s был принят. Сумма к оплате %(sum)s %(dsc)s. CatCult' % {'number': order.get_number(), 'sum': order.get_total_price(request), 'dsc': price_description(request)}
                        text += ' Пожалуйста, укажите в назначении платежа свою фамилию или номер заказа'
                    elif order.lang_code == 'uk':
                        text = 'Ваше замовлення №%(number)s було прийняте. Сума до оплати %(sum)s %(dsc)s. CatCult' % {'number': order.get_number(), 'sum': order.get_total_price(request), 'dsc': price_description(request)}
                        text += ' Буьласка, вкжіть в призначенні платежу своє прізвище або номер замовлення'
                    else:
                        text = ''

                    if order.payment_method == 0:
                        send_sms(order.phone, text)

            if order.payment_method != 5:
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    text
                )

            if order.phone:
                try:
                    ph_s = str(order.phone)
                except:
                    ph_s = _('Error in phone number.')
            else:
                ph_s = _('Phone number is not set.')

            message = _('Your order has been placed. We will contact you shortly.
Order details:
')
            message += str(order.get_number()) + '
' + ph_s + '
'
            for item in order.orderitems_set.all():
                message += item.balance.item.name + ' - '
                message += item.balance.size.name + ' - '
                message += str(item.amount) + '
'
            if delivery_cost:
                if request.session['valuta'] == 'grn':
                    pass
                else:
                    config = Config.objects.get()
                    rate = 1
                    if request.session['valuta'] == 'usd':
                        rate = config.dollar_rate
                    if request.session['valuta'] == 'eur':
                        rate = config.euro_rate
                    delivery_cost = round(delivery_cost / rate, 2)
                message += _('Cost of delivery:') + ' ' + str(delivery_cost) + ' ' + price_description(request) + '
'
            message += _('Total:') + ' ' + str(order.get_total_price(request)) + ' ' + price_description(request) + '
'

            messages.add_message(
                request,
                messages.SUCCESS,
                message
            )

            if order.payment_method == 3:
                """
                LiqPay form below.
                """
                """
                liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY)
                payment_form = liqpay.cnb_form({
                    'action': 'pay',
                    'amount': order.get_total_price_grn(),
                    'currency': 'UAH',
                    'description': 'CatCult order',
                    'order_id': order.id,
                    'server_url': settings.LIQPAY_CALLBACK,
                    'result_url': settings.LIQPAY_SUCCESS
                })

                return {'payment_form': payment_form}
                """
                config = Config.objects.get()
                payment = {}
                payment['account'] = config.merchant_account
                payment['domain'] = config.merchant_domain_name
                payment['tr_type'] = 'SALE'
                payment['auth_type'] = 'SimpleSignature'
                payment['sign'] = ''
                payment['url'] = 'https://' + config.merchant_domain_name + reverse('wfp_callback')
                payment['order_id'] = order.id
                payment['order_date'] = format(order.added, 'U')
                payment['amount'] = order.get_total_price_grn()
                payment['currency'] = 'UAH'
                payment['products'] = []
                payment['prices'] = []
                payment['counts'] = []
                payment['first_name'] = order.name
                payment['last_name'] = order.last_name
                payment['phone'] = order.phone
                payment['lang'] = 'AUTO'

                for order_item in order.orderitems_set.all():
                    payment['products'].append(order_item.balance.item.name)
                    payment['prices'].append(order_item.price)
                    payment['counts'].append(order_item.amount)

                products_str = ';'.join(payment['products'])
                prices_str = ';'.join(str(x) for x in payment['prices'])
                counts_str = ';'.join(str(x) for x in payment['counts'])

                sign_str = ';'.join([
                    payment['account'], payment['domain'], str(payment['order_id']),
                    str(payment['order_date']), str(payment['amount']), payment['currency'],
                    products_str, str(counts_str), str(prices_str)
                ])
                payment['sign'] = hmac.new(
                    str.encode(config.merchant_secret),
                    str.encode(sign_str),
                    hashlib.md5
                ).hexdigest()

                return {'payment': payment}

            return {'form': False}

    t = loader.get_template('orders/cart_checkout.html')
    c = {'form': form}
    html = t.render(c, request)

    button_text = _('Place the order')

    return {'form': True, 'html': html, 'button_text': button_text}

@csrf_exempt
def liqpay_callback(request):
    if request.method == 'POST':
        raw = PaymentRaw()
        raw.data = request.POST.get('data', '')
        raw.sign = request.POST.get('signature', '')
        try:
            raw.data_decoded = base64.b64decode(request.POST.get('data', '')).decode()
        except:
            pass
        raw.save()

        liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY)
        sign = liqpay.str_to_sign(
            settings.LIQPAY_PRIVATE_KEY +
            request.POST.get('data', '') +
            settings.LIQPAY_PRIVATE_KEY
        )

        if request.POST.get('signature', '') == sign.decode():
            response = json.loads(base64.b64decode(request.POST.get('data')).decode())

            if response['status'] == 'success':
                try:
                    order = Orders.objects.get(id=int(response['order_id']))
                except:
                    return HttpResponse()

                payment = Payment()
                payment.order = order
                payment.amount = int(response['amount'])
                payment.comment = 'LiqPay'
                payment.token = response['liqpay_order_id']
                payment.sender_phone = response['sender_phone']
                payment.save()

                if order.get_total_price_grn() == order.get_total_paid():
                    order.paid = True
                    order.save()
                else:
                    order.paid = False
                    order.save()

                try:
                    phone = Phones.objects.get(phone=order.phone)
                    phone.active = True
                    phone.save()
                except:
                    pass

                return HttpResponse()

            else:
                try:
                    order = Orders.objects.get(id=int(response['order_id']))
                except:
                    return HttpResponse()

                order.liqpay_wait_accept = True
                order.save()
                return HttpResponse()

@csrf_exempt
def wfp_callback(request):
    if request.method == 'POST':
        config = Config.objects.get()
        raw = PaymentRaw()
        raw.data = request.body.decode('utf-8')
        raw.sign = ''
        raw.save()
        try:
            data = json.loads(raw.data)
            raw.sign = data['merchantSignature']
            raw.save()
        except:
            raise

        sign_str = ';'.join([
            data['merchantAccount'], str(data['orderReference']), str(data['amount']),
            data['currency'], str(data['authCode']), data['cardPan'],
            data['transactionStatus'], str(data['reasonCode'])
        ])

        sign = hmac.new(
            str.encode(config.merchant_secret),
            str.encode(sign_str),
            hashlib.md5
        ).hexdigest()

        if sign == raw.sign:
            response_dict = {}
            response_dict['orderReference'] = data['orderReference']
            response_dict['status'] = 'accept'
            response_dict['time'] = format(timezone.now(), 'U')
            response_dict['signature'] = ''

            response_sign_str = ';'.join([
                response_dict['orderReference'], response_dict['status'],
                str(response_dict['time'])
            ])

            response_dict['signature'] = hmac.new(
                str.encode(config.merchant_secret),
                str.encode(response_sign_str),
                hashlib.md5
            ).hexdigest()

            if data['transactionStatus'] == 'Approved':
                try:
                    order = Orders.objects.get(id=int(data['orderReference']))
                except:
                    return HttpResponse(json.dumps(response_dict, ensure_ascii=False), content_type="text/plain")

                payment = Payment()
                payment.order = order
                payment.amount = int(data['amount'])
                payment.comment = 'WayForPay'
                payment.token = data['orderReference']
                payment.sender_phone = data['phone']
                payment.save()

                if order.get_total_price_grn() == order.get_total_paid():
                    order.paid = True
                    order.liqpay_wait_accept = False
                    order.save()
                else:
                    order.paid = False
                    order.save()

                try:
                    phone = Phones.objects.get(phone=order.phone)
                    phone.active = True
                    phone.save()
                except:
                    pass

                return HttpResponse(json.dumps(response_dict, ensure_ascii=False), content_type="text/plain")

            else:
                try:
                    order = Orders.objects.get(id=int(data['orderReference']))
                except:
                    return HttpResponse(json.dumps(response_dict, ensure_ascii=False), content_type="text/plain")

                order.liqpay_wait_accept = True
                order.wfp_status = '; '.join([data['transactionStatus'], str(data['reasonCode']), data['reason']])
                order.save()
                return HttpResponse(json.dumps(response_dict, ensure_ascii=False), content_type="text/plain")
        else:
            return HttpResponse()

def messages_off(request, id):
    try:
        phone = Phones.objects.get(id=id)
        phone.news = False
        phone.save()
        message = _('You were successfully unsubscribed.')
        messages.add_message(
            request,
            messages.SUCCESS,
            message
        )

    except:
        message = _('Something went wrong. Please try later or contact us.')
        messages.add_message(
            request,
            messages.WARNING,
            message
        )

    if request.headers.get('x-requested-with') == 'XMLHttpRequest':
        return HttpResponse(json.dumps({'message': message}), content_type = 'application/json')
    else:
        return redirect('main_page')

@json_view()
def cart_valuta(request):
    valuta = request.POST.get('valuta', 'grn')

    request.session['valuta'] = valuta

    return {'success': True}


"""empty message

Revision ID: 34fe96f53049
Revises: 43f3fe0f1fa1
Create Date: 2020-04-17 16:16:04.494204

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '34fe96f53049'
down_revision = '43f3fe0f1fa1'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index('student_id', table_name='circuits')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_index('student_id', 'circuits', ['student_id'], unique=True)
    # ### end Alembic commands ###


#!/usr/bin/python3

# sudo systemctl start bluetooth
# echo "power on" | bluetoothctl

import collections
import struct
import sys
import argparse
import datetime
import time
import pickle
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange
from bluetooth import *
import csv

# Process socket data from USB meter and extract volts, amps etc.
def processdata(d):

    data = {}

    data["Volts"] = struct.unpack(">h", d[2 : 3 + 1])[0] / 1000.0  # volts
    data["Amps"] = struct.unpack(">h", d[4 : 5 + 1])[0] / 10000.0  # amps
    data["Watts"] = struct.unpack(">I", d[6 : 9 + 1])[0] / 1000.0  # watts
    data["temp_C"] = struct.unpack(">h", d[10 : 11 + 1])[0]  # temp in C
    data["temp_F"] = struct.unpack(">h", d[12 : 13 + 1])[0]  # temp in F

    utc_dt = datetime.datetime.now(datetime.timezone.utc)  # UTC time
    dt = utc_dt.astimezone()  # local time
    data["time"] = dt

    g = 0
    for i in range(16, 95, 8):
        ma, mw = struct.unpack(">II", d[i : i + 8])  # mAh,mWh respectively
        gs = str(g)
        data[gs + "_mAh"] = ma
        data[gs + "_mWh"] = mw
        g += 1

    data["data_line_pos_volt"] = struct.unpack(">h", d[96: 97 + 1])[0] / 100.0
    data["data_line_neg_volt"] = struct.unpack(">h", d[98: 99 + 1])[0] / 100.0
    data["resistance"] = struct.unpack(">I", d[122: 125 + 1])[0] / 10.0  # resistance
    return data

def main(target_pods: int, repetition: int, time_analysis: int):

    #Variables
    path_out = '/home/luongtrann/hanoi/code/data_ummeter'

    try:
        addr = '00:16:A5:00:0F:65'
        sock = BluetoothSocket(RFCOMM)
        res = sock.connect((addr, 1))
    except:
        print("Having some problems to connect to the UMMETER")
        # Automagically find USB meter
        nearby_devices = discover_devices(lookup_names=True)

        for v in nearby_devices:
            if "UM25C" in v[1]:
                print("Found", v[0])
                addr = v[0]
                break

        if addr is None:
            print("No address provided", file=sys.stderr)
            quit()

        service_matches = find_service(address=addr)

        if len(service_matches) == 0:
            print("No services found for address ", addr, file=sys.stderr)
            quit()

        first_match = service_matches[0]
        port = first_match["port"]
        name = first_match["name"]
        host = first_match["host"]

        if host is None or port is None:
            print("Host or port not specified", file=sys.stderr)
            quit()

        sock = BluetoothSocket(RFCOMM)
        print('connecting to "{}" on {}:{}'.format(name, host, port))
        res = sock.connect((host, port))

    with open('{}/data_ummeter_{}_{}.csv'.format(path_out, str(target_pods), str(repetition)), 'a+') as f:
        writer = csv.writer(f)
        writer.writerow(["time", "Volts", "Amps", "Watts"])
        leng = 20
        volts = collections.deque(maxlen=leng)
        currents = collections.deque(maxlen=leng)
        watts = collections.deque(maxlen=leng)
        times = collections.deque(maxlen=leng)

        d = b""

        endtime = time.time()+(60*int(time_analysis)+240) #[m]->[s] + 45s for cold and delete
        while endtime-time.time() > 0:
            # Send request to USB meter
            sock.send((0xF0).to_bytes(1, byteorder="big"))

            d += sock.recv(130)

            if len(d) != 130:
                continue

            data = processdata(d)
            volts.append(data["Volts"])
            currents.append(data["Amps"])
            watts.append(data["Watts"])
            times.append(data["time"])

            #print("%s: %fV %fA %fW" % (data["time"], data["Volts"], data["Amps"], data["Watts"]))

            writer.writerow([data["time"], data["Volts"], data["Amps"], data["Watts"]])

            d = b""
            time.sleep(0.1)

        print('Closed')
        sock.close()
    return True


from aiogram import types
from loguru import logger

from bot import emojies
from bot.constants import LookingTripState
from bot.decorators import get_api
from services.atlas.atlas_api import AtlasAPI
from services.atlas.dto import LookingTripParams
from services.atlas.scheduler import scheduler

def start_searching_trip(message: types.Message, param: LookingTripParams):
    logger.log("BOT", f"The trip search {param.id} added to pool")

    scheduler.add_job(
        trip_searching,
        id=str(param.id),
        kwargs={"message": message, "params": param},
        trigger="interval",
        seconds=param.interval * 60,
        coalesce=True,
    )

    if not scheduler.state:
        scheduler.start()

def stop_trip_searching(param: LookingTripParams):
    if scheduler.get_job(str(param.id)):
        logger.log("BOT", f"The trip search {param.id} has stopped")
        scheduler.remove_job(str(param.id))

async def notify_job_users(jobs, msg: str):
    users = set()
    for job in jobs:
        message = job.kwargs.get('message')
        if not message or message and message.from_id in users:
            continue
        users.add(message.from_id)
        await message.answer(msg)

async def stop_all_tips_searching():
    await notify_job_users(
        scheduler.get_jobs(),
        f"{emojies.EXCLAMATION_MARK} Технические неполадки, все задачи были остановлены {emojies.EXCLAMATION_MARK}"
    )
    scheduler.remove_all_jobs()

# def is_job_running(param: LookingTripParams):
#     return LookingTripState.ON if scheduler.get_job(str(param.id)) else LookingTripState.OFF

def change_searching_trip_state(curr_state: LookingTripState) -> LookingTripState:
    return LookingTripState.ON if curr_state == LookingTripState.OFF else LookingTripState.OFF

@get_api
async def trip_searching(message: types.Message, api: AtlasAPI, params: LookingTripParams):
    logger.log("BOT", f"Getting trips to chat_id: {message.chat.id}, by params.id: {params.id}")
    res = await api.get_all_trips(params.departure_city, params.arrival_city, params.date)
    logger.info("BOT", f"Got a response to chat_id: {message.chat.id}, by params.id: {params.id}")
    await message.answer(f"Результат поиска: {res}")


from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField
from drf_writable_nested.serializers import WritableNestedModelSerializer
from manufacture.models import *

class StringSerializer(serializers.StringRelatedField):

    def to_internal_value(self, value):
        return value

class ProcessDetailSerializer(serializers.ModelSerializer):
    bill_of_materials = StringSerializer()
    process_equipment = StringSerializer()
    products = StringSerializer()
    rate = StringSerializer()
    type = serializers.SerializerMethodField()

    class Meta:
        model = Process
        fields = [
            "id",
            "parent_process",
            "process_equipment",
            'name',
            'description',
            'bill_of_materials',
            'type', # display this
            'duration',
            'rate',
            'products',
            'reference_number'

        ]

    def get_type(self, obj):
        return obj.get_type_display()

class ProcessListSerializer(serializers.ModelSerializer):
    type = serializers.SerializerMethodField()

    class Meta:
        model = Process
        fields = [
            'id',
            'name',
            'reference_number',
            'rate',
            'type',
        ]

    def get_type(self, obj):
        return obj.get_type_display()

class ProcessCreateUpdateSerializer(serializers.ModelSerializer):

    class Meta:
        model = Process
        fields = [
            "parent_process",
            "process_equipment",
            'name',
            'description',
            'bill_of_materials',
            'type',
            'duration',
            'rate',
            'products'
        ]

class ProcessRateCreateUpdateSerializer(serializers.ModelSerializer):

    class Meta:
        model = ProcessRate
        fields = [
            "id",
            "unit",
            "unit_time",
            'quantity',
        ]

class ProcessRateSerializer(serializers.ModelSerializer):
    unit = StringSerializer()
    unit_time = serializers.SerializerMethodField()

    class Meta:
        model = ProcessRate
        fields = [
            "id",
            "unit",
            "unit_time",
            'quantity',
        ]

    def get_unit_time(self, obj):
        return obj.get_unit_time_display()


# #numbers (integers, float,complex)

# a =3
# b = -3
# c = 3.1
# d = 3+5j

# print(type(a))
# print(type(b))
# print(type(c))
# print(type(d))

# #string

"""name = "koFfi"
klass = "march2023"
p = "i love to code in python"
"""
# print(type(name))
# print(type(klass))

"""#string methods
print(name.lower())
name_upper = name.upper()
name_title = name.title()
print(p.title())
print(name_title)
print(name.isdigit())
print(name.isalpha())
print(klass.isdigit())
print(klass.isalnum())
#print(help(str))
name2 = name.strip()
#print(len(name))"""

# p = "python"

# print(p[0:4])

##Boolean    to switch

is_student = True
is_cloud = False


import numpy as np
import pandas as pd

from basic import getFeatureType

class CART_Regression:
    def __init__(self):
        self.T={}
        self.featureType=[]
        self.eps=1e-7
    def getSpiltPoint(self,f,t):
        f=np.unique(f)
        return np.linspace(f.min(),f.max(),np.sqrt(len(f)),False) if t else f
    def getSplitArr(self,f,v,t):
        return f<=v if t else f==v
    def getSplitInterval(self,X,by):
        #print(X,by)
        return (X[by],X[by^True])
    def getLeastSquares(self,D):
        c0=np.mean(D[0])
        c1=np.mean(D[1])
        return np.sum(np.square(D[0]-c0))+np.sum(np.square(D[1]-c1))
    def gain(self,f,Y,t):
        #print('gain:',f,Y)
        spiltPoint=self.getSpiltPoint(f,t)
        splitArr=list(map(lambda cp:self.getSplitArr(f,cp,t),spiltPoint))
        splitInterval=list(map(lambda arr:self.getSplitInterval(Y,arr),splitArr))
        splitLeastSquare=list(map(lambda D:self.getLeastSquares(D),splitInterval))
        sp=np.argmin(splitLeastSquare)
        print(spiltPoint[sp],splitLeastSquare[sp])
        return spiltPoint[sp],splitLeastSquare[sp]

    def build(self,X,Y):
        #print('build ',X,Y)
        T={'left':None,'right':None,'key':None,'keyValue':None,'value':None}
        numY=np.unique(Y)
        if numY.size==0:
            return None
        T['value']=np.mean(Y)
        if np.sum(np.square(Y-np.mean(Y)))<self.eps:
            return T
        splitFeature=np.array(list(map(lambda f,t:self.gain(f,Y,t),np.transpose(X),self.featureType)))
        featureIndex=np.argmin(splitFeature[:,1])
        #print('splitFeature:',splitFeature)
        #print('featureIndex:',featureIndex)
        T['key']=featureIndex
        T['keyValue']=splitFeature[featureIndex,0]

        spiltArr=self.getSplitArr(X[:,featureIndex],T['keyValue'],self.featureType[featureIndex])
        T['left'],T['right']=map(lambda A:self.build(A[0],A[1]),
        [(X[spiltArr],Y[spiltArr]),(X[spiltArr^True],Y[spiltArr^True])])
        return T

    def getG(self,T,X,Y):
        G={'g':None,'left':None,'right':None}
        if T['key']==None:
            G['g']=np.Inf
            return G['g'],np.sum(np.square(Y-T['value'])),len(Y),G
        featureIndex=T['key']
        spiltArr=self.getSplitArr(X[:,featureIndex],T['keyValue'],self.featureType[featureIndex])
        lG,lC,lNum,G['left']=self.getG(T['left'],X[spiltArr],Y[spiltArr])
        rG,rC,rNum,G['right']=self.getG(T['right'],X[spiltArr^True],Y[spiltArr^True])
        G['g']=(np.sum(np.square(Y-T['value']))-lC-rC)/(lNum+rNum)
        return min(lG,rG,G['g']),lC+rC,lNum+rNum,G
    def cutByalpha(self,T,G,alpha):
        if T['key']==None:
            return T
        if G['g']<=alpha:
            T['left']=T['right']=T['key']=T['keyValue']=None
            return T
        T['left']=self.cutByalpha(T['left'],G['left'],alpha)
        T['right']=self.cutByalpha(T['right'],G['right'],alpha)
        return T
    def copyT(self,T):
        if T['key']==None:
            return T.copy()
        rT=T.copy()
        rT['left']=self.copyT(T['left'])
        rT['right']=self.copyT(T['right'])
        return rT
    def calTError(self,X,Y,T):
        self.T=T
        preY=self.predict(X)
        return np.sum(np.square(preY-Y))
    def pruningTree(self,X,Y,valX,valY):
        teT=self.copyT(self.T)
        TList=[]

        while teT['key']!=None:
            minG,c,num,G=self.getG(teT,X,Y)
            teT=self.cutByalpha(teT,G,minG)
            TList.append(self.copyT(teT))
            print('g:',minG,'G:',G)
        TlistError=list(map(lambda T:self.calTError(valX,valY,T),TList))
        self.T=TList[np.argmin(TlistError)]
    def findx(self,x,T):
        if T['key'] is None:
            return T['value']
        featureIndex=T['key']
        if self.featureType[featureIndex]:
            next=T['left'] if x[featureIndex]<=T['keyValue'] else T['right']
        else:
            next=T['left'] if x[featureIndex]==T['keyValue'] else T['right']
        return T['value'] if next is None else self.findx(x,next)
    def train(self,X,Y,valX=None,valY=None):
        self.featureType=getFeatureType(X)
        self.T=self.build(X,Y)
        if valX is not None and valY is not None:
            self.pruningTree(X,Y,valX,valY)
    def predict(self,X):
        Y=np.array(list(map(lambda x:self.findx(x,self.T),X)))
        print(list(zip(X,Y)))
        return Y
if __name__=="__main__":
    dt=CART_Regression()

    X=np.array([[0,0],[1,1],[0,1],[1,0],[1,1]])
    Y=np.array([0,0,1,1,0])
    print(X[:2],Y[:2])
    dt.train(X,Y,X[:2],Y[:2])

    dt.predict([[0,0],[1,1],[0,1],[1,0]])
    dt.predict([[0.5,0.5]])


import dlib
import cv2
import imutils
import QT_gui
import global_v as GV

# 開啟影片檔案
cap = cv2.VideoCapture(0)

# Dlib 的人臉偵測器
detector = dlib.get_frontal_face_detector()

# 以迴圈從影片檔案讀取影格，並顯示出來
while(cap.isOpened()):
  ret, frame = cap.read()

  # 偵測人臉
  face_rects, scores, idx = detector.run(frame, 0)
  rectarea=0
  # 取出所有偵測的結果
  for i, d in enumerate(face_rects):
    x1 = d.left()
    y1 = d.top()
    x2 = d.right()
    y2 = d.bottom()
    text = "%2.2f(%d)" % (scores[i], idx[i])

    # 以方框標示偵測的人臉
    cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 4, cv2.LINE_AA)
    rectarea=abs(x1-x2)*abs(y1-y2)
    # 標示分數
    #cv2.putText(frame, text, (x1, y1), cv2.FONT_HERSHEY_DUPLEX,
    #        0.7, (255, 255, 255), 1, cv2.LINE_AA)

  # 顯示結果
  cv2.imshow("Face Detection", frame)
  if rectarea>=180000:
    cv2.imwrite("face.jpg", frame[y1:y2,x1:x2])
    cap.release()
    cv2.destroyAllWindows()
    QT_gui.FirstUi()

  if cv2.waitKey(1) & 0xFF == ord('q'):
    break


from PyDAQmx import *
from PyDAQmx import Task
from PyDAQmx import DAQmxConstants
from numpy import zeros

import time
"""This example is a PyDAQmx version of the ContAcq_IntClk.c example
It illustrates the use of callback functions

This example demonstrates how to acquire a continuous amount of
data using the DAQ device's internal clock. It incrementally stores the data
in a Python list.
"""

#DAQmxResetDevice('Dev3')

class CallbackTask(Task):
    def __init__(self, strDevice='Dev1', strChannelsList=['ai0'], everyNSamplesCallback=None):
        Task.__init__(self)

        self.bDifferential = False
        self.strDevice = strDevice
        self.strChannelsList = strChannelsList
        self.N_channels = len(strChannelsList)
        self.everyNSamplesCallback = everyNSamplesCallback
        self.fs = int(4e3)
        self.N_per_chunk = int(self.fs)
        self.buffer_size = self.N_per_chunk*10
        self.data = np.zeros((self.N_channels, self.N_per_chunk), dtype=np.float64)
        self.data_all = np.zeros((self.N_channels,0), dtype=np.float64)
        self.time_start = time.clock()

        self.initNIDAQ()

    def initNIDAQ(self):
        # Reset device to make sure that we start in a clean state.
        DAQmxResetDevice(self.strDevice)

        # Create every channel
        for strCurrentChannel in self.strChannelsList:
            print(self.strDevice + '/' + strCurrentChannel)
            if self.bDifferential:
                self.CreateAIVoltageChan(self.strDevice + '/' + strCurrentChannel,"", DAQmxConstants.DAQmx_Val_Diff, -10.0,10.0, DAQmxConstants.DAQmx_Val_Volts,None)
            else:
                self.CreateAIVoltageChan(self.strDevice + '/' + strCurrentChannel,"", DAQmxConstants.DAQmx_Val_RSE, -10.0,10.0, DAQmxConstants.DAQmx_Val_Volts,None)

        # Setup clocking scheme (internal clock)
        self.CfgSampClkTiming("", self.fs, DAQmxConstants.DAQmx_Val_Rising, DAQmxConstants.DAQmx_Val_ContSamps, self.buffer_size)
        # Adjust a few settings.
        # This one is to ignore any buffer overrun event (because otherwise it completely stops the recording, and carries over the next time we want to use the dac)
        self.SetReadOverWrite(DAQmxConstants.DAQmx_Val_OverwriteUnreadSamps)
        # Register callback functions
        self.AutoRegisterEveryNSamplesEvent(DAQmxConstants.DAQmx_Val_Acquired_Into_Buffer, self.N_per_chunk,0)
        self.AutoRegisterDoneEvent(0)

    def EveryNCallback(self):
        read = int32()
        timeout = 10.
#        print(int(self.data.size))
        self.ReadAnalogF64(int(self.N_per_chunk), timeout, DAQmxConstants.DAQmx_Val_GroupByChannel, self.data, int(self.data.size), byref(read), None)
#        self.data_all.extend(self.data.tolist())
        self.data_all = np.concatenate((self.data_all, self.data), axis=1)

        # Call the user callback function:
        if self.everyNSamplesCallback is not None:
            self.everyNSamplesCallback()

        print(time.clock() - self.time_start)
        return 0 # The function should return an integer

    def DoneCallback(self, status):
        print("Status: %s" % status)
        errBuff = create_string_buffer(2048)
#        DAQmxGetExtendedErrorInfo(errBuff,2048)
        print(DAQmxGetErrorString(status, errBuff, 2048))
        return 0 # The function should return an integer

task=CallbackTask(strDevice='Dev4', strChannelsList = ['ai0', 'ai1', 'ai2', 'ai3', 'ai4', 'ai5', 'ai6', 'ai7'])
#task=CallbackTask(strDevice='Dev4', strChannelsList = ['ai0'])
task.StartTask()

raw_input('Acquiring samples continuously. Press Enter to interrupt\n')

task.StopTask()
task.ClearTask()

print('Task complete')

# Display the data:
figure();
#subplot(2, 1, 1)
plot(task.data_all.transpose())
#plot(task.data_all.transpose())
#subplot(2, 1, 2)
#plot(np.linspace(0, task.fs, len(task.data_all)), 20*np.log10(np.abs(np.fft.fft(task.data_all))))


print("Please	 enter number of coins: ")
quarters = int(input("# of quarters: "))
dimes = int(input("# of dimes: "))
nickels = int(input("# of nickels: "))
pennies = int(input("# of pennies: "))
q = .25 * quarters
d = .10 * dimes
n = .05 * nickels
p = .01 * pennies
dollars = q + d + n + p
cents = (dollars%1)*100
print("The total is",int(dollars),"dollars and", int(cents),"cents")