load("//:visibility.bzl", "RULES_KOTLIN")
load("//kotlin/common/testing:analysis.bzl", "kt_analysis")
load("//kotlin/common/testing:asserts.bzl", "kt_asserts")
load("@bazel_skylib//lib:sets.bzl", "sets")
load("@bazel_skylib//lib:unittest.bzl", "analysistest", "asserts")

visibility(RULES_KOTLIN)

kt_jvm_library_analysis_test = analysistest.make(
    impl = lambda ctx: _kt_jvm_library_analysis_test_impl(ctx),
    attrs = dict(
        expected_al_ruleset_names = attr.string_list(
            doc = "Android Lint rule JARs reported as run on the given target",
            default = kt_analysis.DEFAULT_LIST,
        ),
        expected_compile_jar_names = attr.string_list(
            doc = "Names of all JavaInfo::compile_jars for the given target",
            default = kt_analysis.DEFAULT_LIST,
        ),
        expected_exported_processor_jar_names = attr.string_list(
            doc = "Names of all JavaInfo::plugins JARs returned by the given target",
            default = kt_analysis.DEFAULT_LIST,
        ),
        expected_exported_processor_classes = attr.string_list(
            doc = "Annotation processors reported as to be run on depending targets",
        ),
        expected_processor_classes = attr.string_list(
            doc = "Annotation processors reported as run on the given target",
        ),
        expected_kotlinc_plugin_jar_names = attr.string_list(
            doc = "Names of all -Xplugin= JARs",
            default = kt_analysis.DEFAULT_LIST,
        ),
        expected_friend_jar_names = attr.string_list(
            doc = "Names of all -Xfriend-paths= JARs",
            default = kt_analysis.DEFAULT_LIST,
        ),
        expected_runfile_names = attr.string_list(
            doc = "Names of all runfiles",
            default = kt_analysis.DEFAULT_LIST,
        ),
        expect_jdeps = attr.bool(default = True),
        expect_processor_classpath = attr.bool(),
        expect_neverlink = attr.bool(),
        required_mnemonic_counts = attr.string_dict(
            doc = "Expected mnemonics to expected action count; unlisted mnemonics are ignored",
        ),
    ),
)

def _kt_jvm_library_analysis_test_impl(ctx):
    kt_analysis.check_endswith_test(ctx)

    env = analysistest.begin(ctx)
    actual = ctx.attr.target_under_test

    actions = analysistest.target_actions(env)
    kt_al_action = kt_analysis.get_action(actions, "KtAndroidLint")

    asserts.true(
        env,
        JavaInfo in actual,
        "kt_jvm_library did not produce JavaInfo provider.",
    )
    asserts.true(
        env,
        ProguardSpecProvider in actual,
        "Expected a ProguardSpecProvider provider.",
    )

    if ctx.attr.expected_runfile_names != kt_analysis.DEFAULT_LIST:
        asserts.set_equals(
            env,
            sets.make(ctx.attr.expected_runfile_names),
            sets.make([
                f.basename
                for f in actual[DefaultInfo].data_runfiles.files.to_list()
            ]),
        )

    if ctx.attr.expected_compile_jar_names != kt_analysis.DEFAULT_LIST:
        asserts.set_equals(
            env,
            sets.make(ctx.attr.expected_compile_jar_names),
            sets.make([f.basename for f in actual[JavaInfo].compile_jars.to_list()]),
            "kt_jvm_library JavaInfo::compile_jars",
        )

    if ctx.attr.expected_exported_processor_jar_names != kt_analysis.DEFAULT_LIST:
        asserts.set_equals(
            env,
            sets.make(ctx.attr.expected_exported_processor_jar_names),
            sets.make([f.basename for f in actual[JavaInfo].plugins.processor_jars.to_list()]),
        )

    asserts.set_equals(
        env,
        sets.make(ctx.attr.expected_exported_processor_classes),
        sets.make(actual[JavaInfo].plugins.processor_classes.to_list()),
    )

    kt_2_java_compile = kt_analysis.get_action(actions, "Kt2JavaCompile")

    if kt_2_java_compile:
        asserts.true(
            env,
            kt_2_java_compile.outputs.to_list()[0].basename.endswith(".jar"),
            "Expected first output to be a JAR (this affects the param file name).",
        )

    if ctx.attr.expected_friend_jar_names != kt_analysis.DEFAULT_LIST:
        friend_paths_arg = kt_analysis.get_arg(kt_2_java_compile, "-Xfriend-paths=")
        kt_asserts.list_matches(
            env,
            expected = ["/" + x for x in ctx.attr.expected_friend_jar_names],
            actual = friend_paths_arg.split(",") if friend_paths_arg else [],
            matcher = lambda expected, actual: actual.endswith(expected),
            items_name = "friend JARs",
        )

    if ctx.attr.expected_kotlinc_plugin_jar_names != kt_analysis.DEFAULT_LIST:
        kt_asserts.list_matches(
            env,
            expected = ["/" + x for x in ctx.attr.expected_kotlinc_plugin_jar_names],
            actual = kt_analysis.get_all_args(kt_2_java_compile, "-Xplugin="),
            matcher = lambda expected, actual: actual.endswith(expected),
            items_name = "kotlinc plugin JARs",
        )

    asserts.equals(
        env,
        ctx.attr.expect_neverlink,
        len(actual[JavaInfo].transitive_runtime_jars.to_list()) == 0,
        "Mismatch: Expected transitive_runtime_jars iff (neverlink == False)",
    )

    kt_asserts.required_mnemonic_counts(env, ctx.attr.required_mnemonic_counts, actions)

    return analysistest.end(env)


from fastapi import Response, status, HTTPException, Depends, APIRouter
from .. import models, schemas
from ..database import get_db
from sqlalchemy.orm import Session
from typing import List, Optional
from app.oauth2 import get_current_user
from sqlalchemy import func

router = APIRouter(prefix='/posts', tags=['Posts'])

### READ ALL POSTS ###
@router.get('/',response_model=List[schemas.PostOut])
def get_posts(db: Session = Depends(get_db),
              current_user: int = Depends(get_current_user),
              limit: int = 3,skip: int = 0,
              search: Optional[str] = ""
              ):

    post= db.query(
        models.Post, func.count(models.Votes.post_id).label("votes")).join(
        models.Votes, models.Votes.post_id == models.Post.id, isouter=True).group_by(
        models.Post.id).filter(
        models.Post.title.contains(search)).limit(limit).offset(skip).all()
    return post

### CREATE NEW POST ###
@router.post('/', status_code=status.HTTP_201_CREATED,response_model=schemas.Post)
def create_post(post: schemas.PostCreate,
                db: Session = Depends(get_db),
                current_user: int = Depends(get_current_user)):
    new_post = models.Post(owner_id = current_user.id,
                            **post.dict())
   #CREATE COMIT AND REFRESH
    db.add(new_post)
    db.commit()
    db.refresh(new_post)
    return new_post

### READ LAST POST ###
@router.get('/last',
            response_model=schemas.Post)
def read_posts(db: Session = Depends(get_db)):
    posts = db.query(models.Post).order_by(models.Post.id.desc()).first()
    return posts

### READ POST BY ID ##
@router.get('/{id}',
            response_model=schemas.Post)
def get_post(id: int,
             db: Session = Depends(get_db),
             current_user: int = Depends(get_current_user)):
    my_posts = db.query(models.Post).filter(models.Post.id == id).first()

    #CHECK IF POST EXISTS
    if not my_posts:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail="Post not found")

    return my_posts

### DELETE POST ###
@router.delete('/{id}',
               status_code=status.HTTP_204_NO_CONTENT,)
def delete(id: int,
           db: Session = Depends(get_db),
           current_user: int = Depends(get_current_user)):

    #FIND POST BY ID
    post_query = db.query(models.Post).filter(models.Post.id == id)
    post = post_query.first()

    #CHECK IF POST EXISTS
    if post == None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail="Post not found")

    #CHECK IF OWNER IS THE CURRENT USER
    if post.owner_id != current_user.id:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
                            detail="You are not the owner of this post")
    #DELETE POST
    post_query.delete()
    db.commit()
    return Response(status_code=status.HTTP_204_NO_CONTENT)

### UPDATE POST ###
@router.put('/{id}',status_code=status.HTTP_202_ACCEPTED,response_model=schemas.Post)
def update_post(id: int, post: schemas.PostCreate, db: Session = Depends(get_db),current_user: int = Depends(get_current_user)):

    #FIND POST BY ID AND TAKE FIRST RESULT
    my_posts_query = db.query(models.Post).filter(models.Post.id == id)
    my_post = my_posts_query.first()
    #CHECK IF POST EXISTS
    if my_post == None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,)

    #CHECK IF OWNER IS THE CURRENT USER
    if my_post.owner_id != current_user.id:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
                            detail="You are not the owner of this post")
    #UPDATE POST
    my_posts_query.update(post.dict(), synchronize_session=False)
    db.commit()

    return my_posts_query.first()


import yaml
import parser
from names import assert_keys

def get_config(name):
    with open(name) as f:
        return yaml.load(f.read())

def parse_proxy(item, t):
    parsed = parser.parse(item)
    if parsed[0] != 'proxy':
        raise ValueError("parse error %s " % parsed)
    config = parsed[1]
    assert_keys(config, ['actual', 'mapsto'])
    config['type'] = t
    return config

def parse_interpreter(item):
    parsed = parser.parse(item)
    if parsed[0] != 'interpreter':
        raise ValueError("parse error %s " % parsed)
    config = parsed[1][1]
    return config

def parse_proxy_list(lst, t):
    proxies = []
    if lst:
        for item in lst:
            proxies.append(parse_proxy(item, t))
    return proxies

def parse_spec(str):
    return []


#!/usr/bin/python3
#This program was created to build 2D plots of the R/Q values which were prepared by CST2018. Also one will have linearity checking plot for 0.0 horizontal line
#Input - .txt file with strings with one number. Output - 2Dplot
#Idea of the input file structure is given by CST modelling. Here - we have loop over all y for each x

#"All X for every Y data" means next data structure:
#	R/Q(X1,Y1) R/Q(X2,Y1) ... R/Q(Xn,Y1)
#	R/Q(X1,Y2) R/Q(X2,Y2) ... R/Q(Xn,Y2)
#           ...
#	R/Q(X1,Yn) R/Q(X2,Yn) ... R/Q(Xn,Yn)

#"All Y for every X data" means next data structure:
#	R/Q(X1,Y1) R/Q(X1,Y2) ... R/Q(X1,Yn)
#	R/Q(X2,Y1) R/Q(X2,Y2) ... R/Q(X2,Yn)
#           ...
#	R/Q(Xn,Y1) R/Q(Xn,Y2) ... R/Q(Xn,Yn)
#	difference one can see when "meshgrid" will be applied

import fileinput
import numpy as np
import sys
from math import sqrt
import matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
matplotlib.rcParams.update({'font.size': 15})
import os.path

def fit_function(x, a, b):
	"""
	Line
	"""
	x = np.asarray(x)
	return b + a *x

class PlotCST:
	def __init__(self):
		self.datafile = sys.argv[1]
		self.direction = sys.argv[2]
		self.line = float(sys.argv[3])
		self.xstart = float(sys.argv[4])
		self.xstop = float(sys.argv[5])
		self.xsteps = int(sys.argv[6])
		self.ystart = float(sys.argv[7])
		self.ystop = float(sys.argv[8])
		self.ysteps = int(sys.argv[9])
		self.xcoord = []
		self.ycoord = []
		self.new_file = self.datafile.replace(".txt", "dot.txt")
		self.old_symbol = ','
		self.new_symbol = '.'

	def symbol_change(self):
		with open(self.new_file, "w", encoding = 'utf-8') as f:
			for line in fileinput.input([self.datafile], inplace = False):
				f.write(line.replace(self.old_symbol, self.new_symbol))
		self.datafile = self.new_file

	def get_CST_data(self): #this function returns XY coordinates for mesh and reshaped R/Q data
		self.dataset = np.genfromtxt( self.datafile, skip_header = 15)#skip internal file description + first point created by first calculation of the field
		self.dataset = self.dataset.reshape(len(self.dataset), 2) #for dividing the string number and data

		for x in range(self.xsteps):
			self.xcoord.append(round ( self.xstart + (self.xstop - self.xstart) / (self.xsteps - 1) * x ,4))
		for y in range(self.ysteps):
			self.ycoord.append(round ( self.ystart + (self.ystop - self.ystart) / (self.ysteps - 1) * y ,4))

		dataset=self.dataset[:, 1].reshape(len(self.ycoord), len(self.xcoord))  #for all Y for every X data
		dataset=np.transpose(dataset) #Uncomment if you work with  "All X for every Y data"

		return self.xcoord, self.ycoord, dataset

	def linear_fit(self, dataset, line): # do linear fit and get errors of parameters
		linecounter = 0
		dataarray = []
		if self.direction == 'h': #when we check linearity along horizontal axis
			x = self.xcoord # already pick an array of all X coordinates
			for coordinate in self.ycoord: #for every position of horizontal fitting
				if coordinate == float(line): #when we found our line
					RQ = dataset [linecounter,:] # to use RQ data from all Y for certain line
					break
				else:
					linecounter += 1 #our data is deeper in array

		if self.direction == 'v': #when we check linearity along vertical axis
			x = self.ycoord # already pick an array of all Y coordinates
			for coordinate in self.xcoord: #for every position of vertical fitting
				if coordinate == float(line): #when we found our line
					RQ = dataset [:, linecounter] # to use RQ data from all X for certain line
					break
				else:
					linecounter += 1 #our data is deeper in array
		#print (RQ)
		#print (x)
		perr=[]
		#linfunc = lambda a,b,x: a*x+b
		#popt, pcov = curve_fit(linfunc, x, RQ) #popt - optimal Hi-square min values for the fit parameters in this point

		slope = 34
		b = -190
		p = (b, slope)
		#popt, pcov = curve_fit(fit_function, x, RQ)
		popt, pcov = curve_fit(fit_function, x, RQ, p0=p)
		fit = [popt[1]*X + popt[0] for X in x] # for every x coordinate fit function = a*x+b
		perr = np.sqrt(np.diag(pcov))
		'''
		for i in range(len(x)):
			perr.append(np.sqrt( (RQ[i] - (popt[1]*x[i] + popt[0]) )**2 )) #RMS formula
		print(perr)
		'''
		return x, RQ, fit, popt, perr

	def rqmap_fitplot(self): #function to check if everything works as it has to. Change it on your own.
		Mydata = PlotCST() #read all parameters from terminal
		mesharray = Mydata.get_CST_data() #get mesh coordinates and R/Q
		X = mesharray[0]
		Y = mesharray[1]
		Z = mesharray[2]
		x, z, fit, popt, perr = Mydata.linear_fit(mesharray[2], Mydata.line) # get array of x-coordinate, R/Q according to Y line and X point and A and B from fit F=A*x+B
		#print("a = ", popt[1], " b = ", popt[0])
		#print("as = ", perr[1], "bs = ", perr[0])

		matplotlib.rcParams.update({'font.size': 12})
		#matplotlib.rcParams['axes.edgecolor'] = 'limegreen'
		#matplotlib.rcParams['axes.facecolor'] = 'black'
		#matplotlib.rcParams['axes.labelcolor'] = 'limegreen'
		#matplotlib.rcParams['xtick.color'] = 'limegreen'
		#matplotlib.rcParams['ytick.color'] = 'limegreen'
		#matplotlib.rcParams['text.color'] = 'limegreen'
		#matplotlib.rcParams['figure.facecolor'] = 'black'
		matplotlib.rcParams['figure.figsize'] = (8, 3)
		#save_path = '/home/skye/Documents/_My_Science/GSIReport2.05.2019R3DALINAC/images/'
		'''
		plt.xlabel('X-position, m')
		plt.ylabel('Y-position, m')
		plt.title('RQ map')
		plt.contourf(X, Y, Z, 100)
		plt.colorbar()
		plt.tight_layout()
		plt.savefig('2pipeR3Elbigcf.pdf')
		plt.show()
		'''
		plt.xlabel('X-position, m')
		plt.ylabel('Y-position, m')
		plt.title('RQ map')
		plt.contour(X, Y, Z, 100)
		plt.colorbar()
		plt.tight_layout()
		plt.savefig('Dael80.pdf')
		plt.show()

		plt.xlabel('X-position, m')
		plt.ylabel('R/Q along center left to the right')
		plt.plot(x, z, 'r-')
		plt.plot(x, fit_function(x, popt[0], popt[1]), 'g--')
		plt.tight_layout()
		plt.title('Resolution map')
		plt.savefig('Dael80Lin.pdf') #, bbox_inches='tight'
		plt.show()

if __name__ == '__main__':
	M=PlotCST()
	M.rqmap_fitplot()


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

from django.db import migrations, models
import django_hstore.fields

class Migration(migrations.Migration):

    dependencies = [
        ('development', '0034_developmentproject_location_description'),
    ]

    operations = [
        migrations.AddField(
            model_name='developmentproject',
            name='misc_textareas',
            field=django_hstore.fields.DictionaryField(null=True, blank=True),
        ),
    ]


################### MT19AIE323 #################

## The program is for showing different option for entering user's details for predicting whether the person
# is having desease or not

import pickle
import streamlit as st
from streamlit_option_menu import option_menu
import re
import preprocess_kgptalkie as ps
from sklearn.feature_extraction.text import TfidfVectorizer
import tweepy as tw
import pandas as pd
from gensim.models import KeyedVectors
import ftfy
from nltk.corpus import stopwords
from nltk import PorterStemmer
import nltk
from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences
import numpy as np

backgroundColor = '#273346'

# loading the saved models

# Load ML model
survey_model = pickle.load(open('D:/MTech/Semester VI/MTP/saved models/mt19aie323_mentaldisorderprediction_survey_model.pkl', 'rb'))
diabetes_model = pickle.load(open('D:/MTech/Semester VI/MTP/saved models/mt19aie323_diabetes_model.sav', 'rb'))
heart_disease_model = pickle.load(open('D:/MTech/Semester VI/MTP/saved models/mt19aie323_heart_disease_model.sav','rb'))
suicidal_prediction_model = pickle.load(open('D:/MTech/Semester VI/MTP/saved models/mt19aie323-twitter-suicidal-model.pkl', 'rb'))

# sidebar for navigation
with st.sidebar:

    selected = option_menu('Mental Disorder, Suicidal,Diabetes and Heart Desease Prediction System',
                          ['Mental Disorder Prediction on Survey Data',
                           'Suicidal Thought on Twitter Profile',
                           'Depression on Twitter Profile',
                           'Diabetes Prediction',
                           'Heart Disease Prediction'],
                          icons=['person','twitter','twitter','activity','heart'],
                          default_index=0)

# Mental Disorder Prediction on Survey Data
if (selected == 'Mental Disorder Prediction on Survey Data'):
    # page title
    st.title('Mental Disorder Prediction on Survey Data')
    # getting the input data from the user
    col1, col2, col3,col4 = st.columns(4,gap="large")

    with col1:

         FHMDoption=('Yes', 'No', 'Do not know')
         FHMD = st.selectbox("Do you have Mental Illness family History?", range(len(FHMDoption)), format_func=lambda x: FHMDoption[x])

    with col2:

         CZoption=('1-5', '6-25', '26-100','101-500','501-1000','More than 1000','Do not know')
         CZ = st.selectbox("What is your company size?", range(len(CZoption)), format_func=lambda x: CZoption[x])
    with col3:
         SurveyYoption=('2014', '2016', '2017','2018','2019')
         SurveyY = st.selectbox("What is year of the Survey?", range(len(SurveyYoption)), format_func=lambda x: SurveyYoption[x])

    with col4:
        Age = st.text_input('What is your Age?')

    with col1:
        if Age<'20':
            AgeG = st.text('0-20')
            AgeG1=1
        elif Age>'20' and Age<='30':
            AgeG = st.text('21-30')
            AgeG1=2
        elif Age>'30' and Age<='40':
            AgeG = st.text('31-40')
            AgeG1=3
        elif Age>'40' and Age<='65':
            AgeG = st.text('41-65')
            AgeG1=4
        elif Age>'65' and Age<='100':
            AgeG = st.text('66-100')
            AgeG1=5
        else:
            AgeG = st.text('66-100')
            AgeG1=6

    with col2:
         Genoption=('Male', 'Female', 'Do not disclosed')
         Gen = st.selectbox("What is your gender?", range(len(Genoption)), format_func=lambda x: Genoption[x])
    with col3:

         PreferAnonymityoption=('Yes', 'No','Do not know')
         PreferAnonymity = st.selectbox("Do you Prefer Anonymity?", range(len(PreferAnonymityoption)), format_func=lambda x: PreferAnonymityoption[x])

    with col4:

         RtPoption=('Above Average', 'Below Average', 'Do not know')
         RtP = st.selectbox("How do you rate Reaction to Problems?", range(len(RtPoption)), format_func=lambda x: RtPoption[x])

    with col1:

         NegConseqoption=('Yes', 'No', 'May be','Do not know')
         NegConseq = st.selectbox("Do you feel  Negative Consequences?", range(len(NegConseqoption)), format_func=lambda x: NegConseqoption[x])

    with col2:

         AcessToInfooption=('Yes', 'No')
         AcessToInfo = st.selectbox("Do you feel problem in accessing Information?", range(len(AcessToInfooption)), format_func=lambda x: AcessToInfooption[x])

    with col3:
         Insuranceoption=('Yes', 'No','Do not know')
         Insurance = st.selectbox("Do you have Insurance?", range(len(Insuranceoption)), format_func=lambda x: Insuranceoption[x])

    with col4:
         Diagnosisoption=('Yes', 'No','Sometime','Do not know')
         Diagnosis = st.selectbox("Did you diagnosis Mental Disorder?", range(len(Diagnosisoption)), format_func=lambda x: Diagnosisoption[x])

    with col1:
         DMHPoption=('Yes', 'No','Maybe','Do not know')
         DMHP = st.selectbox("Is your company is responsible employer?", range(len(DMHPoption)), format_func=lambda x: DMHPoption[x])

    with col2:
        ResEmpoption=('Yes', 'No','Maybe','Self-Employed','Do not know')
        ResEmp = st.selectbox("Is your company is responsible employer?", range(len(ResEmpoption)), format_func=lambda x: ResEmpoption[x])

    with col3:
        Disorderoption=('Yes', 'No')
        Disorder = st.selectbox("Do you have Disorder?", range(len(Disorderoption)), format_func=lambda x: Disorderoption[x])
    with col4:
        PriTechCompoption=('Yes', 'No','Do not know')
        PriTechComp = st.selectbox("Are you working in Sofware Company?", range(len(PriTechCompoption)), format_func=lambda x: PriTechCompoption[x])

    print(AgeG1)
    # creating a button for Prediction
    survey_diagnosis = ''

    print(CZ)
    print(SurveyY)
    print(Age)
    print(AgeG1)
    print(Gen)
    print(PreferAnonymity)
    print(RtP)

    if st.button('Mental Disorder Prediction on SurveyData Test Result'):
        survey_diagnosis = survey_model.predict([[FHMD, CZ, SurveyY, Age, AgeG1, Gen,PreferAnonymity,RtP,NegConseq,AcessToInfo,Insurance,Diagnosis,DMHP,ResEmp,Disorder,PriTechComp]])
        print("predicted figure")
        print(survey_diagnosis)
        if (survey_diagnosis[0] == 1):
          survey_diagnosis = 'The person is having mental Disorder'
        else:
          survey_diagnosis = 'The person is not having mental Disorder'

    st.success(survey_diagnosis)

# Suicidal Prediction on Tweets
if (selected == 'Suicidal Thought on Twitter Profile'):
    # page title
    st.title('Suicidal Thought on Twitter Profile')
    # getting the input data from the user
    col1, col2, col3 = st.columns(3,gap="large")

    with col1:
        screen_name = st.text_input('Screen name')
    with col2:
        consumer_key = st.text_input('consumer key')
    with col3:
        consumer_secret = st.text_input('consumer secret')
    with col1:
        access_token = st.text_input('access token')
    with col2:
        access_token_secret = st.text_input('access token secret')

    # code for Prediction
    ## Data cleaning function
    def fn_get_clean(x):
        x = str(x).lower().replace('\\', '').replace('_', ' ')
        x = ps.cont_exp(x)
        x = ps.remove_emails(x)
        x = ps.remove_urls(x)
        x = ps.remove_html_tags(x)
        x = ps.remove_rt(x)
        x = ps.remove_accented_chars(x)
        x = ps.remove_special_chars(x)
        x = re.sub("(.)\\1{2,}", "\\1", x)
        return x

    tweets_diagnosis = ''
    if st.button('Suicidal Prediction result on tweets'):
        # # Authenticate to Twitter
        auth = tw.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token,access_token_secret)
        api = tw.API(auth)
        # Get the User object for twitter...
        #user = api.get_user(screen_name='SushilDwid')
        posts = api.user_timeline(screen_name=screen_name,count=100, tweet_mode="extended")

        tfidf=TfidfVectorizer(max_features=1000,ngram_range=(1,3),analyzer='char')
        df1=pd.DataFrame([tweet.full_text for tweet in posts] , columns=['Tweets'])
        ## Clean the tweets
        df1['Tweets']=df1['Tweets'].apply(lambda x:fn_get_clean(x))
        X1=tfidf.fit_transform(df1['Tweets'])
        #Prediction on tweets
        y_pred1=suicidal_prediction_model.predict(X1)
        num_correct = 0
        for i in range(len(y_pred1)):
            if y_pred1[i] == 1:
                num_correct += 1
        accuracy=(num_correct/len(y_pred1)*100)

        if (accuracy>8):
          tweets_diagnosis = 'Person is having suicidal thought'
        else:
          tweets_diagnosis = 'Person is not having suicidal thought'

    st.success(tweets_diagnosis)

# Depression Prediction on Tweets
if (selected == 'Depression on Twitter Profile'):
    # page title
    st.title('Depression on Twitter Profile')
    # getting the input data from the user
    col1, col2, col3 = st.columns(3,gap="large")

    with col1:
        screen_name = st.text_input('Screen name')
    with col2:
        consumer_key = st.text_input('consumer key')
    with col3:
        consumer_secret = st.text_input('consumer secret')
    with col1:
        access_token = st.text_input('access token')
    with col2:
        access_token_secret = st.text_input('access token secret')

    # code for Prediction
    MAX_SEQUENCE_LENGTH = 140 # Max tweet size
    MAX_NB_WORDS = 2000
    EMBEDDING_FILE = 'D:/MTech/Semester VI/MTP/GoogleNews-vectors-negative300.bin.gz'
    #user = api.get_user(screen_name='SushilDwid')
    word2vec = KeyedVectors.load_word2vec_format(EMBEDDING_FILE, binary=True)
    # Expand Contraction
    cList = {
      "ain't": "am not",
      "aren't": "are not",
      "can't": "cannot",
      "can't've": "cannot have",
      "'cause": "because",
      "could've": "could have",
      "couldn't": "could not",
      "couldn't've": "could not have",
      "didn't": "did not",
      "doesn't": "does not",
      "don't": "do not",
      "hadn't": "had not",
      "hadn't've": "had not have",
      "hasn't": "has not",
      "haven't": "have not",
      "he'd": "he would",
      "he'd've": "he would have",
      "he'll": "he will",
      "he'll've": "he will have",
      "he's": "he is",
      "how'd": "how did",
      "how'd'y": "how do you",
      "how'll": "how will",
      "how's": "how is",
      "I'd": "I would",
      "I'd've": "I would have",
      "I'll": "I will",
      "I'll've": "I will have",
      "I'm": "I am",
      "I've": "I have",
      "isn't": "is not",
      "it'd": "it had",
      "it'd've": "it would have",
      "it'll": "it will",
      "it'll've": "it will have",
      "it's": "it is",
      "let's": "let us",
      "ma'am": "madam",
      "mayn't": "may not",
      "might've": "might have",
      "mightn't": "might not",
      "mightn't've": "might not have",
      "must've": "must have",
      "mustn't": "must not",
      "mustn't've": "must not have",
      "needn't": "need not",
      "needn't've": "need not have",
      "o'clock": "of the clock",
      "oughtn't": "ought not",
      "oughtn't've": "ought not have",
      "shan't": "shall not",
      "sha'n't": "shall not",
      "shan't've": "shall not have",
      "she'd": "she would",
      "she'd've": "she would have",
      "she'll": "she will",
      "she'll've": "she will have",
      "she's": "she is",
      "should've": "should have",
      "shouldn't": "should not",
      "shouldn't've": "should not have",
      "so've": "so have",
      "so's": "so is",
      "that'd": "that would",
      "that'd've": "that would have",
      "that's": "that is",
      "there'd": "there had",
      "there'd've": "there would have",
      "there's": "there is",
      "they'd": "they would",
      "they'd've": "they would have",
      "they'll": "they will",
      "they'll've": "they will have",
      "they're": "they are",
      "they've": "they have",
      "to've": "to have",
      "wasn't": "was not",
      "we'd": "we had",
      "we'd've": "we would have",
      "we'll": "we will",
      "we'll've": "we will have",
      "we're": "we are",
      "we've": "we have",
      "weren't": "were not",
      "what'll": "what will",
      "what'll've": "what will have",
      "what're": "what are",
      "what's": "what is",
      "what've": "what have",
      "when's": "when is",
      "when've": "when have",
      "where'd": "where did",
      "where's": "where is",
      "where've": "where have",
      "who'll": "who will",
      "who'll've": "who will have",
      "who's": "who is",
      "who've": "who have",
      "why's": "why is",
      "why've": "why have",
      "will've": "will have",
      "won't": "will not",
      "won't've": "will not have",
      "would've": "would have",
      "wouldn't": "would not",
      "wouldn't've": "would not have",
      "y'all": "you all",
      "y'alls": "you alls",
      "y'all'd": "you all would",
      "y'all'd've": "you all would have",
      "y'all're": "you all are",
      "y'all've": "you all have",
      "you'd": "you had",
      "you'd've": "you would have",
      "you'll": "you you will",
      "you'll've": "you you will have",
      "you're": "you are",
      "you've": "you have"
    }

    c_re = re.compile('(%s)' % '|'.join(cList.keys()))

    def expandContractions(text, c_re=c_re):
        def replace(match):
            return cList[match.group(0)]
        return c_re.sub(replace, text)

    def clean_tweets(tweets):
        cleaned_tweets = []
        for tweet in tweets:
            tweet = str(tweet)
            # if url links then dont append to avoid news articles
            # also check tweet length, save those > 10 (length of word "depression")
            if re.match("(\w+:\/\/\S+)", tweet) == None and len(tweet) > 10:
                #remove hashtag, @mention, emoji and image URLs
                tweet = ' '.join(re.sub("(@[A-Za-z0-9]+)|(\#[A-Za-z0-9]+)|(<.>)|(pic\.twitter\.com\/.*)", " ", tweet).split())

                #fix weirdly encoded texts
                tweet = ftfy.fix_text(tweet)

                #expand contraction
                tweet = expandContractions(tweet)

                #remove punctuation
                tweet = ' '.join(re.sub("([^0-9A-Za-z \t])", " ", tweet).split())

                #stop words
                stop_words = set(stopwords.words('english'))
                word_tokens = nltk.word_tokenize(tweet)
                filtered_sentence = [w for w in word_tokens if not w in stop_words]
                tweet = ' '.join(filtered_sentence)

                #stemming words
                tweet = PorterStemmer().stem(tweet)

                cleaned_tweets.append(tweet)

        return cleaned_tweets

    depression_diagnosis = ''

    # creating a button for Prediction

    if st.button('Depression on Twitter Profile'):
        print("Depression Test")
        # Authenticate to Twitter
        auth = tw.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token,access_token_secret)
        api = tw.API(auth)
        posts = api.user_timeline(screen_name=screen_name,count=100, tweet_mode="extended")
        df1=pd.DataFrame([tweet.full_text for tweet in posts] , columns=['Tweets'])
        depressive_tweets_arr = [x for x in df1['Tweets']]
        X_d = clean_tweets(depressive_tweets_arr)
        tokenizer = Tokenizer(num_words=MAX_NB_WORDS)
        tokenizer.fit_on_texts(X_d)
        sequences_d = tokenizer.texts_to_sequences(X_d)
        data_d = pad_sequences(sequences_d, maxlen=MAX_SEQUENCE_LENGTH)
        # Load ML model
        model = pickle.load(open('D:/MTech/Semester VI/MTP/saved models/mt19aie323-twitter-depression-model.pkl', 'rb'))

        labels_pred1 = model.predict(data_d)
        #labels_pred1 = np.round(labels_pred1.flatten())
        num_correct = 0
        for i in range(len(labels_pred1)):
            if labels_pred1[i] == 1:
                num_correct += 1
        accuracy=(num_correct/len(labels_pred1)*100)

        if (accuracy>8):
          depression_diagnosis = 'Person''s'' tweets are showing depression thought'
        else:
          depression_diagnosis = 'Person''s'' tweets are not showing depression thought'

    st.success(depression_diagnosis)

# Diabetes Prediction Page
if (selected == 'Diabetes Prediction'):

    # page title
    st.title('Diabetes Disease Prediction')

    # getting the input data from the user
    col1, col2, col3 = st.columns(3)

    with col1:
        Pregnancies = st.text_input('Number of Pregnancies')

    with col2:
        Glucose = st.text_input('Glucose Level')

    with col3:
        BloodPressure = st.text_input('Blood Pressure value')

    with col1:
        SkinThickness = st.text_input('Skin Thickness value')

    with col2:
        Insulin = st.text_input('Insulin Level')

    with col3:
        BMI = st.text_input('BMI value')

    with col1:
        DiabetesPedigreeFunction = st.text_input('Diabetes Pedigree Function value')

    with col2:
        Age = st.text_input('Age of the Person')

    # code for Prediction
    diab_diagnosis = ''

    # creating a button for Prediction

    if st.button('Diabetes Test Result'):
        diab_prediction = diabetes_model.predict([[Pregnancies, Glucose, BloodPressure, SkinThickness, Insulin, BMI, DiabetesPedigreeFunction, Age]])

        if (diab_prediction[0] == 1):
          diab_diagnosis = 'The person is diabetic'
        else:
          diab_diagnosis = 'The person is not diabetic'

    st.success(diab_diagnosis)

# Heart Disease Prediction Page
if (selected == 'Heart Disease Prediction'):

    # page title
    st.title('Heart Disease Prediction')

    col1, col2, col3 = st.columns(3)

    with col1:
        age = st.text_input('Age')

    with col2:
        sex = st.text_input('Sex')

    with col3:
        cp = st.text_input('Chest Pain types')

    with col1:
        trestbps = st.text_input('Resting Blood Pressure')

    with col2:
        chol = st.text_input('Serum Cholestoral in mg/dl')

    with col3:
        fbs = st.text_input('Fasting Blood Sugar > 120 mg/dl')

    with col1:
        restecg = st.text_input('Resting Electrocardiographic results')

    with col2:
        thalach = st.text_input('Maximum Heart Rate achieved')

    with col3:
        exang = st.text_input('Exercise Induced Angina')

    with col1:
        oldpeak = st.text_input('ST depression induced by exercise')

    with col2:
        slope = st.text_input('Slope of the peak exercise ST segment')

    with col3:
        ca = st.text_input('Major vessels colored by flourosopy')

    with col1:
        thal = st.text_input('thal: 0 = normal; 1 = fixed defect; 2 = reversable defect')

    # code for Prediction
    heart_diagnosis = ''

    # creating a button for Prediction

    if st.button('Heart Disease Test Result'):
        heart_prediction = heart_disease_model.predict([[age, sex, cp, trestbps, chol, fbs, restecg,thalach,exang,oldpeak,slope,ca,thal]])

        if (heart_prediction[0] == 1):
          heart_diagnosis = 'The person is having heart disease'
        else:
          heart_diagnosis = 'The person does not have any heart disease'

    st.success(heart_diagnosis)


import torch
from torch.nn import Module
from torch.nn import functional as F
#%%
# class SmoothL1Loss(Module):
#     def __init__(self, use_gpu):
#         super (SmoothL1Loss, self).__init__()
#         self.use_gpu = use_gpu
#         return

#     def forward(self, clabel, target, routput, rlabel):

# #        rloss = F.smooth_l1_loss(routput, rlabel)
#         rloss = F.smooth_l1_loss(routput, rlabel, size_average=False, reduce=False)

#         e = torch.eq(clabel.float(), target)
#         e = e.squeeze()
#         e0,e1,e2,e3,e4 = e[0].unsqueeze(0),e[1].unsqueeze(0),e[2].unsqueeze(0),e[3].unsqueeze(0),e[4].unsqueeze(0)
#         eq = torch.cat([e0,e0,e0,e0,e1,e1,e1,e1,e2,e2,e2,e2,e3,e3,e3,e3,e4,e4,e4,e4], dim=0).float()

#         rloss = rloss.squeeze()
#         rloss = torch.mul(eq, rloss)
#         rloss = torch.sum(rloss)
#         rloss = torch.div(rloss, eq.nonzero().shape[0]+1e-4)
#         return rloss
# #%%
# class Myloss(Module):
#     def __init__(self):
#         super (Myloss, self).__init__()
#         return

#     def forward(self, coutput, clabel, target, routput, rlabel, lmbda):
#         closs = F.cross_entropy(coutput, clabel)

# #        rloss = F.smooth_l1_loss(routput, rlabel)
#         rloss = F.smooth_l1_loss(routput, rlabel, size_average=False, reduce=False)

#         e = torch.eq(clabel.float(), target)
#         e = e.squeeze()
#         e0,e1,e2,e3,e4 = e[0].unsqueeze(0),e[1].unsqueeze(0),e[2].unsqueeze(0),e[3].unsqueeze(0),e[4].unsqueeze(0)
#         eq = torch.cat([e0,e0,e0,e0,e1,e1,e1,e1,e2,e2,e2,e2,e3,e3,e3,e3,e4,e4,e4,e4], dim=0).float()

#         rloss = rloss.squeeze()
#         rloss = torch.mul(eq, rloss)
#         rloss = torch.sum(rloss)
#         rloss = torch.div(rloss, eq.nonzero().shape[0]+1e-4)

#         loss = torch.add(closs, lmbda, rloss)
#         return loss

class Myloss(Module):
    def __init__(self):
        super (Myloss, self).__init__()
        return

    def forward(self, coutput, clabel, routput, rlabel, lmbda):
        """
        Input:
            - coutput: (bs, 5, 2, 17, 17)
            - clabel: (bs, 5, 17, 17)
            - routput: (bs, 20, 17, 17)
            - rlabel: (bs, 20, 17, 17)
            - lmbda: scalar
            Typically, bs==1
        """
        closs = F.cross_entropy(coutput.permute(0,2,1,3,4), clabel)

        rloss = F.smooth_l1_loss(routput, rlabel, size_average=False, reduce=False)  # (bs, 20, 17, 17)

        C = rlabel.size()[1]
        eq = (clabel==1).unsqueeze(2).float()  # (bs, 5, 1, 17, 17)
        rloss = rloss.view(-1,C//4,4,17,17).mul(eq).sum()  # scalar
        rloss = torch.div(rloss, eq.nonzero().shape[0]*4+1e-4)  # average over all non-zero rloss term

        loss = torch.add(closs, lmbda, rloss)

        return loss, closs, rloss


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul  8 10:56:42 2021

@author: harsh
"""
#1st socket script

import socket
mysock = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org' , 80))     #80 is port number
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)

while True:
    data = mysock.recv(512)
    if(len(data)<1):
        break
    print(data.decode())
mysock.close()

#same thing but using urllib
#skips all the headers
import urllib.request, urllib.error, urllib.parse
fhand = urllib.request.urlopen("http://data.pr4e.org/romeo.txt")
count = dict()
for line in fhand:
    words = line.decode().split()
    for word in words:
        count[word] = count.get(word,0)+1
print(count)


n=int(input())
for x in range(0,n):
    num=bin(int(input()))
    sum=0
    for i in range(2,len(num)):
        if num[i]=="1":
            sum=sum+1
    if sum%2==0:
        print("even")
    else:
        print("odd")


from os import PathLike
from typing import IO, Sequence, TypeAlias, Union

import pygame as pg
from pygame import Color, Rect, Surface

RGBAOutput: TypeAlias = tuple[int, int, int, int]
ColorValue = Union[Color, int, str,
                   tuple[int, int, int],
                   RGBAOutput,
                   Sequence[int]]
AnyPath = Union[str, bytes, PathLike[str], PathLike[bytes]]
FileArg = Union[AnyPath, IO[str], IO[bytes]]

class SpriteSheet:
    """
    A big image containing multiple smaller images which can be extracted
    via `extract_image` or `split` methods.
    """

    def __init__(self,
                 file_path: FileArg,
                 alpha: bool = False,
                 ) -> None:

        sheet = pg.image.load(file_path)
        self._sheet = sheet.convert_alpha() if alpha else sheet.convert()
        self.alpha = alpha

    @property
    def size(self) -> tuple[int, int]:
        return self._sheet.get_size()

    def extract_image(self,
                      rect: tuple[int, int, int, int] | Rect,
                      alpha: bool | None = None,
                      colorkey: ColorValue | None = None,
                      ) -> Surface:
        """
        Extract part of the spritesheet located on the given rect.
        If alpha is not provided, initial alpha value will be used.
        Both alpha and colorkey cannot be true.
        """

        if alpha is None:
            alpha = self.alpha
        if alpha and colorkey:
            raise ValueError("Cannot accept both alpha and colorkey.")

        size = rect[2:4]
        if alpha:
            image = Surface(size, pg.SRCALPHA).convert_alpha()
        else:
            image = Surface(size).convert()
        if colorkey:
            image.set_colorkey(colorkey, pg.RLEACCEL)

        image.blit(self._sheet, (0, 0), rect)
        return image

    def extract_whole(self,
                      alpha: bool | None = None,
                      colorkey: ColorValue | None = None,
                      ) -> Surface:
        """
        Extract the entire spritesheet as a single image.
        If alpha is not provided, initial alpha value will be used.
        Both alpha and colorkey cannot be true.
        """

        rect = self._sheet.get_rect()
        return self.extract_image(rect=rect, alpha=alpha, colorkey=colorkey)

    def split(self,
              size: tuple[int, int],
              alpha: bool | None = None,
              colorkey: ColorValue | None = None,
              ) -> list[Surface]:
        """
        Split the spritesheet into equal chunks (sprites) of the given size.
        Any extra area will be cropped out.
        If alpha is not provided, initial alpha value will be used.
        Both alpha and colorkey cannot be true.
        """

        width, height = size
        rects = [(x, y, width, height)
                 for y in range(0, self._sheet.get_height(), height)
                 for x in range(0, self._sheet.get_width(), width)]
        return [self.extract_image(r, alpha, colorkey) for r in rects]


from tkinter import *

def Convert():
    '''Convert Kg to gram, pounds and ounce'''
    kg = float(a.get())
    gram = kg * 1000
    pounds = kg * 2.20462
    ounce = kg * 35.274

    result_gram['text'] = str(gram)
    result_pound['text'] = str(pounds)
    result_ounce['text'] = str(ounce)

root = Tk()

a = StringVar()
root.title("Convert")

lbl1 = Label(root, text="Enter the weight in Kg", font=('Calibri', 12, 'bold'))
lbl1.grid(column=0, row=0, padx=20, pady=20, sticky="w")

entry_lbl = Entry(root, width=50, borderwidth=3, highlightthickness=3, textvariable=a, font=('Calibri', 12, 'bold'), justify='left')
entry_lbl.grid(column=1, row=0, padx=20, sticky="w")

btn_convert = Button(root, text="Convert", relief=RAISED, bg='grey', font=('Calibri', 12, 'bold'), command=Convert)
btn_convert.grid(column=2, row=0, padx=10)

lbl_gram = Label(root, text="Gram", font=('Calibri', 12, 'bold'))
lbl_gram.grid(column=0, row=1, padx=20, pady=20, sticky="n")

lbl_pounds = Label(root, text="Pounds", font=('Calibri', 12, 'bold'))
lbl_pounds.grid(column=1, row=1, padx=20, pady=20, sticky="n")

lbl_ounce = Label(root, text="Ounce", font=('Calibri', 12, 'bold'))
lbl_ounce.grid(column=2, row=1, padx=20, pady=20, sticky="n")

result_gram = Label(root, text="", font=('Calibri', 12, 'bold'))
result_gram.grid(column=0, row=2, padx=20, sticky='n')

result_pound = Label(root, text="", font=('Calibri', 12, 'bold'))
result_pound.grid(column=1, row=2, padx=20, sticky='n')

result_ounce = Label(root, text="", font=('Calibri', 12, 'bold'))
result_ounce.grid(column=2, row=2, padx=20, sticky='n')

root.mainloop()