# Add this for dumb relative imports
import sys
sys.path.append(".")

import importlib
from src import utils
from src.preprocessing import step2_feature_engineering as feature_eng
from src.evaluators import multiple_evaluator

from pyspark.rdd import RDD
from pyspark.sql import DataFrame, SparkSession, Row
from pyspark.sql.functions import udf,col,count,sum
from pyspark.sql.types import StructType, StructField, IntegerType, StringType, FloatType

import json
import copy as cp

from pyspark.ml import Pipeline
from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.evaluation import BinaryClassificationEvaluator

from numpy.linalg import norm
from numpy.lib.scimath import sqrt

def driver(takeSample=False):
    print("***\n\n\nStarting KNN")

    # Pre-process features
    data_df, features = feature_eng.preprocess_features2(takeSample=takeSample)

    # Assemble all features in a vector using Vector Assembler
    # map it to new column named features
    vector_assembler = VectorAssembler(inputCols=features, outputCol="features")

    data_df = vector_assembler.transform(data_df) # data_df => SK_ID_CURR, ..., .transform(vector_assembler) =>  "features": Vector<float>

    # Split the data into training and test sets (30% held out for testing)
    (trainingData, testData) = data_df.randomSplit([0.8, 0.2])

    # Cross Join train_vector and test_vector
    train_vector = trainingData.select("SK_ID_CURR","features", "TARGET").withColumnRenamed("SK_ID_CURR","train_SK_ID_CURR").withColumnRenamed("features","train_features")
    test_vector = testData.select("SK_ID_CURR","features").withColumnRenamed("SK_ID_CURR","test_SK_ID_CURR").withColumnRenamed("features","test_features")
    cross_join = test_vector.crossJoin(train_vector)
    cross_join.show(20)

    def distance(row):
        '''
        Euclidean Distance Function
        '''
        train_features = row['train_features']
        test_features = row['test_features']
        train_SK_ID_CURR = row['train_SK_ID_CURR']
        test_SK_ID_CURR = row['test_SK_ID_CURR']
        target = row['TARGET']

        # euclid distance
        s = 0
        for i in range(len(train_features)):
            s += (train_features[i]-test_features[i])**2
        distance = float(sqrt(s))

        row = Row(
            train_features=train_features,
            test_features=test_features,
            train_SK_ID_CURR=train_SK_ID_CURR,
            test_SK_ID_CURR=test_SK_ID_CURR,
            TARGET=target,
            distance=distance
        )
        return row

    # Convert to DF
    cross_join = cross_join.rdd.map(distance).toDF()
    cross_join.show()

    # Group by test_SK_ID_CURR
    grouped = cross_join.rdd.map(lambda x: (x.test_SK_ID_CURR, x)).groupByKey()

    def choose_k_and_predict(row):
        '''
        Choose the 5 smallest using heapq and return distances and prediction based on those
        '''
        k = 5
        print(row)
        import heapq
        closest_k = heapq.nsmallest(k, row[1], key=lambda ele: ele.distance)
        distances = []
        target_sum = 0
        for ele in closest_k:
            distances.append((ele.train_SK_ID_CURR, ele.TARGET, ele.distance))
            target_sum += ele.TARGET
        if target_sum/k < 0.5:
            prediction = 0
        else:
            prediction = 1
        return (row[0], prediction, row[1].TARGET, distances)

    # Choose k smallest and predict
    prediction_df = grouped.map(choose_k_and_predict).toDF().withColumnRenamed('_1', 'train_SK_ID_CURR').withColumnRenamed('_2', 'rawPrediction').withColumnRenamed('_3', "TARGET").withColumnRenamed('_4', 'features')
    prediction_df = prediction_df.withColumn('prediction', prediction_df['rawPrediction'])
    prediction_df.show(10)
    return multiple_evaluator(prediction_df)

if __name__ == '__main__':
    driver()


import sageresearch.shallowwater.shallow_water_linearized_moment_equations as swlme
import sageresearch.shallowwater.shallow_water_moment_equations as swme

def test_get_swlme_equations():
    for num_moments in range(5):
        tuple_ = swlme.get_swlme_equations(num_moments)
        f = tuple_[0]
        G = tuple_[1]
        A = tuple_[2]

        num_eqns = num_moments + 2
        assert len(f) == num_eqns
        assert G.nrows() == num_eqns
        assert G.ncols() == num_eqns
        assert A.nrows() == num_eqns
        assert A.ncols() == num_eqns

def test_swlme_equal_to_swme():
    # for 0 and 1 moments swlme should be equivalent to standard shallow water equations
    for num_moments in range(2):
        tuple_ = swlme.get_swlme_equations(num_moments)
        f_swlme = tuple_[0]
        G_swlme = tuple_[1]
        A_swlme = tuple_[2]

        tuple_ = swme.get_generalized_shallow_water_equations_1d(num_moments)
        f_swme = tuple_[0]
        G_swme = tuple_[1]
        A_swme = tuple_[2]

        assert f_swlme == f_swme
        assert G_swlme == G_swme
        assert A_swlme == A_swme


from django.core.management.base import BaseCommand
from bs4 import BeautifulSoup
import requests
from datetime import datetime
from situation_report_app.models import Article, Source

class Command(BaseCommand):

    def handle(self, *args, **options):

        # в бд добавляем новости
        domain = 'https://www.who.int'
        url = f'{domain}/emergencies/diseases/novel-coronavirus-2019/media-resources/news'
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'html.parser')

        first_tag = soup.find("div", class_="sf_colsIn col-md-10")
        info_tag = first_tag.find_all('div', class_="list-view--item")
        # print(f'{len(info_tag)} articles were found')
        print("------------------------------------------------------")
        articles_added = 0
        for each in info_tag:

            if not len(each.find('div', class_="info")) == 1:

                date1_tag = each.find('span', class_="timestamp")
                # print(f'date1_tag {date1_tag} {type(date1_tag)}')
                if date1_tag != None:
                    # print("обработка tag1")
                    date = str(date1_tag.get_text(strip=True))
                    new_date = datetime.strptime(date, '%d %B %Y').date()
                    # print(f'new_date {new_date}')
                else:
                    # print("ищем tag2")
                    date2_tag = each.find('p', class_="sub-title")
                    date_str = str(date2_tag)
                    # print(f'date_str {date_str}')
                    if date_str != 'None':
                        date2_tag = date2_tag.text
                        year = '2020'
                        position = date2_tag.find(year, 0)
                        if position != -1:
                            date2_tag = date2_tag[0:position + 4]
                            # print(date2_tag)
                        date = str(date2_tag)
                        new_date = datetime.strptime(date, '%d %B %Y').date()
                    else:
                        new_date = None
                print(f'{new_date}')
                title_tag = each.find('p', class_='heading text-underline').text
                print(title_tag)
                a_tag = str(each.find('a', href=True)['href'])
                if not Article.objects.filter(url=a_tag).exists():
                    source = 'World Health Organization (WHO)'
                    if not Source.objects.filter(name=source).exists():
                        Source.objects.create(name=source, url='www.who.int')
                    Article.objects.create(url=a_tag,
                                           date=new_date,
                                           name=title_tag,
                                           source=Source.objects.filter(name=source).first())
                    articles_added += 1
            print("------------------------------------------------------")

        total_articles = Article.objects.all()

        print(f'added {articles_added}')
        print(f'total number of articles = {len(total_articles)}')


import boto3, json

ec2 = boto3.client('ec2')

def getRegions():
    return  [region['RegionName'] for region in ec2.describe_regions()['Regions']]

def assess_all_instances():
    main_array = []
    for region in getRegions():
        ec2 = boto3.client('ec2',region_name=region)
        instances = ec2.describe_instances()
        for i in instances["Reservations"]:
           main_array.append({"region": region,"state":i['Instances'][0]['State'], "instance_id":i['Instances'][0]['InstanceId']})

    return {"data":main_array}

def lambda_handler(event,context):
    return {
            'statusCode': 200,
            'headers': {'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*' },
            'body': json.dumps(assess_all_instances()),
                "isBase64Encoded": False

        }


#!/usr/bin/env python3

def fun(x):
	print('x is', x)
	x = 10
	print('change x to', x)
	return x

def main():
	x = 24
	ret = fun(x)
	print('local x is', x)
	print('ret is', ret)

main()


import re
import gzip
import time
import uproot
import cloudpickle
import numpy as np
from optparse import OptionParser
from multiprocessing import Process

parser = OptionParser()
parser.add_option('-d', '--dataset', help='dataset', dest='dataset')
(options, args) = parser.parse_args()

start_time = time.time()

#path_name = '/home/furkan/work/tpc/'

binsize = 2000
output = {}
external = uproot.open(options.dataset + '.root')['opdigianaExternal']

def run(xar):

    result_array = np.array([])
    for key in external.allkeys():
        kanal = re.findall("_op(.*?)_waveform", format(key))[0]
        searchResult = re.search(xar, kanal, re.M | re.I)
        if searchResult:
            vector = external[key].values
            # print(vector)
            result_array = np.append(result_array, vector, axis=0)
            # print(xar, result_array.shape)
    eventDump = result_array.reshape(int(result_array.size / binsize), binsize)
    output.update({xar: eventDump})
    print(output)
    with gzip.open(options.dataset + '_' + xar + '.pkl.gz', 'wb') as fout:
        cloudpickle.dump(output, fout)
    return xar

if __name__ == '__main__':

    arapuca1 = ['channel_132', 'channel_133', 'channel_134',
                'channel_135', 'channel_136', 'channel_137',
                'channel_138', 'channel_139', 'channel_140',
                'channel_141', 'channel_142', 'channel_143',
                'channel_264', 'channel_265', 'channel_266',
                'channel_267', 'channel_268', 'channel_269',
                'channel_270', 'channel_271', 'channel_272',
                'channel_273', 'channel_274', 'channel_275', ]

    process = []

    for i in arapuca1:
        proc = Process(target=run, args=(i,))
        process.append(proc)
        proc.start()
    for p in process:
        p.join()

print("--- %.2f seconds ---" % (time.time() - start_time))


#! python3
# trent.py - This simple script uses the os.walk function to show
# folders, subfolders and filenames in a given directory.
# usage: write trent,py <directory>

import sys, os
if len(sys.argv) != 2:
    print ('Please enter the filepath when calling the script as described in the script documentation')
    exit()
dirPath = sys.argv[1]
isDir = os.path.isdir(dirPath)
if isDir == False:
    print ('Please enter an existing directory.')
    exit()
else:
    for folderName, subfolders, filenames in os.walk(dirPath):
        print('The folder is '+folderName)
        print('The subfolders in '+ folderName+" are "+str(subfolders))
        print('The filenames in '+ folderName+' are '+str(filenames))
        print()


import sys
import os
import string
import time
import re
import pandas as pd
import random

t = time.time()

### Make a logs folder if one doesn't exist.
if not os.path.isdir('logs'):
    print('Made a logs folder')
    os.mkdir('logs')

###print function and log function (writes to log/time_output_file if specified)
def log(x, t, print2screen=False, output_file =None):
    if print2screen: print(x)
    if output_file:
        with open("logs/"+str(t)+ "_" +output_file, 'a+') as ofile:
            ofile.write(x+'\n')

### Fill in template with random words from word bank
def fillin_template(template_file, word_table, story_num):
    file = open(template_file + str(story_num)+ ".txt", "r")
    var_dict = {}
    for line in file:
        keys = [str(s) for s in re.findall('\(([^)]+)', line)]
        new_line = line
        for k in keys:
            if k[-1] == '*':
                temp_k = k[:-1]
            else:
                temp_k = k
            col = word_table[temp_k]
            if re.search('[a-z]', temp_k):
                i = re.search('[a-z]', temp_k).start()
                if temp_k[:i] in var_dict:
                    index = var_dict[temp_k[:i]]
                    word = col.iloc[index]
            elif temp_k in var_dict:
                index = var_dict[temp_k]
                word = col.iloc[index]
            else:
                while True:
                    random_index = random.randint(0,len(col)-1)
                    word = col.iloc[random_index]
                    if pd.notna(word):
                        var_dict[temp_k] = random_index
                        break
            if temp_k != k:
                word = word.capitalize()
            new_line = new_line.replace("("+k+")", word)

        if new_line != "":
            log(new_line,t,print2screen=True,output_file=str(story_num))

    file.close()
    return

log("Welcome to Mad Libs!", t, print2screen=True)
log("Pick a story number: ", t, print2screen=True)
story_num = int(input())

log("You selected story #" + str(story_num) + ".",t,print2screen=True)

word_bank = pd.read_csv("word_bank_"+str(story_num)+".csv")

log(" ", t, print2screen=True)
log("Your story is: ", t, print2screen=True)
log(" ", t, print2screen=True)
fillin_template("story_template_", word_bank, story_num)


from django.shortcuts import render
from django.contrib.auth.decorators import login_required

from savings.models import Savings
from installment.models import LoanInstallment
from loan.models import Loan

# def login(request):
#     return render(request, 'login.html')

@login_required
def dashboard(request):

    sv = Savings.objects.all()
    ls = Loan.objects.all()

    total_savings_person = sv.count()
    total_loan_person = ls.count()

    total_savings_amount = 0
    for s in sv:
        total_savings_amount += int(s.amount)

    total_loan_amount = 0
    for l in ls:
        total_loan_amount += int(l.amount)

    loan_after_interest = total_loan_amount * 1.2

    total_loan_paid = 0

    for n in ls:
        i = LoanInstallment.objects.filter(name=n.id)
        amount = (int(n.amount) *1.2) / 12
        total_loan_paid += i.count() * int(amount)

    loan_due = loan_after_interest - total_loan_paid

    context = {
        'title': 'Dashboard',
        'total_savings': total_savings_person,
        'total_savings_amount': total_savings_amount,
        'total_loan_person': total_loan_person,
        'total_loan_amount': int(loan_due)
    }

    return render(request, 'dashboard.html', context)

@login_required
def profile(request):
    return render(request, 'profile.html')


from sys import stdin
from functools import cmp_to_key

# 17% 틀립니다

# 반례
# 2 2
# 34
# 344

# ans : 34434
# output : 34344
K, N = map(int, stdin.readline().split())

def sol():
    target = ""

    numbers = []

    for _ in range(K):
        numbers.append(stdin.readline().rstrip())

    # 자릿수가 긴것을 앞으로,자릿수가 같다면 크기가 큰 것
    # 자릿수가 길고 가장 큰것이 가장 많이 사용됨 N-K번
    # 나머지는 다 한번씩만 사용해줘야함
    key = str(max(list(map(int, numbers))))

    for _ in range(N - K):
        numbers.append(key)

    new_numbers = custom_sort(numbers)

    target = "".join(new_numbers)

    # for num in new_numbers:
    #   target+=num

    # if N!=K:
    #   target=target+key*(N-K)

    return int(target)

def custom_digit_compare(a, b):
    if int(str(a) + str(b)) > int(str(b) + str(a)):
        return 1
    else:
        return -1

# 수정필요
def custom_sort(list_):
    # tmp = []

    # max_len = 0

    # for item in list_:
    #   max_len = max(len(item), max_len)

    # for idx, num in enumerate(list_):
    #   diff = 0

    #   list_num = list(num)

    #   first_digit = int(list_num[0])

    #   # 가장 큰 자리수의 숫자로부터
    #   # 나머지 숫자들이 얼마나 떨어져있는지 기록
    #   # 작을수록 큰 값
    #   for i in range(1, len(list_num)):
    #     diff += first_digit - int(list_num[i])

    #   digit = int(num) % 10

    #   if len(num) < max_len:
    #     tmp.append((idx, num + str(digit) * (max_len - len(num)), diff))
    #   else:
    #     tmp.append((idx, num, diff))

    # # 일의 자리를 연장한 값을 먼저 비교하고
    # # 32  322 같이 연장한 값이 같다면
    # # 위에서 계산한 diff를 그다음 기준
    # tmp.sort(key=lambda x: (-int(x[1]), x[2]))
    # ret = []

    list_ = sorted(
        list_, key=cmp_to_key(lambda a, b: -1 if int(str(a) + str(b)) > int(str(b) + str(a)) else 1)
    )

    return list_

    # for idx, num, diff in tmp:
    #   ret.append(list_[idx])

    # return ret

print(sol())


# review_NaverMovie_CallbackEmbedding

import pandas as pd
import re
import numpy as np
import tensorflow as tf

def get_data(file_path):
    df = pd.read_csv(file_path, delimiter='\t', index_col=0)
    df = df.dropna()
    # df.info()

    x, y = [], []
    for row in zip(df.document.values, df.label.values):
        x.append(clean_str(row[0]))
        y.append(row[1])

    return np.array(x[:10000]), np.array(y[:10000])

# https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
def clean_str(string, TREC=False):
    """
    Tokenization/string cleaning for all datasets except for SST.
    Every dataset is lower cased except for TREC
    """
    string = re.sub(r"[^가-힣A-Za-z0-9(),!?\'\`]", " ", string)
    string = re.sub(r"\'s", " \'s", string)
    string = re.sub(r"\'ve", " \'ve", string)
    string = re.sub(r"n\'t", " n\'t", string)
    string = re.sub(r"\'re", " \'re", string)
    string = re.sub(r"\'d", " \'d", string)
    string = re.sub(r"\'ll", " \'ll", string)
    string = re.sub(r",", " , ", string)
    string = re.sub(r"!", " ! ", string)
    # string = re.sub(r",", " ", string)        # custom
    # string = re.sub(r"!", " ", string)
    string = re.sub(r"\(", " \( ", string)
    string = re.sub(r"\)", " \) ", string)
    string = re.sub(r"\?", " \? ", string)
    string = re.sub(r"\s{2,}", " ", string)

    return string.strip() if TREC else string.strip().lower()

class TrackEmbedding(tf.keras.callbacks.Callback):
    def __init__(self, layer):
        self.layer = layer

    def on_epoch_end(self, epoch, logs=None):
        print(epoch,
              self.layer.weights[0].shape, self.layer.embeddings.shape,
              self.layer.weights[0][0, 0], self.layer.embeddings[0, 0])

def review_model_embedding():
    x_train, y_train = get_data('data/naver_ratings_train.txt')
    x_test, y_test = get_data('data/naver_ratings_test.txt')

    y_train = np.reshape(y_train, newshape=[-1, 1])
    y_test = np.reshape(y_test, newshape=[-1, 1])

    vocab_size = 2000
    tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=vocab_size)
    tokenizer.fit_on_texts(x_train)

    x_train_sequence = tokenizer.texts_to_sequences(x_train)
    x_test_sequence = tokenizer.texts_to_sequences(x_test)

    seq_length = 20
    x_train_pad = tf.keras.preprocessing.sequence.pad_sequences(x_test_sequence, maxlen=seq_length)
    x_test_pad = tf.keras.preprocessing.sequence.pad_sequences(x_test_sequence, maxlen=seq_length)

    model = tf.keras.Sequential([
        tf.keras.layers.InputLayer(input_shape=[seq_length]),
        tf.keras.layers.Embedding(vocab_size, 100),
        tf.keras.layers.LSTM(30),
        tf.keras.layers.Dense(1, activation='sigmoid'),
    ])

    # model.summary()

    model.compile(optimizer=tf.keras.optimizers.Adam(0.001),
                  loss=tf.keras.losses.binary_crossentropy,
                  metrics=['acc'])

    tracker = TrackEmbedding(model.get_layer(name='embedding'))
    model.fit(x_train_pad, y_train, epochs=10, batch_size=128, verbose=0, callbacks=tracker)

review_model_embedding()


import requests
import re
from flask import current_app

class WebSpider:
    """网络爬虫"""
    def __init__(self, words):
        self.result = []
        self.words = words
        self.url = ''
        self.html = ''
        self.headersParameters = {    # 发送HTTP请求时的HEAD信息，用于伪装为浏览器
            'Connection': 'Keep-Alive',
            'Accept': 'text/html, application/xhtml+xml, */*',
            'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
            'Accept-Encoding': 'gzip, deflate',
            'User-Agent': 'Mozilla/6.1 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'
        }

    def get_baidu(self):
        self.url = 'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=monline_dg&wd={}'.format(self.words)
        response = requests.get(self.url, headers=self.headersParameters)
        if response.status_code is not 200:
            current_app.logger.info('爬虫请求链接响应的状态码不是200')
            return self.result
        else:
            self.html = response.text
            self.result = re.findall(r'''href = "(.*?)".*?>(.*?).*?style="text-decoration:none;">(.*?) ''',
                                     self.html, re.MULTILINE | re.DOTALL)
            return self.result


from logger import input_data, print_data, edit_data, delete_data, search_data

def print_menu():
    print('\nМеню:\n'
          '1. Добавить контакт\n'
          '2. Удалить контакт\n'
          '3. Редактировать контакт\n'
          '4. Вывести данные\n'
          '5. Поиск контакта\n'
          '6. Выход')

def interface():
    command = -1
    while command != 6:
        print_menu()
        command = int(input("Введите номер операции: "))

        while command < 1 or command > 6:
            print('Вы ошиблись при выборе.')
            command = int(input("Введите номер операции: "))

        if command == 1:
            input_data()
        elif command == 2:
            delete_data()
        elif command == 3:
            edit_data()
        elif command == 4:
            print_data()
        elif command == 5:
            search_data()
        elif command == 6:
            print("Всего доброго!")


import sys
import configparser
from distutils.util import strtobool
import json
import pandas as pd
import numpy as np
from tabulate import tabulate
import ray
import time

# read csv files containing production and curtailment data into a dataframe
def import_data(production, curtailment):

    production = pd.read_csv(production,
        names=['date','hour','interval','demand','solar','wind',
        'net_load','renewables','nuclear','large_hydro',
        'imports','generation','thermal','load_less'])

    curtailment = pd.read_csv(curtailment,
        names=['date','hour','interval','wind_curtailment','solar_curtailment'],
        index_col=[0,1,2])

    data = production.join(curtailment,
        on=['date', 'hour', 'interval'],
        how='left')

    data.fillna(0, inplace=True)

    data['wind'] += data['wind_curtailment']
    data['solar'] += data['solar_curtailment']

    #print(tabulate(data.head(20), headers='keys', tablefmt='psql'))

    return data

# read the provided JSON configuration file and generate all combinations of inputs
def import_config(config_file_name):

    with open(config_file_name, 'r') as config_file:
        config = json.load(config_file)

    data = import_data(config['data']['production'], config['data']['curtailment'])

    configs = pd.DataFrame(
        columns=['battery','initial_soc','min_soc','max_soc',
        'nuclear','solar','wind'])

    wind_same_as_solar = config['wind']['wind_same_as_solar']
    nuclear_samples = config['nuclear']['nuclear_samples']
    solar_samples = config['solar']['solar_samples']
    battery_samples = config['battery']['battery_samples']

    if wind_same_as_solar:
        wind_samples = 1
    else:
        wind_samples = config['wind']['wind_samples']

    configs['nuclear'] = np.repeat(
        np.linspace(
            config['nuclear']['nuclear_min'],
            config['nuclear']['nuclear_max'],
            nuclear_samples
        ),
        solar_samples * wind_samples * battery_samples
    )

    configs['solar'] = np.tile(
        np.repeat(
            np.linspace(
                config['solar']['solar_min'],
                config['solar']['solar_max'],
                solar_samples
            ),
            wind_samples * battery_samples
        ),
        nuclear_samples
    )

    if wind_same_as_solar:
        configs['wind'] = configs['solar']
    else:
        configs['wind'] = np.tile(
            np.repeat(
                np.linspace(
                    config['wind']['wind_min'],
                    config['wind']['wind_max'],
                    wind_samples
                ),
                battery_samples
            ),
            nuclear_samples * solar_samples
        )

    configs['battery'] = np.tile(
        np.linspace(
            config['battery']['battery_min'],
            config['battery']['battery_max'],
            battery_samples
        ),
        nuclear_samples * solar_samples * wind_samples
    )

    configs['min_soc'] = config['battery']['min_soc']
    configs['max_soc'] = config['battery']['max_soc']
    configs['initial_soc'] = config['battery']['initial_soc']
    configs['wind_same_as_solar'] = config['wind']['wind_same_as_solar']
    configs['export_intermediate'] = config['data']['export_intermediate']
    configs['time_factor'] = config['data']['time_factor']

    # print(tabulate(configs.head(20), headers='keys', tablefmt='psql'))

    config_list = configs.to_dict('records')

    return (config, config_list, data)

# simulate the sources of electricity on the grid at every data point
@ray.remote
def simulate(config, data):

    output = data.copy()

    # these operations can be done without loops
    output['solar'] *= config['solar']
    output['wind'] *= config['wind']
    output['nuclear'] = config['nuclear']
    output['clean'] = output['nuclear'] + output['solar'] + output['wind']
    output['net'] = output['clean'] - output['demand']

    current_value = config['battery'] * config['initial_soc']
    min_value = config['battery'] * config['min_soc']
    max_value = config['battery'] * config['max_soc']

    samples = len(output)
    stored = [0.0] * samples
    battery = [0.0] * samples
    gas = [0.0] * samples
    curtailed = [0.0] * samples
    soc = [0.0] * samples
    net = output['net'].array

    time_factor = config['time_factor']

    # a loop is required because the core simulation depends on the previous row
    for i in range(samples):
        temp = current_value + net[i] / time_factor

        if temp < min_value:
            stored[i] = min_value
            battery[i] = (current_value - min_value) * time_factor
            gas[i] = (min_value - current_value) * time_factor - net[i]
            curtailed[i] = 0.0
        elif temp > max_value:
            stored[i] = max_value
            battery[i] = (current_value - max_value) * time_factor
            gas[i] = 0.0
            curtailed[i] = net[i] - (max_value - current_value) * time_factor
        else:
            stored[i] = current_value + net[i] / time_factor
            battery[i] = -net[i]
            gas[i] = 0.0
            curtailed[i] = 0.0

        if config['battery'] != 0:
            soc[i] = stored[i] / config['battery']
        else:
            soc[i] = 0.0

        current_value = stored[i]

    # calculate totals
    output['gas'] = pd.Series(gas)
    output['curtailed'] = pd.Series(curtailed)
    output['stored'] = pd.Series(stored)
    output['battery'] = pd.Series(battery)
    output['soc'] = pd.Series(soc)

    total_demand = sum(output['demand']) / time_factor
    total_clean = sum(output['clean']) / time_factor
    total_gas = sum(output['gas']) / time_factor
    total_curtailed = sum(output['curtailed']) / time_factor

    if not config['export_intermediate']:
        output = None

    totals = {
        'clean': (1.0 - total_gas / total_demand) * 100,
        'curtailed': (total_curtailed / total_demand) * 100,
        'demand_value': total_demand,
        'clean_value': total_clean,
        'gas_value': total_gas,
        'curtailed_value': total_curtailed
    }

    # result = {
    #     'config': config,
    #     'output': output,
    #     'totals': totals
    # }

    # this dictionary will be used as a row in a new dataframe
    result_flat = config.copy()
    result_flat.update(totals)

    # print(json.dumps(result_flat))

    return result_flat

def generate_plot_data(config, result_list):

    results = pd.DataFrame(result_list)

    # determine how many constants there should be
    constants = 3
    if config['graph']['x2'] != 'none':
        constants -= 1
    if config['wind']['wind_same_as_solar']:
        constants -= 1

    # filter the data by the constants
    # this shouldn't do anything with a proper configuration
    if constants == 1:
        subset = results.groupby(
            results[config['graph']['c1']]
        ).get_group(
            config['graph']['v1']
        )
    elif constants == 2:
        subset = results.groupby(
            [results[config['graph']['c1']],results[config['graph']['c2']]]
        ).get_group(
            (config['graph']['v1'],config['graph']['v2'])
        )
    elif constants == 3:
        subset = results.groupby(
            [results[config['graph']['c1']],results[config['graph']['c2']],results[config['graph']['c3']]]
        ).get_group(
            (config['graph']['v1'],config['graph']['v2'],config['graph']['v3'])
        )

    # generate the plot data objects for plot.ly
    traces = []
    if config['graph']['x2'] == 'none':
        traces.append({
            'x': subset[config['graph']['x1']].tolist(),
            'y': subset[config['graph']['y']].tolist(),
            'type': 'scatter',
            'name': config['graph']['x1'],
        })
    else:
        for name, group in subset.groupby(config['graph']['x2']):
            traces.append({
                'x': group[config['graph']['x1']].tolist(),
                'y': group[config['graph']['y']].tolist(),
                'type': 'scatter',
                'name': config['graph']['x2'] + " = " + str(name),
            })

    # label the axes for plot.ly
    layout = {
        'title': config['graph']['y'] + " vs " + config['graph']['x1'],
        'xaxis': { 'title': config['graph']['x1'] },
        'yaxis': { 'title': config['graph']['y'] }
    }

    plot_data = {
        'traces': traces,
        'layout': layout
    }

    return plot_data

# runs the simulations specified in the config list on the ray cluster
def simulate_distributed(config_list, data):

    data_id = ray.put(data)

    result_ids = []
    for config in config_list:
        result_ids.append(simulate.remote(config, data_id))

    result_list = []
    for result_flat in ray.get(result_ids):
        result_list.append(result_flat)

    return result_list

if __name__ == '__main__':

    # run the simulation locally or on a ray cluster if specified
    argc = len(sys.argv)
    if argc == 5:
        ray.init(address=sys.argv[4])
    elif argc == 4:
        ray.init()
    else:
        print("Usage: python simulate.py <config> <output> <plot> [address]")
        sys.exit()

    print("Generating configs...", end='', flush=True)
    start = time.time()
    config, config_list, data = import_config(sys.argv[1])
    print("Done! ({:.2f}s)".format(time.time()-start))

    print("Running " + str(len(config_list)) + " simuations...", end='', flush=True)
    start = time.time()
    result_list = simulate_distributed(config_list, data)
    print("Done! ({:.2f}s)".format(time.time()-start))

    print("Generating plot data...", end='', flush=True)
    start = time.time()
    plot_data = generate_plot_data(config, result_list)
    print("Done! ({:.2f}s)".format(time.time()-start))

    print("Writing files...", end='', flush=True)
    start = time.time()
    with open(sys.argv[2], 'w') as output_file:
        json.dump(result_list, output_file, indent=4)
    with open(sys.argv[3], 'w') as output_file:
        json.dump(plot_data, output_file, indent=4)
    print("Done! ({:.2f}s)".format(time.time()-start))


def longestPalindrome(s: str) -> str:
    result = ""
    resultLength = 0

    for i in range(len(s)):
        l, r = i, i
        while l >= 0 and r < len(s) and s[l] == s[r]:
            if (r - l + 1) > resultLength:
                result = s[l:r+1]
                resultLength = r - l + 1
            l -= 1
            r += 1

        l, r = i, i + 1
        while l >= 0 and r < len(s) and s[l] == s[r]:
            if (r - l + 1) > resultLength:
                result = s[l:r+1]
                resultLength = r - l + 1
            l -= 1
            r += 1

    return result

print(longestPalindrome("babad"))
print(longestPalindrome("cbbd"))


#COMPARADOR V1
#Versión 1 del comparador que permite con un símbolo, precio y hace cuantas horas comprado, chequear las variaciones con
#respecto a las demás monedas

import config
from binance.client import Client
from binance.enums import *
from pandas.core.frame import DataFrame
import pandas as pd
import time
#import vlc
#import threading
#import math
#import csv
#import itertools
import datetime
from scipy import stats
import numpy as np
from colorama import init
from colorama import Fore, Back, Style

#que funcione con un ingreso de fecha especifica y moneda especifica o precio especifioco y moneda para calcular con respecto a todos de una vez

#-----------------------------------------------------------------------------------------------------------
#CONEXIÓN
#-----------------------------------------------------------------------------------------------------------

client = Client(config.API_KEY, config.API_SECRET, tld='com')

#-----------------------------------------------------------------------------------------------------------
#VARIABLES GLOBALES
#-----------------------------------------------------------------------------------------------------------

#Moneda base que será analizada, comparada y quizá cambiada
#moneda_base = 'ETHUSDT'

#Cantidad de horas atras cuando se compró la moneda base
#cantidad_horas_atras = 14

#precio base con el que se compró la moneda, para que sirva de referencia en la comparativa
precio_base = 2120.99

#Cantidad comprada de moneda base, se utilizará  para hacer la transacción con otra moneda
cantidad_moneda_base = 0.01541

#Lista de monedas a analizar
listacoin = ['BTCUSDT',
'ETHUSDT',
'MATICUSDT',
'ADAUSDT',
'BNBUSDT',
'XRPUSDT',
'DOTUSDT',
'ICPUSDT',
'SOLUSDT',
'SHIBUSDT',
'LINKUSDT',
'LTCUSDT',
'THETAUSDT',
'DOGEUSDT',
'VETUSDT',
'EOSUSDT',
'TRXUSDT',
'BCHUSDT',
'NEOUSDT',
'COMPUSDT',
'UNIUSDT'
]
#listacoin = ['BTCUSDT','ETHUSDT','MATICUSDT']

#-----------------------------------------------------------------------------------------------------------
#FUNCIONES
#-----------------------------------------------------------------------------------------------------------

#Esta función proporciona el precio de mercado actual
def precio_mercado_actual(simbolo):

    try:
        list_of_tickers = client.get_all_tickers()

        for tick_2 in list_of_tickers:
            if tick_2['symbol'] == simbolo:
                symbolPrice = float(tick_2['price'])
                return float(symbolPrice)
    except:
        return 'null'

#-----------------------------------------------------------------------------------------------------------
#MAIN
#-----------------------------------------------------------------------------------------------------------

print('---------------------------------------------')
print('COMPARADOR V1')
print('---------------------------------------------')

r_moneda= input('Por favor ingrese la MONEDA base que compró: ')

r_precio= input('Por favor ingrese el PRECIO con el que compró: ')

r_dias= input('Por favor ingrese HACE CUANTAS HORAS lo ha comprado: ')

print('************************************************')

if (r_moneda=='') and (r_precio==''):

    moneda_base = 'NONE'

else:

    moneda_base = str(r_moneda)
    precio_base = float(r_precio)

cantidad_horas_atras = int(r_dias)
#agrupa para convertir en df
agrupador2=[]
fecha_referencia= str(cantidad_horas_atras)+' hour ago UTC'

for coin in listacoin:

    agrupador = []

    #Si moneda es igual a la moneda base, toma el precio base y no lo jala como el resto para la comparativa
    if coin == moneda_base:
        precio_referencia = precio_base

    else:
        precio_referencia = float(client.get_historical_klines(coin, Client.KLINE_INTERVAL_1MINUTE, fecha_referencia )[0][2])

    #precio actual de mercado para el coin en curso
    precio_actual = precio_mercado_actual(coin)

    print('trabajando: ',coin)
    #print(coin)
    #print(precio_referencia)
    #print(precio_actual)
    porcentaje=round(((precio_actual-precio_referencia)/precio_referencia)*100,2)
    #print(porcentaje,'%')
    #print("-------------")

    agrupador.append(coin)
    agrupador.append(precio_referencia)
    agrupador.append(precio_actual)
    agrupador.append(porcentaje)

    agrupador2.append(agrupador)

dfr = pd.DataFrame(agrupador2, columns = ['Symbol', 'precio_inicial','precio_actual','variacion'])
dfr_sorted = dfr.sort_values(by=['variacion'],ascending=True)
print(dfr_sorted)

#Seleccionando la moneda elegida
moneda_destino = dfr_sorted.iloc[0,0]
#Seleccionando precio de la moneda elegida
precio_ref_moneda_destino = dfr_sorted.iloc[0,1]

#Si la moneda a cambiar es la misma no se realiza ninguna transacción transacciòn
if moneda_destino==moneda_base:
    print('No se realizará la transacciòn, porque se trata de la misma moneda')
    transaccion = 0

else:
    transaccion = 1

#-------------------------------------TRANSACCIÒN-------------------------------------------------------


from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import Ridge
from sklearn.feature_extraction import DictVectorizer
import pandas as pd
import re
from scipy.sparse import hstack

dataTrainRaw = pd.read_csv('salary-train.csv', nrows=50000)
dataTestRaw = pd.read_csv('salary-test-mini.csv')

def answer(list, name):
    f = open(name, 'w')
    space=''
    for i in list:
        f.write(space+str(i))
        space=' '

def modify_text(x):
    x = x.lower()
    x = re.sub('[^a-zA-Z0-9]', ' ', x)
    return x

def one_hot_encoding(df, DV, type):
    if type == 'train':
        DV = DictVectorizer()
        X_categ = DV.fit_transform(df.to_dict('records'))
        return X_categ, DV
    else:
        X_categ = DV.transform(df.to_dict('records'))
        return X_categ, DV

def prepare_data(data, vectorizer, DV, type):
    data_fd_list = data["FullDescription"].tolist()
    data_fd_list = list(map(modify_text, data_fd_list))
    if type == 'train':
        vectorizer = TfidfVectorizer(min_df=5)
        data_fd_vector = vectorizer.fit_transform(data_fd_list)
    else:
        data_fd_vector = vectorizer.transform(data_fd_list)
    data['LocationNormalized'].fillna('nan', inplace=True)
    data['ContractTime'].fillna('nan', inplace=True)
    X_categ, DV = one_hot_encoding(data[['LocationNormalized', 'ContractTime']], DV, type)
    X = hstack([data_fd_vector, X_categ])
    if type == 'train':
        return X, vectorizer, DV
    return X

X_train, vectorizer, DV = prepare_data(dataTrainRaw, None, None, 'train')
y_train = dataTrainRaw['SalaryNormalized']
X_test = prepare_data(dataTestRaw, vectorizer, DV, 'test')

Regression = Ridge(alpha=1, random_state=241)
Regression.fit(X_train, y_train)

P = Regression.predict(X_test)

print(P)
answer(P, "1")

Linear regression: salary forecast by job description/main.py


"""Urls of properties."""

# Views
from .views import PropertiesView

properties = PropertiesView()

def url_resolver(path: str, request_type: str, query_params: dict = None):
    """Return the url of the view.

    Args:
        path (str): The path of the view.
        request_type (str): The request type.
        query_params (dict, optional): The query parameters. Defaults to None.

    Returns:
        the status code and the data of the request.
    """
    if request_type == 'GET':
        paths = [
            ('/properties', properties.get(query_params)),
        ]
        if any(path in url for url in paths):
            return paths[0][1].status_code, paths[0][1].data
        else:
            return 404, 'URL not found'
    else:
        return 405, 'Method not allowed'


preco = float(input('Qual o valor das compras? R$'))
print('''
Qual a sua forma de pagamento:
[1] à vista dinheiro/pix
[2] à vista cartão
[3] 2x no cartão
[4] 3x ou mais no cartão
''')
opcao = int(input('Qual é a sua opção? '))

if opcao == 1:
    total = preco - (preco * 10 / 100)
    desconto = (preco * 10) / 100
    print(f'Sua compra de R${preco:.2f} saiu por R${total:.2f} seu desconto foi de R${desconto:.2f}!')
elif opcao == 2:
    total = preco - (preco * 5 / 100)
    desconto = (preco * 5) / 100
    print(f'Sua compra de R${preco:.2f} saiu por R${total:.2f} seu desconto foi de R${desconto:.2f}!')
elif opcao == 3:
    total = preco
    parcela = total / 2
    print(f'Sua parcerla será de 2x de R${parcela}')
    print(f'Sua compra de R${preco:.2f} saiu por R${total:.2f}!')
elif opcao == 4:
    total = preco + (preco * 20 / 100)
    juros = (preco * 20) / 100
    totalpar = int(input('Deseja dividir em 3 ou mais vezes, quantas parcelas serão? '))
    parcela = total / totalpar
    print(f'A compra de R${preco} parcelada de {totalpar} saira por R${total} \n Com parcelas de R${parcela} o acrescimo de  juros de foi R${juros}')
else:
    print('Opção invalida, tente novamente!')


# from https://github.com/dparks1134/UniteM/blob/master/unitem/markers.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import logging
from collections import defaultdict

from checkm.defaultValues import DefaultValues
from checkm.markerSets import MarkerSetParser, BinMarkerSets

from unitem_defaults import *

"""
CHECKM_BAC_MS = 'bacteria.ms'
CHECKM_AR_MS = 'archaea.ms'
"""

class Markers():
    """Read marker information."""

    def __init__(self):
        """Initialization."""

        self.logger = logging.getLogger('timestamp')

        parser = MarkerSetParser()
        bin_marker_sets = parser.parseTaxonomicMarkerSetFile(CHECKM_BAC_MS)
        self.bac_ms = bin_marker_sets.mostSpecificMarkerSet()

        bin_marker_sets = parser.parseTaxonomicMarkerSetFile(CHECKM_AR_MS)
        self.ar_ms = bin_marker_sets.mostSpecificMarkerSet()

        self.bac_markers_on_contigs = None
        self.ar_markers_on_contigs = None

    # update for metabinner
    def read_table(self, marker_gene_table):
        """Read table indicating marker genes for each bin."""

        markers = defaultdict(lambda: defaultdict(list))
        if not os.path.exists(marker_gene_table):
            # did not identify any markers
            return markers

        with open(marker_gene_table) as f:
            f.readline()

            for line in f:
                line_split = line.strip().split('\t')

                # bin_id = line_split[0]
                marker_id = line_split[1]
                gene_id = line_split[2]
                if '&&' in gene_id:
                    # indicates a marker gene is identified
                    # in adjacent genes and is likely an
                    # assembly or gene calling error
                    gene_ids = gene_id.split('&&')
                    gene_id = gene_ids[0]
                scaffold_id = gene_id[0:gene_id.rfind('_')]

                if marker_id not in markers:
                    markers[marker_id] = [scaffold_id]
                else:
                    markers[marker_id].append(scaffold_id)

        return markers

    def evaluate_bac(self, gene_table, individual_markers=False):
        """Evaluate completeness and contamination of genome using bacterial marker sets."""

        comp, cont = self.bac_ms.genomeCheck(gene_table, individual_markers)
        return comp, cont

    def evaluate_ar(self, gene_table, individual_markers=False):
        """Evaluate completeness and contamination of genome using archaeal marker sets."""

        comp, cont = self.ar_ms.genomeCheck(gene_table, individual_markers)
        return comp, cont

    def evaluate(self, bac_gene_table, ar_gene_table):
        """Evaluate completeness and contamination of genome using best domain-level marker sets."""

        bac_comp, bac_cont = self.evaluate_bac(bac_gene_table, True)
        ar_comp, ar_cont = self.evaluate_ar(ar_gene_table, True)

        if bac_comp + bac_cont > ar_comp + ar_cont:
            # select domain set with the larget number of identified markers
            # including those present multiple times
            bac_comp, bac_cont = self.evaluate_bac(bac_gene_table, False)
            return 'Bacteria', bac_comp, bac_cont

        ar_comp, ar_cont = self.evaluate_ar(ar_gene_table, False)
        return 'Archaea', ar_comp, ar_cont

    def bin_quality(self, bin):
        """Estimate quality of bin."""

        # create gene tables for bin
        bac_gene_table = defaultdict(list)
        ar_gene_table = defaultdict(list)
        for cid in bin:
            for marker_id in self.bac_markers_on_contigs[cid]:
                bac_gene_table[marker_id].append(cid)

            for marker_id in self.ar_markers_on_contigs[cid]:
                ar_gene_table[marker_id].append(cid)

        domain, comp, cont = self.evaluate(bac_gene_table,
                                           ar_gene_table)

        return domain, comp, cont

    # changed for metabinner
    def marker_gene_tables(self, bac_mg_table, ar_mg_table):
        """Get marker genes for bins across all binning methods."""

        markers = Markers()
        # binning_methods_dir = os.path.join(profile_dir, BINNING_METHOD_DIR)

        # bac_mg_table = os.path.join(binning_methods_dir, bm, CHECKM_BAC_DIR, MARKER_GENE_TABLE)
        # bac_mg_table ='/home1/wangzy/binning_data/sim40_20/output/metabinner_res/unitem/my_profile/binning_methods/X_cov_notrans1/checkm_bac/marker_gene_table.tsv'
        bac_gene_tables = markers.read_table(bac_mg_table)

        # ar_mg_table = os.path.join(binning_methods_dir, bm, CHECKM_AR_DIR, MARKER_GENE_TABLE)
        # ar_mg_table ='/home1/wangzy/binning_data/sim40_20/output/metabinner_res/unitem/my_profile/binning_methods/X_cov_notrans1/checkm_ar/marker_gene_table.tsv'
        ar_gene_tables = markers.read_table(ar_mg_table)

        gene_tables = (bac_gene_tables, ar_gene_tables)

        self._markers_on_contigs(gene_tables)

        return gene_tables

    # update for metabinner
    def _markers_on_contigs(self, gene_tables):
        """Get markers on each contig."""

        self.bac_markers_on_contigs = defaultdict(list)
        self.ar_markers_on_contigs = defaultdict(list)
        processed_contigs = set()
        (bac_gene_tables, ar_gene_tables) = gene_tables
        scaffolds_in_binning_method = set()
        for marker_id, scaffold_ids in bac_gene_tables.items():
            for scaffold_id in scaffold_ids:
                if scaffold_id in processed_contigs:
                    continue
                self.bac_markers_on_contigs[scaffold_id].append(marker_id)
            scaffolds_in_binning_method.update(scaffold_ids)

        for marker_id, scaffold_ids in ar_gene_tables.items():
            for scaffold_id in scaffold_ids:
                if scaffold_id in processed_contigs:
                    continue
                self.ar_markers_on_contigs[scaffold_id].append(marker_id)
            scaffolds_in_binning_method.update(scaffold_ids)

        processed_contigs.update(scaffolds_in_binning_method)

    def create_gene_table(self, contig_ids):
        """Create gene tables for a set of contigs."""

        bac_table = defaultdict(list)
        ar_table = defaultdict(list)
        for cid in contig_ids:
            for mid in self.bac_markers_on_contigs[cid]:
                bac_table[mid].append(cid)

            for mid in self.ar_markers_on_contigs[cid]:
                ar_table[mid].append(cid)

        return bac_table, ar_table


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

from odoo import api, fields, models, _

class SaleOrder(models.Model):
    _inherit = "sale.order"
    _description = 'Sale Order'

    customer_comment = fields.Text('Customer Order Comment',default="No comment")

    @api.multi
    def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, **kwargs):
        values = super(SaleOrder, self)._cart_update(product_id, line_id, add_qty, set_qty, **kwargs)
        try:
            if self:
                self._check_carrier_quotation()
        except Exception as e:
            return values
        return values

    @api.multi
    def action_quotation_send(self):
        """
        @desc: if order is done and any transaction is also done then only send the mail.
        @args: None
        @return: Base super method.
        """
        if self.state in ['sale', 'done'] and (self.transaction_ids.filtered(lambda r: r.state in ['done']) or (self.coupon_applied and not self.amount_total)):
            return super(SaleOrder, self).action_quotation_send()
        else:
            return False


from __future__ import unicode_literals, absolute_import

import json
import unittest
import shutil
import sys
import tempfile
import time
import os

import pygit2
from mock import patch

sys.path.insert(
    0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
)

import pagure.lib.query
import tests

from pagure.config import config as pagure_config, reload_config

class PagureFlaskDumpLoadTicketTests(tests.Modeltests):
    """Tests for flask application for dumping and re-loading the JSON of
    a ticket.
    """

    @patch("pagure.lib.notify.send_email")
    @patch("pagure.lib.git._maybe_wait")
    def test_dumping_reloading_ticket(self, mw, send_email):
        """Test dumping a ticket into a JSON blob."""
        mw.side_effect = lambda result: result.get()
        send_email.return_value = True

        tests.create_projects(self.session)

        # Create repo
        self.gitrepo = os.path.join(self.path, "repos", "tickets", "test.git")
        repopath = os.path.join(self.path, "repos", "tickets")
        os.makedirs(self.gitrepo)
        repo_obj = pygit2.init_repository(self.gitrepo, bare=True)

        repo = pagure.lib.query.get_authorized_project(self.session, "test")
        # Create an issue to play with
        msg = pagure.lib.query.new_issue(
            session=self.session,
            repo=repo,
            title="Test issue",
            content="We should work on this",
            user="pingou",
        )
        self.assertEqual(msg.title, "Test issue")

        # Need another two issue to test the dependencie chain
        msg = pagure.lib.query.new_issue(
            session=self.session,
            repo=repo,
            title="Test issue #2",
            content="Another bug",
            user="pingou",
        )
        self.assertEqual(msg.title, "Test issue #2")
        msg = pagure.lib.query.new_issue(
            session=self.session,
            repo=repo,
            title="Test issue #3",
            content="That would be nice feature no?",
            user="foo",
        )
        self.assertEqual(msg.title, "Test issue #3")

        issue = pagure.lib.query.search_issues(self.session, repo, issueid=1)
        issue2 = pagure.lib.query.search_issues(self.session, repo, issueid=2)
        issue3 = pagure.lib.query.search_issues(self.session, repo, issueid=3)

        # Add a couple of comment on the ticket
        msg = pagure.lib.query.add_issue_comment(
            session=self.session,
            issue=issue,
            comment="Hey look a comment!",
            user="foo",
        )
        self.session.commit()
        self.assertEqual(msg, "Comment added")
        msg = pagure.lib.query.add_issue_comment(
            session=self.session,
            issue=issue,
            comment="crazy right?",
            user="pingou",
        )
        self.session.commit()
        self.assertEqual(msg, "Comment added")
        # Assign the ticket to someone
        msg = pagure.lib.query.add_issue_assignee(
            session=self.session, issue=issue, assignee="pingou", user="pingou"
        )
        self.session.commit()
        self.assertEqual(msg, "Issue assigned to pingou")
        # Add a couple of tags on the ticket
        msg = pagure.lib.query.add_tag_obj(
            session=self.session,
            obj=issue,
            tags=[" feature ", "future "],
            user="pingou",
        )
        self.session.commit()
        self.assertEqual(msg, "Issue tagged with: feature, future")
        # Add dependencies
        msg = pagure.lib.query.add_issue_dependency(
            session=self.session,
            issue=issue,
            issue_blocked=issue2,
            user="pingou",
        )
        self.session.commit()
        self.assertEqual(msg, "Issue marked as depending on: #2")
        msg = pagure.lib.query.add_issue_dependency(
            session=self.session, issue=issue3, issue_blocked=issue, user="foo"
        )
        self.session.commit()
        self.assertEqual(msg, "Issue marked as depending on: #1")

        # Dump the JSON
        pagure.lib.git.update_git(issue, repo).wait()
        repo = pygit2.Repository(self.gitrepo)
        cnt = len(
            [
                commit
                for commit in repo.walk(
                    repo.head.target, pygit2.GIT_SORT_TOPOLOGICAL
                )
            ]
        )
        self.assertIn(cnt, (9, 10, 11))

        last_commit = repo.revparse_single("HEAD")
        patch = pagure.lib.git.commit_to_patch(repo, last_commit)
        for line in patch.split("\n"):
            if line.startswith("--- a/"):
                fileid = line.split("--- a/")[1]
                break

        newpath = tempfile.mkdtemp(prefix="pagure-dump-load")
        clone_repo = pygit2.clone_repository(self.gitrepo, newpath)

        self.assertEqual(len(os.listdir(newpath)), 4)

        ticket_json = os.path.join(self.path, "test_ticket.json")
        self.assertFalse(os.path.exists(ticket_json))
        shutil.copyfile(os.path.join(newpath, fileid), ticket_json)
        self.assertTrue(os.path.exists(ticket_json))
        jsondata = None
        with open(ticket_json) as stream:
            jsondata = json.load(stream)
        self.assertNotEqual(jsondata, None)

        shutil.rmtree(newpath)

        # Test reloading the JSON

        # Re-create the DB from scratch
        self.session.rollback()
        self._clear_database()
        self.db_session.close()
        del self.session
        del self.db_session

        os.unlink(os.path.join(self.dbfolder, "db.sqlite"))

        self.db_session = pagure.lib.model.create_tables(
            self.dbpath,
            acls=pagure_config.get("ACLS", {}),
        )
        self._prepare_db()
        tests.create_projects(self.session)

        # Create repo
        self.gitrepo = os.path.join(self.path, "tickets", "test.git")
        repopath = os.path.join(self.path, "tickets")
        os.makedirs(self.gitrepo)
        pygit2.init_repository(self.gitrepo, bare=True)

        pagure.lib.git.update_ticket_from_git(
            self.session,
            reponame="test",
            namespace=None,
            username=None,
            issue_uid="foobar",
            json_data=jsondata,
            agent="pingou",
        )

        # Post loading
        repo = pagure.lib.query.get_authorized_project(self.session, "test")
        self.assertEqual(len(repo.issues), 1)
        issue = pagure.lib.query.search_issues(self.session, repo, issueid=1)

        # Check after re-loading
        self.assertEqual(len(issue.comments), 3)
        self.assertEqual(len(issue.tags), 2)
        self.assertEqual(
            sorted(issue.tags_text), sorted(["future", "feature"])
        )
        self.assertEqual(issue.assignee.username, "pingou")
        self.assertEqual(issue.children, [])
        self.assertEqual(issue.parents, [])
        self.assertEqual(issue.status, "Open")

if __name__ == "__main__":
    unittest.main(verbosity=2)


from multiprocessing import Process, Queue
from random import randint
from typing import Union
import pygame
import time
import os

def update_queue(q: Queue, msg: Union[str, bool]) -> None:
    """Put a new message in the multiprocessing queue for main process.

    Will check if the queue is full. If it is it will empty it first.

    Args:
        q (Queue):              The queue to put the new message in.
        msg (Union[str, bool]): The message to put in the queue.
    """

    if q.full():
        q.get()

    q.put(msg)

def lower_song_volume(mixer: pygame.mixer, cutoff_value: float = 0.05,
                      cutoff_speed: float = 0.2) -> None:
    """Lower the volume of the song rather than a sharp cutoff.

    Args:
        mixer (pygame.mixer):           To pygame mixer used to lower the
                                        volume.
        cutoff_value (float, optional): The value used to decrease the volume
                                        after each loop. Defaults to 0.05.
        cutoff_speed (float, optional): The speed used to decrease the volume.
                                        Defaults to 0.2.
    """

    volume_value = 1

    while volume_value > 0:

        volume_value -= cutoff_value
        mixer.music.set_volume(volume_value)
        time.sleep(cutoff_speed)

def song_process(rx_queue: Queue, song_name_queue: Queue,
                 play_state_queue: Queue, song_name: str, loop: bool,
                 timer_length: int, random: bool) -> None:
    """Main process for the audio player.

    Play songs and take care of the various settings set by the user such as
    loop, random, timer cutoff, etc. By default it will play each song in the
    Songs/ directory in order.

    Args:
        rx_queue (Queue):         Queue used by the main process to update
                                  settings of the audio player.
        song_name_queue (Queue):  Queue used by the audio player process to
                                  tell the main process which song is currently
                                  playing.
        play_state_queue (Queue): Queue used by the audio player process to
                                  tell the main process if it stopped playing.
        song_name (str):          The name of the song to play selected by the
                                  user in the web browser.
        loop (bool):              Used to loop or not over all the songs.
        timer_length (int):       Used to cutoff the audio player after a
                                  certain amount of time.
        random (bool):            Used to play songs in a random order or not.
    """

    terminate = False  # Stop the audio player.
    timer_count = 0  # Used to keep track of the time spent playing songs.
    sleep_time = 0.1  # Sleep value inside the loop when the player is playing.
    songs_played = 0  # Used only when random = True.
    new_song = None  # The new song to play.
    user_stop = False

    songs = sorted(os.listdir('Songs/'))  # Sorted songs in 'Songs/'.
    songs_len = len(songs) - 1

    # Initialise Pygame mixer, store it and load the specified song.
    pygame.mixer.init()
    mixer = pygame.mixer
    mixer.music.load('Songs/' + song_name)

    # If rx_queue is not empty we make sure to clear it before.
    while not rx_queue.empty():
        rx_queue.get()

    # Main player loop.
    while True and not terminate:

        # We update the current song name and play it.
        update_queue(song_name_queue, song_name)
        mixer.music.play()

        # Loop while the music is playing. We check if settings have been
        # changed, or if we should stop playing (user stop or cutoff timer).
        while mixer.music.get_busy():

            if not rx_queue.empty():

                dict = rx_queue.get()
                loop = dict.get('loop', loop)
                random = dict.get('random', random)
                timer_length = dict.get('timer', timer_length)
                terminate = dict.get('terminate', terminate)

                if terminate:
                    user_stop = True
                    lower_song_volume(mixer, 0.15, 0.1)
                    break

            time.sleep(sleep_time)
            timer_count += 1

            if timer_length and (timer_count * sleep_time) == timer_length:
                lower_song_volume(mixer)
                terminate = True
                break

        if terminate:
            break

        # If random not selected we play the song in order.
        elif not random:

            for i, song in enumerate(songs):
                if song == song_name and i < songs_len:
                    new_song = songs[i + 1]
                    mixer.music.load('Songs/' + new_song)
                    song_name = new_song
                    break
                elif i == songs_len and loop:
                    new_song = songs[0]
                    mixer.music.load('Songs/' + new_song)
                    song_name = new_song
                    break
                elif i == songs_len and not loop:
                    terminate = True
                    break

        # If random selected we choose random songs
        # (but not the same twice in a row).
        elif random:

            # If loop is not selected we terminate the player when we have
            # played all songs.
            if not loop and songs_played == songs_len:
                break

            if songs_len > 0:
                while True:
                    new_song = songs[randint(0, songs_len)]
                    if new_song != song_name:
                        break
            else:
                new_song = songs[randint(0, songs_len)]

            mixer.music.load('Songs/' + new_song)
            song_name = new_song

            if not loop:
                # Used to keep track of how many song we have played
                songs_played += 1

    # We tell the main process the audio player has stopped.
    if not user_stop:
        update_queue(play_state_queue, False)
        update_queue(song_name_queue, 'Nothing.')

class Player:
    """Class used to control the audio player process.

    Spawn the process playing songs and sending it settings set by the user in
    AirJukeBox's web page.
    """

    def __init__(self) -> None:

        self.process = None
        self.tx_queue = Queue()
        self.song_name_queue = Queue(maxsize=1)
        self.play_state_queue = Queue(maxsize=1)

    def play_song(self, song_name: str, loop: bool, timer_time: str,
                  istimer: bool, random: bool) -> None:
        """Spawn the audio player process

        It will first check if the audio player process is alive, if yes, it
        will send a command to terminate it.

        Args:
            song_name (str):  Song to play selected by the user.
            loop (bool):      If the loop setting is activated or not.
            timer_time (str): The time used by the cutoff timer.
            istimer (bool):   If the timer setting is activated or not.
            random (bool):    If the random setting is activated or not.
        """

        if self.process and self.process.is_alive():
            self.tx_queue.put({"terminate": True})

        # If timer is activated or timer time setting is 0 we don't activate
        # the timer. Else we convert the time value from minutes to seconds.
        if not istimer or int(timer_time) == 0:
            timer_time = None
        else:
            timer_time *= 60

        self.process = Process(target=song_process,
                               args=(self.tx_queue, self.song_name_queue,
                                     self.play_state_queue, song_name, loop,
                                     timer_time, random))

        self.process.start()

    def stop_song(self) -> None:
        """Send a terminate command to the audio player process by putting it
        in the tx queue.
        """

        if self.process and self.process.is_alive():
            self.tx_queue.put({"terminate": True})

    def change_loop(self, loop: bool) -> None:
        """Update the loop setting in the audio player process by sending it
        the new value in the tx queue.

        Args:
            loop (bool): If the loop setting is activated or not.
        """

        if self.process and self.process.is_alive():
            self.tx_queue.put({"loop": loop})

    def change_random(self, random: bool) -> None:
        """Update the random setting in the audio player process by sending it
        the new value in the tx queue.

        Args:
            random (bool): If the random setting is activated or not.
        """

        if self.process and self.process.is_alive():
            self.tx_queue.put({"random": random})

    def change_timer(self, istimer: bool, timer_time: str) -> None:
        """Update the timer setting in the audio player process by sending it
        the new value in the tx queue.

        Args:
            istimer (bool):   If the timer setting is activated or not.
            timer_time (str): The time selected for the timer cutoff.
        """

        if self.process and self.process.is_alive():
            if istimer and int(timer_time) > 0:
                self.tx_queue.put({"timer": int(timer_time) * 60})
            elif not istimer or int(timer_time) == 0:
                self.tx_queue.put({"timer": None})


import pickle
import pandas as pd
from tqdm import tqdm
import re
# >>> with open('parrot.pkl', 'rb') as f:
# ...   mynewlist = pickle.load(f)

def get_aka_from_ids(aka_list_all, ncbi_ref_list):
    aka = ''
    isval = True

    for ncbi_ref in ncbi_ref_list:
        if isval == False:
            continue
        if aka_list_all[ncbi_ref] == '':
            isval = False
        if aka == '':
            aka = aka_list_all[ncbi_ref]
        elif aka_list_all[ncbi_ref] != aka:
            isval = False

    if isval == False:
        aka = ''

    return aka

# mapping between orignal_data and lnc2rna_data
mapping = [
    "1Colorectal.xlsx",
    "2Ovarian.xlsx",
    "3Pancreatic.xlsx",
    "4Cervical.xlsx",
    "5Gastric.xlsx",
    "6Head and neck.xlsx",
    "7Lung.xlsx",
    "8Liver.xlsx",
    "9Prostate.xlsx",
]

for sheet in mapping:
    print(sheet)
    sheet_num = int(sheet[0])
    with open(f'excel_{sheet_num}_aka_list_all.pkl', 'rb') as f:
        aka_list_all = pickle.load(f)

    database = pd.read_excel(f"../data/lnc2rna_filled_data/{sheet}",sheet_name="Validated & Reviewed GQ LncRNAs")
    new = pd.DataFrame(columns=database.columns)

    filled = 0
    filled_empty = 0
    for i, row in tqdm(database.iterrows()):
        flag = 1
        if pd.isnull(row).all():
            continue

        if pd.isnull(row["NCBI Reference Number"]):
            flag = 0
        elif not pd.isnull(row["Remarks"]):
            flag = 0

        if flag:
            ncbi_ref_list = re.findall(r'NR_\d*.\d*', row['NCBI Reference Number'])
            aka = get_aka_from_ids(aka_list_all, ncbi_ref_list)
            row['Remarks'] = f'Also Known As: {aka}'
            filled += 1
            if aka == '':
                filled_empty += 1
            # else:
            #     print(f'Change at row {i}\n{row}')

        new = new.append(row)

    print(f'Total filled: {filled}\nTotal filled empty: {filled_empty}')
    new.to_excel(f"{sheet.split('.')[0]}_remarks.xlsx",sheet_name='Validated & Reviewed GQ LncRNAs',header=1,index=False)
# final_df = pd.DataFrame([ncbi_ref_list_all]).T
# final_df[1] = aka_final
# print(final_df)
# final_df.to_csv(f'excel_{SHEET}.csv', index=False, header=False)
# # print(aka_final)
# print(f'Total entries: {len(aka_final)}\nTotal empty strings: {count, count1+count2}\nEmpty strings of second kind: {count2}')


import threading
from time import sleep

def sum_and_product(a, b):
    sleep(.2)
    s, p = a + b, a * b
    print(f'{a}+{b}={s}, {a}*{b}={p}')

def status(t):
    if t.is_alive():
        print(f'Thread {t.name} is alive.')
    else:
        print(f'Thread {t.name} has terminated.')

def print_current():
    print('The current thread is {}.'.format(
        threading.currentThread()
    ))
    print('Threads: {}'.format(list(threading.enumerate())))

print_current()
t = threading.Thread(
    target=sum_and_product, name='SumProd', args=(3, 7)
)

t.start()
status(t)
t.join()
status(t)


from gpiozero import LED
from time import sleep
import random
import threading
import sys
import pygame
pygame.mixer.init()
pygame.mixer.music.load("SugarPlum.wav")
pygame.mixer.music.play()

bpm= 121
bps = 121*1.0/60/8

relays= [ LED(4),LED(17) ,LED(27),LED(22) ,
         LED(12),LED(16) ,LED(20),LED(21) ]
prev_x= 0
prev_y= 0
x = 0
def relayLed():
  threading.Timer(bps,relayLed).start()
  [l.off() for l in relays]

  x = random.randint(0,7)
  y = random.randint(0,7)
  while y == x and (x == prev_x or y == prev_y) :
    x = random.randint(0,7)
    y = random.randint(0,7)
  prev_x = x
  prev_y = y
  relays[x].on()
  relays[y].on()

relayLed()
while pygame.mixer.music.get_busy() == True:
    continue
sys.exit()


import ast
import os
from re import A
import time
from modulos import *
def resgistro():
        resgistro_produtos["nome"] = str(input("Nome do produto: "))
        quantidade_estoque = str(input("Quantidade em estoque: "))
        while not quantidade_estoque.isdigit():
            quantidade_estoque = str(input("Quantidade em estoque: "))
        qe1 = int(quantidade_estoque)
        resgistro_produtos["Qnt.estoque"] = qe1
        custo_produto = str(input("Preço de custo: "))
        while not custo_produto.isdigit():
            custo_produto = str(input("Preço de custo: "))
        cp1 = int(custo_produto)
        resgistro_produtos["custo"] = cp1
        preço_venda = str(input("Preço de venda: "))
        while not preço_venda.isdigit():
            preço_venda = str(input("Preço de venda: "))
        ve1 = int(preço_venda)
        resgistro_produtos["venda"] = ve1
        produtos_reg.append(resgistro_produtos.copy())
        return produtos_reg[0]
produtos_reg = list()
resgistro_produtos = dict()
tot_valor_custo = 0
tot_valor_venda = 0
pro = ""
while True:
    op = menu()
    while not op.isdigit():
        op=menu()
    opc = int(op)
    if opc == 0:
        for t in range(3, 0, -1):
            print("\033[1;95m")
            print(f"Saindo do programa até a proxima... {t}")
            time.sleep(1)
        os.system('cls')
        print("\033[1;97m")
        break
    if opc == 1:
        print("\033[1;95m","                  Acessando opção de cadastro...")
        time.sleep(1)
        os.system('cls')
        while True:
            cad = selecao()
            while cad == 1:
                os.system('cls')
                teste = resgistro()
                arquivo = open("cadastro.txt", "a")
                arquivo.write(f'{teste}\n')
                produtos_reg.clear()
                arquivo.close()
                cad = selecao()
            if cad == 2:
                os.system('cls')
                break
    if opc == 2:
        print("\033[1;95m","                  Acessando opção de alteração...")
        time.sleep(1)
        os.system('cls')
        alr = selecao()
        while True:
            while alr  == 1:
                os.system('cls')
                print("=========================== PRODUTOS CADASTRADOS ===========================")
                arquivo = open('cadastro.txt')
                conteudo = arquivo.readlines()
                cont = 0
                for linha in conteudo:
                    linha = linha.replace("{","")
                    linha = linha.replace("}","")
                    print(f"[{cont}] {linha}")
                    cont += 1
                arquivo.close()
                print("=============================================================================")
                num_produto = int(input("Numero do produto: "))
                prod_selec = conteudo[num_produto].strip()
                print(f"Você selecionou: {prod_selec}")
                reg_produto = resgistro()
                troca_produto = str(reg_produto)
                arquivo = open("cadastro.txt", "r")
                substituir = ""
                for linha in arquivo:
                    linha = linha.strip()
                    alteração = linha.replace(prod_selec, troca_produto)
                    substituir = substituir + alteração + "\n"
                produtos_reg.clear()
                arquivo.close()
                arquivo = open("cadastro.txt", "w")
                arquivo.write(substituir)
                arquivo.close()
                print("Alteração concluida...")
                alr = selecao()
            if alr == 2:
                os.system('cls')
                break
    if opc == 3:
        os.system('cls')
        print("\033[1;95m","                  Acessando opção de exclusão...")
        time.sleep(1)
        exc =  selecao()
        if exc == 1:
            os.system('cls')
            print("=========================== PRODUTOS CADASTRADOS ===========================")
            arquivo = open('cadastro.txt')
            conteudo0 = arquivo.readlines()
            cont = 0
            for linha in conteudo0:
                linha = linha.replace("{","")
                linha = linha.replace("}","")
                print(f"[{cont}] {linha}")
                cont += 1
            arquivo.close()
            print("=============================================================================")
            numero_excluir = int(input("Selecione o numero do produto que deseja excluir do sistema: "))
            excluir_selecionado = conteudo0[numero_excluir].strip()
            arquivo = open("cadastro.txt", "r")
            substituir = ""
            for linha in arquivo:
                linha = linha.strip()
                if linha != excluir_selecionado:
                    substituir = substituir + linha + "\n"
                aux = substituir.strip()
            arquivo.close()
            for t in range(3,-1,-1):
                print:tempo(f"Exclusão concluida em...{t}")
            arquivo = open("cadastro.txt", "w")
            arquivo.write(aux)
            arquivo.close()
            os.system('cls')
    if opc == 4:
        print("\033[1;95m","                  Acessando opção de venda...")
        time.sleep(1)
        os.system('cls')
        ven = selecao()
        if ven == 1:
            os.system('cls')
            print("=========================== PRODUTOS CADASTRADOS ===========================")
            arquivo = open('cadastro.txt')
            conteudo2 = arquivo.readlines()
            cont = 0
            for linha in conteudo2:
                linha = linha.replace("{","")
                linha = linha.replace("}","")
                print(f"[{cont}] {linha}")
                cont += 1
            arquivo.close()
            print("=============================================================================")
            numero_produto = int(input("Selecione o produto vendido: "))
            qnt_vendido = int(input("Quantidade vendida: "))
            produto_nome = conteudo2[numero_produto].strip()
            produto_alterado1 = produto_nome
            dicionario_produto = ast.literal_eval(str(produto_alterado1))
            if dicionario_produto["Qnt.estoque"] <= 0:
                print("Por favor selecione outro produto o atual se esgotou!")
                time.sleep(3)
                break
            dicionario_produto["Qnt.estoque"] -= qnt_vendido
            volta_str = str(dicionario_produto)
            del dicionario_produto["nome"]
            del dicionario_produto["Qnt.estoque"]
            del dicionario_produto["custo"]
            del dicionario_produto["venda"]
            print(dicionario_produto)
            arquivo = open("cadastro.txt", "r")
            substituir = ""
            for linha in arquivo:
                linha = linha.strip()
                alteração = linha.replace(produto_nome, volta_str)
                substituir = substituir + alteração + "\n"
            arquivo.close()
            arquivo = open("cadastro.txt", "w")
            arquivo.write(substituir)
            arquivo.close()
            print("Operação concluida...")
            os.system('cls')
    if opc == 5:
        print("\033[1;95m","                  Acessando opção de compra...")
        time.sleep(1)
        os.system('cls')
        com = selecao()
        if com == 1:
            os.system('cls')
            print("=========================== PRODUTOS CADASTRADOS ===========================")
            arquivo = open('cadastro.txt')
            conteudo3 = arquivo.readlines()
            cont = 0
            for linha in conteudo3:
                linha = linha.replace("{","")
                linha = linha.replace("}","")
                print(f"[{cont}] {linha}")
                cont += 1
            arquivo.close()
            print("=============================================================================")
            numero_produto2 = int(input("Selecione o produto comprado: "))
            qnt_comprada = int(input("Quantidade comprada: "))
            produto_nome2 = conteudo3[numero_produto2].strip()
            produto_alterado1 = produto_nome2
            dicionario_produto2 = ast.literal_eval(str(produto_alterado1))
            dicionario_produto2["Qnt.estoque"] += qnt_comprada
            volta_str2 = str(dicionario_produto2)
            del dicionario_produto2["nome"]
            del dicionario_produto2["Qnt.estoque"]
            del dicionario_produto2["custo"]
            del dicionario_produto2["venda"]
            arquivo = open("cadastro.txt", "r")
            substituir = ""
            for linha in arquivo:
                linha = linha.strip()
                alteração = linha.replace(produto_nome2, volta_str2)
                substituir = substituir + alteração + "\n"
            arquivo.close()
            arquivo = open("cadastro.txt", "w")
            arquivo.write(substituir)
            arquivo.close()
            print("Operação concluida...")
            os.system('cls')
    if opc == 6:
        print("\033[1;95m","                  Acessando opção de estoque...")
        time.sleep(1)
        os.system('cls')
        es = selecao()
        if es == 1:
            estq = int(es)
            arquivo = open("cadastro.txt")
            conteudo4 = arquivo.readlines()
            lista_estoque = ""
            lista_estoque = list()
            for linha in conteudo4:
                lista_estoque.append(linha.strip())
            lista_aux = list()
            arquivo.close()
            for k, v in enumerate(lista_estoque):
                mult = 0
                valor = 0
                lista_aux.append(lista_estoque[k])
                estoque_aux = lista_aux[0]
                lista_aux.pop(0)
                estoque_aux2 = str(estoque_aux)
                dicionario_estoque = ast.literal_eval(str(estoque_aux2))
                mult = dicionario_estoque["Qnt.estoque"]
                valor = dicionario_estoque["custo"]
                tot_valor_custo += mult * valor
                del dicionario_estoque
            print(f"Valor total de preço de custo dos produtos em estoque: R$ {tot_valor_custo}")
            for k, v in enumerate(lista_estoque):
                mult = 0
                valor = 0
                lista_aux.append(lista_estoque[k])
                estoque_aux = lista_aux[0]
                lista_aux.pop(0)
                estoque_aux2 = str(estoque_aux)
                dicionario_estoque = ast.literal_eval(str(estoque_aux2))
                mult = dicionario_estoque["Qnt.estoque"]
                valor = dicionario_estoque["venda"]
                tot_valor_venda += mult * valor
                del dicionario_estoque
            print(f"Valor total de preço de venda dos produtos em estoque: R$ {tot_valor_venda}")
            consul_especifica = input("Deseja colsultar um produto especifico? [S/N] ")
            os.system('cls')
            if consul_especifica in "Ss":
                mult1 = 0
                custo1 = 0
                venda1 = 0
                arquivo = open("cadastro.txt")
                conteudo5 = arquivo.readlines()
                lista_estoque = ""
                lista_estoque = list()
                cont = 0
                for linha in conteudo5:
                    linha = linha.replace("{","")
                    linha = linha.replace("}","")
                    print(f"[{cont}] {linha}")
                    cont += 1
                lista_aux = list()
                arquivo.close()
                numero_produto4 = int(input("Selecione o numero produto que deseja consultar: "))
                produto_nome4 = conteudo5[numero_produto4].strip()
                estoque_alterado = produto_nome4
                dicionario_estoque3 = ast.literal_eval(str(estoque_alterado))
                mult1 = dicionario_estoque3["Qnt.estoque"]
                custo1 = dicionario_estoque3["custo"]
                venda1 = dicionario_estoque3["venda"]
                tot_valor_venda_especifica = mult1 * venda1
                tot_valor_custo_especifica = mult1 * custo1
                print(f'O valor de custo total do produto "{dicionario_estoque3["nome"]}" em estoque é: R$ {tot_valor_custo_especifica}')
                print(f'O valor de venda total do produto "{dicionario_estoque3["nome"]}" em estoque é: R$ {tot_valor_venda_especifica}')


# Introduction to Computation and Programming Using Python (2021)
# Chapter 2, Finger Exercise 4
"""
Write a program that asks the user to input 10
integers, and then prints the largest odd number that was entered. If
no odd number was entered, it should print a message to that effect.
"""

counter = 0
numbers = []
while counter < 10:
    new_number = int(input(f"Please enter an integer. {10-counter} remaining. ")) # no input checking
    if new_number%2 != 0:
        numbers.append(new_number)
    counter += 1
print(max(numbers) if len(numbers) > 0 else "No odd number was entered.")


from math import exp

def sig(x):
    return 1 / (1 + exp(-x))

class LR:
    def __init__(self, noOfClasses=0, labels=[]):
        self.__intercept = [0.0 for _ in range(noOfClasses)]
        self.__w = [[] for _ in range(noOfClasses)]
        self.__classesNr = noOfClasses # solutiile posibile
        self.__labels = labels

    @property
    def coefficients(self):
        return self.__w

    @property
    def intercept(self):
        return self.__intercept

    def fit(self, inputs, outputs, learning_rate=0.001, number_of_epochs=150):
        for ind in range(self.__classesNr):
            label_class = self.__labels[ind]

            out_class = [1 if outputs[i] == label_class else 0 for i in range(len(outputs))]

            self.__w[ind] = [0.0 for _ in range(len(inputs[0]) + 1)]

            # ne folosim de SGD pentru calcularea si identificarea coeficientilor
            for _ in range(number_of_epochs):
                new_coefficients = self.__w[ind]

                for i in range(len(inputs)):

                    error = sig(self.eval(inputs[i], self.__w[ind])) - out_class[i]

                    for j in range(len(inputs[0])):
                        # formula curs
                        new_coefficients[j + 1] = self.__w[ind][j + 1] - learning_rate * error * inputs[i][j]

                    new_coefficients[0] = self.__w[ind][0] - learning_rate * error

                self.__w[ind] = new_coefficients

            #update coef
            self.__intercept[ind] = self.__w[ind][0]
            self.__w[ind] = self.__w[ind][1:]

    def eval(self, xi, coef):
        #evaluation
        yi = coef[0]
        for j in range(len(xi)):
            yi += coef[j + 1] * xi[j]
        return yi

    #
    # def predictOneSample(self, sampleFeatures):
    #     threshold = 0.5
    #     coefficients = [self.__intercept] + [c for c in self.coef_]
    #     computedFloatValue = self.eval(sampleFeatures, coefficients)
    #     computed01Value = sigmoid(computedFloatValue)
    #     computedLabel = 0 if computed01Value < threshold else 1
    #     return computedLabel

    def predict(self, data):
        #predicting data
        out = []
        for i in range(len(data)):
            rez = []

            for clasa in range(self.__classesNr):
                eval = self.eval(data[i], [self.__intercept[clasa]] + self.__w[clasa])
                rez.append([sig(eval)])

            # output e format din pozitia labelurilor cu valorile cele mai mari
            out.append(self.__labels[rez.index(max(rez))])

        return out


class ContactList(list):
    def search(self, name):
        matching_contacts = []
        for contact in self:
            if name in contact.name:
                matching_contacts.append(contact)
        return matching_contacts

class Contact:
    all_contacts = []

    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.all_contacts.append(self)

c1 = Contact("John A", "JJA.net")
c2 = Contact("John B", "JJB.net")
c3 = Contact("Jean A", "JeC.net")
print(
# [contact.name for contact in Contact.all_contacts.search('John')]
[contact.name for contact in Contact.all_contacts if 'John' in contact.name]
)

a = 1
print(
    dir(a)
)


import itertools
import scipy
#import stanza
#from spacy_stanza import StanzaLanguage
import spacy
from sentence_transformers import SentenceTransformer
from typing import Dict, Tuple, List
import lib.utils.spacy_utils as spacy_utils

from lib.nlp.qa_bert.run_bert_qa import RunBertQA

class NLPFunc:
    def __init__(self, disable=False):
        self.disable = disable
        self.sbert = None
        self.qa = None
        self.spacy = None
        # self.sbert = SBERT()
        # self.qa = QA()
        # self.spacy = SPACY()
        # print("nlp init finished")

    def get_spacy(self):
        if self.spacy is None:
            self.spacy = SPACY()
        return self.spacy

    def get_sbert(self):
        if self.sbert is None:
            self.sbert = SBERT()
        return self.sbert

    def run_sbert(self, texts, keywords):
        if self.disable:
            return
        if self.sbert is None:
            self.sbert = SBERT()
        return self.sbert.run(texts, keywords)

    # NOTE: Assumption: there will be only one question
    def run_qa_on_doc(self, contexts: [str], question: str, max_k=5) -> Dict:
        if self.disable:
            return
        if self.qa is None:
            self.qa = QA()
        results = {question: []}
        for context in contexts:
            res = self.qa.run(context, question, max_k)

            results[question].extend(res[question])

        return results

    def run_qa_on_sec_batch(self, contexts: List[str], question: str, max_k=5) -> Dict:
        if self.disable:
            return
        if self.qa is None:
            self.qa = QA()
        return self.qa.run_batch(contexts, question, max_k=max_k)

    def run_qa_on_sec(self, context: str, question: str, max_k=5) -> Dict:
        if self.disable:
            return
        if self.qa is None:
            self.qa = QA()
        return self.qa.run(context, question, max_k)

    def run_qa_on_json(self, contexts: List[str], question: str, max_k=5) -> Dict:
        if self.disable:
            return
        if self.qa is None:
            self.qa = QA()
        return self.qa.obtain_all_node_results(contexts, question, max_k)

    def spacy_init(self, text: str):
        if self.disable:
            return
        if self.spacy is None:
            self.spacy = SPACY()
        # print('spacy_init', text)
        return self.spacy.model(text)

    def run_entity(self, text, label):
        if self.disable:
            return
        raise NotImplementedError

class SBERT:
    # bert-large-nli-max-tokens
    def __init__(self, model_name="bert-large-nli-max-tokens"):
        self.model = SentenceTransformer(model_name)

    def run(self, sentences, refs):
        # TODO: need to cache
        sentence_embeddings = self.model.encode(sentences)
        refs_embedding = self.model.encode(refs)

        # scipy.spatial.distance.cdist(
        #     XA -> ma, XB -> mb, metric='euclidean', *args, **kwargs)
        distances = scipy.spatial.distance.cdist(
            refs_embedding, sentence_embeddings, "cosine")

        # convert distances to
        # {"cand_str":[("ref_str_1", score_1), ("ref_str_2", score_2))], ..}
        return_dict = {}
        for (cand_idx, cand_str), (ref_idx, ref_str) in \
                itertools.product(enumerate(sentences), enumerate(refs)):
            entry = return_dict.get(cand_str)

            score = 1 - distances[ref_idx, cand_idx] if distances[ref_idx, cand_idx] > 0.01 else 1.0

            if entry is None:
                return_dict[cand_str] = [
                    (ref_str, score)]
            else:
                entry.append((ref_str, score))

        # print(return_dict)
        return return_dict

class QA:
    def __init__(self):
        self.qa = RunBertQA()

    def obtain_all_node_results(self, contexts: List[str], question: str, max_k):

        sections_results, results = self.qa.predict_from_input_squad(contexts, question, "0", get_mapping=True)

        # assume there are only one conext
        sections_result = list(sections_results.values())[0]
        return sections_result

    def run_batch(self, contexts: List[str], question: str, max_k):
        """

        :param contexts:
        :param question:
        :param max_k:
        :return: {title: {question: prediction, dt: dt}}
        """

        res = {}
        _, results = self.qa.predict_from_input_squad(contexts, question, "0")

        for title, result in results:
            (context, qas_all) = result[0]  # only one paragraph

            curr_res = {}
            for (q, a, t, dt, _) in qas_all:
                filtered_a = []
                count = 0
                for curr_a in a:
                    if count >= max_k:
                        break
                    if curr_a["text"] == "" or curr_a['text'] == 'empty':
                        continue
                    else:
                        filtered_a.append(curr_a)
                        count += 1
                # print("run answer:", a)
                curr_res[q] = filtered_a
                curr_res['dt'] = dt
            res[title] = curr_res

        return res

    def run(self, context: str, question: str, max_k):

        # self.qa.args.n_best_size = k

        curr_res = {}
        section_results, results = self.qa.predict_from_input_squad([context], question, "0")
        _, result = \
            results[0]
        # print("result:", result)
        (text, qas_all) = result[0]

        # print(qas_all)
        for (q, a, t, dt, _) in qas_all:
            filtered_a = []
            count = 0
            for curr_a in a:
                if count >= max_k:
                    break
                if curr_a["text"] == "" or curr_a['text'] == 'empty':
                    continue
                else:
                    filtered_a.append(curr_a)
                    count += 1
            # print("run answer:", a)
            curr_res[q] = filtered_a
            curr_res['dt'] = dt

        return curr_res

class SPACY:
    def __init__(self):
        # a mix of the stanza and spacy model
        #snlp = stanza.Pipeline(lang="en", processors='tokenize, ner')
        #self.model = StanzaLanguage(snlp)
        #sentencizer = self.model.create_pipe("sentencizer")
        #self.model.add_pipe(sentencizer)
        #spacy_model = spacy.load("en_core_web_md")
        #self.model.vocab = spacy_model.vocab
        #self.model.remove_pipe("tokenizer")
        #self.model.add_pipe(spacy_model.get_pipe("tokenizer"))
       # self.model.remove_pipe("tagger")
        #self.model.add_pipe(spacy_model.get_pipe("tagger"))
        #self.model.add_pipe(spacy_model.get_pipe("parser"))
        #self.model.add_pipe(spacy_model.get_pipe("sentencizer"))
        self.model = spacy.load("en_core_web_md")
        spacy_utils.nlp_add_pipe(self.model, "merge_subtokens")

    def entity(self, text, label):
        raise NotImplementedError


import tensorflow as tf

# constants ####################################################################
a = tf.constant(5.0)
b = tf.constant(6.0)

c = a * b

sess = tf.Session()

file_written = tf.summary.FileWriter('C:\\repos\\neureal-prototype-testing\\notes\\tensorflow-tutorial\\graph', sess.graph)
print(sess.run(c))

sess.close()

# cmd: tensorboard --logdir="TensorFlow"

# placeholders #################################################################

a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)

adder_node = a + b

with tf.Session() as sess:
    output = sess.run( adder_node, {a : [1,3],
                                    b : [2,4]} )
    print(output)

# variables ####################################################################

# create model ##

# model parameters
W = tf.Variable([.3], tf.float32)       # if  W = -1
b = tf.Variable([-.3], tf.float32)      # and b =  1 then immediately converge.

# inputs and outputs
x = tf.placeholder(tf.float32)

# output values
y = tf.placeholder(tf.float32)
linear_model = W * x + b

# calculate loss, update variables.
squared_deltas= tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)

# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    #print(sess.run( loss, { x:[1,2,3,4], y:[0,-1,-2,-3] } )

    # train
    for i in range(1000):
        sess.run(train, {   x:[1,2,3,4],
                            y:[0,-1,-2,-3] } )
        output = sess.run([W,b])
        print(output)