Sunday 15 March 2020

Tkinter Game

import tkinter
#...and for creating random numbers.
import random
 
#the list of possible colour.
colours = ['Red','Blue','Green','Pink','Black','Yellow','Orange','White','Purple','Brown']
#the player's score, initially 0.
score=0
#the game time left, initially 30 seconds.
timeleft=30
 
#a function that will start the game.
def startGame(event):
 
    #if there's still time left...
    if timeleft == 30:
        #start the countdown timer.
        countdown()
        
    #run the function to choose the next colour.
    nextColour()
 
#function to choose and display the next colour.
def nextColour():
 
    #use the globally declared 'score' and 'play' variables above.
    global score
    global timeleft
 
    #if a game is currently in play...
    if timeleft > 0:
 
        #...make the text entry box active.
        e.focus_set()
 
        #if the colour typed is equal to the colour of the text...
        if e.get().lower() == colours[1].lower():
            #...add one to the score.
            score += 1
 
        #clear the text entry box.
        e.delete(0, tkinter.END)
        #shuffle the list of colours.
        random.shuffle(colours)
        #change the colour to type, by changing the text _and_ the colour to a random colour value
        label.config(fg=str(colours[1]), text=str(colours[0]))
        #update the score.
        scoreLabel.config(text="Score: " + str(score))
 
#a countdown timer function. 
def countdown():
 
    #use the globally declared 'play' variable above.
    global timeleft
 
    #if a game is in play...
    if timeleft > 0:
 
        #decrement the timer.
        timeleft -= 1
        #update the time left label.
        timeLabel.config(text="Time left: " + str(timeleft))
        #run the function again after 1 second.
        timeLabel.after(1000, countdown)
    
#create a GUI window.
root = tkinter.Tk()
#set the title.
root.title("TTCANTW")
#set the size.
root.geometry("375x200")
 
#add an instructions label.
instructions = tkinter.Label(root, text="Type in the colour of the words, and not the word text!", font=('Helvetica', 12))
instructions.pack()
 
#add a score label.
scoreLabel = tkinter.Label(root, text="Press enter to start", font=('Helvetica', 12))
scoreLabel.pack()
 
#add a time left label.
timeLabel = tkinter.Label(root, text="Time left: " + str(timeleft), font=('Helvetica', 12))
timeLabel.pack()
 
#add a label for displaying the colours.
label = tkinter.Label(root, font=('Helvetica', 60))
label.pack()
 
#add a text entry box for typing in colours.
e = tkinter.Entry(root)
#run the 'startGame' function when the enter key is pressed.
root.bind('<Return>', startGame)
e.pack()
#set focus on the entry box.
e.focus_set()
 
#start the GUI
root.mainloop()

MR Python

from pandas import DataFrame
from sklearn import linear_model
import statsmodels.api as sm

#statsmodels is a Python module that provides classes and functions
#for the estimation of many different statistical models,
#as well as for conducting statistical tests, and statistical
#data exploration.

Stock_Market = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
                'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
                'Interest_Rate': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
                'Unemployment_Rate': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
                'Stock_Index_Price': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]       
                }

df = DataFrame(Stock_Market,columns=['Year','Month','Interest_Rate',
                                     'Unemployment_Rate','Stock_Index_Price'])

X = df[['Interest_Rate','Unemployment_Rate']] # here we have 2 variables for multiple regression. If you just want to use one variable for simple linear regression, then use X = df['Interest_Rate'] for example.Alternatively, you may add additional variables within the brackets
Y = df['Stock_Index_Price']

# with sklearn
regr = linear_model.LinearRegression()
regr.fit(X, Y)

print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)

# prediction with sklearn
New_Interest_Rate = 2.75
New_Unemployment_Rate = 5.3
print ('Predicted Stock Index Price: \n',
       regr.predict([[New_Interest_Rate ,New_Unemployment_Rate]]))

# with statsmodels
X = sm.add_constant(X) # adding a constant

#OLS stands for ordinary least squares
#As we know, the simplest linear regression algorithm assumes
#that the relationship between an independent variable (x)
#and dependent variable (y) is of the following form: y = mx + c,
#which is the equation of a line.
#In line with that, OLS is an estimator in which the values of m and
#c (from the above equation) are chosen in such a
#way as to minimize the sum of the squares of the differences between the
#observed dependent variable and predicted dependent variable.
#That’s why it’s named ordinary
#least squares.Also, it should be noted that when the sum of
#the squares of the differences is minimum,
#the loss is also minimum—hence the prediction is better.

model = sm.OLS(Y, X).fit()
predictions = model.predict(X)

print_model = model.summary()
print(print_model)


#Stock_Index_Price = (Intercept) + (Interest_Rate coef)*X1 + (Unemployment_Rate coef)*X2
#Stock_Index_Price = (1798.4040) + (345.5401)*X1 + (-250.1466)*X2
Interest Rate = 2.75 (i.e., X1= 2.75)
Unemployment Rate = 5.3 (i.e., X2= 5.3)

#Stock_Index_Price = (1798.4040) + (345.5401)*(2.75) + (-250.1466)*(5.3) = 1422.86

Saturday 14 March 2020

Tkinter2

from openpyxl.workbook import Workbook
import tkinter as tk
import pandas as pd

def saveinfo():
    valor1 = entry1.get()
    valor2 = entry2.get()
    valor3 = entry3.get()

    data.append([valor1, valor2, valor3])
    print(data)

def export():
    df = pd.DataFrame(data)
    df.to_excel("DataBase.xlsx")

def opennewwindow():
    global entry1
    global entry2
    global entry3

    window.destroy()

    newwindow = tk.Tk()

    tk.Label(newwindow, text="Please, enter data: ").grid(column=0, row=0, columnspan=3)

    tk.Label(newwindow, text="Number").grid(column=0, row=1)
    entry1 = tk.Entry(newwindow)
    entry1.grid(column=1, row=1)

    tk.Label(newwindow, text="Description", ).grid(column=0, row=2)
    entry2 = tk.Entry(newwindow)
    entry2.grid(column=1, row=2)

    tk.Label(newwindow, text="Brand").grid(column=0, row=3)
    entry3 = tk.Entry(newwindow)
    entry3.grid(column=1, row=3)

    tk.Button(newwindow, text="Save", command=saveinfo).grid(column=2, row=2, sticky='we')
    tk.Button(newwindow, text="Export", command=export).grid(column=2, row=3, sticky='we')

    newwindow.mainloop()

# --- main ---

df = pd.DataFrame
data = []

window = tk.Tk()
tk.Label(window, text="Platform").grid(column=0, row=0)
tk.Button(window, text="Choose an element: ", command=opennewwindow).grid(column=0, row=1)

window.mainloop()

Tkinter1

import tkinter as tk

root= tk.Tk()

canvas1 = tk.Canvas(root, width = 400, height = 300,  relief = 'raised')
canvas1.pack()

label1 = tk.Label(root, text='Calculate the Square Root')
label1.config(font=('helvetica', 14))
canvas1.create_window(200, 25, window=label1)

label2 = tk.Label(root, text='Type your Number:')
label2.config(font=('helvetica', 10))
canvas1.create_window(200, 100, window=label2)

entry1 = tk.Entry (root)
canvas1.create_window(200, 140, window=entry1)

def getSquareRoot ():
 
    x1 = entry1.get()
 
    label3 = tk.Label(root, text= 'The Square Root of ' + x1 + ' is:',font=('helvetica', 10))
    canvas1.create_window(200, 210, window=label3)
 
    label4 = tk.Label(root, text= float(x1)**0.5,font=('helvetica', 10, 'bold'))
    canvas1.create_window(200, 230, window=label4)
 
button1 = tk.Button(text='Get the Square Root', command=getSquareRoot, bg='brown', fg='white', font=('helvetica', 9, 'bold'))
canvas1.create_window(200, 180, window=button1)

root.mainloop()

Ganpat Uni

from tkinter import *
parent = Tk()
name = Label(parent,text = "Name").grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = "Password").grid(row = 1, column = 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
parent.mainloop()

______________________________________________________

import tkinter
#...and for creating random numbers.
import random
 
#the list of possible colour.
colours = ['Red','Blue','Green','Pink','Black','Yellow','Orange','White','Purple','Brown']
#the player's score, initially 0.
score=0
#the game time left, initially 30 seconds.
timeleft=30
 
#a function that will start the game.
def startGame(event):
 
    #if there's still time left...
    if timeleft == 30:
        #start the countdown timer.
        countdown()
        
    #run the function to choose the next colour.
    nextColour()
 
#function to choose and display the next colour.
def nextColour():
 
    #use the globally declared 'score' and 'play' variables above.
    global score
    global timeleft
 
    #if a game is currently in play...
    if timeleft > 0:
 
        #...make the text entry box active.
        e.focus_set()
 
        #if the colour typed is equal to the colour of the text...
        if e.get().lower() == colours[1].lower():
            #...add one to the score.
            score += 1
 
        #clear the text entry box.
        e.delete(0, tkinter.END)
        #shuffle the list of colours.
        random.shuffle(colours)
        #change the colour to type, by changing the text _and_ the colour to a random colour value
        label.config(fg=str(colours[1]), text=str(colours[0]))
        #update the score.
        scoreLabel.config(text="Score: " + str(score))
 
#a countdown timer function. 
def countdown():
 
    #use the globally declared 'play' variable above.
    global timeleft
 
    #if a game is in play...
    if timeleft > 0:
 
        #decrement the timer.
        timeleft -= 1
        #update the time left label.
        timeLabel.config(text="Time left: " + str(timeleft))
        #run the function again after 1 second.
        timeLabel.after(1000, countdown)
    
#create a GUI window.
root = tkinter.Tk()
#set the title.
root.title("TTCANTW")
#set the size.
root.geometry("375x200")
 
#add an instructions label.
instructions = tkinter.Label(root, text="Type in the colour of the words, and not the word text!", font=('Helvetica', 12))
instructions.pack()
 
#add a score label.
scoreLabel = tkinter.Label(root, text="Press enter to start", font=('Helvetica', 12))
scoreLabel.pack()
 
#add a time left label.
timeLabel = tkinter.Label(root, text="Time left: " + str(timeleft), font=('Helvetica', 12))
timeLabel.pack()
 
#add a label for displaying the colours.
label = tkinter.Label(root, font=('Helvetica', 60))
label.pack()
 
#add a text entry box for typing in colours.
e = tkinter.Entry(root)
#run the 'startGame' function when the enter key is pressed.
root.bind('<Return>', startGame)
e.pack()
#set focus on the entry box.
e.focus_set()
 
#start the GUI
root.mainloop()

Thursday 12 March 2020

Ganpat University

https://drive.google.com/open?id=1oD1mFi4zmqz5xGuCJ7_OdUKZgW5fekct

https://drive.google.com/file/d/1M4sGfss3DLYosCxWZoai2i9X1AMZoolb/view?usp=sharing

https://drive.google.com/open?id=1ayhZqjZfCQep_1q6LypAv9HMMyq11HzD

Tuesday 10 March 2020

code

http://www-eio.upc.edu/~pau/cms/rdata/datasets.html



## KAJAL

import pandas as pd
import numpy as np
z= [];
letters = [];
for num in range(1, 20):
   
    # checking condition
    if num % 2 != 0:
        z.append(num)
     
print(z)

for c in range(97, 107):
        letters.append(chr(c))
print(letters)
numbers = np.random.randint(100,200,10)
df=pd.DataFrame({"a":z,"b":letters,"c":numbers})
df
________________________________________________

## Abhishek

l = []
for i in range (1,20) :
    if(i %2 != 0):
        l.append(i)
l1= []
for letter in 'abcdefghij':
    l1.append(letter)

import random
l2=random.sample(range(1,100),10)

df=pd.DataFrame(list(zip(l,l1,l2)))

Saturday 7 March 2020

IIT Indore

library(shiny)

ui = fluidPage(
   titlePanel("TABLE"),
    sidebarLayout(
      sidebarPanel(
        sliderInput("num", "integer", 1, 200, 1,step = 1, animate =
animationOptions(interval=400, loop=TRUE))),
      mainPanel(
        tableOutput("iit")
      )) )

server = function(input, output) {
    output$iit = renderPrint({ x<-input$num
    for(i in 1:10){
      a=x*i
      cat(x,"x",i,"=",a,"<br>")
       }})}

shinyApp(ui = ui, server = server)
_______________________________________________________

library(shiny)
ui<-fluidPage(
  sidebarPanel(
    sliderInput("num","integer",1,200,5,step=1,animate = animationOptions(interval = 1000,loop = TRUE))),
  radioButtons("radio",label = h1("Choose one"),choices = list("Table"=1,"Even/Odd"=2,"Fact"=3),selected = 1),
  hr(),
  mainPanel(
    tableOutput("abc")
  )
)


server<-function(input,output)
{

    output$abc<-renderPrint({
      r<-input$radio
      x<-input$num
      if(r==1){
        for(i in 1:10)
        {
          cat(x,"X",i,"=",x*i,"<br>")
        }
      }else if(r==2)
      {
        if(x%%2==0)
        {
          print("Even")
        }else{
          print("Odd")
        }
      }
      else{
        print(factorial(x))
      }
    })
 

 
shinyApp(ui=ui,server=server)

____________________________________________________________


# Splitting the dataset into the Training set and Test set

install.packages('caTools')
library(caTools)

set.seed(123)
split = sample.split(dataset$Purchased, SplitRatio = 0.75)

training_set = subset(dataset, split == TRUE)
test_set = subset(dataset, split == FALSE)
View(training_set)
View(test_set)

# Feature Scaling

training_set[-3] = scale(training_set[-3])
test_set[-3] = scale(test_set[-3])

View(training_set)
View(test_set)
##############################################

# Fitting SVM to the Training set
install.packages('e1071')
library(e1071)

classifier = svm(formula = Purchased ~ .,
                 data = training_set,
                 type = 'C-classification',
                 kernel = 'linear')

print(classifier)

A=classifier$SV
Print(A)

# Predicting the Test set results

y_pred = predict(classifier, newdata = test_set[-3])


# Making the Confusion Matrix

cm = table(test_set[, 3], y_pred)
print(cm)
################################################

#Visualizing the Training set results

# installing library ElemStatLearn
library(ElemStatLearn)

# Plotting the training data set results
set = training_set
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)

grid_set = expand.grid(X1, X2)
colnames(grid_set) = c('Age', 'EstimatedSalary')
y_grid = predict(classifier, newdata = grid_set)

plot(set[, -3],
     main = 'SVM (Training set)',
     xlab = 'Age', ylab = 'Estimated Salary',
     xlim = range(X1), ylim = range(X2))

contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)
points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'coral1', 'aquamarine'))
points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))

##################################################

#Visualizing the Test set results
set = test_set
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)

grid_set = expand.grid(X1, X2)
colnames(grid_set) = c('Age', 'EstimatedSalary')
y_grid = predict(classifier, newdata = grid_set)

plot(set[, -3], main = 'SVM (Test set)',
     xlab = 'Age', ylab = 'Estimated Salary',
     xlim = range(X1), ylim = range(X2))

contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)

points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'coral1', 'aquamarine'))

points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))

#############################################

Wednesday 4 March 2020

IBM BigData


CREATE TABLE feedback_vnr(comments STRING);
load data LOCAL INPATH '/home/cloudera/Desktop/file.txt' INTO TABLE feedback_vnr;
select * from feedback_vnr;
select split(comments,' ') FROM feedback_vnr;
select explode(split(comments,' ')) FROM feedback_vnr
select word,count(*) from (select explode(split(comments,' ')) as word from feedback_vnr)  tmp GROUP BY word;

___________________________

A = load '/user/cloudera/55';
B = foreach A generate flatten(TOKENIZE((chararray)$0)) as word;
C = filter B by word matches '\\w+';
D = group C by word;
E = foreach D generate COUNT(C),group;
store E into '/user/cloudera/n66';
____________________________



 Most occurred first character in the word of a  file


lines  = LOAD '/user/cloudera/my-friends' AS (line: chararray); 
tokens = FOREACH lines GENERATE flatten(TOKENIZE(line)) As token:chararray;
letters = FOREACH tokens  GENERATE SUBSTRING(token,0,1) As letter:chararray;
lettergrp = GROUP letters by letter; 
countletter  = FOREACH  lettergrp  GENERATE group,COUNT(letters);
OrderCnt = ORDER countletter BY $1 DESC; 
result = LIMIT OrderCnt 1;
STORE result into '/user/cloudera/dummy5556777777';

____________________________________



tier1.sources  = source1
tier1.channels = channel1
tier1.sinks    = sink1 

tier1.sources.source1.type     = netcat
tier1.sources.source1.bind     = 127.0.0.1
tier1.sources.source1.port     = 44444
tier1.sources.source1.channels = channel1

tier1.channels.channel1.type   = memory
tier1.channels.channel1.capacity = 100

tier1.sinks.sink1.type= HDFS
tier1.sinks.sink1.fileType=DataStream
tier1.sinks.sink1.channel      = channel1

tier1.sinks.sink1.hdfs.path = hdfs://localhost:8020/user/cloudera/flume/events_manish_rvim