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

import os
import shutil

# récupération des bases de données
from tensorflow.examples.tutorials.mnist import input_data
fashionMnist = input_data.read_data_sets('./FM_DATA/', one_hot=True)

import tensorflow as tf
with tf.name_scope('X'):
  # entrées
  x = tf.placeholder(tf.float32, [None, 784], name = "X")

with tf.name_scope('Y_True'):
  # sorties voulues
  y_ = tf.placeholder(tf.float32, [None, 10], name = "Y_True")

# Le modèle
with tf.name_scope("Weights"):
  W = tf.Variable(tf.zeros([784, 10]),name ="W")

with tf.name_scope("Biases"):
  b = tf.Variable(tf.zeros([10]), name = "b")

with tf.name_scope("score"):
 score = tf.matmul(x, W) + b

with tf.name_scope("Classe"):
    classe = tf.argmax(score,1, name="classe")

# calcul de l'entropie croisée
# Cross entropy version 1 (un peu instable)
with tf.name_scope('softmax'):
  softmax = y = tf.nn.softmax(score)
with tf.name_scope('cross_entropy'):
  cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

# Cross entropy version 2
#with tf.name_scope('cross_entropy'):
#  cross_entropy = tf.reduce_mean(
#      tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=score))

# Calcul de la prédiction finale
with tf.name_scope('Accuracy'):
  correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name="accuracy")

# Choix d'une méthode de minimisation
with tf.name_scope('train'):
  train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess = tf.Session()

# Configuration de TensorBoard
# If the model_dir exists, we delete it.
# to avoid accidental multiple trainings.
visuPath = './VisuMonoCouche'
if os.path.exists(visuPath):
  shutil.rmtree(visuPath)
os.makedirs(visuPath)

writer = tf.summary.FileWriter(visuPath, sess.graph)
tf.summary.scalar('Entropie Croisee', cross_entropy)
tf.summary.scalar('Precision', accuracy)

#tf.summary.scalar('W', W)
merged = tf.summary.merge_all()

init = tf.global_variables_initializer();
sess.run(init);

for i in range(1000):
  batch_xs, batch_ys = fashionMnist.train.next_batch(1000)
  summary, _ = sess.run([merged,train_step], feed_dict={x: batch_xs, y_: batch_ys})
  #print("Resultats en Apprentissage", sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys}))

  writer.add_summary(summary, i)

#Create a saver object which will save all the variables
saver = tf.train.Saver()

# sauvegarde en fin d'apprentissage
savePath = 'SavedNetworks/'
modelName = 'myMonoCouchemodel.ckpt'
if os.path.exists(savePath):
  shutil.rmtree(savePath)
os.makedirs(savePath)

savePathFull = os.path.join(savePath, modelName)

saver.save(sess, savePathFull)

print("Resultats en Apprentissage", sess.run(accuracy, feed_dict={x: fashionMnist.train.images, y_: fashionMnist.train.labels}))
print("Résultats en Généralisation", sess.run(accuracy, feed_dict={x: fashionMnist.test.images, y_: fashionMnist.test.labels}))


import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import cv2
import pyautogui
import msvcrt

listener=sr.Recognizer()
engine=pyttsx3.init()
voices=engine.getProperty('voices')
engine.setProperty('voice',voices[1].id)
def talk(text):
    engine.say(text)
    engine.runAndWait()

def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            voice=listener.listen(source)
            command = listener.recognize_google(voice)
            command=command.lower()
            if 'meera' in command:
                command=command.replace('meera','')

    except:
        pass
    return command
def run_alexa():
    global t
    command=take_command()
    t=0
    print(command)
    if 'i love you' in command:
        talk('i am glad to hear that')
        t=1
    if 'hello' in command:
        talk('hello, how can i help you')
        t=1
    if 'your name' in command:
        talk('my name is meera 1.0')
        t=1
    if 'aapka naam' in command:
        talk('mera naam meera hai')
        t=1
    if 'how are you' in command:
        talk('i am doing great')
        t=1
    if 'play' in command:
        song=command.replace('play','')
        talk('playing'+song)
        pywhatkit.playonyt(song)
        t=1
    if 'time' in command:
        time=datetime.datetime.now().strftime('%I:%M %p')
        talk('current time is'+time)
        print(time)
        t=1
    if 'date' in command:
        date=datetime.datetime.now().strftime('%d %B')
        talk('the date is'+date)
        t=1
    if 'day' in command:
        day=datetime.datetime.now().strftime('%A')
        talk('today is '+day)
        t=1
    if 'find about' in command:
        ques=command.replace('find about','')
        info=wikipedia.summary(ques,1)
        talk(info)
        t=1
    if 'meaning' in command:
        mean=command.replace('meaning','')
        info=wikipedia.summary(mean,1)
        talk(info)
        t=1
    if 'your father' in command:
        talk('My father is Mayank Verma')
        t=1
    if 'you single' in command:
        talk('no, i am commited to my work')
        t=1
    if 'search' in command:
        talk('searching on google')
        sea=command.replace('search','')
        pywhatkit.search(sea)
        t=1
    if 'gmail' in command:
        talk('opening mail')
        pywhatkit.search('gmail')
        t=1
    #if 'temperature' in command:
    if 'joke' in command:
        talk(pyjokes.get_joke())
        t=1
    if 'bye'in command:
        talk('see you soon')
        t=2
    if 'no' in command:
        talk('ok good bye')
        t=2
    if 'thank you' in command:
        talk('happy to serve you, any other help?')
        t=1

    if t==0:
        talk('i am not trained that much to do that task')
        talk('i will tell mayank to programme me for your task')
        talk('say other command')

run_alexa()
while t!=2:
    run_alexa()


''' Company similarity

'''
import collections
import csv

from scipy.sparse import lil_matrix
from scipy.stats import pearsonr
import numpy

def read_named_data():
    with open('../input/us_companies.csv') as f:
        reader = csv.reader(f)
        NameData = collections.namedtuple('NameData', next(reader))
        for datum in map(NameData._make, reader):
            yield datum

STOP_WORDS = set(['a',
                  'all',
                  'an',
                  'and',
                  'are',
                  'as',
                  'at',
                  'be',
                  'by',
                  'can',
                  'for',
                  'from',
                  'has',
                  'in',
                  'is',
                  'it',
                  'of',
                  'on',
                  'or',
                  'our',
                  'that',
                  'their',
                  'to',
                  'that',
                  'the',
                  'there'
                  'this',
                  'you',
                  'your',
                  'you\'re',
                  'we',
                  'with'])

def whitespace_tokenizer(blob, stop_words=STOP_WORDS):
    return [t.lower() for t in blob.split() if t.lower() not in stop_words]

def parse_token_frequency(blob,
                          tokenizer=whitespace_tokenizer,
                          counter=None):
    tokens = tokenizer(blob)
    if counter:
        counter.update(tokens)
    else:
        counter = collections.Counter(tokens)
    return counter

def gather_lexicon():
    data = read_named_data()
    all_tokens = set()
    for datum in data:
        tokens = whitespace_tokenizer(datum.description)
        all_tokens.update(tokens)
    return sorted(all_tokens)

def write_lexicon():
    lexicon = gather_lexicon()
    with open('../input/lexicon', 'wb') as f:
        for word in lexicon:
            f.write(word.encode('utf-8'))
            f.write(b'\n')

def read_lexicon():
    with open('../input/lexicon', 'rb') as f:
        data = [word.strip().decode('utf-8') for word in f]
    lexicon = collections.OrderedDict()
    for position, word in enumerate(data):
        lexicon[word] = position
    return lexicon

class BlobToVector(object):
    def __init__(self, lexicon=None):
        if lexicon is None:
            lexicon = read_lexicon()
        self.lexicon = lexicon
        self.columns = len(lexicon)

    def make_vector(self, blob):
        token_frequency = parse_token_frequency(blob)
        shape = (1, self.columns)
        vector = lil_matrix(shape)
        for token, frequency in token_frequency.items():
            try:
                position = self.lexicon[token]
            except KeyError:
                continue
            vector[0, position] = frequency
        l = self.lexicon
        return vector

def similarity(v1, v2):
    coefficient, p_value = pearsonr(v1, v2)
    return coefficient


from classes.HashTable import HashTable
from classes.CountMinSketch import CountMinSketch
from timeit import default_timer as timer

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import re

def insertCMS(num_hash, buckets, filepath):
    """
    Helper function that inputs every word from a file into a CMS and times
    how long the insertion takes.

    :param num_hash: The number of hash functions to use.
    :param buckets: The number of buckets to initialize the CMS with.
    :param filepath: The path to file that we want counted.
    :return: A tuple in the form of (CMS, time)
    """
    file = open(filepath, "r")
    start = timer()

    cms = CountMinSketch(num_hash, buckets)

    for line in file:
        for word in line.split():
            word = re.sub(r'[^\w\s]', '', word)
            cms.insert(word)

    end = timer()
    file.close()
    time = end - start
    return cms, time

def insertHT(filepath):
    """
    Helper function that inputs every word from a file into a Hash Table
    and times how long the insertion takes.

    :param filepath: The path to file that we want counted.
    :return: A tuple in the form of (HT, time)
    """
    file = open(filepath, "r")
    start = timer()

    ht = HashTable()

    for line in file:
        for word in line.split():
            word = re.sub(r'[^\w\s]', '', word)
            try:
                ht.insert(word, ht.find(word) + 1)
                continue
            except KeyError:
                ht.insert(word, 1)

    end = timer()
    file.close()
    time = end - start
    return ht, time

def searchCMS(cms, word):
    """
    A helper function that returns the frequency of a word within a CMS
    and how long the CMS took to search for it.

    :param cms: Count-Min Sketch to search in.
    :word: A word that we want to search for.
    :return: A tuple in the form of (Frequency, Time)
    """
    start = timer()
    count = cms.count(word)
    end = timer()
    time = end - start
    return count, time

def searchHT(ht, word):
    """
    A helper function that returns the frequency of a word within a Hash Table
    and how long the Hash Table took to search for it.

    :param ht: Hash Table to search in.
    :word: A word that we want to search for.
    :return: A tuple in the form of (Frequency, Time)
    """
    start = timer()
    count = ht.find(word)
    end = timer()
    time = end - start
    return count, time

def autolabel(rects):
    """
    This function was taken from matplotlib.org
    """
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

if __name__ == '__main__':
    # Open all the files (sorted from smallest to largest)
    cse = "cse312.txt"
    alice = "aliceinwonderland.txt"
    moby = "mobydick.txt"
    monte = "countofmontecristo.txt"
    war = "warandpeace.txt"
    filenames = [cse, alice, moby, monte, war]
    filewordcounts = [170, 29455, 215133, 462169, 565450]

    ntrials = 3

    # HT vs CMS Insertion & Search
    fig1, (iplot, splot) = plt.subplots(2,1)
    actual_counts = []
    estimate_counts = []
    unique_counts = []
    for i in range(ntrials):
        ht_init_times = []
        cms_init_times = []
        ht_search_times = []
        cms_search_times = []
        actual_counts_sub = []
        estimate_counts_sub = []
        unique_counts_sub = []
        for filename in filenames:
            filepath = "text/" + filename
            # insertion time
            cms, cms_time = insertCMS(5, 272, filepath)
            ht, ht_time = insertHT(filepath)

            cms_init_times.append(cms_time)
            ht_init_times.append(ht_time)

            # search time
            cms_count, cms_search_time = searchCMS(cms, "the")
            ht_count, ht_search_time = searchHT(ht, "the")

            cms_search_times.append(cms_search_time)
            ht_search_times.append(ht_search_time)

            # print("{} has {} distinct words".format(filename, ht.size()))
            # print("     (HT) actual count \"the\": {}".format(ht_count))
            # print("     (CMS) estimated count \"the\": {}".format(cms_count))
            actual_counts_sub.append(ht_count)
            estimate_counts_sub.append(cms_count)
            unique_counts_sub.append([ht.size(), ht.size(), 272 * 5])

        iplot.plot(filewordcounts, ht_init_times, 'bo', filewordcounts, ht_init_times, 'b--')
        iplot.plot(filewordcounts, cms_init_times, 'rs', filewordcounts, cms_init_times, 'r--')

        splot.plot(filewordcounts, ht_search_times, 'bo', filewordcounts, ht_search_times, 'b--')
        splot.plot(filewordcounts, cms_search_times, 'rs', filewordcounts, cms_search_times, 'r--')

        actual_counts = actual_counts_sub
        estimate_counts = estimate_counts_sub
        unique_counts = unique_counts_sub

    # Build line graph for time comparisons
    iplot.set_ylabel('Insertion Time (seconds)')
    splot.set_ylabel('Search Time (seconds)')
    splot.set_xlabel('Number of Words Inserted')

    # Legend
    red_patch = mpatches.Patch(color='red', label='Count-Min Sketch')
    blue_patch = mpatches.Patch(color='blue', label='Hash Table')
    iplot.legend(handles=[red_patch, blue_patch])
    splot.legend(handles=[red_patch, blue_patch])

    fig1.suptitle('CMS vs HashTable Time')
    fig1.savefig('cms_ht_time.png', bbox_inches='tight')

    # Build bar graph for actual vs est comparisons
    x = np.arange(len(filenames))  # the label locations
    width = 0.4  # width of the bars

    fig2, ax = plt.subplots()
    rects1 = ax.bar(x - width/2, actual_counts, width, label='Actual')
    rects2 = ax.bar(x + width/2, estimate_counts, width, label='Estimate')

    ax.set_ylabel('Number of occurrences of \"the\"')
    ax.set_xlabel('Number of total words in input file')
    ax.set_xticks(x)
    ax.set_xticklabels(filewordcounts)
    ax.legend()
    autolabel(rects1)
    autolabel(rects2)
    fig2.tight_layout()
    fig2.suptitle('Actual Count vs Estimated Count')
    fig2.savefig('cms_actual_estimate.png')

    # Build table for space used comparisons
    plt.figure(linewidth=2)
    columns = ('Unique Elements', 'Hash Table', 'CMS')
    rows = ('CSE312', 'Alice in Wonderland', 'Moby Dick',
               'Count of Monte Cristo', 'War and Peace')
    rcolors = plt.cm.BuPu(np.full(len(rows), 0.1))
    ccolors = plt.cm.BuPu(np.full(len(columns), 0.1))

    table = plt.table(cellText=unique_counts, rowLabels=rows, rowColours=rcolors,
                      rowLoc='right', colColours=ccolors, colLabels=columns, loc='center')
    ax = plt.gca()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

    plt.box(on=None)
    plt.suptitle('Space Usage')
    plt.draw()
    fig3 = plt.gcf()
    fig3.tight_layout()
    plt.savefig('space_usage.png', dpi=150)


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('contacts', '0005_contactorganization_department'),
        ('projects', '0018_taskstatus_count_open'),
    ]

    operations = [
        migrations.CreateModel(
            name='ProjectTeam',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('contact', models.ForeignKey(to='contacts.Contact')),
                ('project', models.ForeignKey(to='projects.Project')),
            ],
        ),
        migrations.AlterField(
            model_name='taskstatus',
            name='count_open',
            field=models.BooleanField(default=True, verbose_name=b'Count as Open'),
        ),
    ]


class Solution(object):
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l = len(nums)
        if l == 0:
            return 0
        dp = [1 for _ in range(l)]
        for i in range(1, l):
            max_lis = 1
            for j in range(i):
                if nums[i] > nums[j]:
                    max_lis = max(max_lis, dp[j]+1)
            dp[i] = max_lis
        return max(dp)


from numpy import *
from matplotlib.pyplot import *
import time

def gausselim(a,b):
    n = b.size
    f = zeros(n, float)
    for k in range(0,n-1):
        for i in range(k+1,n):
            em = a[i,k]/a[k,k]
            a[i,k] = em
            b[i] -= em*b[k]
            for j in range(k+1,n):
                a[i,j] -= em*a[k,j]

    f[n-1] = b[n-1]/a[n-1,n-1]

    for i in range(n-2,-1,-1):
        f[i] = b[i]
        for j in range(n-1,i,-1):
            f[i] -= a[i,j]*f[j]
        f[i] = f[i]/a[i,i]

    return f

start = time.time()

# definition of computational domain
w = 10.0
h = 15.0
nx = 20
ny = 20
nmax = (nx-1)*(ny-1)
dx = w/nx
dy = h/ny
beta = dx/dy
bsq = beta*beta
dnm = 0.5/(1.0+bsq)

# initialization
x = linspace(0, w, nx+1)
y = linspace(0, h, ny+1)
b = zeros(nmax, float)
a = zeros((nmax,nmax), float)
T = zeros((nx+1,ny+1), float)

# Dirichlet boundary condition for upper boundary (j = ny)
for i in range(0, nx+1):
    T[i,ny] = 100.0*sin(pi*x[i]/w)

n = 0
for j in range(1, ny):
    for i in range(1, nx):
        if ( j==1 ):
            b[n] += bsq*dnm*T[i,j-1]      # lower boundary
        else:
            a[n-nx+1,n] = -bsq*dnm
        if ( i==1):
            b[n] += dnm*T[i-1,j]          # left boundary
        else:
            a[n-1,n] = -dnm
        if ( i==nx-1 ):
            b[n] += dnm*T[i+1,j]          # right boundary
        else:
            a[n+1,n] = -dnm
        if ( j==ny-1 ):
            b[n] += bsq*dnm*T[i,j+1]      # upper boundary
        else:
            a[n+nx-1,n] = -bsq*dnm
        a[n,n] = 1.0
        n += 1

f = gausselim(a,b)
n = 0
for j in range(1, ny):
    for i in range(1, nx):
        T[i,j] = f[n]
        n += 1

# obtained solution in standard output
print ("solution =",T)
print ("elapsed time =",time.time()-start)

# plot setting
X, Y = meshgrid(x,y,indexing='ij')
contour(X,Y,T)
xlabel('X')
ylabel('Y')
cbar=colorbar()
cbar.set_label('T')
show()


def parseString (expression):

    print(expression)##########

    openPar = ['(']
    closePar = [')']
    queue = []
    result = []

    def doSomethingUseful(string):
        result.append(string)

    for pos, char in enumerate(expression):
        #print(pos, char)
        if char in openPar:
            queue.append([pos, char])
        elif char in closePar:
            if len(queue) == 0: #or i != queue.pop():
                #print('error', expression, result, queue, pos, char)
                return "no open parentneses for {i}"
            temp = queue.pop()
            #print('closePar', temp, queue)
            if len(queue) == 0:
                doSomethingUseful(parseString(expression[temp[0]+1:pos]))
        elif len(queue) == 0:
            doSomethingUseful(char)

    if len(queue)>0:
        #print('error at end', expression, result, queue)
        return "unBalanced"

    print(result)

    return '{' + ','.join(result) + '}'

if __name__=='__main__':
    print(parseString('1+2*(8+3+9+1-(1*2)) +()-34'))
    print('----------------')
    print(parseString('(1+2+3+4-(5*6))'))


#!/usr/bin/python3
# Question from http://www.codechef.com/problems/MARCHA4/

def solve(num, digits):
    ans = str(num ** num)
    return "%s %s" %(ans[:digits], ans[-digits:])

for i in range(int(input())):
    params = tuple(input().split())
    print(solve(int(params[0]), int(params[1])))


# python3.5+
import os

import transcripts_sessions
import extract_terms as extract

def main(path, fn):
    all_ref_terms = []
    all_hyp_terms = []

    result_f = open('eval_results/sessions/final/' + fn, 'w')
    # load file
    lines = transcripts_sessions.load(fn, path)
    sent_pairs = transcripts_sessions.get_sent_pairs(lines)
    total_terms = 0
    total_true_positive = 0
    total_false_positive = 0

    # get med terms for each sent pairs
    for pi, pair in enumerate(sent_pairs):
        #print(pair[0])
        #print(pair[1])

        # extract terms
        ref_terms = extract.parse_terms(extract.find_matches(pair[0]), pair[0])
        hyp_terms = extract.parse_terms(extract.find_matches(pair[1]), pair[1])
        # record terms
        if len(ref_terms) > 0: all_ref_terms = extend_terms(all_ref_terms, ref_terms)
        if len(hyp_terms) > 0: all_hyp_terms = extend_terms(all_hyp_terms, hyp_terms)
        # log acc
        print(ref_terms, hyp_terms)
        print(count_correct(ref_terms, hyp_terms))
        true_positive, false_positive, num_terms = count_correct(ref_terms, hyp_terms)
        total_true_positive += true_positive
        total_false_positive += false_positive
        total_terms += num_terms
        print('Sentence {}: prcision = {}/{}, recall = {}/{}'.format(pi, true_positive, true_positive+false_positive, true_positive, num_terms))
        result_f.write('Sentence {}: prcision = {}/{}, recall = {}/{}\n'.format(pi, true_positive, true_positive+false_positive, true_positive, num_terms))
        result_f.flush()
        ref_terms_string = format_terms_string(ref_terms, pair[0][5:])
        hyp_terms_string = format_terms_string(hyp_terms, pair[1][5:])
        # log terms
        print('REF      : ' + pair[0][5:])
        print('REF Terms: ' + ref_terms_string)
        print('HYP      : ' + pair[1][5:])
        print('HYP Terms: ' + hyp_terms_string)
        result_f.write('REF      : ' + pair[0][5:] + '\n')
        result_f.write('REF Terms: ' + ref_terms_string + '\n')
        result_f.write('HYP      : ' + pair[1][5:] + '\n')
        result_f.write('HYP Terms: ' + hyp_terms_string + '\n\n')
        result_f.flush()
    session_true_positive, session_false_positive, session_terms = count_correct_session(all_ref_terms, all_hyp_terms)

    print('SESSION REF TERMS: {}'.format(', '.join(list(set(all_ref_terms)))))
    print('SESSION HYP TERMS: {}'.format(', '.join(list(set(all_hyp_terms)))))
    result_f.write('SESSION REF TERMS: {}\n'.format(', '.join(list(set(all_ref_terms)))))
    result_f.write('SESSION HYP TERMS: {}\n'.format(', '.join(list(set(all_hyp_terms)))))
    print('Precision = {}/{}, Recall = {}/{}\n'.format(session_true_positive, session_true_positive+session_false_positive, session_true_positive, session_terms))
    result_f.write('Precision = {}/{}, Recall = {}/{}\n'.format(session_true_positive, session_true_positive+session_false_positive, session_true_positive, session_terms))
    result_f.flush()
    result_f.close()

def test(path, fn):
    lines = transcripts_sessions.load(fn, path)

    print(lines[0])
    print('\n\n')
    print(lines[1])
    sent_pairs = transcripts_sessions.get_sent_pairs(lines)
    print(sent_pairs, len(sent_pairs))

    for pi, pair in enumerate(sent_pairs):
        print(pair[0])
        print(pair[1])

        # extract terms
        ref_terms = extract.parse_terms(extract.find_matches(pair[0]), pair[0])
        hyp_terms = extract.parse_terms(extract.find_matches(pair[1]), pair[1])

        print(ref_terms)
        print(hyp_terms)

def count_correct(ref_terms_, hyp_terms_):
    ref_terms = [term[0] for term in ref_terms_]
    hyp_terms = [term[0] for term in hyp_terms_]
    true_positive = 0
    false_postive = 0
    total_ref_terms = len(ref_terms)
    for term in hyp_terms:
        if term in ref_terms:
            true_positive += 1
            ref_terms.remove(term)
        else:
            false_postive += 1

    return true_positive, false_postive, total_ref_terms

def count_correct_session(ref_terms, hyp_terms):
    ref_terms = list(set(ref_terms))
    hyp_terms = list(set(hyp_terms))
    true_positive = 0
    false_postive = 0
    for term in hyp_terms:
        if term in ref_terms:
            true_positive += 1
        else:
            false_postive += 1

    return true_positive, false_postive, len(ref_terms)

def extend_terms(spider, fly):
    for term in fly:
        spider.append(term[0])
    return spider

def format_terms_string(terms, sentence):
    string = ' ' * len(sentence)
    for term in terms:
        string = string[:term[1][0]-5] + term[0] + string[term[1][1]-5+1:]

    return string

if __name__ == '__main__':
    transcripts_path = ''
    file_list = os.listdir(transcripts_path)
    for fn in file_list:
        print(fn)
        main(transcripts_path, fn)


import math

def compute_news_user_score(news_rating, review_count, given_score, user_rating):
    """
    iteratively re-calculate news attributes
    """
    discount_factor = 0.1
    if review_count == 0:
        raw_news_rating = discount_factor * given_score
        new_rating = discount_factor * user_rating * raw_news_rating
        review_count = review_count + 1
    else:
        average = review_count * news_rating
        review_count = review_count + 1
        weighted_average = (average + user_rating * given_score) / review_count
        p = 0.5
        weighted_average = weighted_average * p
        discounting_count_factor = 10 * (1 - p) * (1 - math.exp(- review_count / 100))
        new_rating = weighted_average + discounting_count_factor
    return new_rating, news_rating, review_count

def compute_user_rating_iterative(given_score, user_rating, user_cnt, old_score, news_count):
    """
    iteratively re-calculate user attributes
    """
    diff_new = abs(given_score - old_score)
    max_diff = 9

    if user_cnt == 0:
        raw_user_rating = (1 - diff_new / max_diff)
        discounting_user_factor = 0.3
        user_new_rating = raw_user_rating * discounting_user_factor
        user_cnt = user_cnt + 1
    else:
        discounting_user_factor = 1 - (1/user_cnt)
        raw_user_rating = 1 - (diff_new/27)
        user_new_rating = (user_rating * user_cnt + raw_user_rating) / (user_cnt + 1)
        user_new_rating = discounting_user_factor * user_new_rating
        user_cnt = user_cnt + 1

    return user_new_rating, user_cnt


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 14 11:43:16 2018

@author: David

parts of code adapted from code here:
    https://www.kaggle.com/dbsnail/diabetes-prediction-over-0-86-accuracy
    https://towardsdatascience.com/building-a-logistic-regression-in-python-step-by-step-becd4d56c9c8

class imbalance adapted partly from:
    https://elitedatascience.com/imbalanced-classes

ROC Curve plotting adapted from:
    https://datamize.wordpress.com/2015/01/24/how-to-plot-a-roc-curve-in-scikit-learn/

"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('ggplot')

'''
import warnings
warnings.filterwarnings('ignore')
'''

### read CSV file containing BR census data
di_df = pd.read_csv('C:\\Users\\David\\Documents\\Data Science Related\\Datasets\\pima-indians-diabetes\\diabetes.csv')

### checking class balance (levels of Outcome variable)
di_df.Outcome.value_counts()

### Check how many columns contain missing data
print(di_df.isnull().any().sum(), ' / ', len(di_df.columns))

### Check how many entries in total are missing
print(di_df.isnull().any(axis=1).sum(), ' / ', len(di_df))

### function to replace particular value in a feature column with mean of subset
### of column grouped by target variable level (i.e. mean imputation by group)
def impute_mean_byGroup(df, field, val, target):
    df_copy = df.copy() # make copy of df (not strictly necessary?)
    df_copy[field].replace(val, np.nan, inplace=True) # replace values of field that match val with nan
    field_grouped = df_copy[field].groupby(df_copy[target])  # field grouped by target (creates group object)
    field_nanRepByMean = field_grouped.apply(lambda x: x.fillna(x.mean())) # replace nan in each group by mean of field for that group
    df_copy[field] = field_nanRepByMean.values
    return(df_copy)

### impute mean for 0 values by grouped outcome for selected columns
di_df_imputed = di_df.copy()
for col in ['Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI']:
    di_df_imputed = impute_mean_byGroup(di_df_imputed, col, 0, 'Outcome')

### assess balance of classes (counts of 0 and 1)
di_df_imputed['Outcome'].value_counts()

### copy di_df_imputed to new df simply called 'df' to use for modifying entries for balancing classes
df = di_df_imputed.copy()

### using upsampling (resampling) of minority class (1) to address class imbalance
from sklearn.utils import resample

### Separate majority and minority classes into new dfs
df_maj = df[df.Outcome==0]
df_min = df[df.Outcome==1]

### Upsample minority class
df_min_upsamp = resample(df_min,
                                 replace=True,     # sample with replacement
                                 n_samples=500,    # to match majority class
                                 random_state=123) # reproducible results

### Combine majority class with upsampled minority class
df_combined_upsamp = pd.concat([df_maj, df_min_upsamp])

### Display new class counts
df_combined_upsamp.Outcome.value_counts()

### import sklearn functions for Random Forest Classifier and train/test split
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

### split data into features and target
X = df_combined_upsamp.iloc[:,:-1]
y = df_combined_upsamp.iloc[:, -1]

### split into train/test (stratify by y to ensure split by Outcome)
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state=100)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size = 0.3, random_state=100)

### check dimensions of train/test data
print(X_train.shape)
print(X_test.shape)
print(y_train.size)
print(y_test.size)

### instantiate and fit logistic regression model
rf = RandomForestClassifier()
rf.fit(X_train, y_train)

### predict on test set and assess accuracy
y_pred = rf.predict(X_test)
print('Accuracy of rf on test set: {:.2f}'.format(rf.score(X_test, y_test)))

### predict class probabilities for X-test
y_classProbs = rf.predict_proba(X_test)

### Look at feature importance in classifier performance

importances = rf.feature_importances_
std = np.std([rf.feature_importances_ for feature in rf.estimators_],
             axis=0)
indices = np.argsort(importances)[::-1]

# Print the feature ranking
print("Feature ranking:")

for f in range(X.shape[1]):
    print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))

# Plot the feature importances of the forest
plt.figure()
plt.title("Feature importances")
plt.bar(range(X.shape[1]), importances[indices],
       color="r", yerr=std[indices], align="center")
plt.xticks(range(X.shape[1]), indices)
plt.xlim([-1, X.shape[1]])
plt.show()

### import libraries for cross-validation
from sklearn import model_selection
from sklearn.model_selection import cross_val_score

### Perform 10-fold cross-validation and compute mean accuracy over folds
kfold = model_selection.KFold(n_splits=10)
modelCV = RandomForestClassifier()
scoring = 'accuracy'
results = cross_val_score(modelCV, X_train, y_train, cv=kfold, scoring=scoring)
print("10-fold cross-validation mean accuracy: %.3f" % (results.mean()))

### confusion matrix metrics and visualization
from sklearn.metrics import confusion_matrix

confusion_matrix = confusion_matrix(y_test, y_pred)
print(confusion_matrix)

plt.figure(figsize=(9,9))
sns.heatmap(confusion_matrix, annot=True, fmt=".1f", linewidths=.5, square = True, cmap = 'Blues_r');
plt.ylabel('Actual label');
plt.xlabel('Predicted label');
acc_title = 'Accuracy Score: {0}'.format(round(results.mean(),2))
plt.title(acc_title, size = 15);

### Compute ROC Curve and Plot
### calculate the fpr and tpr for all thresholds of the classification
from sklearn.metrics import roc_curve, auc

fpr, tpr, threshold = roc_curve(y_test, y_pred)
roc_auc = auc(fpr, tpr)

plt.title('ROC')
plt.plot(fpr, tpr, 'b', label='AUC = %0.2f'% roc_auc)
plt.legend(loc='lower right')
plt.plot([0,1],[0,1],'r--')
plt.xlim([-0.025, 1.025])  # just giving a little padding to plot range
plt.ylim([-0.025, 1.025])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()

### show validation curves for different number of estimators used to fit KNN
from sklearn.learning_curve import validation_curve
depth = np.arange(1, 20)
train_score, val_score = validation_curve(RandomForestClassifier(), X, y, 'max_depth', depth, cv=10)

plt.plot(depth, np.median(train_score, 1), color='blue', label='training score')
plt.plot(depth, np.median(val_score, 1), color='red', label='validation score')
plt.legend(loc='best')
plt.ylim(0, 1.05)
plt.xlabel('depth')
plt.ylabel('score');


character_properties_ranges = {"radius": (28.0, 50.0),
                               "moveVelocity": (200.0, 800.0)}

melee_ability_ranges = {
    "name": "abilityName",
    "type": "MELEE",
    "radius": (16.0, 200.0),
    "distanceFromChar": (0.0, 200.0),
    "speed": (0.0, 0.0),
    "startupTime": (1, 30),
    "activeTime": (1, 60),
    "executionTime": (1, 30),
    "endlagTime": (1, 30),
    "rechargeTime": (10, 30),
    "damage": (100.0, 1000.0),
    "baseKnockback": (10.0, 1000.0),
    "knockbackRatio": (0.1, 1.0),
    "knockbackPoint": (-500.0, 500.0),
    "knockbackTowardPoint": (False, True)
}

projectile_ability_ranges = {
    "name": "abilityName",
    "type": "PROJECTILE",
    "radius": (5, 50),
    "distanceFromChar": (0, 200),
    "speed": (100, 800),
    "startupTime": (1, 60),
    "activeTime": (20, 1000),
    "executionTime": (1, 30),
    "endlagTime": (1, 30),
    "rechargeTime": (10, 120),
    "damage": (15, 500),
    "baseKnockback": (50, 1000),
    "knockbackRatio": (0.1, 1.0),
    "knockbackPoint": (-500, 500),
    "knockbackTowardPoint": (False, True)
}


import pandas as pd
import plotly.express as px

# Source for basis of mapping Script: https://gist.github.com/jbrobst
df = pd.read_csv(r"C:\Users\Arnav Joshi\OxygenNeed.csv")

fig = px.choropleth(
    df,
    geojson="https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson",
    featureidkey='properties.ST_NM',
    locations='State',
    color='Oxygen Needed Daily(tonnes)',
    color_continuous_scale='Blues'
)

fig.update_geos(fitbounds="locations", visible=False)

fig.show()


"""
This class validates all requirements should be passed by package.
"""
from PartNLP.models.helper.color import Color
from PartNLP.models.validation.validator import Validator
from PartNLP.models.helper.constants import NAME_OF_SUPPORTED_PACKAGES
from pathlib import Path
import stanza
import json
import os

class PackageValidator(Validator):
    def __init__(self, config):
        super().__init__(config)

    def isvalid(self):
        success, message, val = True, '', None
        success, message, val = self.is_name_valid()
        if success:
            return self.check_install_resources()
        else:
            return success, message, val

    def is_name_valid(self):
        # Check whether package selected.
        if not self.config['package']:
            return False, f'{Color.FAIL}Warning:{Color.ENDC} no package selected. List of supported package:' \
                          f'{Color.HEADER}{NAME_OF_SUPPORTED_PACKAGES}{Color.ENDC}', self.config['Language']
        self.prepare_input_value()
        if self.config['package'] not in NAME_OF_SUPPORTED_PACKAGES:
            package = self.config['package']
            return False, f'{package} is not supported. List of supported packages: ' \
                          f'{NAME_OF_SUPPORTED_PACKAGES}', package
        return True, '', None

    def check_install_resources(self):
        if self.config['package'] == 'STANZA':
            HOME_DIR = str(Path.home())
            DEFAULT_MODEL_DIR = os.getenv('STANZA_RESOURCES_DIR', os.path.join(HOME_DIR, 'stanza_resources/'))
            dir = DEFAULT_MODEL_DIR
            # rename persian language to fa and use dir = dir + self.config['Language']
            dir = dir + 'fa'
            if not os.path.isdir(dir):
                lang = self.config['Language']
                return False, f'stanza needs {Color.HEADER}{lang} resource. do you want to install(y, n){Color.ENDC}', \
                       'install_resource'
        return True, '', None

    def prepare_input_value(self):
        self.config['package'] = self.config['package'].upper()

    def update_config_value(self, name, old_value, new_value):
        if old_value == 'install_resource':
            if new_value == 'y':
                stanza.download('fr')
            else:
                raise Exception('you can not run this package without the resources')
        else:
            self.config['package'] = new_value

    def get_dependencies(self):
        return []


## prime factors generator divisors.py
import sys

def prime_divisors(n):
	"""
	Check divisors for range(5)
	>>> prime_divisors(5)
	5
	"""
	for i in range(2,n+1):
		if n % i == 0:
			for y in range(2,i+1):
				if i % y == 0 and i != y:
					break
			else:
				yield i

"""
if __name__ == "__main__":
	##import doctest
	##doctest.testmod()
	import argparse
	parser = argparse.ArgumentParser()
	parser.add_argument('-n','--number',type=int, help='Give integer number to calulate divisors')
	args = parser.parse_args()
	number = args.number
	for i in prime_divisors(number):
		print(i)
		print("next")
	help(prime_divisors)
"""


import cv2 as cv
import numpy as np
from PIL import Image

Input_Batch = [[0 for x in range(6)] for y in range(6)]
Kernel = [[0 for x in range(3)] for y in range(3)]
Output = [[0 for x in range(2)] for y in range(2)]

def Fill_Input_Batch(Param):
    value = float(0.0)
    for x in range(len(Param)):
        value = float(x)
        for y in range(len(Param[x])):
            Param[y][x] = value
            value += 0.1

#Kernel[0][0] = 0;
#Kernel[0][1] = 0;
#Kernel[0][2] = 0;

Kernel[0][1] = 0.5;
Kernel[1][1] = 1;
Kernel[2][1] = 0.5;

#Kernel[2][0] = 0;
#Kernel[2][1] = 0;
#Kernel[2][2] = 0;

def Display_Input_Batch(Param1):
    for a in range(len(Param1)):
        for b in range(len(Param1[a])):
            print('%.1f'%Param1[a][b], end =' ')
        print()

def Display_Kernel(Param1):
    for a in range(len(Param1)):
        for b in range(len(Param1[a])):
            print('%.1f'%Param1[a][b], end =' ')
        print()

def Display_Output(Param1):
    for a in range(len(Param1)):
        for b in range(len(Param1[a])):
            print('%.1f'%Param1[a][b], end =' ')
        print()

def Convolutional_Transform(Input, Kernel,Output):
    pos = int()
    pos = (6*6)/(3*3)
    output_counter = int()
    value = float()
    stride = int(3)
    #for x in range(0,int(pos)):
    print();
    for y in range(0,len(Output)):
        for z in range(0,len(Output[y])):
            value = 0.0
            for a in range(len(Kernel)):
                for b in range(len(Kernel[a])):
                    value += (Input[y*stride + a][z*stride + b] * Kernel[a][b])
                #print(value)
            Output[y][z] = value
    print()

Fill_Input_Batch(Input_Batch)
Display_Input_Batch(Input_Batch)
print()
Display_Kernel(Kernel)
Convolutional_Transform(Input_Batch,Kernel,Output)
print()
Display_Output(Output)

# Load an color image in grayscale
img = cv.imread("red_eyes.jpg",1)
print(type(img))

data = np.asarray( img, dtype="int32" )
#print(data)

#cv.imshow('image',img)
#cv.waitKey(0)
#cv.destroyAllWindows()

height, width, channels = img.shape

print(width)
print(height)

data_R =  [[0 for x in range(width)] for y in range(height)]

for x in range(0,height):
    for y in range(width):
        #data_R[x][y] = data[x][y]
        #print(data[x][y])
        temp = data[x][y]
        if(temp[0] < 0):
            temp[0] = 0
        if(temp[0] > 255):
            temp[0] = 255

        if(temp[1] < 0):
            temp[1] = 0
        if(temp[1] > 255):
            temp[1] = 255

        if(temp[2] < 0):
            temp[2] = 0
        if(temp[2] > 255):
            temp[2] = 255
        #temp[0] = 0
        #temp[1] = 100
        #temp[2] = 100
        data_R[x][y] = temp[0]
        data[x][y] = temp
        #print(data_R[x][y])
        #input()

#image_2d = np.vstack(itertools.imap(numpy.uint16, data[x][y]))

#im = Image.fromarray(data, 'RGB')
#im.save("your_file.png")
#im.show()
#w, h = 512, 512
#data = np.zeros((h, w, 3), dtype=np.uint8)
#data[0:256, 0:256] = [255, 0, 0] # red patch in upper left
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()

from matplotlib import pyplot as plt
plt.imshow(data)
plt.show()


from die import Die
import matplotlib.pyplot as plt

die1 = Die()
die2 = Die()

#随机模拟两个六面骰子10000次投掷相加结果
results = [die1.roll() + die2.roll() for i in range(10000)]

#分析结果
max = die1.num_sides + die2.num_sides
frequencies = [results.count(num) for num in range(2, max+1)]

#可视化结果
possible = [num for num in range(2, max+1)]
plt.plot(possible, frequencies, linewidth=5)
#设置标题,给坐标轴加上标签
plt.title("随机模拟两个六面骰子10000次投掷相加结果", fontsize=24)
plt.xlabel("数", fontsize=14)
plt.ylabel("对应次数", fontsize=14)

#设置刻度标记大小

plt.show()

数据可视化/使用matplotlib来可视化模拟掷骰子的情况.py

使用matplotlib来可视化模拟掷骰子的情况.py


import random
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import os
#
# def random_int_list(start, stop, length):
#
#     assert(stop-start+1 >= length)
#
#     random_list = []
#     for i in range(length):
#         v = random.randint(start, stop)
#         while v in random_list:
#             v = random.randint(start, stop)
#         random_list.append(v)
#     return np.array(random_list)

def make_one_hot(data, class_count):

    return (np.arange(class_count) == data[:, None]).astype(np.integer)

def imshow(img):
    img = (img / 2 + 0.5) * 255  # unnormalize
    npimg = img.numpy().astype(int)
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()

def imsave(img, path, prediction):
    img = (img / 2 + 0.5) * 255 # unnormalize
    npimg = img.numpy().astype(int)
    npimg = np.transpose(npimg, (1, 2, 0))
    result = Image.fromarray(np.uint8(npimg))
    if not os.path.exists(path+'/predictions'):
        os.mkdir(path+'/predictions')

    i = 0
    file_path = path + '/predictions/' + prediction + str(i) + '.jpg'
    while os.path.exists(file_path):
        i += 1
        file_path = path + '/predictions/' + prediction + str(i) + '.jpg'
    print('saving image')
    result.save(file_path)

def get_folders(path):

    result = []
    for entry in os.scandir(path):
        result.append(path+'/'+entry.name)
    return result

def get_class_names(path):

    result = []
    for entry in os.scandir(path):
        result.append(str(entry.name))
    return result

if __name__ == '__main__':
    print(get_folders('./dataset/train'))


import random
import telebot

# import webbrowser
# import time

bot_token = '988563200:AAHTscEL3pmsgAnSsQwdVuhpfAqjbmyrMMs'
bot = telebot.TeleBot(token=bot_token)

@bot.message_handler(func=lambda message: message.voice is not None)
def aud(message):
    bot.reply_to(message, 'its an audio')

@bot.message_handler(content_types=['sticker'])
def per(message):
    if message.sticker.emoji == "👋":
        rand = ['1.tgs', '2.webp', '3.tgs', '5.tgs', '6.tgs', '7.tgs']
        sti = open('stickers/hi/' + random.choice(rand), 'rb')
        bot.send_sticker(message.chat.id, sti)
    elif message.sticker.emoji == '😡' or message.sticker.emoji == '😠':
        rand = ['1.tgs', '2.tgs', '3.tgs', '5.tgs', '6.tgs', '7.tgs', '8.webp', '9.webp']
        sti = open('stickers/shock/' + random.choice(rand), 'rb')
        bot.send_sticker(message.chat.id, sti)
    elif message.sticker.emoji == '🤦♂' or message.sticker.emoji == '🙄' or message.sticker.emoji == "😑":
        rand = ['1.tgs', '2.tgs', '3.tgs', '5.tgs', '6.tgs', '7.tgs', '8.webp', '9.webp']
        sti = open('stickers/shock/' + random.choice(rand), 'rb')
        bot.send_sticker(message.chat.id, sti)
    else:
        rand = ['tgs1.tgs', 'tgs2.tgs', 'tgs3.tgs', 'tgs4.tgs', 'tgs5.tgs', 'tgs6.tgs', 'tgs7.tgs', 'tgs8.tgs',
                'tgs9.tgs', 'tgs10.tgs', 'h (1).tgs', 'h (2).tgs', 'h (4).tgs', 'h (3).tgs', 'h (5).tgs', 'h (6).tgs',
                'h (7).tgs', 'h (8).tgs', 'h (9).tgs', 'h (10).tgs', 'h (11).tgs', 'h (12).tgs', 'hw (1).tgs',
                'hw (2).tgs', 'hw (3).tgs', 'hw (4).tgs', 'hw (5).tgs', 'hw (6).tgs', 'hw (7).tgs', 'hw (8).tgs',
                'hw (9).tgs', 'hw (10).tgs', 'hw (11).tgs', 'hw (12).tgs', 'hw (13).tgs', 'hw (14).tgs', 'hw (15).tgs']
        sti = open('stickers/Randstickers/' + random.choice(rand), 'rb')
        bot.send_sticker(message.chat.id, sti)

@bot.message_handler(regexp="(?=.*(are you|name))(?=.*(who|what))")
def name(message):
    bot.reply_to(message, "I am your Medical Assistant")

@bot.message_handler(func=lambda
        message: message.text is not None and 'hi' in message.text.lower() or message.text is not None and 'hello' in message.text.lower())
def wel(message):
    bot.reply_to(message,
                 'Hello ' + message.from_user.first_name + '. Welcome to MedicalBot using pyTelegramBotAPI.How can i help you?🙂')

@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.reply_to(message, 'Welcome!I am active as ever.Go ahead and ask me your Queries.')
    file_id = ['1.tgs', '2.webp', '3.tgs', '4.webp', '5.tgs', '6.tgs', '7.tgs']
    sti = open('stickers/hi/' + random.choice(file_id), 'rb')
    bot.send_sticker(message.chat.id, sti)

@bot.message_handler(commands=['help'])
def send_help(message):
    bot.reply_to(message,
                 "Here's the list of features in provide:\n/start-Activate me😋\n/desc-About me😍\n/medinfo-Health Info\npretty cool huh😎")

@bot.message_handler(commands=['medinfo'])
def send_m(message):
    bot.reply_to(message, 'Please send name of the disease to continue✌:\n/amru-send to know about Maa Amrutam Yojna')

@bot.message_handler(commands=['desc'])
def send_d(message):
    bot.reply_to(message,
                 'This bot was created to fulfill otherwordly http://www.magujarat.com/about-gujarati.html of E divsion.Proceed with caution.')

@bot.message_handler(func=lambda message: message.text is not None and 'how are you' in message.text.lower())
def sendd(message):
    bot.reply_to(message, "i've had an exciting day,looking up some fun things to do,What can i do for you🙂")

@bot.message_handler(func=lambda message: message.text is not None and 'flu' in message.text.lower())
def flu(message):
    bot.reply_to(message,
                 "The flu, also called influenza, is a respiratory infection caused by viruses. Sometimes it causes mild illness. But it can also be serious or even deadly, especially for people over 65, newborn babies, and people with certain chronic illnesses.\nFor more Information visit:Wiki",
                 parse_mode='HTML')

@bot.message_handler(func=lambda message: message.text is not None and 'diabetes' in message.text.lower())
def dia(message):
    bot.reply_to(message,
                 "Diabetes is a disease that occurs when your blood glucose, also called blood sugar, is too high. Blood glucose is your main source of energy and comes from the food you eat. Insulin, a hormone made by the pancreas, helps glucose from food get into your cells to be used for energy.\nFor more information visit:Wiki",
                 parse_mode='HTML')

@bot.message_handler(func=lambda message: message.text is not None and 'fever' in message.text.lower())
def fev(message):
    bot.reply_to(message,
                 "Fever is when a human's body temperature goes above the normal range of 36–37° Centigrade (98–100° Fahrenheit). It is a common medical sign. Other terms for a fever include pyrexia and controlled hyperthermia. As the body temperature goes up, the person may feel cold until it levels off and stops rising.\nFor more information visit:Wiki",
                 parse_mode='HTML')

@bot.message_handler(func=lambda
        message: message.text is not None and 'measure' in message.text.lower() and 'blood pressure' in message.text.lower())
def sendbp1(message):
    bot.reply_to(message,
                 'Unfortunately, I am physically unable to provide what you ask for🤷♂.But visiting a doctor would definitely help you😊.')

@bot.message_handler(func=lambda message: message.text is not None and 'what is blood pressure' in message.text.lower())
def sendbp(message):
    bot.reply_to(message,
                 "Blood pressure (BP) is the pressure of circulating blood on the walls of blood vessels. Most of this pressure is due to work done by the heart by pumping blood through the circulatory system.\nNormal resting blood pressure in an adult is approximately 120 millimetres of mercury (16 kPa) systolic, and 80 millimetres of mercury (11 kPa) diastolic, abbreviated 120/80 mmHg.\nFor more Information visit:Wiki",
                 parse_mode='HTML')

@bot.message_handler(regexp="(?=.*appetite)(?=.*(loss|decrease))")
def lapp(message):
    bot.reply_to(message,
                 "Lack of appetite, or decreased hunger, is one of the most troublesome nutrition problems you can experience. Although it is a common problem, its cause is unknown. There are some medicines that might stimulate your appetite. Ask your doctor if such medicines would help you.\n*Solutions:-*\n~Eat smaller meals and snacks more frequently.\n~Eating six or seven or eight times a day might be more easily tolerated than eating the same amount of food in three meals.\n~Talk to your doctor. Sometimes, poor appetite is due to depression, which can be treated. Your appetite is likely to improve after depression is treated.\n~Avoid non-nutritious beverages such as black coffee and tea.\n~Try to eat more protein and fat, and less simple sugars.\n~Walk or participate in light activity to stimulate your appetite.",
                 parse_mode="Markdown")

@bot.message_handler(regexp="(?=.*weight)(?=.*(loss|decrease))")
def lwei(message):
    bot.reply_to(message,
                 'If your doctor tells you that you have lost too much weight, or if you are having difficulty maintaining a healthy weight, here are some tips:\n=>Drink milk or try  "high-calorie recipes"  instead of drinking low-calorie beverages.\n=>Ask your doctor or dietitian about nutritional supplements. Sometimes, supplements in the form of snacks, drinks (such as Ensure® or Boost®), or vitamins might be prescribed to eat between meals. These supplements help you increase your calories and get the right amount of nutrients every day. Note: Do not use supplements in place of your meals.\n=>Avoid low-fat or low-calorie products unless you have been given other dietary guidelines. Use whole milk, whole milk cheese, and yogurt.\n=>Use the "*Calorie Boosters*"  to add calories to your favorite foods.',
                 parse_mode="Markdown")

@bot.message_handler(regexp="(?=.*anemia)(?=.*(what|mean|how))")
def ane(message):
    bot.reply_to(message,
                 "Anemia is a condition in which you lack enough healthy red blood cells to carry adequate oxygen to your body's tissues. Having anemia can make you feel tired and weak. There are many forms of anemia, each with its own cause. Anemia can be temporary or long term, and it can range from mild to severe.\nFor more Information visit:Click Here",
                 parse_mode='HTML')

@bot.message_handler(regexp="(?=.*arthritis)(?=.*(what|mean|how))")
def art(message):
    bot.reply_to(message,
                 "Arthritis means joint inflammation, but the term is used to describe around 200 conditions that affect joints, the tissues that surround the joint, and other connective tissue. It is a rheumatic condition. The most common form of arthritis is osteoarthritis.\nFor more Information visit:Click Here",
                 parse_mode='HTML')

@bot.message_handler(regexp="(?=.*cancer)(?=.*(what|mean|how))")
def can(message):
    keyboard = telebot.types.InlineKeyboardMarkup()
    keyboard.add(telebot.types.InlineKeyboardButton('Visit the page',
                                                    url='https://www.medicalnewstoday.com/articles/323648.php'))
    bot.reply_to(message,
                 "Cancer is a group of diseases involving abnormal cell growth with the potential to invade or spread to other parts of the body. These contrast with benign tumors, which do not spread.\nFor more Information visit:Click Here",
                 parse_mode="HTML", reply_markup=keyboard)
@bot.message_handler(regexp="(?=.*bp)(?=.*(what|mean|how))")
def sendbp1(message):
    bot.reply_to(message,
                 "Blood pressure (BP) is the pressure of circulating blood on the walls of blood vessels. Most of this pressure is due to work done by the heart by pumping blood through the circulatory system.\nNormal resting blood pressure in an adult is approximately 120 millimetres of mercury (16 kPa) systolic, and 80 millimetres of mercury (11 kPa) diastolic, abbreviated 120/80 mmHg.\nFor more Information visit:Wiki",
                 parse_mode='HTML')
@bot.message_handler(func=lambda message: message.text is not None and 'what is bmi' in message.text.lower())
def send1(message):
    '''keyboard = telebot.types.InlineKeyboardMarkup()
    keyboard.row(
    telebot.types.InlineKeyboardButton('Yes!', callback_data='get-yes'),
    telebot.types.InlineKeyboardButton('No!', callback_data='get-no')
    )'''
    msg = bot.reply_to(message,
                       "Body Mass Index(BMI) is a measurement of a person's leanness or corpulence based on their height and weight, and is intended to quantify tissue mass. It is widely used as a general indicator of whether a person has a healthy body weight for their height. Specifically, the value obtained from the calculation of BMI is used to categorize whether a person is underweight, normal weight, overweight, or obese depending on what range the value falls between.Do you want to calculate your BMI?🧐")
    bot.register_next_step_handler(msg, send2)

'''@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
    if call.data == "get-yes":
        bot.answer_callback_query(call.id, "Answer is Yes")
    elif call.data == "get-no":
        bot.answer_callback_query(call.id, "Answer is No")'''

def send2(message):
    if message.text.lower() == 'yes':
        bot.reply_to(message,
                     'BMI Calculator',
                     parse_mode='HTML')
    elif message.text.lower() == 'no':
        bot.reply_to(message, 'Have fun😄')
    else:
        bot.reply_to(message, 'Well, that was unexpected!')

@bot.message_handler(commands=['amru'])
def amru_hand(message):
    keyboard = telebot.types.InlineKeyboardMarkup()
    keyboard.add(telebot.types.InlineKeyboardButton('Click Here', url='http://www.magujarat.com/about-gujarati.html'))
    bot.send_message(message.chat.id, 'Ma Amrutam Yojna Website', reply_markup=keyboard)

@bot.message_handler(content_types=['text'])
def unrec(message):
    bot.send_message(message.chat.id, "Sorry! I wasn't able to recognize what you sent.Please try again")

bot.polling(none_stop=True)


from sys import argv

ignore = ['duplex', 'alias', 'Current configuration']

with open('C:\\GitHub\\181_352_PythonThirdTERM\\Tasks 7\\'+argv[1], 'r') as f, open('C:\\GitHub\\181_352_PythonThirdTERM\\Tasks 7\\'+argv[2], 'w') as fw:
    fileStr = []
    for line in f:
        fileStr.append(line.rstrip())

    for line in fileStr:
        if not any(ignore in line for ignore in ignore) and not (line.startswith('!')):
            fw.write(line + "\n")
            continue
        else:
            print(line)

Python for networkers/Tasks 7/TASK7.2C.py


import numpy as np
np.random.seed(33)

import feather
import pandas as pd
import xgboost as xgb
from sklearn.metrics import log_loss
from sklearn.model_selection import KFold

train = pd.read_csv('train_recode_9a.csv.gz', compression="gzip")
test = pd.read_csv('test_recode_9a.csv.gz', compression="gzip")
train.shape
test.shape

all_data = pd.concat([train.drop(['loss', 'target'], axis=1), test], ignore_index=True)
all_data.index
all_data.head()

df_normal = pd.DataFrame(all_data, columns = ['claim_id'])
for f in all_data.columns:
    if 'cat' in f:
        d = pd.get_dummies(all_data[f])
        frames = [df_normal, d]
        df_normal = pd.concat(frames, axis=1)

len(df_normal.columns)
df_normal.head()

num_cols = [f for f in all_data.columns if 'cat' not in f]
all_data[num_cols].head()

train_norm = pd.merge(pd.DataFrame(train[num_cols]), df_normal, on='claim_id', how='inner', sort=False)
test_norm = pd.merge(pd.DataFrame(test[num_cols]), df_normal, on='claim_id', how='inner', sort=False)

y_train = train['target'].ravel()
X = train_norm.drop(['claim_id'], axis=1)
X_test = test_norm.drop(['claim_id'], axis=1)

train_id = train['claim_id'].values
test_id = test['claim_id'].values

params = {"objective": "multi:softprob",
          "eval_metric": "mlogloss",
          "num_class": 21,
          'colsample_bytree': .1,
          'min_child_weight': 5,
          'subsample': 1,
          'max_depth': 20,
          'alpha': 3,
          'gamma': 5,
          'lambda': 3,
          'nthread': 16,
          'silent': 1,
          'eta': .02,
          'verbose_eval': True
        }

dtrain = xgb.DMatrix(X.values, label=y_train)
xgtest = xgb.DMatrix(X_test.values)

bst_cv = xgb.cv(params, dtrain, num_boost_round=10000,
                early_stopping_rounds=25,
                nfold=5,
                verbose_eval=50)

print(bst_cv['test-mlogloss-mean'].values[-1])
nrounds = round(bst_cv.shape[0]/.8)

bst = xgb.train(params, dtrain, num_boost_round = nrounds,
                verbose_eval=50)

pred_final = bst.predict(xgtest)

df = pd.DataFrame(test_id, columns = ['claim_id'])
df = pd.concat([df, pd.DataFrame(pred_final)], axis=1)

df.to_csv('gbm_m4a_data9a_hot.csv.gz', index = False, compression='gzip')


#! /usr/bin/env python

#Definition for singly-linked list.
class ListNode:
  def __init__(self, x):
    self.val = x
    self.next = None

class Solution:
  # @param {ListNode} head
  # @return {ListNode}
  def reverseList(self, head):
    temp1 = None
    while head != None:
      temp2 = head.next
      head.next = temp1
      temp1 = head
      head = temp2
    head = temp1

    return head


import socket
import re
import sys
import multiprocessing

EOL1 = b'\n\n'
EOL2 = b'\n\r\n'

class WSGIServer:
    def __init__(self, port, app, static_path):
        # create tcp socket
        self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # bind port
        self.tcp_server_socket.bind(('', port))
        # set listen state
        self.tcp_server_socket.listen(128)
        # get frame app name
        self.application = app
        # get static file path
        self.static_path = static_path

    def serve_client(self, new_client_socket):
        # receive client request
        request = b''
        while EOL1 not in request and EOL2 not in request:
            request += new_client_socket.recv(1024)
        # print(request)
        request_lines = request.decode('utf-8').splitlines()
        # print(request_lines)
        # GET /index.html HTTP/1.1:match example
        file_name = ''
        ret = re.match(r'[^/]+(/[^ ]*)', request_lines[0])
        if ret:
            file_name = ret.group(1)
            if file_name == '/':
                file_name = '/index.html'
        if not file_name.endswith('.html'):
            file_path = self.static_path + file_name
            try:
                f = open(file_path, 'rb')
            except:
                response = 'HTTP/1.1 404 NOT FOUND\r\n'
                response += '\r\n'
                response += '------file not found------'
                new_client_socket.send(response.encode('utf-8'))
            else:
                # get response body
                file_contend = f.read()
                f.close()
                response = 'HTTP/1.1 200 OK\r\n'
                response += '\r\n'
                new_client_socket.send(response.encode('utf-8'))
                new_client_socket.send(file_contend)
        else:
            env = {'file_path': file_name}
            body = self.application(env, self.start_response_header)
            header = 'HTTP/1.1 {}\r\n'.format(self.status)
            for temp in self.response_headers:
                header += '{}:{}'.format(temp[0], temp[1])
                header += '\r\n'
            header += '\r\n'
            response = header + body
            new_client_socket.send(response.encode('utf-8'))

        new_client_socket.close()

    def start_response_header(self, status, headers):
        self.status = status
        self.response_headers = headers

    def server_run(self):
        while True:
            new_client_socket, _ = self.tcp_server_socket.accept()
            # serve_client(new_client_socket)
            p = multiprocessing.Process(target=self.serve_client, args=(new_client_socket,))
            p.start()
            new_client_socket.close()
        # tcp_server_socket.close()

def main():
    # print(sys.argv)
    if len(sys.argv) == 3:
        try:
            port = int(sys.argv[1])
            frame_app_name = sys.argv[2]
        except ValueError:
            raise ValueError('The port value is wrong')
            # return
    else:
        print('please input command line as: python3 7890 mini_frame:application emails.txt')
        return
    # mini_frame:application
    ret = re.match(r'([^:]+):(.*)', frame_app_name)
    if ret:
        frame_name = ret.group(1)
        app_name = ret.group(2)
    else:
        print('please input command line as: python3 7890 mini_frame:application')
        return

    with open('./web_server.conf', 'r') as f:
        path_info = eval(f.read())
    sys.path.append(path_info['dynamic_path'])
    frame = __import__(frame_name)
    app = getattr(frame, app_name)
    # print(frame, app)
    wsgi_server = WSGIServer(port, app, path_info['static_path'])
    wsgi_server.server_run()

if __name__ == '__main__':
    main()


import os
import numpy as np
import csv
from sklearn.decomposition import PCA

# calculate the var in one seq with window_size
def calculate_var(point_seq, window_size):
    point_var = []
    window_var = []
    window = []
    for index_of_point in range(0, 20):
        point_var.append([])
    for index_of_frame in range(0, round(len(point_seq[0]) / window_size)):
        window_var.append([])

    for index_of_point in range(0, len(point_seq)):
        point_data = point_seq[index_of_point]
        for index_of_frame in range(0, len(point_data)):
            if index_of_frame != 0 and index_of_frame % window_size == 0:
                var = numpy.var(window)
                # print(window, var)
                point_var[index_of_point].append(var)
                window_var[round(index_of_frame / window_size) - 1].append(var)
                window = []
            window.append(point_data[index_of_frame])
    return [point_var, window_var]

# smooth the sequence with (-3,12,17,12,-3)/3
def savitzky_filter(sequence):
    num_element = len(sequence)
    temp_seq = []
    for i in range(0, num_element):
        if (i < 2 or i + 2 >= num_element):
            temp = sequence[i]
        else:
            temp = [0.0,0.0,0.0]
            for j in range(len(temp)):
                temp[j] = (-3.0*(sequence[i - 2][j] + sequence[i + 2][j]) + 12.0*(sequence[i - 1][j]+sequence[i + 1][j]) + 17.0*sequence[i][j]) / 35.0
        temp_seq.append(temp)

    return temp_seq

# smooth the sequence with (-3,12,17,12,-3)/3
def savitzky_one_dim(sequence):
    num_element = len(sequence)
    temp_seq = []
    for i in range(0, num_element):
        if (i < 2) or (i + 2 >= num_element):
            temp = sequence[i]
        else:
            temp = (-3.0*(sequence[i - 2] + sequence[i + 2])
                    + 12.0*(sequence[i - 1]+sequence[i + 1])
                    + 17.0*sequence[i]) / 35.0
        temp_seq.append(temp)

    return temp_seq

def taylor_one_dim(sequence):
    num_element = len(sequence)
    temp_seq = []
    for i in range(1, num_element):
        if i+1 >= num_element:
            temp = temp_seq[i-1]
        else:
            temp = (sequence[i+1] - sequence[i-1])/(0.125 * 2.0)
        if i == 1:
            temp_seq.append(temp)

        temp_seq.append(temp)

    return temp_seq

def taylor_transfer(sequence):
    num_element = len(sequence)
    num_axi = len(sequence[0])
    temp_seq = []
    for i in range(1, num_element):
        if(i+1 >= num_element):
            temp = temp_seq[i-1]
        else:
            temp = [0.0,0.0,0.0]
            for j in range(num_axi):
                temp[j] = (sequence[i+1][j] - sequence[i-1][j])/(0.125 * 2.0)
        if(1 == i):
            temp_seq.append(temp)

        temp_seq.append(temp)

    return temp_seq

def gaussion_curve(i, s, stdvv):
    temp = - float((abs(s-i) **2)) / float(2*stdvv*stdvv)
    return np.exp(temp)

##############################  useless function #################################
'''
# calculate bounder of a sequence of (x,y,z)
def calculate_bounder(sequence):
    bounder = [[float("inf"),float("-inf")],[float("inf"),float("-inf")],[float("inf"),float("-inf")]]
    for i in sequence:
        x_value = i[0]
        y_value = i[1]
        z_value = i[2]
        if x_value < bounder[0][0]:
            bounder[0][0] = x_value
        if x_value > bounder[0][1]:
            bounder[0][1] = x_value
        if y_value < bounder[1][0]:
            bounder[1][0] = y_value
        if y_value > bounder[1][1]:
            bounder[1][1] = y_value
        if z_value < bounder[2][0]:
            bounder[2][0] = z_value
        if z_value > bounder[2][1]:
            bounder[2][1] = z_value
    return bounder

# get pca components of data sequence
def PCA_vector(data):
    pca = PCA(n_components=3)
    data_t = pca.fit_transform(data)
    return pca.components_

# calculate fuzzy(a) of the given a and its bounder(min, max)
def fuzzy(a, min_bounder, max_bounder):
    q = [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]
    q[0] = min_bounder
    q[8] = max_bounder
    q[4] = 1.0 * (q[0] + q[8]) / 2.0
    q[2] = 1.0 * (q[0] + q[4]) / 2.0
    q[1] = 1.0 * (q[0] + q[2]) / 2.0
    q[3] = 1.0 * (q[2] + q[4]) / 2.0
    q[6] = 1.0 * (q[8] + q[4]) / 2.0
    q[7] = 1.0 * (q[6] + q[8]) / 2.0
    q[5] = 1.0 * (q[4] + q[6]) / 2.0

    fuzzy_value = [0.0, 0.0, 0.0, 0.0,0.0,0.0,0.0,0.0]
    for i in range(0,8):
        if(a > q[i]):
            if(a > q[i+1]):
                fuzzy_value[i] = 0
            else:
                fuzzy_value[i] = maxmin_linear(a,q[i-1],q[i])
        else:
            fuzzy_value[i] = 1

    return fuzzy_value

def maxmin_linear(x, min_bounder, max_bounder):
    return 1.* (x-min_bounder) / (max_bounder - min_bounder)

'''


import urllib.request
from requests import get

def get_url(url):
    '''
    Checks that a given url is reachable and returns its contents
    :param url: A URL string
    :return: url contents or None
    '''
    try:
        urllib.request.urlopen(url)
        return get(url)
    except urllib.request.HTTPError:
        print("Website does not exist")
        return None
    except urllib.request.URLError:
        print("Website does not exist")
        return None

def check_url(url):
    '''
    Checks that a given url is reachable
    :param url: A URL string
    :return: True if site exists, False if otherwise
    '''
    try:
        urllib.request.urlopen(url)
        return True
    except urllib.request.HTTPError as e:
        print('The server couldn\'t fulfill the request.')
        print('Error code: ', e.code)
        return False
    except urllib.request.URLError as e:
        print('Failed to reach a server.')
        print('Reason: ', e.reason)
        return False


import urllib.request
import  time
import itertools
# 重试次数num_retrise
def download(url,user_agent='wswp',num_retrise=2):
    while num_retrise>0 :
        print ('Downloading:',url)
        headers={'User-agent':user_agent}
        request=urllib.request.Request(url,headers=headers)
        try:
            html=urllib.request.urlopen(request).read()
            return html
        except urllib.error.URLError as e:
            print('Downloading Error',e.reason)
            html=None
        if num_retrise>0:
            num_retrise-=1
            continue
        else:
            break
    return html


class Solution:
    def removeOuterParentheses(self, S: str) -> str:
        output = ""
        smark = False
        content = 0

        for c in S:
            #print (c,content,smark)
            if smark == False and c == '(' and content== 0 :
                #print('?')
                smark = True
                continue

            if smark == True and c ==')' and content== 0 :
                smark = False
                continue

            if smark == True and c =='(':
                 content = content + 1
                 output = output + c

            if smark == True and c ==')':
                 content = content - 1
                 output = output + c

        return output

s = Solution()
print(s.removeOuterParentheses("(()())(())"))


import discord
from discord.ext import commands
from .StaticMethods import StaticMethods
from discord import Embed, Colour
import random as r

class School(commands.Cog, name="Szkoła itd."):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def updateplan(self, ctx):
        """Developer command"""
        role_names = [role.name for role in ctx.message.author.roles]
        if "Developer" in role_names:
            StaticMethods.replace(ctx.message.content[12:])
            await ctx.send("Zaktualizowano plan")
        else:
            await ctx.send("Odmowa dostępu")

    @commands.command()
    async def ocena(self, ctx):
        r_ocena = r.randint(1,6)
        await ctx.send(str(ctx.message.author.name) + " dostał: "+str(r_ocena))

    @commands.command()
    async def gac(self, ctx):
        await ctx.send("http://www.pangac.c0.pl")

    @commands.command()
    async def siuda(self, ctx):
        await ctx.send("http://siudyzm.cba.pl")

    @commands.command()
    async def plan(self, ctx):
        embed = Embed(
            Color = Colour.red()
        )
        embed.set_image(url=StaticMethods.getPlan())
        await ctx.send(embed=embed)

def setup(bot):
    bot.add_cog(School(bot))
    print("Added School")


import re
from itertools import zip_longest

def text2sentences(txt, equal_to_space = ["\n"]):
    """
    Разбивает текст на предложения, учитывая, что фразы типа "мат. алгоритмы", "и т. д.", ".NET" --- это всё одно предложение
    """

    inds = []

    for i in range(len(txt)):
        if txt[i] == '.':
            if i+1 == len(txt):
                inds.append(i+1)
            elif txt[i+1].isspace():
                if i+2 < len(txt) and (not txt[i+2].islower() or txt[i+2]=='.'):
                    inds.append(i+1)

    if len(inds) > 0:
        answer = [txt[i:j-1] for i,j in zip_longest([0]+inds[:-1], inds)]
        if inds[-1] != len(txt):
            answer += [txt[inds[-1]+1:]]
    else:
        answer = [txt]
    #raise Exception()
    r_template = '\s*[' + "".join(equal_to_space + ["\s"]) + '\s*]'
    answer = [" ".join([v for v in re.split(r_template, t) if len(v)>0]) for t in answer]

    return answer

def split_by_words(sentence, words):
    """
    Делает split предложения по stopwords
    """
    result = []
    tmp=[]
    for w in sentence.split():
        if w in words:
            if len(tmp)>0:
                result.append(' '.join(tmp))
                tmp=[]
        else:
            tmp.append(w)

    if len(tmp) > 0:
        result.append(' '.join(tmp))

    return result

def sentence_split(sentence, separators = ",;!?", stop_words = None):
    """
    Делает split предложения по указанным стоп-словам и сепараторам
    """

    r_template = fr"[{separators}]\s*"
    phrases = re.split(r_template, sentence)

    if not (stop_words is None):
        phrases = sum([split_by_words(phrase, stop_words) for phrase in phrases], [])

    return phrases


import ast
import logging
import sys

from flake8_requests import __version__
from flake8_requests.no_auth_over_http import NoAuthOverHttpVisitor
from flake8_requests.use_scheme import UseSchemeVisitor
from flake8_requests.use_timeout import UseTimeoutVisitor

logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stderr)
handler.setFormatter(
    logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
)
logger.addHandler(handler)

class Flake8Requests:
    name = "flake8-requests"
    version = __version__

    def __init__(self, tree, add_parents=True):
        self.tree = tree

    def run(self):
        visitors = [
            NoAuthOverHttpVisitor(),
            UseSchemeVisitor(),
            # UseTimeoutVisitor(),
        ]
        for visitor in visitors:
            visitor.visit(self.tree)

            for report in visitor.report_nodes:
                node = report["node"]
                message = report["message"]
                yield (
                    node.lineno,
                    node.col_offset,
                    message,
                    visitor.__class__.__name__,
                )

if __name__ == "__main__":
    import argparse

    logger.setLevel(logging.DEBUG)

    parser = argparse.ArgumentParser()
    # Add arguments here
    parser.add_argument("inputfile")

    args = parser.parse_args()

    logger.info(f"Parsing {args.inputfile}")
    with open(args.inputfile, "r") as fin:
        data = fin.read()
    tree = ast.parse(data)
    lines = data.split("\n")

    flake8plugin = Flake8Requests(tree)

    print("*** Hits:")
    results = flake8plugin.run()
    for report in results:
        print(report)


#! /usr/bin/env python

import os
import sys
import json
from uuid import uuid4
import logging
import socket
from os import path
from functools import wraps
from subprocess import Popen, PIPE
import datetime

from flask import Flask, request, make_response
from flask import render_template
from flask import g
from jinja2 import ChoiceLoader, FileSystemLoader
from werkzeug import secure_filename
from werkzeug.http import http_date
from werkzeug.routing import Submount, Map

from . import messages

STATIC_DIR = os.environ.get('STATIC_DIR', path.join(os.getcwd(), 'static'))
TEMPLATE_DIR = os.environ.get('TEMPLATE_DIR', path.join(os.getcwd(), 'templates'))
app = Flask(__name__, static_folder=STATIC_DIR, template_folder=TEMPLATE_DIR)

app.config['VERSION'] = os.environ.get('CURRENT_SHA', None)
app.config['X-HOSTNAME'] = os.environ.get('X_HOSTNAME', socket.gethostname())
app.config['BIND_INTERFACE'] = os.environ.get('BIND_INTERFACE', '127.0.0.1')
app.config['LOG_LEVEL'] = os.environ.get('LOG_LEVEL', 'INFO')
app.config['USER_HEADER_NAME'] = os.environ.get('USER_HEADER_NAME', 'Uid')
app.config['ROOT_STORAGE_PATH'] = os.environ.get("ROOT_STORAGE_PATH", "./storage")
app.config['CACHE_ROOT'] = os.environ.get('CACHE_ROOT', '%s/cache' % (app.config['ROOT_STORAGE_PATH']))
app.config['USE_RELOADER'] = os.environ.get('USE_RELOADER', 'True')
app.config['TEMPLATE_DIR'] = TEMPLATE_DIR
app.config['SUBMOUNT_PATH'] = os.environ.get('SUBMOUNT_PATH', None)
# this is to be a comman delimited list of sources for which events will be emitted
# this of course depends on the system supporting events for those sources
app.config['LOCAL_EVENT_SOURCES'] = frozenset(os.environ.get('LOCAL_EVENT_SOURCES', '').split(","))

app.jinja_loader = ChoiceLoader([
        FileSystemLoader("./templates"),
        FileSystemLoader("./pyserver/templates")
    ])

logging.basicConfig(
    format='%(asctime)s [%(levelname)s]: %(message)s',
    stream=sys.stderr,
    level=app.config['LOG_LEVEL']
)

process_start_time = datetime.datetime.now()

def emit_local_message(source, message=None):
    if source in app.config['LOCAL_EVENT_SOURCES']:
        wrapped = json.dumps(dict(source=source, message=message, user_token=g.user_token))
        messages.send(wrapped, messages.LOCAL_PUBLISH)

def get_storage_location(named):
    return path.abspath(path.join(app.config['ROOT_STORAGE_PATH'], named))

def remove_single_element_lists(d):
    new_dict = {}
    for key, value in list(d.items()):
        if type(value) == list and len(value) == 1:
            new_dict[key] = value[0]
        else:
            new_dict[key] = value
    return new_dict

def try_run(this):
    try:
        return this()
    except:
        return None

def convert_into_number(value):
    as_number = try_run(lambda: int(value)) or try_run(lambda: float(value))
    if as_number or as_number == 0:
        return as_number
    else:
        return value

def convert_types_in_dictionary(this_dictionary):
    into_this_dictionary = {}
    for key, value in list(this_dictionary.items()):
        if type(value) == dict:
            value = convert_types_in_dictionary(value)
        elif type(value) == list:
            value = convert_types_in_list(value)
        else:
            value = convert_into_number(value)
        into_this_dictionary[key] = value
    return into_this_dictionary

def convert_types_in_list(this_list):
    into_this_list = []
    for item in this_list:
        if type(item) == list:
            new_value = convert_types_in_list(item)
        elif type(item) == dict:
            new_value = convert_types_in_dictionary(item)
        else:
            new_value = convert_into_number(item)
        into_this_list.append(new_value)
    return into_this_list

def cache_my_response(vary_by=None, expiration_seconds=900):
    def cache_wrapper_decorator(f):
        @wraps(f)
        def cache_wrapper(*args, **kwargs):
            if not vary_by:
                cache_key = request.url
            else:
                from io import StringIO
                key_buffer = StringIO()
                key_buffer.write(request.url)
                for vary_by_this in vary_by:
                    key_buffer.write("%s" % request.values.get(vary_by_this, ''))
                cache_key = key_buffer.getvalue()
            cr = app.config['_CACHE'].get_or_return_from_cache(
                cache_key,
                expiration_seconds,
                lambda: f(*args, **kwargs),
                force_refresh = request.values.get('_reload_cache', False)
            )
            resp = app.make_response(cr[1])
            if cr[0]:
                resp.headers['Expires'] = http_date(cr[0])
            return resp
        return cache_wrapper
    return cache_wrapper_decorator

def make_my_response_json(f):
    @wraps(f)
    def view_wrapper(*args, **kwargs):
        try:
            view_return = f(*args, **kwargs)
            if type(view_return) == dict:
                return json_response(**view_return)
            elif type(view_return) == list:
                return json_response(view_return)
            elif type(view_return) == int:
                return json_response(**dict(status_code=view_return))
            elif type(view_return) == str:
                return json_response(view_return)
            elif type(view_return) == tuple:
                return json_response(view_return[0], status_code=view_return[1])
            else:
                return json_response(**{})
        except Exception as e:
            return json_response(**dict(status_code=400, description=e.description))
    return view_wrapper

def json_response(*args, **kwargs):
    """ Creates a JSON response for the given params, handling the creation a callback wrapper
        if a callback is provided, and allowing for either a string arg (expected to be JSON)
        or kwargs to be passed formatted correctly for the response.
        Also sets the Content-Type of the response to application/json
    """
    content_type = "application/json"
    # if provided, use the status code otherwise default to 200
    # we remove it so it doesn't end up in our response
    status_code = kwargs.pop('status_code', 200)

    # we're going to allow the callback to come essentially from wherever the user
    # choses to provide it, again remove it from kwargs so it doesn't end
    # up in the response
    callback = kwargs.pop('callback', None) or request.values.get('callback', None)

    # handle the response being a list of items
    if args:
        if type(args[0]) == list:
            response_string = json.dumps(args[0])
        # if the return is a string assume it's valid json
        elif type(args[0]) == str:
            response_string = json.dumps(args[0]) if callback else args[0]
    else:
        response_string = json.dumps(kwargs)

    if callback:
        response_string = "%s(%s);" % (callback, response_string)
        content_type = "application/javascript"
        # I know it's sucky but many clients will fail on jsonp requests
        # that return a 404
        if status_code == 404:
            status_code = 200

    headers = {"Content-Type": content_type, "Cache-Control": "no-cache", "Pragma": "no-cache"}

    return (
        response_string,
        status_code,
        headers
    )

def return_cors_response():
    headers = dict()
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, DELETE, PATCH'
    headers['Access-Control-Allow-Headers'] = request.headers.get('Access-Control-Request-Headers', '*')
    return ( "", 204, headers )

def global_response_handler(response):
    response.headers['Access-Control-Allow-Origin'] = request.headers.get('Origin', '*')
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['X-HOSTNAME'] = app.config['X-HOSTNAME']
    response.headers['X-APP-VERSION'] = app.config['VERSION']
    return response

def global_request_handler():
    # this needs to be safe for use by the app
    g.user_token = secure_filename(request.headers.get(app.config['USER_HEADER_NAME'], 'DEFAULT'))

app.process_response = global_response_handler
app.preprocess_request = global_request_handler

################################################################################
# views

@app.route("/", methods=["GET"])
@app.route("/diag", methods=["GET"])
@app.route("/diagnostic", methods=["GET"])
def pyserver_core_diagnostic_view():
    """
        Used to return the status of the application, including the version
        of the running application.

        :statuscode 200: returned as long as all checks return healthy
        :statuscode 500: returned in the case of any diagnostic tests failing
    """
    diag_info = {}
    diag_info['machine_name'] = socket.gethostname()
    diag_info['process_start_time'] = process_start_time.isoformat()
    diag_info['process_uptime_secs'] = (datetime.datetime.now() - process_start_time).seconds
    diag_info['server_port'] = os.environ.get('PORT', None)

    response = make_response(json.dumps(diag_info, sort_keys=True))
    response.headers['X-Robots-Tag'] = 'noindex'
    return response

@app.route("/diagnostic/echo", methods=["GET"])
@make_my_response_json
def pyserver_core_diagnostic_echo_view():
    """
        Helper endpoint for developing diagnostic checks.  Simply echoes back
        any values provided in the inbound request.

        :param '*': any inbound request parameters will be echoed back
        :statuscode 200: always returns OK
    """
    return request.values.to_dict()

@app.route("/diagnostic/fail", methods=["GET"])
def pyserver_core_fail():
    """ This endpoint is designed to show how the application fails.  Can be used
        to assist in creating monitors to check the application health and respond
        to failures.

        :statuscode 500: always returns failure
    """
    raise Exception("Test exception so you know how the app behaves")

@app.route("/message/local_publish", methods=["POST"])
@make_my_response_json
def pyserver_core_publish_message():
    """ Allows for publishing of a local message.  """
    if request.json:
        msg = json.dumps(request.json)
    else:
        data = request.values.to_dict(flat=False)
        msg = convert_types_in_dictionary(remove_single_element_lists(data))
        msg = json.dumps(msg)
    messages.send(msg, messages.LOCAL_PUBLISH)
    return dict(message="ok")

# end views
################################################################################

@app.errorhandler(500)
def general_error_handler(error):
    et, ev, tb = sys.exc_info()
    assert ev == error
    eid = str(uuid4())
    logging.error("unhandled exception(%s):" % (eid), exc_info = (et, ev, tb))
    context = dict(eid=eid)
    if request.content_type and 'json' in request.content_type:
        return (render_template("500.json", **context),
            500,
            {"Content-Type": "application/json"})
    else:
        return render_template("500.html", **context), 500

from .core_handlers import keyvalue_handlers, echo


#!/usr/bin/env python
import telebot
from telebot import types
import const
from geopy.distance import vincenty

bot = telebot.TeleBot(token=const.API_TOKEN)

markup_menu = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn_address = types.KeyboardButton('Отправка вашей геолокации', request_location=True)
btn_payment = types.KeyboardButton('Просто кнопка')
btn_delivery = types.KeyboardButton('Просто кнопка2')

markup_menu.add(btn_address, btn_delivery, btn_payment)

markup_inline_payment = types.InlineKeyboardMarkup()
btn_in_cash = types.InlineKeyboardButton('Наличные', callback_data='cash')
btn_in_card = types.InlineKeyboardButton('Картой', callback_data='card')
btn_in_invoice = types.InlineKeyboardButton('Банковский перевод', callback_data='invoice')

markup_inline_payment.add(btn_in_cash, btn_in_card, btn_in_invoice)

photo = open('image2.jpg', 'rb')
@bot.message_handler(commands=['photo'])
def send_photo(message):
    bot.send_photo(message.chat.id, photo)

audio = open('audio.mp3', 'rb')
@bot.message_handler(commands=['audio'])
def send_photo(message):
    bot.send_audio(message.chat.id, audio)

doc = open('file.txt', 'rb')
@bot.message_handler(commands=['doc'])
def send_doc(message):
    bot.send_document(message.chat.id, doc)

sti = open('sticker.webp', 'rb')
@bot.message_handler(commands=['sticker'])
def send_sticker(message):
    bot.send_sticker(message.chat.id, sti)

@bot.message_handler(commands=['start'])
def send_welcome(message):
	bot.reply_to(message,   "Здраствуйте, я тестовый бот, который был создан исключительно в ознакомительных целях.\n"
                            "Моя задача - продемонстрировать функционал подобных мне ботов.")

@bot.message_handler(commands=['menu'])
def send_menu(message):
    bot.reply_to(message, "Ваше меню", reply_markup=markup_menu)

@bot.message_handler(commands=['help'])
def send_message(message):
	bot.reply_to(message,   "/start - Краткое описание бота\n/help - список команд с их описанием\n"
                            "/menu - показывает меню из 3-х кнопок\n"
                            "/photo - отправляем фото\n"
                            "/audio - отправляем аудио\n"
                            "/sticker - отправляем стикер\n"
                            "/doc - отправляем .txt файл\n"
                 )

@bot.message_handler(func=lambda message: True)
def echo_all(message):
    if message.text == "Просто кнопка":
        bot.reply_to(message, "Доставка курьером, самовывоз, Новая почта")
    elif message.text == "Просто кнопка2":
        bot.reply_to(message, "В наших магазинах доступны следующие способы оплаты",
                     reply_markup=markup_inline_payment)
    else:
	    bot.reply_to(message, "Я бот! Я не понимаю вас!\nБудьте любезны, используйте команды /help .")

@bot.message_handler(func=lambda message: True, content_types=['location'])
def shop_location(message):
    lon = message.location.longitude
    lat = message.location.latitude

    distance = []
    for m in const.SHOP:
        result = vincenty((m['latm'], m['lonm']), (lat, lon)).kilometers
        distance.append(result)
    index = distance.index(min(distance))

    bot.send_message(message.chat.id, 'Ближайший магазин')
    bot.send_venue(message.chat.id,
                   const.SHOP[index]['latm'],
                   const.SHOP[index]['lonm'],
                   const.SHOP[index]['title'],
                   const.SHOP[index]['address'])

@bot.callback_query_handler(func=lambda call: True)
def call_back_paymen(call):
    if call.data == 'cash':
        bot.send_message(call.message.chat.id, text="""
            Наличная Оплата производится в золоте! Всего лишь нужно посетить магазин.
        """, reply_markup=markup_inline_payment)

bot.polling()


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('add/', views.addTodo, name='add'),
    path('complete/<str:todo_id>/', views.completeTodo, name='complete'),
    path('deletecomplete/', views.delete_completed, name='deletecomplete')
]